xonecas.io
64875
Mc

mini-coder / commit 950a980

fix: simple shell passthrough

xonecas2026-03-15 950a980fce8528e94eddc60c017f53cda6048d82 parent 0bd31e8

5 files changed

TODO.md+9−12
@@ -1,9 +1,5 @@
11 # TODO
22
3-- Assistant responses are no longer rendered with highlighted markdown syntax. It's just plain text with no coloring. Let's condider markdown rendering libraries and their performance costs and completly rethink our approach. We want to keep our fast output above all, even if that means no markdown rendering.
4-- Investigate using tmux to allow agents to use mc from a users perspective
5-- Follow up on the recent CLI simplification pass: interactive `!cmd` now logs the command first, streamed shell results no longer duplicate stdout in summaries, and the status bar prioritizes session identity over cwd. Keep pushing this direction across the remaining UI surface.
6-
73 ---
84
95 ## UI Audit
@@ -15,17 +11,18 @@
1511
1612 ---
1713
18-## LSP Diagnostics (not very important, with strong linting this is not as necessary, but we should implement asap)
14+## Deferred fixes
1915
20-We should have a closed loop feedback for LSP diagnostics on edits/reads.
16+- Investigate using tmux to allow agents to use mc from a users perspective
17+- Subagent and shell tools are very similar, shell could do what subagent does without changes. This could be leveraged to reduce code. Subagent process runner is used for custom commands that fork context as well, there will need to be refactored.
18+- `/_debug` hidden command that snapshots recent logs/db and creates a report in the cwd. For dev mostly but available to all. Do not list it anywhere, only documented here and in the code itself.
2119
22-This could potentially be a very big slowdown, waiting for updated diagnostics every edit. This also has bias downsides, stale diagnostics confuse the LLM, and can cause negative distractions.
20+---
2321
24-We need to do research first and find an approach that fits the current shell-first architecture without the performance penalties. Needs brainstorming
22+### LSP Diagnostics (not very important, with strong linting this is not as necessary, but we should implement asap)
2523
26----
24+We should have a closed loop feedback for LSP diagnostics on edits/reads.
2725
28-## Deferred fixes
26+This could potentially be a very big slowdown, waiting for updated diagnostics every edit. This also has bias downsides, stale diagnostics confuse the LLM, and can cause negative distractions.
2927
30-- Subagent and shell tools are very similar, shell could do what subagent does without changes. This could be leveraged to reduce code. Subagent process runner is used for custom commands that fork context as well, there will need to be refactored.
31-- `/_debug` hidden command that snapshots recent logs/db and creates a report in the cwd. For dev mostly but available to all. Do not list it anywhere, only documented here and in the code itself.
28+We need to do research first and find an approach that fits the current shell-first architecture without the performance penalties. Needs brainstorming
src/cli/cli-helpers.ts+0−26
@@ -1,5 +1,3 @@
1-import type { AgentReporter } from "../agent/reporter.ts";
2-
31 export async function getGitBranch(cwd: string): Promise<string | null> {
42 try {
53 const proc = Bun.spawn(["git", "rev-parse", "--abbrev-ref", "HEAD"], {
@@ -15,27 +13,3 @@ export async function getGitBranch(cwd: string): Promise<string | null> {
1513 return null;
1614 }
1715 }
18-
19-export async function runShellPassthrough(
20- command: string,
21- cwd: string,
22- reporter: AgentReporter,
23-): Promise<string> {
24- const proc = Bun.spawn(["bash", "-c", command], {
25- cwd,
26- stdout: "pipe",
27- stderr: "pipe",
28- });
29- try {
30- const [stdout, stderr] = await Promise.all([
31- new Response(proc.stdout).text(),
32- new Response(proc.stderr).text(),
33- ]);
34- await proc.exited;
35- const out = [stdout, stderr].filter(Boolean).join("\n").trim();
36- if (out) reporter.streamChunk(`${out}\n`);
37- return out;
38- } finally {
39- reporter.restoreTerminal();
40- }
41-}
src/cli/commands-help.ts+46−48
@@ -5,41 +5,56 @@ import { writeln } from "./output.ts";
55 import { loadSkillsIndex } from "./skills.ts";
66 import type { CommandContext } from "./types.ts";
77
8+function renderEntries(
9+ entries: ReadonlyArray<readonly [string, string]>,
10+): void {
11+ for (const [label, description] of entries) {
12+ writeln(` ${c.cyan(label.padEnd(28))} ${c.dim(description)}`);
13+ }
14+}
15+
816 export function renderHelpCommand(
917 ctx: CommandContext,
1018 custom: Map<string, CustomCommand>,
1119 ): void {
1220 writeln();
21+ writeln(` ${c.dim("session")}`);
22+ renderEntries([
23+ ["/new", "start a fresh session"],
24+ ["/undo", "remove the last conversation turn"],
25+ ["/exit", "quit"],
26+ ]);
1327
14- const cmds: [string, string][] = [
15- ["/model [id]", "list or switch models (fetches live list)"],
16- ["/undo", "remove the last conversation turn (no filesystem revert)"],
17- ["/reasoning [on|off]", "toggle display of model reasoning output"],
18- ["/context [prune|cap]", "configure context pruning and tool-result caps"],
19- [
20- "/cache [on|off|openai|gemini]",
21- "configure provider prompt-caching settings",
22- ],
23- ["/agent [name]", "set or clear active primary agent"],
28+ writeln();
29+ writeln(` ${c.dim("model + context")}`);
30+ renderEntries([
31+ ["/model [id]", "list or switch models"],
32+ ["/reasoning [on|off]", "toggle reasoning display"],
33+ ["/context [prune|cap]", "configure pruning and tool-result caps"],
34+ ["/cache [...]", "configure provider prompt caching"],
35+ ["/agent [name]", "set or clear the active primary agent"],
2436 ["/mcp list", "list MCP servers"],
2537 ["/mcp add <n> <t> [u]", "add an MCP server"],
2638 ["/mcp remove <name>", "remove an MCP server"],
27- ["/new", "start a new session with clean context"],
28- ["/help", "this message"],
29- ["/exit", "quit"],
30- ];
31- for (const [cmd, desc] of cmds) {
32- writeln(` ${c.cyan(cmd.padEnd(26))} ${c.dim(desc)}`);
33- }
39+ ["/help", "show this help"],
40+ ]);
41+
42+ writeln();
43+ writeln(` ${c.dim("prompt")}`);
44+ renderEntries([
45+ ["ask normally", "send a prompt to the current agent"],
46+ ["!cmd", "run a shell command and keep the result in context"],
47+ ["@file", "inject a file into the prompt (Tab to complete)"],
48+ ["@skill", "inject a skill into the prompt (Tab to complete)"],
49+ ]);
3450
3551 if (custom.size > 0) {
3652 writeln();
37- writeln(c.dim(" custom commands:"));
53+ writeln(` ${c.dim("custom commands")}`);
3854 for (const cmd of custom.values()) {
39- const tag =
40- cmd.source === "local" ? c.dim(" (local)") : c.dim(" (global)");
55+ const source = cmd.source === "local" ? c.dim("local") : c.dim("global");
4156 writeln(
42- ` ${c.green(`/${cmd.name}`.padEnd(26))} ${c.dim(cmd.description)}${tag}`,
57+ ` ${c.green(`/${cmd.name}`.padEnd(28))} ${c.dim(cmd.description)} ${c.dim("·")} ${source}`,
4358 );
4459 }
4560 }
@@ -47,13 +62,13 @@ export function renderHelpCommand(
4762 const agents = loadAgents(ctx.cwd);
4863 if (agents.size > 0) {
4964 writeln();
50- writeln(c.dim(" agents (~/.agents/agents/ or .agents/agents/):"));
65+ writeln(` ${c.dim("agents")}`);
5166 for (const agent of agents.values()) {
52- const modeTag = agent.mode ? c.dim(` [${agent.mode}]`) : "";
53- const tag =
54- agent.source === "local" ? c.dim(" (local)") : c.dim(" (global)");
67+ const mode = agent.mode ? c.dim(agent.mode) : c.dim("agent");
68+ const source =
69+ agent.source === "local" ? c.dim("local") : c.dim("global");
5570 writeln(
56- ` ${c.magenta(agent.name.padEnd(26))} ${c.dim(agent.description)}${modeTag}${tag}`,
71+ ` ${c.magenta(agent.name.padEnd(28))} ${c.dim(agent.description)} ${c.dim("·")} ${mode} ${c.dim("·")} ${source}`,
5772 );
5873 }
5974 }
@@ -61,36 +76,19 @@ export function renderHelpCommand(
6176 const skills = loadSkillsIndex(ctx.cwd);
6277 if (skills.size > 0) {
6378 writeln();
64- writeln(
65- c.dim(
66- " skills (walk-up local .agents/.claude/skills + global ~/.agents/skills ~/.claude/skills):",
67- ),
68- );
79+ writeln(` ${c.dim("skills")}`);
6980 for (const skill of skills.values()) {
70- const tag =
71- skill.source === "local" ? c.dim(" (local)") : c.dim(" (global)");
81+ const source =
82+ skill.source === "local" ? c.dim("local") : c.dim("global");
7283 writeln(
73- ` ${c.yellow(`@${skill.name}`.padEnd(26))} ${c.dim(skill.description)}${tag}`,
84+ ` ${c.yellow(`@${skill.name}`.padEnd(28))} ${c.dim(skill.description)} ${c.dim("·")} ${source}`,
7485 );
7586 }
7687 }
7788
7889 writeln();
7990 writeln(
80- ` ${c.green("/agent <name>".padEnd(26))} ${c.dim("activate a custom agent by name")}`,
81- );
82- writeln(
83- ` ${c.green("@skill".padEnd(26))} ${c.dim("load a skill body on demand into the prompt (Tab to complete)")}`,
84- );
85- writeln(
86- ` ${c.green("@file".padEnd(26))} ${c.dim("inject file contents into prompt (Tab to complete)")}`,
87- );
88- writeln(
89- ` ${c.green("!cmd".padEnd(26))} ${c.dim("run shell command, output added as context")}`,
90- );
91- writeln();
92- writeln(
93- ` ${c.dim("esc")} cancel response ${c.dim("·")} ${c.dim("ctrl+c")} exit ${c.dim("·")} ${c.dim("ctrl+d")} exit ${c.dim("·")} ${c.dim("ctrl+r")} history search ${c.dim("·")} ${c.dim("↑↓")} history`,
91+ ` ${c.dim("keys")} ${c.dim("esc")} cancel response ${c.dim("·")} ${c.dim("ctrl+c / ctrl+d")} exit ${c.dim("·")} ${c.dim("ctrl+r")} history search ${c.dim("·")} ${c.dim("↑↓")} history`,
9492 );
9593 writeln();
9694 }
src/cli/input-loop.ts+22−5
@@ -3,14 +3,15 @@ import type { AgentReporter } from "../agent/reporter.ts";
33 import type { SessionRunner } from "../agent/session-runner.ts";
44
55 import { getContextWindow } from "../llm-api/providers.ts";
6-import { getGitBranch, runShellPassthrough } from "./cli-helpers.ts";
6+import { runShellCommand, type ShellOutput } from "../tools/shell.ts";
7+import { getGitBranch } from "./cli-helpers.ts";
78 import { handleCommand } from "./commands.ts";
89 import { resolveFileRefs } from "./file-refs.ts";
910 import { createGitBranchCache } from "./git-branch-cache.ts";
1011 import { type InputResult, readline } from "./input.ts";
1112 import { renderUserMessage, tildePath } from "./output.ts";
1213 import { buildStatusBarSignature } from "./status-bar.ts";
13-import { buildToolCallLine } from "./tool-render.ts";
14+import { buildToolCallLine, renderToolResult } from "./tool-render.ts";
1415
1516 import type { CommandContext } from "./types.ts";
1617
@@ -21,6 +22,15 @@ interface InputLoopOptions {
2122 runner: SessionRunner;
2223 }
2324
25+function buildShellContext(result: ShellOutput): string {
26+ const sections: string[] = [];
27+ if (result.stdout) sections.push(result.stdout);
28+ if (result.stderr) sections.push(`stderr:\n${result.stderr}`);
29+ if (result.timedOut) sections.push("command timed out");
30+ if (!result.success) sections.push(`exit code: ${result.exitCode}`);
31+ return sections.join("\n\n").trim();
32+}
33+
2434 export async function runInputLoop(opts: InputLoopOptions): Promise<void> {
2535 const { cwd, reporter, cmdCtx, runner } = opts;
2636
@@ -98,9 +108,16 @@ export async function runInputLoop(opts: InputLoopOptions): Promise<void> {
98108 reporter.writeText(
99109 ` ${buildToolCallLine("shell", { command: input.command })}`,
100110 );
101- const out = await runShellPassthrough(input.command, cwd, reporter);
102- if (out) {
103- runner.addShellContext(input.command, out);
111+ const result = await runShellCommand({
112+ command: input.command,
113+ timeout: 30_000,
114+ cwd,
115+ onOutput: (chunk) => reporter.streamChunk(chunk),
116+ });
117+ renderToolResult("shell", result, false);
118+ const context = buildShellContext(result);
119+ if (context) {
120+ runner.addShellContext(input.command, context);
104121 }
105122 gitBranchCache.refreshInBackground(true);
106123 continue;
src/tools/shell.ts+122−126
@@ -35,139 +35,135 @@ export interface ShellOutput {
3535
3636 const MAX_OUTPUT_BYTES = 10_000; // 10KB per stream
3737
38-export const shellTool: ToolDef<ShellInput, ShellOutput> = {
39- name: "shell",
40- description:
41- "Execute a shell command. Returns stdout, stderr, and exit code. " +
42- "Use this for reading/searching code, running tests, builds, git commands, and invoking `mc-edit` for partial file edits. " +
43- "Prefer non-interactive commands. Avoid commands that run indefinitely.",
44- schema: ShellSchema,
45- execute: async (input) => {
46- const cwd = input.cwd ?? process.cwd();
47- const timeout = input.timeout ?? 30_000;
48- const env: Record<string, string | undefined> = Object.assign(
49- {},
50- process.env as Record<string, string | undefined>,
51- input.env ?? {},
52- );
53-
54- let timedOut = false;
55- const readers: { cancel: () => Promise<void> }[] = [];
56-
57- const wasRaw = process.stdin.isTTY ? process.stdin.isRaw : false;
58-
59- const proc = Bun.spawn(
60- ["bash", "-c", `${buildFileEditShellPrelude()}\n${input.command}`],
61- {
62- cwd,
63- env,
64- stdout: "pipe",
65- stderr: "pipe",
66- },
67- );
68-
69- // Set up timeout
70- const timer = setTimeout(() => {
71- timedOut = true;
72- try {
73- proc.kill("SIGTERM");
74- setTimeout(() => {
75- try {
76- proc.kill("SIGKILL");
77- } catch {
78- /* already dead */
79- }
80- }, 2000);
81- } catch {
82- /* already done */
83- }
84- for (const r of readers) {
85- r.cancel().catch(() => {});
86- }
87- }, timeout);
88-
89- // Collect output with size limit; forward each decoded chunk to onOutput.
90- async function collectStream(
91- stream: ReadableStream<Uint8Array>,
92- onChunk?: (text: string) => void,
93- ): Promise<string> {
94- const reader = stream.getReader();
95- readers.push(reader);
96- const chunks: Uint8Array[] = [];
97- let totalBytes = 0;
98- let truncated = false;
99- const decoder = new TextDecoder();
100-
101- while (true) {
38+export async function runShellCommand(input: ShellInput): Promise<ShellOutput> {
39+ const cwd = input.cwd ?? process.cwd();
40+ const timeout = input.timeout ?? 30_000;
41+ const env: Record<string, string | undefined> = Object.assign(
42+ {},
43+ process.env as Record<string, string | undefined>,
44+ input.env ?? {},
45+ );
46+
47+ let timedOut = false;
48+ const readers: { cancel: () => Promise<void> }[] = [];
49+ const wasRaw = process.stdin.isTTY ? process.stdin.isRaw : false;
50+
51+ const proc = Bun.spawn(
52+ ["bash", "-c", `${buildFileEditShellPrelude()}\n${input.command}`],
53+ {
54+ cwd,
55+ env,
56+ stdout: "pipe",
57+ stderr: "pipe",
58+ },
59+ );
60+
61+ const timer = setTimeout(() => {
62+ timedOut = true;
63+ try {
64+ proc.kill("SIGTERM");
65+ setTimeout(() => {
10266 try {
103- const { done, value } = await reader.read();
104- if (done) break;
105- if (value) {
106- onChunk?.(decoder.decode(value, { stream: true }));
107- if (totalBytes + value.length > MAX_OUTPUT_BYTES) {
108- chunks.push(value.slice(0, MAX_OUTPUT_BYTES - totalBytes));
109- truncated = true;
110- reader.cancel().catch(() => {});
111- break;
112- }
113- chunks.push(value);
114- totalBytes += value.length;
115- }
116- } catch (_err) {
117- // Reader was cancelled or stream errored
118- break;
67+ proc.kill("SIGKILL");
68+ } catch {
69+ /* already dead */
11970 }
120- }
121-
122- const text = Buffer.concat(chunks).toString("utf-8");
123- return truncated ? `${text}\n[output truncated]` : text;
71+ }, 2000);
72+ } catch {
73+ /* already done */
12474 }
75+ for (const reader of readers) {
76+ reader.cancel().catch(() => {});
77+ }
78+ }, timeout);
79+
80+ async function collectStream(
81+ stream: ReadableStream<Uint8Array>,
82+ onChunk?: (text: string) => void,
83+ ): Promise<string> {
84+ const reader = stream.getReader();
85+ readers.push(reader);
86+ const chunks: Uint8Array[] = [];
87+ let totalBytes = 0;
88+ let truncated = false;
89+ const decoder = new TextDecoder();
90+
91+ while (true) {
92+ try {
93+ const { done, value } = await reader.read();
94+ if (done) break;
95+ if (!value) continue;
96+
97+ onChunk?.(decoder.decode(value, { stream: true }));
98+ if (totalBytes + value.length > MAX_OUTPUT_BYTES) {
99+ chunks.push(value.slice(0, MAX_OUTPUT_BYTES - totalBytes));
100+ truncated = true;
101+ reader.cancel().catch(() => {});
102+ break;
103+ }
125104
126- let stdout = "";
127- let stderr = "";
128- let exitCode = 1;
129- const onOutput = input.onOutput;
130- const hasOutputHandler = typeof onOutput === "function";
131- let streamedAnyOutput = false;
132- let streamedEndsWithNewline = true;
133- const emitOutput = (chunk: string): void => {
134- if (!chunk || !hasOutputHandler) return;
135- streamedAnyOutput = true;
136- streamedEndsWithNewline = /[\r\n]$/.test(chunk);
137- onOutput(chunk);
138- };
139-
140- try {
141- [stdout, stderr] = await Promise.all([
142- collectStream(proc.stdout, hasOutputHandler ? emitOutput : undefined),
143- collectStream(proc.stderr, hasOutputHandler ? emitOutput : undefined),
144- ]);
145- if (streamedAnyOutput && !streamedEndsWithNewline) {
146- emitOutput("\n");
105+ chunks.push(value);
106+ totalBytes += value.length;
107+ } catch {
108+ break;
147109 }
110+ }
148111
149- exitCode = await proc.exited;
150- } finally {
151- clearTimeout(timer);
152- // Ensure the terminal is in a sane state if the spawn caused any
153- // raw-mode or cursor-visibility side-effects
154- restoreTerminal();
155- if (wasRaw) {
156- try {
157- process.stdin.setRawMode(true);
158- } catch {
159- /* ignore */
160- }
112+ const text = Buffer.concat(chunks).toString("utf-8");
113+ return truncated ? `${text}\n[output truncated]` : text;
114+ }
115+
116+ let stdout = "";
117+ let stderr = "";
118+ let exitCode = 1;
119+ const onOutput = input.onOutput;
120+ const hasOutputHandler = typeof onOutput === "function";
121+ let streamedAnyOutput = false;
122+ let streamedEndsWithNewline = true;
123+ const emitOutput = (chunk: string): void => {
124+ if (!chunk || !hasOutputHandler) return;
125+ streamedAnyOutput = true;
126+ streamedEndsWithNewline = /[\r\n]$/.test(chunk);
127+ onOutput(chunk);
128+ };
129+
130+ try {
131+ [stdout, stderr] = await Promise.all([
132+ collectStream(proc.stdout, hasOutputHandler ? emitOutput : undefined),
133+ collectStream(proc.stderr, hasOutputHandler ? emitOutput : undefined),
134+ ]);
135+ if (streamedAnyOutput && !streamedEndsWithNewline) {
136+ emitOutput("\n");
137+ }
138+ exitCode = await proc.exited;
139+ } finally {
140+ clearTimeout(timer);
141+ restoreTerminal();
142+ if (wasRaw) {
143+ try {
144+ process.stdin.setRawMode(true);
145+ } catch {
146+ /* ignore */
161147 }
162148 }
149+ }
150+
151+ return {
152+ stdout: stdout.trimEnd(),
153+ stderr: stderr.trimEnd(),
154+ exitCode,
155+ success: exitCode === 0,
156+ timedOut,
157+ streamedOutput: streamedAnyOutput,
158+ };
159+}
163160
164- return {
165- stdout: stdout.trimEnd(),
166- stderr: stderr.trimEnd(),
167- exitCode,
168- success: exitCode === 0,
169- timedOut,
170- streamedOutput: streamedAnyOutput,
171- };
172- },
161+export const shellTool: ToolDef<ShellInput, ShellOutput> = {
162+ name: "shell",
163+ description:
164+ "Execute a shell command. Returns stdout, stderr, and exit code. " +
165+ "Use this for reading/searching code, running tests, builds, git commands, and invoking `mc-edit` for partial file edits. " +
166+ "Prefer non-interactive commands. Avoid commands that run indefinitely.",
167+ schema: ShellSchema,
168+ execute: runShellCommand,
173169 };