xonecas.io
64875
Mc

mini-coder / commit a5bec0c

feat: add syntax highlight to the conversation log

And a bunch of lag :/

xonecas2026-04-23 a5bec0c12969b6fbba5ab30f12d8f49d64b92909 parent 86932d9

7 files changed

src/agent.ts+6−7
@@ -18,14 +18,16 @@ Behaviour guidelines:
1818 - Tone: use a jovial but motivated colleague persona. Be less verbose and more concise. You are working with software engineers, act appropriate, no fluff, only direct talk.
1919 `;
2020
21+// TODO: `AGENTS.md` support: find it in current folder and a global one. (`.agents/AGENTS.md` || ~/.AGENTS.md)
22+
2123 export async function streamAgent(
2224 apiKey: string,
2325 tools: ToolAndRunner[],
2426 systemPrompt: string,
2527 messages: Message[],
2628 options: CliOptions,
27- streamFn?: (ev: AssistantMessageEvent) => void,
28- toolsFn?: (tool: ToolResultMessage) => void,
29+ streamFn?: (ev: AssistantMessageEvent, dur: number) => void,
30+ toolsFn?: (tool: ToolResultMessage, dur: number) => void,
2931 completeFn?: (
3032 msg: AssistantMessage,
3133 context: Context,
@@ -46,7 +48,7 @@ export async function streamAgent(
4648 });
4749
4850 for await (const ev of s) {
49- streamFn?.(ev);
51+ streamFn?.(ev, Date.now() - startTs);
5052 }
5153
5254 const finalMessage = await s.result();
@@ -67,7 +69,7 @@ export async function streamAgent(
6769 timestamp: Date.now(),
6870 };
6971 context.messages.push(msg);
70- toolsFn?.(msg);
72+ toolsFn?.(msg, Date.now() - startTs);
7173 }
7274
7375 if (toolCalls.length > 0) {
@@ -79,10 +81,7 @@ export async function streamAgent(
7981 context.messages.push(cont);
8082 }
8183
82- // TODO: usageFn?
83-
8484 if (["stop", "error", "aborted"].includes(finalMessage.stopReason)) {
85- // TODO: Reason?
8685 completeFn?.(finalMessage, context, Date.now() - startTs);
8786 return;
8887 }
src/shared.ts+64−0
@@ -0,0 +1,64 @@
1+export function secureRandomString(
2+ length: number,
3+ chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
4+): string {
5+ const result: string[] = [];
6+ const charsLength = chars.length;
7+ const maxValid = Math.floor(256 / charsLength) * charsLength;
8+ const randomBytes = new Uint8Array(length * 2);
9+
10+ while (result.length < length) {
11+ crypto.getRandomValues(randomBytes);
12+
13+ for (const byte of randomBytes) {
14+ if (byte < maxValid) {
15+ result.push(chars[byte % charsLength]);
16+ if (result.length === length) break;
17+ }
18+ }
19+ }
20+
21+ return result.join("");
22+}
23+
24+export function elapsedTime(seconds: number): string {
25+ if (seconds < 60) return `${seconds}s`;
26+
27+ const minutes = Math.floor(seconds / 60);
28+ if (minutes < 60) return `${minutes}m`;
29+
30+ const hours = Math.floor(minutes / 60);
31+ if (hours < 24) return `${hours}h`;
32+
33+ const days = Math.floor(hours / 24);
34+ if (days < 7) return `${days}d`;
35+
36+ const weeks = Math.floor(days / 7);
37+ if (weeks < 4) return `${weeks}w`;
38+
39+ const months = Math.floor(days / 30);
40+ if (months < 12) return `${months}mo`;
41+
42+ const years = Math.floor(days / 365);
43+ return `${years}y`;
44+}
45+
46+export function relativeTime(timestamp: number): string {
47+ const seconds = Math.floor((Date.now() - timestamp) / 1000);
48+ return elapsedTime(seconds);
49+}
50+
51+export function onceEvery<T extends unknown[]>(
52+ n: number,
53+ fn: (...args: T) => void,
54+) {
55+ let calls = 0;
56+
57+ return (...args: T) => {
58+ calls++;
59+
60+ if (calls % n === 0) {
61+ fn(...args);
62+ }
63+ };
64+}
src/tool-bash.ts+4−26
@@ -1,4 +1,5 @@
11 import { type Tool, Type } from "@mariozechner/pi-ai";
2+import { secureRandomString } from "./shared";
23
34 const OUTPUT_TRESHOLD = 10000;
45 const description = `## Bash CLI tool
@@ -39,12 +40,12 @@ export async function runBashTool(args: Record<string, any>) {
3940 stderr: "pipe",
4041 });
4142 await proc.exited;
42- const stdout = await proc.stdout.text();
43- const stderr = await proc.stderr?.text();
43+ const stdout = (await proc.stdout.text()).trim();
44+ const stderr = (await proc.stderr?.text())?.trim();
4445 let out =
4546 proc.exitCode === 0
4647 ? (stdout ?? "Exit 0")
47- : (stderr ?? `Exit ${proc.exitCode}`);
48+ : stderr || stdout || `Exit ${proc.exitCode}`;
4849
4950 // If `out` is too big, more than ~10KB, write it to a temp file
5051 // And add that to the truncation label for the agent to be able
@@ -61,26 +62,3 @@ Truncated at ${OUTPUT_TRESHOLD}. Full ouput at ${pathname}`;
6162
6263 return out;
6364 }
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- }
83- }
84-
85- return result.join("");
86-}
src/tui-components.ts+0−23
@@ -43,26 +43,3 @@ export function TextPill(content: string, fgColor: Color, bgColor: Color) {
4343 ]),
4444 ]);
4545 }
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+28−32
@@ -1,35 +1,9 @@
11 import { cel, HStack, Text, VStack } from "@cel-tui/core";
2+import { elapsedTime, relativeTime } from "./shared";
23 import { TextPill, theme } from "./tui-components";
34 import { memoizedSyntaxHighlight } from "./tui-syntax-highlight";
45 import type { TUIState } from "./types";
56
6-function elapsedTime(seconds: number): string {
7- if (seconds < 60) return `${seconds}s`;
8-
9- const minutes = Math.floor(seconds / 60);
10- if (minutes < 60) return `${minutes}m`;
11-
12- const hours = Math.floor(minutes / 60);
13- if (hours < 24) return `${hours}h`;
14-
15- const days = Math.floor(hours / 24);
16- if (days < 7) return `${days}d`;
17-
18- const weeks = Math.floor(days / 7);
19- if (weeks < 4) return `${weeks}w`;
20-
21- const months = Math.floor(days / 30);
22- if (months < 12) return `${months}mo`;
23-
24- const years = Math.floor(days / 365);
25- return `${years}y`;
26-}
27-
28-function relativeTime(timestamp: number): string {
29- const seconds = Math.floor((Date.now() - timestamp) / 1000);
30- return elapsedTime(seconds);
31-}
32-
337 export function Conversation(state: TUIState) {
348 return VStack(
359 {
@@ -49,15 +23,37 @@ export function Conversation(state: TUIState) {
4923 ? `Took ${elapsedTime(msg.durationMs / 1000)}`
5024 : "-";
5125 return VStack({ gap: 1 }, [
52- // TODO: `@cel-tui/components` only keeps **4 cached highlight states per language/theme** (`MAX_STATES_PER_KEY = 4` in the
53- // installed package). After the 4th agent reply, older messages will be re-tokenized from scratch on every render.
5426 msg.role === "agent"
5527 ? memoizedSyntaxHighlight(
56- msg.id ?? `${Date.now()}`,
28+ (msg.id ? msg.id : "") + String(msg.timestamp),
5729 msg.content,
5830 "markdown",
5931 )
60- : Text(msg.content, { wrap: "word" }),
32+ : msg.role === "user"
33+ ? VStack(
34+ {
35+ padding: { x: 1, y: 1 },
36+ bgColor: theme.bblack,
37+ fgColor: theme.white,
38+ },
39+ [
40+ memoizedSyntaxHighlight(
41+ msg.id ?? String(msg.timestamp),
42+ msg.content,
43+ "markdown",
44+ ),
45+ ],
46+ )
47+ : msg.role === "tool"
48+ ? VStack({ gap: 1 }, [
49+ memoizedSyntaxHighlight(
50+ msg.id ?? String(msg.timestamp),
51+ msg.header ?? "",
52+ "bash",
53+ ),
54+ Text(msg.content, { wrap: "word", fgColor: theme.bwhite }),
55+ ])
56+ : Text(msg.content, { wrap: "word", fgColor: theme.bwhite }),
6157 HStack({ gap: 1, justifyContent: "end" }, [
6258 Text(`${relativeTime(msg.timestamp)} ago.`, {
6359 fgColor: theme.bblack,
@@ -67,7 +63,7 @@ export function Conversation(state: TUIState) {
6763 fgColor: theme.bblack,
6864 italic: true,
6965 }),
70- TextPill(msg.role, theme.bwhite, theme.bblack),
66+ TextPill(msg.label ?? msg.role, theme.bwhite, theme.bblack),
7167 ]),
7268 ]);
7369 }),
src/tui.ts+42−5
@@ -3,6 +3,7 @@ import { cel, HStack, ProcessTerminal, VStack } from "@cel-tui/core";
33 import type { Message } from "@mariozechner/pi-ai";
44 import { streamAgent, TASK_PROMPT } from "./agent";
55 import { getApiKey } from "./oauth";
6+import { onceEvery, secureRandomString } from "./shared";
67 import { bash, runBashTool } from "./tool-bash";
78 import { TextPill, theme } from "./tui-components";
89 import { Conversation } from "./tui-conversation";
@@ -12,6 +13,23 @@ import type { ToolAndRunner, TUIMessage, TUIState } from "./types";
1213 export function initTUI(state: TUIState, leave: (s: string) => void) {
1314 const cwd = basename(process.cwd());
1415
16+ // TODO: move to components, have a function return the everyFn and current spinner
17+ const spinnerFrames = ["⠤", "⠆", "⠒", "⠰"];
18+ let spinnerTick = 0;
19+ const spinnerEvery = onceEvery(5, () => spinnerTick++);
20+ const currentSpinner = () =>
21+ spinnerFrames[spinnerTick % spinnerFrames.length];
22+
23+ // Because we don't render often, the ui feels unresponsive at times.
24+ // This ensure 60fps, and excessive calls get coalesced in cel-tui.
25+ const fps = 60;
26+ const baseFramerateIntervalId = setInterval(() => {
27+ if (state.streaming) {
28+ spinnerEvery();
29+ }
30+ cel.render();
31+ }, 1000 / fps);
32+
1533 cel.init(new ProcessTerminal());
1634 cel.setTitle(`mc | ${cwd}`);
1735
@@ -23,6 +41,7 @@ export function initTUI(state: TUIState, leave: (s: string) => void) {
2341 padding: { x: 1, y: 1 },
2442 onKeyPress: (key) => {
2543 if (key === "ctrl+q" || key === "ctrl+c" || key === "ctrl+d") {
44+ clearInterval(baseFramerateIntervalId);
2645 cel.stop();
2746 leave("Done.");
2847 }
@@ -35,6 +54,9 @@ export function initTUI(state: TUIState, leave: (s: string) => void) {
3554 TextPill(state.options.model.name, theme.bblack, theme.bwhite),
3655 TextPill(`../${cwd}`, theme.bwhite, theme.bblack),
3756 VStack({ flex: 1 }, []),
57+ state.streaming
58+ ? TextPill(currentSpinner(), theme.bblack, theme.bwhite)
59+ : TextPill(currentSpinner(), theme.bwhite, theme.bblack),
3860 TextPill(state.activeState, theme.bwhite, theme.bblack),
3961 ]),
4062
@@ -71,6 +93,7 @@ export async function streamTUI(state: TUIState) {
7193 role: "user",
7294 content: state.prompt || "",
7395 timestamp: Date.now(),
96+ id: secureRandomString(8),
7497 };
7598 state.messages.push(userPrompt as TUIMessage);
7699 let messages: Message[] = [userPrompt as Message];
@@ -86,7 +109,7 @@ export async function streamTUI(state: TUIState) {
86109 TASK_PROMPT,
87110 messages,
88111 state.options,
89- (ev) => {
112+ (ev, dur) => {
90113 switch (ev.type) {
91114 case "text_start":
92115 state.activeState = "answering";
@@ -109,9 +132,14 @@ export async function streamTUI(state: TUIState) {
109132 for (const call of newToolCalls) {
110133 const toolMessage: TUIMessage = {
111134 role: "tool",
112- content: `${call.name}: ${JSON.stringify(call.arguments, null, 4)}`,
135+ label: call.name.toLocaleUpperCase(),
136+ header: call.arguments.command
137+ ? call.arguments.command
138+ : `Calling ${call.name}...`,
139+ content: "",
113140 id: call.id,
114141 timestamp: Date.now(),
142+ durationMs: dur,
115143 };
116144 let found = false;
117145 state.messages = state.messages.map((msg) => {
@@ -140,9 +168,14 @@ export async function streamTUI(state: TUIState) {
140168 for (const call of finishedToolCalls) {
141169 const toolMessage: TUIMessage = {
142170 role: "tool",
143- content: `${call.name}: ${JSON.stringify(call.arguments, null, 4)}`,
171+ label: call.name.toLocaleUpperCase(),
172+ header: call.arguments.command
173+ ? call.arguments.command
174+ : `"Calling ${call.name}..."`,
175+ content: "",
144176 id: call.id,
145177 timestamp: Date.now(),
178+ durationMs: dur,
146179 };
147180 let updated = false;
148181 state.messages = state.messages.map((msg) => {
@@ -172,7 +205,7 @@ export async function streamTUI(state: TUIState) {
172205 }
173206 },
174207
175- (tool) => {
208+ (tool, dur) => {
176209 // Append the output to the existing TUI messages
177210 state.messages = state.messages.map((msg) => {
178211 if (tool.toolCallId === msg.id) {
@@ -191,8 +224,9 @@ export async function streamTUI(state: TUIState) {
191224
192225 return {
193226 ...msg,
194- content: `${msg.content}\n\n${truncated}`,
227+ content: truncated,
195228 timestamp: Date.now(),
229+ durationMs: dur,
196230 };
197231 }
198232 return msg;
@@ -203,9 +237,11 @@ export async function streamTUI(state: TUIState) {
203237 (msg, context, dur) => {
204238 if (msg.errorMessage) {
205239 state.messages.push({
240+ id: secureRandomString(8),
206241 role: "agent",
207242 content: `Error (${msg.stopReason}): ${msg.errorMessage}`,
208243 timestamp: Date.now(),
244+ durationMs: dur,
209245 });
210246 } else {
211247 const text = msg.content
@@ -213,6 +249,7 @@ export async function streamTUI(state: TUIState) {
213249 .map((c) => c.text)
214250 .join("\n");
215251 state.messages.push({
252+ id: secureRandomString(8),
216253 role: "agent",
217254 content: text,
218255 timestamp: Date.now(),
src/types.ts+2−0
@@ -15,6 +15,8 @@ export type TUIMessage = {
1515 durationMs?: number;
1616 id?: string;
1717 timestamp: number;
18+ label?: string;
19+ header?: string; // Not a great name, this is used for arguments in tool calls.
1820 };
1921
2022 export type TUIState = {