xonecas.io
64875
Mc

mini-coder / commit d039c9b

fix: dont call completeSimple, rely only on the main loop

xonecas2026-04-25 d039c9bd0f5a5b483d14d6b0722237f744060852 parent a9089ea

7 files changed

TODO.md+0−3
@@ -2,7 +2,4 @@
22
33 > This file is managed by the user, only edit if asked to.
44
5-- [ ] Write a minimal python harbor agent, we removed the overcomplicated last one since we change our
6- json output format. Which is now more like a ndjson output.
7-
85 - [ ] `Took XXXX` label in the TUI are all wrong ahah, need to be revised.
benchmarks/local-harbor-agent.py+0−2
@@ -1,5 +1,3 @@
1-# TODO: `LocalMiniCoderAgent` so we can run terminal bench with our current local modified code.
2-
31 from __future__ import annotations
42
53 import json
src/agent.ts+24−19
@@ -5,12 +5,11 @@ import {
55 type AssistantMessage,
66 type AssistantMessageEvent,
77 type Context,
8- completeSimple,
98 type Message,
109 streamSimple,
1110 type ToolResultMessage,
1211 } from "@mariozechner/pi-ai";
13-import { simpleGit, type StatusResult } from "simple-git";
12+import { type StatusResult, simpleGit } from "simple-git";
1413 import { parseSkillFrontmatter } from "./shared";
1514 import type { CliOptions, ToolAndRunner } from "./types";
1615
@@ -76,11 +75,11 @@ export const TASK_PROMPT = `${IDENTITY_PROMPT}
7675
7776 async function getEnvPrompt() {
7877 // TODO: What else do the agents always check before answering every time?
79- let gitStatus: StatusResult | {nogit: string};
78+ let gitStatus: StatusResult | { nogit: string };
8079 try {
8180 gitStatus = await simpleGit().status();
8281 } catch (_) {
83- gitStatus = {nogit: "No git repo in this folder."};
82+ gitStatus = { nogit: "No git repo in this folder." };
8483 }
8584 const envStatus = JSON.stringify(
8685 {
@@ -216,6 +215,7 @@ export async function streamAgent(
216215 const onAbort = () => {
217216 controller?.abort();
218217 };
218+
219219 // Wire the global abort signal to each turn http requests
220220 abortController?.signal.addEventListener("abort", onAbort);
221221
@@ -237,11 +237,12 @@ export async function streamAgent(
237237
238238 // Check if the agent is done, or an error/abort happened before moving
239239 // on towards tool calling.
240- if (["stop", "error", "aborted"].includes(finalMessage.stopReason)) {
240+ if (
241+ ["stop", "error", "aborted", "length"].includes(finalMessage.stopReason)
242+ ) {
241243 // Agent is done, send the final message, and current context.
242244 completeFn?.(finalMessage, context);
243- abortController?.signal.removeEventListener("abort", onAbort);
244- return;
245+ break;
245246 }
246247
247248 // Call tolls and per tool result callback.
@@ -250,14 +251,27 @@ export async function streamAgent(
250251 );
251252
252253 for (const call of toolCalls) {
254+ let output = "";
255+ let isError = false;
253256 const toolDef = tools.find((i) => i.tool.name === call.name);
254- const result = (await toolDef?.runner(call.arguments)) || "";
257+ if (toolDef) {
258+ try {
259+ output = await toolDef.runner(call.arguments);
260+ } catch (err) {
261+ const error = err instanceof Error ? err.message : "Unknown error";
262+ output = `Tool call failed: ${error}`;
263+ isError = true;
264+ }
265+ } else {
266+ output = `Unknown tool: ${call.name}`;
267+ }
268+
255269 const msg: ToolResultMessage = {
256270 role: "toolResult",
257271 toolCallId: call.id,
258272 toolName: call.name,
259- content: [{ type: "text", text: result }],
260- isError: false,
273+ content: [{ type: "text", text: output }],
274+ isError,
261275 timestamp: Date.now(),
262276 };
263277 context.messages.push(msg);
@@ -265,15 +279,6 @@ export async function streamAgent(
265279 // Update with tool results.
266280 toolsFn?.(msg, context);
267281 }
268-
269- if (toolCalls.length > 0) {
270- const cont = await completeSimple(options.model, context, {
271- apiKey,
272- reasoning: options.effort,
273- signal: controller.signal,
274- });
275- context.messages.push(cont);
276- }
277282 }
278283 } finally {
279284 abortController?.signal.removeEventListener("abort", onAbort);
src/headless.ts+8−5
@@ -41,7 +41,9 @@ export async function streamHeadless(
4141 break;
4242 case "toolcall_end":
4343 // TODO: other tools output
44- log({ msg: `> ${ev.toolCall.name}: ${ev.toolCall.arguments.command}` });
44+ log({
45+ msg: `> ${ev.toolCall.name}: ${JSON.stringify(ev.toolCall.arguments)}`,
46+ });
4547 break;
4648 case "error":
4749 log({ msg: `> Error ${ev.reason}\n${ev.error.content}` });
@@ -58,14 +60,15 @@ export async function streamHeadless(
5860 let text = tool.content
5961 .filter((c) => c.type === "text")
6062 .map((c) => c.text)
61- .join("\n").slice(-400);
63+ .join("\n")
64+ .slice(-400);
6265
6366 if (text.length === 400) {
64- text += `...${text}`
67+ text = `...${text}`;
6568 }
6669
6770 log({
68- msg: `> ${tool.toolName} output:\n---\n${text}\n---\n`,
71+ msg: `> ${tool.toolName} output:\n---\n${text}\n---`,
6972 json: JSON.stringify(tool),
7073 });
7174 };
@@ -74,7 +77,7 @@ export async function streamHeadless(
7477 log({
7578 msg: `\nTotal tokens: ${msg.usage.input} in, ${msg.usage.output} out`,
7679 });
77- log({ msg: `Cost: $${msg.usage.cost.total.toFixed(4)}` });
80+ log({ msg: `Cost: $${msg.usage.cost.total.toFixed(4)}\n` });
7881
7982 if (["stop", "error", "aborted"].includes(msg.stopReason)) {
8083 log({ msg: `Reason for stopping: "${msg.stopReason}"` });
src/tool-bash.ts+16−9
@@ -1,7 +1,7 @@
11 import { type Tool, Type } from "@mariozechner/pi-ai";
22 import { secureRandomString } from "./shared";
33
4-const OUTPUT_THRESHOLD = 10000;
4+const OUTPUT_THRESHOLD = 16000;
55 const description = `## Bash CLI tool
66
77 Best practices using this tool:
@@ -39,26 +39,33 @@ export async function runBashTool(args: Record<string, any>) {
3939 const proc = Bun.spawn(["bash", "-c", args.command], {
4040 stdout: "pipe",
4141 stderr: "pipe",
42+ env: {
43+ ...Bun.env,
44+ NO_COLOR: "1",
45+ },
4246 });
43- const stdout = (await proc.stdout.text()).trim();
44- const stderr = (await proc.stderr?.text())?.trim();
45- await proc.exited;
4647
47- let out = `# EXIT CODE: ${proc.exitCode}`;
48+ const [stdout, stderr, exitCode] = await Promise.all([
49+ proc.stdout.text(),
50+ proc.stderr.text(),
51+ proc.exited,
52+ ]);
53+
54+ let out = `# EXIT CODE: ${exitCode}`;
4855 if (stderr.length) {
4956 out += `
5057 # STDERR:
5158
52-${stderr}`;
59+${Bun.stripANSI(stderr)}`;
5360 }
5461 if (stdout.length) {
5562 out += `
5663 # STDOUT:
5764
58-${stdout}`;
65+${Bun.stripANSI(stdout)}`;
5966 }
6067
61- // If `out` is too big, more than ~10KB, write it to a temp file
68+ // If `out` is too big, more than ~XXKB, write it to a temp file
6269 // And add that to the truncation label for the agent to be able
6370 // to continue the read with scans. This is to protect context,
6471 // not a general read guard. The hint is for the agent, not the TUI
@@ -68,7 +75,7 @@ ${stdout}`;
6875 await Bun.write(pathname, out);
6976 out = `${out.substring(0, OUTPUT_THRESHOLD)}
7077
71-Truncated at ${OUTPUT_THRESHOLD}. Full output at ${pathname}`;
78+Truncated at ~${OUTPUT_THRESHOLD / 1000}KB. Full output at ${pathname}`;
7279 }
7380
7481 return out;
src/tui-conversation.ts+4−109
@@ -1,28 +1,9 @@
1-import {
2- HStack,
3- measureContentHeight,
4- type Node,
5- Text,
6- VStack,
7-} from "@cel-tui/core";
1+import { HStack, type Node, Text, VStack } from "@cel-tui/core";
82 import { elapsedTime, relativeTime } from "./shared";
93 import { TextPill, theme } from "./tui-components";
104 import { memoizedSyntaxHighlight } from "./tui-syntax-highlight";
115 import type { TUIMessage, TUIState } from "./types";
126
13-const gap = 1;
14-
15-type ConversationLayout = {
16- messages: TUIMessage[];
17- count: number;
18- width: number;
19- heights: number[];
20- tops: number[];
21- totalHeight: number;
22-};
23-
24-let cachedLayout: ConversationLayout | undefined;
25-
267 function agentMessageNode(msg: TUIMessage): Node {
278 return memoizedSyntaxHighlight(
289 (msg.id ? msg.id : "") + String(msg.timestamp),
@@ -89,98 +70,12 @@ function conversationMessageNode(msg: TUIMessage): Node {
8970 ]);
9071 }
9172
92-function getConversationLayout(
93- messages: TUIMessage[],
94- width: number,
95-): ConversationLayout {
96- if (
97- cachedLayout &&
98- cachedLayout.messages === messages &&
99- cachedLayout.count === messages.length &&
100- cachedLayout.width === width
101- ) {
102- return cachedLayout;
103- }
104-
105- const heights = messages.map((msg) =>
106- measureContentHeight(conversationMessageNode(msg), { width }),
107- );
108-
109- const tops: number[] = [];
110- let totalHeight = 0;
111-
112- for (let i = 0; i < heights.length; i++) {
113- tops.push(totalHeight);
114- totalHeight += heights[i];
115- if (i < heights.length - 1) {
116- totalHeight += gap;
117- }
118- }
119-
120- cachedLayout = {
121- messages,
122- count: messages.length,
123- width,
124- heights,
125- tops,
126- totalHeight,
127- };
128-
129- return cachedLayout;
130-}
131-
13273 export function Conversation(state: TUIState) {
133- // The root viewport only adds padding.x = 1 on each side.
134- const width = Math.max(20, (process.stdout.columns ?? 80) - 2);
135- const viewportEstimate = Math.max(10, (process.stdout.rows ?? 24) - 8);
136- const overscan = viewportEstimate;
137- const { heights, tops, totalHeight } = getConversationLayout(
138- state.messages,
139- width,
140- );
141-
142- const scrollTop = state.stickToBottom
143- ? Math.max(0, totalHeight - viewportEstimate)
144- : Math.max(0, Math.min(state.scrollOffset, totalHeight));
145-
146- const minY = Math.max(0, scrollTop - overscan);
147- const maxY = scrollTop + viewportEstimate + overscan;
148-
149- let start = 0;
150- while (start < heights.length && tops[start] + heights[start] <= minY) {
151- start++;
152- }
153-
154- let end = start;
155- while (end < heights.length && tops[end] < maxY) {
156- end++;
157- }
158-
159- // Always render at least one item when possible.
160- if (end === start && end < heights.length) {
161- end++;
162- }
163-
164- const children: Node[] = [];
165-
166- // Spacer before first visible item.
167- if (start > 0) {
168- children.push(VStack({ height: tops[start] - gap }, []));
169- }
170-
171- children.push(
172- ...state.messages.slice(start, end).map(conversationMessageNode),
173- );
174-
175- // Spacer after last visible item.
176- if (end < heights.length) {
177- children.push(VStack({ height: totalHeight - tops[end] }, []));
178- }
179-
74+ // TODO: We need inteligent caching?
18075 return VStack(
18176 {
18277 flex: 1,
183- gap,
78+ gap: 1,
18479 overflow: "scroll",
18580 scrollOffset: state.stickToBottom ? Infinity : state.scrollOffset,
18681 onScroll(offset, maxOffset) {
@@ -188,6 +83,6 @@ export function Conversation(state: TUIState) {
18883 state.stickToBottom = offset >= maxOffset;
18984 },
19085 },
191- children,
86+ state.messages.map(conversationMessageNode),
19287 );
19388 }
src/tui.ts+5−4
@@ -28,6 +28,7 @@ function clearOrAbort(state: TUIState) {
2828 // Is the user clearing a state prompt?
2929 if (state.prompt?.length) {
3030 state.prompt = "";
31+ cel.render();
3132 }
3233 }
3334
@@ -38,7 +39,7 @@ function ContextPill(state: TUIState) {
3839 } else {
3940 const current = estimateTokens(JSON.stringify(state.context));
4041 const max = state.options.model.contextWindow;
41- const percent = Math.round((current / max) * 100);
42+ const percent = Math.floor((current / max) * 100);
4243 text = `~${percent}%`;
4344 }
4445
@@ -49,14 +50,14 @@ export function initTUI(state: TUIState, leave: (s: string) => void) {
4950 const cwd = basename(process.cwd());
5051 const { spinnerEvery, currentSpinner } = Spinner();
5152
52- // Because we don't render often, the ui feels unresponsive at times.
53+ // Spinner and animations timer.
5354 // This ensure Xfps, and excessive calls get coalesced in cel-tui.
54- const fps = 60;
55+ const fps = 30;
5556 const baseFramerateIntervalId = setInterval(() => {
5657 if (state.streaming) {
5758 spinnerEvery();
59+ cel.render();
5860 }
59- cel.render();
6061 }, 1000 / fps);
6162
6263 cel.init(new ProcessTerminal());