xonecas.io
64875
Mc

mini-coder / commit 9f09926

feat: colored shell output with structured command display

- Add FORCE_COLOR=1 to shell subprocess env for colored tool output
- Strip ANSI from stdout/stderr for LLM, preserve raw for user display
- Color mc-edit unified diff output (red/green/cyan/dim) when FORCE_COLOR set
- Parse 'cd path && cmd' shell patterns to show command with dimmed cwd suffix
- Use command-specific glyphs (←read, ?search, ✎write, $run) for shell calls
- Extract shared stripAnsi utility to src/internal/ansi.ts
- Increase shell command truncation from 72 to 80 chars

xonecas2026-03-18 9f09926a701af261af918b30bb5186ca93f1f62c parent d30923b

9 files changed

TODO.md+14−4
@@ -1,11 +1,21 @@
11 # TODO
22
3-## Colored shell output
3+## Refactor and add color to shell tool console output
44
5-We could look into coloring the most used shell commands.
5+When the llm uses the shell tool, it shows the following patterns:
66
7-- Check the db for most used commands.
8-- Use yoctocolors for the coloring.
7+- Chained shell commands `cd ... && cat ...` and even longer chains.
8+- `mc-edit` calls weaved into cat and other shell calls.
9+
10+These patterns affect how we render the calls to the user, with most call lines being truncated early and not showing the important parts of the shell call. We could show these as a structured human readable.
11+
12+Coloring the outputs, could we just ask for colors when running shell commands safely, maybe set an env var for the subprocess? Then we could just let those colors render.
13+
14+`mc-edit` could be improved to print a colored diff.
15+
16+- Check the db for most used commands. We don't need to support the whole shell ecosystem, just take a sample of the most used.
17+- Use yoctocolors for the coloring of the diffs in mc-edit.
18+- This is about the output for the **user** the llm get's the no color, as is today.
919
1020 ---
1121
src/cli/status-bar.test.ts+1−6
@@ -1,16 +1,11 @@
11 import { afterEach, describe, expect, test } from "bun:test";
22 import { buildStatusBarSignature, renderStatusBar } from "./status-bar.ts";
33 import { terminal } from "./terminal-io.ts";
4-import { withTerminalColumns } from "./test-helpers.ts";
4+import { stripAnsi, withTerminalColumns } from "./test-helpers.ts";
55
66 let stdout = "";
77 const originalStdoutWrite = terminal.stdoutWrite.bind(terminal);
88
9-function stripAnsi(s: string): string {
10- const esc = String.fromCharCode(0x1b);
11- return s.replace(new RegExp(`${esc}\\[[0-9;]*m`, "g"), "");
12-}
13-
149 afterEach(() => {
1510 stdout = "";
1611 terminal.stdoutWrite = originalStdoutWrite;
src/cli/structured-output.ts+25−1
@@ -4,6 +4,18 @@ import type {
44 FileEditErrorCode,
55 } from "../internal/file-edit/exact-text.ts";
66
7+function shouldColorize(): boolean {
8+ return process.env.FORCE_COLOR === "1" || process.env.FORCE_COLOR === "true";
9+}
10+
11+/** Raw ANSI codes for diff coloring (works in piped subprocesses). */
12+const ansi = {
13+ red: (s: string) => `\x1b[31m${s}\x1b[39m`,
14+ green: (s: string) => `\x1b[32m${s}\x1b[39m`,
15+ cyan: (s: string) => `\x1b[36m${s}\x1b[39m`,
16+ dim: (s: string) => `\x1b[2m${s}\x1b[22m`,
17+};
18+
719 export interface StructuredOutputWriter {
820 stdout: (text: string) => void;
921 stderr: (text: string) => void;
@@ -46,6 +58,14 @@ function normalizePatchLines(patchText: string): string[] {
4658 });
4759 }
4860
61+function colorizeDiffLine(line: string): string {
62+ if (line.startsWith("---") || line.startsWith("+++")) return ansi.dim(line);
63+ if (line.startsWith("@@")) return ansi.cyan(line);
64+ if (line.startsWith("+")) return ansi.green(line);
65+ if (line.startsWith("-")) return ansi.red(line);
66+ return line;
67+}
68+
4969 export function renderUnifiedDiff(
5070 filePath: string,
5171 before: string,
@@ -66,7 +86,11 @@ export function renderUnifiedDiff(
6686 context: 3,
6787 },
6888 );
69- return normalizePatchLines(patchText).join("\n");
89+ const lines = normalizePatchLines(patchText);
90+ if (shouldColorize()) {
91+ return lines.map(colorizeDiffLine).join("\n");
92+ }
93+ return lines.join("\n");
7094 }
7195
7296 function renderMetadataBlock(
src/cli/test-helpers.ts+4−6
@@ -1,3 +1,4 @@
1+import { stripAnsi } from "../internal/ansi.ts";
12 import type { CoreMessage } from "../llm-api/turn.ts";
23 import type { TurnEvent } from "../llm-api/types.ts";
34 import { terminal } from "./terminal-io.ts";
@@ -49,10 +50,7 @@ export function restoreStdout(): void {
4950 terminal.doStdoutWrite = _originalDoStdoutWrite;
5051 }
5152
52-export function stripAnsi(text: string): string {
53- const esc = String.fromCharCode(0x1b);
54- return text.replace(new RegExp(`${esc}\\[[0-9;]*m`, "g"), "");
55-}
53+export { stripAnsi };
5654
5755 /**
5856 * Simulate terminal rendering for cursor-control sequences:
@@ -60,8 +58,8 @@ export function stripAnsi(text: string): string {
6058 * Strips ANSI SGR codes so the result is plain text.
6159 */
6260 export function simulateTerminal(raw: string): string {
63- const esc = String.fromCharCode(0x1b);
64- const noColor = raw.replace(new RegExp(`${esc}\\[[0-9;]*m`, "g"), "");
61+ const esc = "\x1b";
62+ const noColor = stripAnsi(raw);
6563 const lines: string[] = [""];
6664 let row = 0;
6765 let col = 0;
src/cli/tool-render.ts+72−3
@@ -1,5 +1,5 @@
11 import * as c from "yoctocolors";
2-import { G, writeln } from "./output.ts";
2+import { G, tildePath, writeln } from "./output.ts";
33 import { renderToolResultByName } from "./tool-result-renderers.ts";
44
55 function toolGlyph(name: string): string {
@@ -13,6 +13,76 @@ function toolGlyph(name: string): string {
1313 return G.info;
1414 }
1515
16+/** Resolve glyph for well-known shell commands (lazy to avoid init-order issues). */
17+function shellCmdGlyph(cmd: string): string {
18+ switch (cmd) {
19+ case "cat":
20+ case "head":
21+ case "tail":
22+ case "ls":
23+ case "wc":
24+ return G.read;
25+ case "grep":
26+ case "find":
27+ return G.search;
28+ case "mc-edit":
29+ case "sed":
30+ case "rm":
31+ case "mkdir":
32+ case "cp":
33+ case "mv":
34+ case "touch":
35+ return G.write;
36+ case "git":
37+ case "bun":
38+ case "echo":
39+ return G.run;
40+ default:
41+ return G.run;
42+ }
43+}
44+
45+/**
46+ * Strip a leading `cd <path> &&` prefix from a shell command string.
47+ * Returns the directory (tilde-abbreviated) and the remaining command.
48+ */
49+function parseShellCdPrefix(cmd: string): {
50+ cwd: string | null;
51+ rest: string;
52+} {
53+ const match = cmd.match(/^cd\s+(\S+)\s*&&\s*/);
54+ if (!match) return { cwd: null, rest: cmd };
55+ const rawPath = match[1] ?? "";
56+ const rest = cmd.slice(match[0].length).trim();
57+ return { cwd: tildePath(rawPath), rest: rest || cmd };
58+}
59+
60+/**
61+ * Extract the first command word from a shell string,
62+ * skipping inline env vars like `FOO=bar cmd ...`.
63+ */
64+function extractFirstCommand(cmd: string): string {
65+ const tokens = cmd.split(/\s+/);
66+ for (const token of tokens) {
67+ if (token.includes("=") && !token.startsWith("-")) continue;
68+ return token;
69+ }
70+ return tokens[0] ?? "";
71+}
72+
73+function truncate(s: string, max: number): string {
74+ return s.length > max ? `${s.slice(0, max - 1)}…` : s;
75+}
76+
77+function formatShellCallLine(cmd: string): string {
78+ const { cwd, rest } = parseShellCdPrefix(cmd);
79+ const firstCmd = extractFirstCommand(rest);
80+ const glyph = shellCmdGlyph(firstCmd);
81+ const cwdSuffix = cwd ? ` ${c.dim(`in ${cwd}`)}` : "";
82+ const display = truncate(rest, 80);
83+ return `${glyph} ${display}${cwdSuffix}`;
84+}
85+
1686 export function buildToolCallLine(name: string, args: unknown): string {
1787 const a =
1888 args && typeof args === "object" ? (args as Record<string, unknown>) : {};
@@ -29,8 +99,7 @@ export function buildToolCallLine(name: string, args: unknown): string {
2999 if (name === "shell") {
30100 const cmd = String(a.command ?? "").trim();
31101 if (!cmd) return `${G.run} ${c.dim("shell")}`;
32- const shortCmd = cmd.length > 72 ? `${cmd.slice(0, 69)}…` : cmd;
33- return `${G.run} ${shortCmd}`;
102+ return formatShellCallLine(cmd);
34103 }
35104
36105 if (name === "listSkills") {
src/cli/tool-result-renderers.ts+6−2
@@ -122,12 +122,16 @@ function renderShellResult(
122122 exitCode: number;
123123 success: boolean;
124124 timedOut: boolean;
125+ rawStdout?: string;
126+ rawStderr?: string;
125127 };
126128 if (!r || typeof r.stdout !== "string" || typeof r.stderr !== "string") {
127129 return false;
128130 }
129131
130132 const verboseOutput = opts?.verboseOutput === true;
133+ const displayStdout = r.rawStdout ?? r.stdout;
134+ const displayStderr = r.rawStderr ?? r.stderr;
131135 const stdoutLines = countShellLines(r.stdout);
132136 const stderrLines = countShellLines(r.stderr);
133137 const stdoutSingleLine = getSingleShellLine(r.stdout);
@@ -148,7 +152,7 @@ function renderShellResult(
148152
149153 writePreviewLines({
150154 label: "stderr",
151- value: r.stderr,
155+ value: displayStderr,
152156 lineColor: c.red,
153157 maxLines: verboseOutput ? Number.POSITIVE_INFINITY : 10,
154158 });
@@ -162,7 +166,7 @@ function renderShellResult(
162166 ) {
163167 writePreviewLines({
164168 label: "stdout",
165- value: r.stdout,
169+ value: displayStdout,
166170 lineColor: c.dim,
167171 maxLines: verboseOutput ? Number.POSITIVE_INFINITY : 20,
168172 });
src/cli/ui-audit.test.ts+5−5
@@ -204,7 +204,7 @@ describe("UI audit: full turn scenarios", () => {
204204 );
205205
206206 const plain = simulateTerminal(getCapturedStdout());
207- expect(plain).toContain(" $ ls");
207+ expect(plain).toContain(" ← ls");
208208 expect(plain).toMatch(/^ {4}done/m);
209209 expect(plain).toContain("\n\n◆ Found file.txt");
210210 });
@@ -250,7 +250,7 @@ describe("UI audit: full turn scenarios", () => {
250250 const firstResultIdx = lines.findIndex((l) =>
251251 l.match(/^ {4}done.*out: hello/),
252252 );
253- const secondCallIdx = lines.findIndex((l) => l.includes("$ cat b.txt"));
253+ const secondCallIdx = lines.findIndex((l) => l.includes("← cat b.txt"));
254254 expect(firstResultIdx).toBeGreaterThan(-1);
255255 expect(secondCallIdx).toBeGreaterThan(firstResultIdx);
256256 const between = lines.slice(firstResultIdx + 1, secondCallIdx);
@@ -488,7 +488,7 @@ describe("UI audit: parallel tool calls", () => {
488488 const plain = simulateTerminal(getCapturedStdout());
489489
490490 // All three calls rendered
491- expect(plain).toContain(" $ ls src");
491+ expect(plain).toContain(" ← ls src");
492492 expect(plain).toMatch(/^ {2}⇢/m);
493493 expect(plain).toMatch(/^ {2}←/m);
494494
@@ -717,8 +717,8 @@ describe("UI audit: parallel tool calls", () => {
717717 expect(plain).toContain("I'll check two files");
718718
719719 // Both parallel calls
720- expect(plain).toContain("$ cat a.ts");
721- expect(plain).toContain("$ cat b.ts");
720+ expect(plain).toContain("← cat a.ts");
721+ expect(plain).toContain("← cat b.ts");
722722
723723 // Second reasoning block
724724 const reasoningCount = (plain.match(/· reasoning/g) ?? []).length;
src/internal/ansi.ts+7−0
@@ -0,0 +1,7 @@
1+/** Pre-compiled regex for ANSI color/style escape sequences. */
2+const ANSI_REGEX = new RegExp(`${String.fromCharCode(0x1b)}\\[[0-9;]*m`, "g");
3+
4+/** Strip ANSI color/style escape sequences from a string. */
5+export function stripAnsi(text: string): string {
6+ return text.replace(ANSI_REGEX, "");
7+}
src/tools/shell.ts+13−2
@@ -1,5 +1,6 @@
11 import { z } from "zod";
22 import { restoreTerminal } from "../cli/output.ts";
3+import { stripAnsi } from "../internal/ansi.ts";
34 import { buildFileEditShellPrelude } from "../internal/file-edit/command.ts";
45 import type { ToolDef } from "../llm-api/types.ts";
56
@@ -29,6 +30,10 @@ export interface ShellOutput {
2930 exitCode: number;
3031 success: boolean;
3132 timedOut: boolean;
33+ /** Raw stdout with ANSI escape codes preserved (for user display). */
34+ rawStdout?: string | undefined;
35+ /** Raw stderr with ANSI escape codes preserved (for user display). */
36+ rawStderr?: string | undefined;
3237 }
3338
3439 const MAX_OUTPUT_BYTES = 10_000; // 10KB per stream
@@ -39,6 +44,7 @@ export async function runShellCommand(input: ShellInput): Promise<ShellOutput> {
3944 const env: Record<string, string | undefined> = Object.assign(
4045 {},
4146 process.env as Record<string, string | undefined>,
47+ { FORCE_COLOR: "1" },
4248 input.env ?? {},
4349 );
4450
@@ -130,12 +136,17 @@ export async function runShellCommand(input: ShellInput): Promise<ShellOutput> {
130136 }
131137 }
132138
139+ const rawOut = stdout.trimEnd();
140+ const rawErr = stderr.trimEnd();
141+ const hasAnsi = rawOut.includes("\x1b[") || rawErr.includes("\x1b[");
133142 return {
134- stdout: stdout.trimEnd(),
135- stderr: stderr.trimEnd(),
143+ stdout: hasAnsi ? stripAnsi(rawOut) : rawOut,
144+ stderr: hasAnsi ? stripAnsi(rawErr) : rawErr,
136145 exitCode,
137146 success: exitCode === 0,
138147 timedOut,
148+ rawStdout: hasAnsi ? rawOut : undefined,
149+ rawStderr: hasAnsi ? rawErr : undefined,
139150 };
140151 }