xonecas.io
64875
Mc

mini-coder / commit b789630

feat: truncation logic and components

xonecas2026-04-23 b7896305de29b4a117141b6c76c554202be56863 parent 99dcf36

6 files changed

src/index.ts+4−2
@@ -1,7 +1,7 @@
11 import { handleArgv } from "./args.ts";
22 import { streamHeadless } from "./headless.ts";
33 import { initTUI } from "./tui.ts";
4-import type { TUIActiveState } from "./types.ts";
4+import type { TUIActiveState, TUIState } from "./types.ts";
55
66 function leave(msg: string) {
77 console.log(msg);
@@ -16,12 +16,14 @@ export async function main(): Promise<void> {
1616 process.exit(0);
1717 }
1818
19- const state = {
19+ const state: TUIState = {
2020 options,
2121 prompt: "",
2222 messages: [],
2323 activeState: "idle" as TUIActiveState,
2424 streaming: false,
25+ stickToBottom: true,
26+ scrollOffset: 0,
2527 };
2628
2729 initTUI(state, leave);
src/tool-bash.ts+43−5
@@ -1,5 +1,6 @@
11 import { type Tool, Type } from "@mariozechner/pi-ai";
22
3+const OUTPUT_TRESHOLD = 10000;
34 const description = `## Bash CLI tool
45
56 Best practices using this tool:
@@ -38,11 +39,48 @@ export async function runBashTool(args: Record<string, any>) {
3839 stderr: "pipe",
3940 });
4041 await proc.exited;
41- const out = await proc.stdout.text();
42- const errorOut = await proc.stderr?.text();
42+ const stdout = await proc.stdout.text();
43+ const stderr = await proc.stderr?.text();
44+ let out =
45+ proc.exitCode === 0
46+ ? (stdout ?? "Exit 0")
47+ : (stderr ?? `Exit ${proc.exitCode}`);
4348
44- if (proc.exitCode === 0) {
45- return out;
49+ // If `out` is too big, more than ~10KB, write it to a temp file
50+ // And add that to the truncation label for the agent to be able
51+ // to continue the read with scans. This is to protect context,
52+ // not a general read guard. The hint is for the agent, not the TUI
53+ if (out.length > OUTPUT_TRESHOLD) {
54+ const key = `${Date.now()}-${secureRandomString(4)}`;
55+ const pathname = `/tmp/bash_result_${key}.txt`;
56+ await Bun.write(pathname, out);
57+ out = `${out.substring(0, OUTPUT_TRESHOLD)}
58+
59+Truncated at ${OUTPUT_TRESHOLD}. Full ouput at ${pathname}`;
60+ }
61+
62+ return out;
63+}
64+
65+function secureRandomString(
66+ length: number,
67+ chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
68+): string {
69+ const result: string[] = [];
70+ const charsLength = chars.length;
71+ const maxValid = Math.floor(256 / charsLength) * charsLength;
72+ const randomBytes = new Uint8Array(length * 2);
73+
74+ while (result.length < length) {
75+ crypto.getRandomValues(randomBytes);
76+
77+ for (const byte of randomBytes) {
78+ if (byte < maxValid) {
79+ result.push(chars[byte % charsLength]);
80+ if (result.length === length) break;
81+ }
82+ }
4683 }
47- return errorOut === "" ? `Exit code ${proc.exitCode}` : errorOut;
84+
85+ return result.join("");
4886 }
src/tui-components.ts+68−0
@@ -0,0 +1,68 @@
1+import { type Color, HStack, Text } from "@cel-tui/core";
2+
3+export const theme = {
4+ black: "color00" as Color,
5+ bblack: "color08" as Color,
6+
7+ red: "color01" as Color,
8+ bred: "color09" as Color,
9+
10+ green: "color02" as Color,
11+ bgreen: "color10" as Color,
12+
13+ yellow: "color03" as Color,
14+ byellow: "color11" as Color,
15+
16+ blue: "color04" as Color,
17+ bblue: "color12" as Color,
18+
19+ magenta: "color05" as Color,
20+ bmagenta: "color13" as Color,
21+
22+ cyan: "color06" as Color,
23+ bcyan: "color14" as Color,
24+
25+ white: "color07" as Color,
26+ bwhite: "color15" as Color,
27+};
28+
29+// Examples:
30+//
31+// TextPill("mini-coder", theme.bblack, theme.black),
32+// TextPill("mini-coder", theme.bred, theme.red),
33+// TextPill("mini-coder", theme.bgreen, theme.green),
34+// TextPill("mini-coder", theme.byellow, theme.yellow),
35+// TextPill("mini-coder", theme.bblue, theme.blue),
36+// TextPill("mini-coder", theme.bmagenta, theme.magenta),
37+// TextPill("mini-coder", theme.bcyan, theme.cyan),
38+// TextPill("mini-coder", theme.bwhite, theme.white),
39+export function TextPill(content: string, fgColor: Color, bgColor: Color) {
40+ return HStack({ gap: 1 }, [
41+ HStack({ bgColor, padding: { x: 1 } }, [
42+ Text(content, { bold: true, fgColor }),
43+ ]),
44+ ]);
45+}
46+
47+// const spinnerFrames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
48+// let spinnerTick = 0;
49+// let spinnerTimer: ReturnType<typeof setInterval> | null = null;
50+
51+// function startSpinner() {
52+// stopSpinner();
53+// spinnerTimer = setInterval(() => {
54+// spinnerTick++;
55+// cel.render();
56+// }, 80);
57+// }
58+
59+// function stopSpinner() {
60+// if (spinnerTimer) {
61+// clearInterval(spinnerTimer);
62+// spinnerTimer = null;
63+// }
64+// }
65+
66+// function currentSpinner(): string {
67+// return spinnerFrames[spinnerTick % spinnerFrames.length]!;
68+// }
src/tui-conversation.ts+62−0
@@ -0,0 +1,62 @@
1+import { cel, HStack, Text, VStack } from "@cel-tui/core";
2+import { TextPill, theme } from "./tui-components";
3+import type { TUIState } from "./types";
4+
5+function timeAgo(timestamp: number): string {
6+ const seconds = Math.floor((Date.now() - timestamp) / 1000);
7+
8+ if (seconds < 60) return `${seconds}s ago`;
9+
10+ const minutes = Math.floor(seconds / 60);
11+ if (minutes < 60) return `${minutes}m ago`;
12+
13+ const hours = Math.floor(minutes / 60);
14+ if (hours < 24) return `${hours}h ago`;
15+
16+ const days = Math.floor(hours / 24);
17+ if (days < 7) return `${days}d ago`;
18+
19+ const weeks = Math.floor(days / 7);
20+ if (weeks < 4) return `${weeks}w ago`;
21+
22+ const months = Math.floor(days / 30);
23+ if (months < 12) return `${months}mo ago`;
24+
25+ const years = Math.floor(days / 365);
26+ return `${years}y ago`;
27+}
28+
29+export function Conversation(state: TUIState) {
30+ return VStack(
31+ {
32+ flex: 1,
33+ gap: 1,
34+ overflow: "scroll",
35+ scrollOffset: state.stickToBottom ? Infinity : state.scrollOffset,
36+ onScroll(offset, maxOffset) {
37+ state.scrollOffset = offset;
38+ state.stickToBottom = offset >= maxOffset;
39+ cel.render();
40+ },
41+ },
42+ [
43+ ...state.messages.map((msg) => {
44+ const dur = msg.durationMs ? `Took ${msg.durationMs / 1000}s` : "-";
45+ return VStack({ gap: 1 }, [
46+ Text(msg.content, { wrap: "word" }),
47+ HStack({ gap: 1, justifyContent: "end" }, [
48+ Text(timeAgo(msg.timestamp), {
49+ fgColor: theme.bblack,
50+ italic: true,
51+ }),
52+ Text(dur, {
53+ fgColor: theme.bblack,
54+ italic: true,
55+ }),
56+ TextPill(msg.role, theme.bwhite, theme.bblack),
57+ ]),
58+ ]);
59+ }),
60+ ],
61+ );
62+}
src/tui.ts+42−69
@@ -1,57 +1,14 @@
11 import { basename } from "node:path";
2-import type { Color } from "@cel-tui/core";
3-import { cel, HStack, ProcessTerminal, Text, VStack } from "@cel-tui/core";
2+import { cel, HStack, ProcessTerminal, VStack } from "@cel-tui/core";
43 import type { Message } from "@mariozechner/pi-ai";
54 import { streamAgent, TASK_PROMPT } from "./agent";
65 import { getApiKey } from "./oauth";
76 import { bash, runBashTool } from "./tool-bash";
7+import { TextPill, theme } from "./tui-components";
8+import { Conversation } from "./tui-conversation";
89 import { Editor } from "./tui-editor";
910 import type { ToolAndRunner, TUIMessage, TUIState } from "./types";
1011
11-const theme = {
12- black: "color00" as Color,
13- bblack: "color08" as Color,
14-
15- red: "color01" as Color,
16- bred: "color09" as Color,
17-
18- green: "color02" as Color,
19- bgreen: "color10" as Color,
20-
21- yellow: "color03" as Color,
22- byellow: "color11" as Color,
23-
24- blue: "color04" as Color,
25- bblue: "color12" as Color,
26-
27- magenta: "color05" as Color,
28- bmagenta: "color13" as Color,
29-
30- cyan: "color06" as Color,
31- bcyan: "color14" as Color,
32-
33- white: "color07" as Color,
34- bwhite: "color15" as Color,
35-};
36-
37-// Examples:
38-//
39-// TextPill("mini-coder", theme.bblack, theme.black),
40-// TextPill("mini-coder", theme.bred, theme.red),
41-// TextPill("mini-coder", theme.bgreen, theme.green),
42-// TextPill("mini-coder", theme.byellow, theme.yellow),
43-// TextPill("mini-coder", theme.bblue, theme.blue),
44-// TextPill("mini-coder", theme.bmagenta, theme.magenta),
45-// TextPill("mini-coder", theme.bcyan, theme.cyan),
46-// TextPill("mini-coder", theme.bwhite, theme.white),
47-function TextPill(content: string, fgColor: Color, bgColor: Color) {
48- return HStack({ gap: 1 }, [
49- HStack({ bgColor, padding: { x: 1 } }, [
50- Text(content, { bold: true, fgColor }),
51- ]),
52- ]);
53-}
54-
5512 export function initTUI(state: TUIState, leave: (s: string) => void) {
5613 const cwd = basename(process.cwd());
5714
@@ -72,14 +29,7 @@ export function initTUI(state: TUIState, leave: (s: string) => void) {
7229 },
7330 },
7431 [
75- VStack({ flex: 1, gap: 1, overflow: "scroll" }, [
76- ...state.messages.map((msg) => {
77- return VStack({ gap: 1 }, [
78- TextPill(msg.role, theme.bwhite, theme.bblack),
79- Text(msg.content, { wrap: "word" }),
80- ]);
81- }),
82- ]),
32+ Conversation(state),
8333
8434 HStack({ gap: 1 }, [
8535 TextPill(state.options.model.name, theme.bblack, theme.bwhite),
@@ -122,8 +72,11 @@ export async function streamTUI(state: TUIState) {
12272 content: state.prompt || "",
12373 timestamp: Date.now(),
12474 };
125- const messages: Message[] = [userPrompt as Message];
12675 state.messages.push(userPrompt as TUIMessage);
76+ let messages: Message[] = [userPrompt as Message];
77+ if (state.context) {
78+ messages = [...state.context.messages, ...messages];
79+ }
12780 state.prompt = "";
12881 cel.render();
12982
@@ -148,7 +101,7 @@ export async function streamTUI(state: TUIState) {
148101 case "toolcall_start": {
149102 state.activeState = "calling_tool";
150103
151- // Collect tool calls state
104+ // Create initial tool tui messages
152105 const newToolCalls = ev.partial.content.filter(
153106 (c) => c.type === "toolCall",
154107 );
@@ -160,12 +113,15 @@ export async function streamTUI(state: TUIState) {
160113 id: call.id,
161114 timestamp: Date.now(),
162115 };
116+ let found = false;
163117 state.messages = state.messages.map((msg) => {
164118 if (call.id === msg.id) {
119+ found = true;
165120 return toolMessage;
166121 }
167122 return msg;
168123 });
124+ if (!found) state.messages.push(toolMessage);
169125 }
170126
171127 cel.render();
@@ -180,6 +136,7 @@ export async function streamTUI(state: TUIState) {
180136 (c) => c.type === "toolCall",
181137 );
182138
139+ // Update tui messages with arguments
183140 for (const call of finishedToolCalls) {
184141 const toolMessage: TUIMessage = {
185142 role: "tool",
@@ -210,24 +167,31 @@ export async function streamTUI(state: TUIState) {
210167 break;
211168
212169 case "error":
170+ state.activeState = "idle";
171+ break;
213172 }
214173 },
215174
216175 (tool) => {
176+ // Append the output to the existing TUI messages
217177 state.messages = state.messages.map((msg) => {
218178 if (tool.toolCallId === msg.id) {
179+ // This truncation is TUI only. The file is also
180+ // truncated at tool level to avoid big files being
181+ // sent to the llm. We truncate that even further.
182+ const truncateLimit = 1000;
219183 const result = tool.content
220184 .map((c) => (c.type === "text" ? c.text : ""))
221185 .filter((c) => Boolean(c))
222186 .join("\n");
223187 const truncated =
224- result.length > 6000
225- ? `${result.substring(0, 6000)}...\n\nTruncated at 6000 chars`
188+ result.length > truncateLimit
189+ ? `${result.substring(0, truncateLimit)}...\n\nTruncated at ${truncateLimit} of ${result.length} chars`
226190 : result;
227191
228192 return {
229193 ...msg,
230- content: `${tool.toolName}:\n\n${truncated}`,
194+ content: `${msg.content}\n\n${truncated}`,
231195 timestamp: Date.now(),
232196 };
233197 }
@@ -237,16 +201,25 @@ export async function streamTUI(state: TUIState) {
237201 },
238202
239203 (msg, context, dur) => {
240- const text = msg.content
241- .filter((c) => c.type === "text")
242- .map((c) => c.text)
243- .join("\n");
244- state.messages.push({
245- role: "agent",
246- content: text,
247- timestamp: Date.now(),
248- durationMs: dur,
249- });
204+ if (msg.errorMessage) {
205+ state.messages.push({
206+ role: "agent",
207+ content: `Error (${msg.stopReason}): ${msg.errorMessage}`,
208+ timestamp: Date.now(),
209+ });
210+ } else {
211+ const text = msg.content
212+ .filter((c) => c.type === "text")
213+ .map((c) => c.text)
214+ .join("\n");
215+ state.messages.push({
216+ role: "agent",
217+ content: text,
218+ timestamp: Date.now(),
219+ durationMs: dur,
220+ });
221+ }
222+
250223 state.streaming = false;
251224 state.context = context;
252225 cel.render();
src/types.ts+2−0
@@ -24,6 +24,8 @@ export type TUIState = {
2424 context?: Context;
2525 activeState: TUIActiveState;
2626 streaming: boolean;
27+ stickToBottom: boolean;
28+ scrollOffset: number;
2729 };
2830
2931 export type SavedOAuthAuth = OAuthCredentials & {