xonecas.io
64875
Mc

mini-coder / commit f11242a

fix(tools): avoid mutating input object in withShellOutput

Use object spread instead of reference alias so onOutput is written
onto a fresh copy rather than the caller's original input object.

xonecas2026-03-14 f11242a741b0030548efb1aed477459c85eedd1d parent 84d8cf8

11 files changed

TODO.md+9−3
@@ -26,14 +26,20 @@
2626 · src/cli/stream-render.ts 296 lines
2727 ```
2828
29-- Console output/UI updates: add a spinner state showing the user when the undo snapshotting is happening and more granular output of tools lifecycle: start, running, hooks, and done states.
30-- Structuted output when a skill is auto loaded for the agent and improve context pruning output to match out style
31-
3229 - `src/cli/stream-render.ts` is 448 lines; could be split for maintainability
3330 - `src/llm-api/turn.ts` is 1273 lines; handles many concerns (pruning, compacting, normalization)
3431
3532 ---
3633
34+# Console output/UI updates:
35+
36+- add a spinner state showing the user when the undo snapshotting is happening and more granular output of tools lifecycle: start, running, hooks, and done states.
37+- Structuted output when a skill is auto loaded for the agent and improve context pruning output to match out style
38+
39+Implement these improvements.
40+
41+---
42+
3743 ## UI Audit
3844
3945 - We need to revise all of our output to ensure consistency, **performance** and correctness.
src/agent/agent.ts+4−0
@@ -68,6 +68,9 @@ export async function initAgent(opts: AgentOptions): Promise<{
6868 cwd,
6969 runSubagent,
7070 onHook: (tool, path, ok) => opts.reporter.renderHook(tool, path, ok),
71+ onBeforeHook: (toolName) =>
72+ opts.reporter.renderSubState(`hook post-${toolName}`),
73+ onShellOutput: (chunk) => opts.reporter.streamChunk(chunk),
7174 availableAgents: subagentAgents(agents),
7275 snapshotCallback: async (filePath) => {
7376 if (currentRunner) {
@@ -75,6 +78,7 @@ export async function initAgent(opts: AgentOptions): Promise<{
7578 }
7679 },
7780 });
81+
7882 const mcpTools: ToolDef[] = [];
7983
8084 async function connectAndAddMcp(name: string): Promise<void> {
src/agent/reporter.ts+5−0
@@ -29,9 +29,14 @@ export interface AgentReporter {
2929 error(msg: string | Error, hint?: string): void;
3030 warn(msg: string): void;
3131 writeText(text: string): void; // For raw text like passthrough shell output
32+ /** Write a raw output chunk without adding a newline (e.g. streaming shell output). */
33+ streamChunk(text: string): void;
3234
3335 startSpinner(label?: string): void;
3436 stopSpinner(): void;
37+ /** Print a persistent indented sub-state line (e.g. "snapshot", "hook post-create")
38+ * while the tool is still running. The spinner resumes after. */
39+ renderSubState(label: string): void;
3540
3641 renderTurn(
3742 events: AsyncIterable<TurnEvent>,
src/agent/session-runner.ts+2−0
@@ -65,6 +65,8 @@ export class SessionRunner {
6565
6666 public async snapshotCallback(filePath: string) {
6767 if (this.currentTurn !== null && this.currentSnappedPaths !== null) {
68+ this.reporter.renderSubState("snapshot");
69+
6870 await snapshotBeforeEdit(
6971 this.cwd,
7072 this.session.id,
src/agent/tools.ts+42−3
@@ -54,6 +54,26 @@ function withCwdDefault(
5454 };
5555 }
5656
57+/**
58+ * Inject an onOutput streaming callback into the shell tool's input.
59+ */
60+function withShellOutput(
61+ tool: ToolDef,
62+ onOutput: (chunk: string) => void,
63+): ToolDef {
64+ const originalExecute = tool.execute;
65+ return {
66+ ...tool,
67+ execute: async (input: unknown) => {
68+ const patched = {
69+ ...(typeof input === "object" && input !== null ? input : {}),
70+ onOutput,
71+ } as Record<string, unknown>;
72+ return originalExecute(patched);
73+ },
74+ };
75+}
76+
5777 type EnvBuilder<TInput, TOutput> = (
5878 result: TOutput,
5979 input: TInput,
@@ -67,7 +87,8 @@ type ResultFinalizer<TOutput, TFinalOutput> = (
6787 * Wrap a tool to fire its post-hook (if one exists) after each successful execute.
6888 * Hooks are looked up via the session-scoped cache — no filesystem access per call.
6989 * Errors are always swallowed. onHook is called with the result so the caller can
70- * render a UI line.
90+ * render a UI line. onBeforeHook is called just before the hook script runs so the
91+ * UI can update the spinner label.
7192 */
7293 function withHooks<
7394 TInput extends { cwd?: string },
@@ -80,6 +101,7 @@ function withHooks<
80101 buildEnv: EnvBuilder<TInput, TOutput>,
81102 onHook: (toolName: string, scriptPath: string, success: boolean) => void,
82103 finalizeResult?: ResultFinalizer<TOutput, TFinalOutput>,
104+ onBeforeHook?: (toolName: string, scriptPath: string) => void,
83105 ): ToolDef<TInput, TFinalOutput> {
84106 const originalExecute = tool.execute;
85107 return {
@@ -88,6 +110,7 @@ function withHooks<
88110 const result = await originalExecute(input);
89111 const hookScript = lookupHook(tool.name);
90112 if (hookScript) {
113+ onBeforeHook?.(tool.name, hookScript);
91114 const env = buildEnv(result, input);
92115 const success = await runHook(hookScript, env, cwd);
93116 onHook(tool.name, hookScript, success);
@@ -118,10 +141,13 @@ export function buildToolSet(opts: {
118141 ) => Promise<SubagentOutput>;
119142
120143 onHook: (toolName: string, scriptPath: string, success: boolean) => void;
144+ onBeforeHook?: (toolName: string, scriptPath: string) => void;
145+ onShellOutput?: (chunk: string) => void;
121146 availableAgents: ReadonlyMap<string, { description: string }>;
122147 snapshotCallback?: (filePath: string) => Promise<void>;
123148 }): ToolDef[] {
124- const { cwd, onHook } = opts;
149+ const { cwd, onHook, onBeforeHook, onShellOutput } = opts;
150+
125151 const lookupHook = createHookCache(HOOKABLE_TOOLS, cwd);
126152
127153 const tools: ToolDef[] = [
@@ -135,6 +161,8 @@ export function buildToolSet(opts: {
135161 cwd,
136162 (_, input) => hookEnvForRead(input, cwd),
137163 onHook,
164+ undefined,
165+ onBeforeHook,
138166 ) as ToolDef,
139167 withCwdDefault(listSkillsTool as ToolDef, cwd),
140168 withCwdDefault(readSkillTool as ToolDef, cwd),
@@ -150,6 +178,7 @@ export function buildToolSet(opts: {
150178 (result) => hookEnvForCreate(result, cwd),
151179 onHook,
152180 finalizeWriteResult,
181+ onBeforeHook,
153182 ) as ToolDef,
154183 withHooks(
155184 withCwdDefault(
@@ -162,6 +191,7 @@ export function buildToolSet(opts: {
162191 (result) => hookEnvForReplace(result, cwd),
163192 onHook,
164193 finalizeWriteResult,
194+ onBeforeHook,
165195 ) as ToolDef,
166196 withHooks(
167197 withCwdDefault(
@@ -174,10 +204,16 @@ export function buildToolSet(opts: {
174204 (result) => hookEnvForInsert(result, cwd),
175205 onHook,
176206 finalizeWriteResult,
207+ onBeforeHook,
177208 ) as ToolDef,
178209 // Shell and subagent
179210 withHooks(
180- withCwdDefault(shellTool as ToolDef, cwd) as ToolDef<
211+ (onShellOutput
212+ ? withShellOutput(
213+ withCwdDefault(shellTool as ToolDef, cwd),
214+ onShellOutput,
215+ )
216+ : withCwdDefault(shellTool as ToolDef, cwd)) as ToolDef<
181217 { cwd?: string; command: string },
182218 ShellOutput
183219 >,
@@ -185,7 +221,10 @@ export function buildToolSet(opts: {
185221 cwd,
186222 (result, input) => hookEnvForShell(result, input, cwd),
187223 onHook,
224+ undefined,
225+ onBeforeHook,
188226 ) as ToolDef,
227+
189228 createSubagentTool(async (prompt, agentName) => {
190229 const output = await opts.runSubagent(prompt, agentName, undefined);
191230 return output;
src/cli/headless-reporter.ts+3−0
@@ -20,8 +20,11 @@ export class HeadlessReporter implements AgentReporter {
2020 error(_msg: string | Error, _hint?: string): void {}
2121 warn(_msg: string): void {}
2222 writeText(_text: string): void {}
23+ streamChunk(_text: string): void {}
24+
2325 startSpinner(_label?: string): void {}
2426 stopSpinner(): void {}
27+ renderSubState(_label: string): void {}
2528
2629 async renderTurn(
2730 events: AsyncIterable<TurnEvent>,
src/cli/output-reporter.ts+13−0
@@ -1,3 +1,4 @@
1+import * as c from "yoctocolors";
12 import type {
23 AgentReporter,
34 StatusBarData,
@@ -13,6 +14,7 @@ import {
1314 renderTurn,
1415 restoreTerminal,
1516 Spinner,
17+ write,
1618 writeln,
1719 } from "./output.ts";
1820
@@ -43,6 +45,11 @@ export class CliReporter implements AgentReporter {
4345 writeln(text);
4446 }
4547
48+ streamChunk(text: string): void {
49+ this.spinner.stop();
50+ write(text);
51+ }
52+
4653 startSpinner(label?: string): void {
4754 this.spinner.start(label);
4855 }
@@ -51,6 +58,12 @@ export class CliReporter implements AgentReporter {
5158 this.spinner.stop();
5259 }
5360
61+ renderSubState(label: string): void {
62+ this.spinner.stop();
63+ writeln(` ${G.info} ${c.dim(label)}`);
64+ this.spinner.start();
65+ }
66+
5467 async renderTurn(
5568 events: AsyncIterable<TurnEvent>,
5669 opts?: { showReasoning?: boolean },
src/cli/stream-render.test.ts+2−4
@@ -378,7 +378,7 @@ describe("renderTurn", () => {
378378 );
379379
380380 expect(strip(stdout)).toContain(
381- "context-pruned mode=balanced removed_messages=30 removed_bytes=15000 messages_before=120 messages_after=90",
381+ "· context pruned balanced –30 messages –14.6 KB",
382382 );
383383 });
384384
@@ -412,8 +412,6 @@ describe("renderTurn", () => {
412412 );
413413
414414 const plain = strip(stdout);
415- expect(plain).toContain(
416- 'skill-auto-loaded name=deploy source=local description="Deploy app"',
417- );
415+ expect(plain).toContain("· skill deploy · local · Deploy app");
418416 });
419417 });
src/cli/stream-render.ts+2−1
@@ -401,8 +401,9 @@ export async function renderTurn(
401401 case "context-pruned": {
402402 flushAnyText();
403403 spinner.stop();
404+ const removedKb = (event.removedBytes / 1024).toFixed(1);
404405 writeln(
405- `${G.info} ${c.dim(`context-pruned mode=${event.mode} removed_messages=${event.removedMessageCount} removed_bytes=${event.removedBytes} messages_before=${event.beforeMessageCount} messages_after=${event.afterMessageCount}`)}`,
406+ `${G.info} ${c.dim("context pruned")} ${c.dim(event.mode)} ${c.dim(`–${event.removedMessageCount} messages`)} ${c.dim(`–${removedKb} KB`)}`,
406407 );
407408 break;
408409 }
src/cli/tool-render.ts+5−2
@@ -219,14 +219,17 @@ export function renderToolResult(
219219 };
220220 };
221221 if (!r.skill) {
222- writeln(` ${G.info} ${c.dim("skill-auto-load miss")}`);
222+ writeln(` ${G.info} ${c.dim("skill")} ${c.dim("(not found)")}`);
223223 return;
224224 }
225225 const name = r.skill.name ?? "(unknown)";
226226 const source = r.skill.source ?? "unknown";
227227 const description = r.skill.description?.trim();
228+ const descPart = description
229+ ? ` ${c.dim("·")} ${c.dim(description.length > 60 ? `${description.slice(0, 57)}…` : description)}`
230+ : "";
228231 writeln(
229- ` ${G.info} ${c.dim(`skill-auto-loaded name=${name} source=${source}${description ? ` description=${JSON.stringify(description)}` : ""}`)}`,
232+ ` ${G.info} ${c.dim("skill")} ${name} ${c.dim("·")} ${c.dim(source)}${descPart}`,
230233 );
231234 return;
232235 }
src/tools/shell.ts+11−4
@@ -18,7 +18,10 @@ const ShellSchema = z.object({
1818 .describe("Additional environment variables to set"),
1919 });
2020
21-type ShellInput = z.infer<typeof ShellSchema> & { cwd?: string };
21+type ShellInput = z.infer<typeof ShellSchema> & {
22+ cwd?: string;
23+ onOutput?: (chunk: string) => void;
24+};
2225
2326 export interface ShellOutput {
2427 stdout: string;
@@ -78,21 +81,24 @@ export const shellTool: ToolDef<ShellInput, ShellOutput> = {
7881 }
7982 }, timeout);
8083
81- // Collect output with size limit
84+ // Collect output with size limit; forward each decoded chunk to onOutput.
8285 async function collectStream(
8386 stream: ReadableStream<Uint8Array>,
87+ onChunk?: (text: string) => void,
8488 ): Promise<string> {
8589 const reader = stream.getReader();
8690 readers.push(reader);
8791 const chunks: Uint8Array[] = [];
8892 let totalBytes = 0;
8993 let truncated = false;
94+ const decoder = new TextDecoder();
9095
9196 while (true) {
9297 try {
9398 const { done, value } = await reader.read();
9499 if (done) break;
95100 if (value) {
101+ onChunk?.(decoder.decode(value, { stream: true }));
96102 if (totalBytes + value.length > MAX_OUTPUT_BYTES) {
97103 chunks.push(value.slice(0, MAX_OUTPUT_BYTES - totalBytes));
98104 truncated = true;
@@ -118,9 +124,10 @@ export const shellTool: ToolDef<ShellInput, ShellOutput> = {
118124
119125 try {
120126 [stdout, stderr] = await Promise.all([
121- collectStream(proc.stdout),
122- collectStream(proc.stderr),
127+ collectStream(proc.stdout, input.onOutput),
128+ collectStream(proc.stderr, input.onOutput),
123129 ]);
130+
124131 exitCode = await proc.exited;
125132 } finally {
126133 clearTimeout(timer);