xonecas.io
64875
Mc

mini-coder / commit fc73958

feat: add first-class delegation and safer compaction

xonecas2026-04-21 fc73958ca3313c1512de0518ebf4c3a3e382d94b parent e65e10e

20 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

PROGRESS.md+3−3
@@ -1,5 +1,5 @@
11 # CURRENT TASK PROGRESS
22
3-- Loop errored out and possibly crashed running benchmarks.
4-- Fixes were done to the code, `mc` is now updated to the latest dev.
5-- Benchmark loop re-started
3+## Current status
4+
5+- Restarted the benchmark loop
TODO.md+0−1
@@ -7,7 +7,6 @@ The spec and code are the sources of truth; this file is just the verified backl
77
88 ## Open issues:
99
10-- [ ] Add first-class delegation/subagent support instead of relying on shell-level `mc -p` delegation (`src/agent.ts`, `src/tools.ts`, `src/prompt.ts`, `src/headless.ts`)
1110 - [ ] Read tool output should include line numbers to help the llm find it's anchors.
1211 - [ ] If an agent uses readImage on a non-image file, mc crashes
1312 - [ ] If a conversation is truncated away from the db when the UI is still open somewhere, the app crashes.
spec.md+19−4
@@ -57,7 +57,7 @@ This replaces: `yoctocolors`, `yoctomarkdown`, `yoctoselect`, and all our custom
5757
5858 ## Tools
5959
60-Six built-in tools, plus a conditional read-only image tool and any tools imported from configured MCP servers.
60+Seven built-in tools, plus a conditional read-only image tool and any tools imported from configured MCP servers.
6161
6262 ### `shell`
6363
@@ -68,11 +68,24 @@ Implementation details:
6868 - Large outputs are truncated as a safety guard against context explosion from bad or overly broad commands (for example, accidentally reading a huge file, binary, or unbounded command output). This guard applies to both very tall output (many lines) and very wide output (a few extremely long lines), and is not related to the user-configured verbose setting.
6969 - The truncation threshold is configurable, tuned to keep useful output while staying well within context limits. This tool-level truncation is intentionally narrow in scope: it protects the model context from pathological output, not as a general-purpose presentation layer for every output-shaping concern.
7070 - Commands run via `$SHELL -c "<command>"` (falling back to `/bin/sh` if `$SHELL` is unset) with the CWD set to the session's working directory.
71+- Shell-launched `mc -p` subagents inherit a small namespaced delegation context through the environment. That context enforces a shallow maximum delegation depth and a small per-run delegation budget so shell-level subagents can help with compaction without recursing forever.
7172 - Verification commands that produce build artifacts should prefer temporary output paths or clean up generated files before the agent finishes.
7273 - Before execution, the harness may apply a small set of silent, lossless compatibility normalizations for common model-authored shell mistakes when the intended command is unambiguous (for example, moving a heredoc trailer's `|`, `&&`, or `>` continuation back onto the heredoc start line, or rewriting `printf '--- ...'` to `printf -- '--- ...'` when the format string begins with `-`).
7374 - Compatibility normalization is best-effort and intentionally narrow. If a rewrite is ambiguous or the normalization step itself fails, the raw command is executed unchanged.
7475 - Timeout: no default timeout. The user can interrupt via `Escape`.
7576
77+### `delegate`
78+
79+Runs a bounded subtask in an isolated subagent session using the current model, prompt context, and tools. Use it when a focused second agent pass will help, and prefer it over shelling out to `mc -p` unless you are explicitly testing the CLI itself.
80+
81+Implementation details:
82+
83+- Takes a single `task` string containing the delegated subtask prompt.
84+- Delegated runs inherit the current system prompt, model, working directory, MCP availability, and built-in tools.
85+- Delegated runs execute in an isolated temporary session that is deleted after the tool finishes, so first-class delegation does not clutter the user's session list or prompt history.
86+- Delegated runs share the same shallow maximum delegation depth and per-run delegation budget as shell-launched `mc -p` subagents. Delegated children may not delegate again.
87+- Tool results include the delegated subagent stop reason plus its final answer text, and delegated assistant activity can stream back through normal tool-delta updates while the tool is running.
88+
7689 ### `read`
7790
7891 Reads a UTF-8 text file from disk, optionally by line window. Use it for reading file contents instead of shelling out to `cat`, `sed`, `head`, or `tail`.
@@ -217,7 +230,7 @@ The core runtime. Streaming is the default behavior throughout the turn: user-vi
217230 - `error` → display error in the log, return to the input prompt.
218231
219232 4. **Tool execution** — when the LLM requests tool calls:
220- - Execute each tool call. For `shell`: run the command, capture output, truncate if needed. For `read`: read the requested file slice and include continuation guidance when needed. For `grep`: run the structured ripgrep search and return parsed match data. For `edit`: perform the replacement. For `todoWrite`: apply the incremental todo changes and return the full current list. For `todoRead`: return the full current list. For `readImage`: read and base64-encode the file.
233+ - Execute each tool call. For `shell`: run the command, capture output, truncate if needed. For `delegate`: run the bounded delegated subtask in an isolated temporary session and return the subagent's summarized final result. For `read`: read the requested file slice and include continuation guidance when needed. For `grep`: run the structured ripgrep search and return parsed match data. For `edit`: perform the replacement. For `todoWrite`: apply the incremental todo changes and return the fu …
221234 - Each result becomes a `ToolResultMessage` appended to history and DB (same turn number).
222235 - After all tool results are appended, if queued steering messages exist go to step 6; otherwise loop back to step 2 (re-stream with the updated context).
223236
@@ -329,7 +342,9 @@ The current environment is:
329342 - A todo item is only complete if the requested work is actually finished and verified to the degree the task requires.
330343 - Use `cancelled` to remove tasks that are no longer relevant.
331344 - Skip todo tools for single trivial tasks and purely conversational/informational requests.
332-- You have the option to delegate tasks to copies of yourself with `mc -p "subtask prompt"` in the shell.
345+- Use the `delegate` tool for bounded subtasks when another focused agent pass would help.
346+- Prefer `delegate` over shelling out to `mc -p` unless you specifically need to exercise the CLI itself.
347+- Do not re-delegate the whole task, spin on repeated self-review prompts, or ask a delegated child to delegate again.
333348 - Delegate when you are orchestarting a large to-do/plan execution.
334349 ```
335350
@@ -386,7 +401,7 @@ Key decisions informed by the Codex prompting guide and Claude prompting best pr
386401 - **Minimality over flourish**: the prompt emphasizes concise, direct help, discourages extra work the user did not ask for, and explicitly calls for the smallest implementation that satisfies the request.
387402 - **Targeted changes over rewrites**: the prompt tells the agent to preserve working behavior where possible, prefer targeted fixes, and avoid speculative abstractions.
388403 - **Operational discipline**: separate sections for shell use, code changes, and task management keep the prompt easy to scan while reinforcing non-interactive shell usage, environment checks, and cleanup expectations.
389-- **Verification and delegation**: the prompt explicitly requires verification, requires a `/tmp` to-do list, and reminds the agent it can delegate subtasks with `mc -p` when that helps.
404+- **Verification and delegation**: the prompt explicitly requires verification, requires a `/tmp` to-do list, and reminds the agent it can use the first-class `delegate` tool for bounded subtasks while avoiding recursive re-delegation.
390405 - **Single prompt**: no branching based on model family. Complexity in the prompt is complexity we maintain.
391406
392407 ## CLI UX
src/agent.test.ts+194−12
@@ -109,6 +109,78 @@ const ZERO_USAGE: Usage = {
109109 cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
110110 };
111111
112+function withUsage(
113+ message: AssistantMessage,
114+ api: string,
115+ totalTokens: number,
116+): AssistantMessage {
117+ return {
118+ ...message,
119+ api,
120+ provider: "test",
121+ model: api,
122+ usage: {
123+ ...ZERO_USAGE,
124+ input: totalTokens,
125+ totalTokens,
126+ cost: { ...ZERO_USAGE.cost },
127+ },
128+ };
129+}
130+
131+function advanceCompleteToolHistorySpan(
132+ messages: readonly Message[],
133+ startIndex: number,
134+): number | null {
135+ const message = messages[startIndex];
136+ if (!message) {
137+ return null;
138+ }
139+ if (message.role === "toolResult") {
140+ return null;
141+ }
142+ if (message.role !== "assistant") {
143+ return startIndex + 1;
144+ }
145+
146+ const pendingToolCallIds = message.content.flatMap((block) => {
147+ return block.type === "toolCall" ? [block.id] : [];
148+ });
149+ if (pendingToolCallIds.length === 0) {
150+ return startIndex + 1;
151+ }
152+
153+ let cursor = startIndex + 1;
154+ while (pendingToolCallIds.length > 0) {
155+ const nextMessage = messages[cursor];
156+ if (!nextMessage || nextMessage.role !== "toolResult") {
157+ return null;
158+ }
159+
160+ const matchIndex = pendingToolCallIds.indexOf(nextMessage.toolCallId);
161+ if (matchIndex === -1) {
162+ return null;
163+ }
164+
165+ pendingToolCallIds.splice(matchIndex, 1);
166+ cursor += 1;
167+ }
168+
169+ return cursor;
170+}
171+
172+function isCompleteToolHistory(messages: readonly Message[]): boolean {
173+ let index = 0;
174+ while (index < messages.length) {
175+ const nextIndex = advanceCompleteToolHistorySpan(messages, index);
176+ if (nextIndex === null) {
177+ return false;
178+ }
179+ index = nextIndex;
180+ }
181+ return true;
182+}
183+
112184 function getTextContent(
113185 content: ReadonlyArray<{ type: string; text?: string }>,
114186 ): string {
@@ -2316,6 +2388,120 @@ describe("agent loop", () => {
23162388 }
23172389 });
23182390
2391+ test("context compaction keeps tool call history valid across compaction boundaries", async () => {
2392+ const api = "test/context-compaction-tool-history";
2393+ const sourceId = "test-context-compaction-tool-history";
2394+ const model: Model<string> = {
2395+ id: api,
2396+ name: "Context Compaction Tool History Model",
2397+ api,
2398+ provider: "test",
2399+ baseUrl: "http://localhost:0",
2400+ reasoning: false,
2401+ input: ["text"],
2402+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
2403+ contextWindow: 250,
2404+ maxTokens: 4096,
2405+ };
2406+ const compactionRequests: Message[][] = [];
2407+ const mainRequests: Message[][] = [];
2408+
2409+ const buildProviderStream = (context: Context) => {
2410+ const isCompaction = (context.systemPrompt ?? "").includes(
2411+ "You summarize earlier conversation context for a coding agent.",
2412+ );
2413+ if (isCompaction) {
2414+ compactionRequests.push(structuredClone(context.messages));
2415+ } else {
2416+ mainRequests.push(structuredClone(context.messages));
2417+ }
2418+
2419+ const stream = createAssistantMessageEventStream();
2420+ const finalMessage = isCompaction
2421+ ? fauxAssistantMessage("summary")
2422+ : fauxAssistantMessage("done");
2423+
2424+ queueMicrotask(() => {
2425+ stream.push({ type: "done", reason: "stop", message: finalMessage });
2426+ stream.end(finalMessage);
2427+ });
2428+
2429+ return stream;
2430+ };
2431+
2432+ registerApiProvider(
2433+ {
2434+ api,
2435+ stream: (_model, context) => buildProviderStream(context),
2436+ streamSimple: (_model, context) => buildProviderStream(context),
2437+ },
2438+ sourceId,
2439+ );
2440+
2441+ try {
2442+ const session = createSession(db, { cwd: tmp });
2443+ const currentUser = makeUser(`current request ${"x".repeat(380)}`);
2444+ const turn = appendMessage(db, session.id, currentUser);
2445+ const toolCall = fauxToolCall("shell", { command: "echo tool" });
2446+ const toolCallMessage = withUsage(
2447+ fauxAssistantMessage([toolCall], { stopReason: "toolUse" }),
2448+ api,
2449+ 250,
2450+ );
2451+ const toolResultMessage: Message = {
2452+ role: "toolResult",
2453+ toolCallId: toolCall.id,
2454+ toolName: "shell",
2455+ content: [{ type: "text", text: `tool output ${"t".repeat(380)}` }],
2456+ isError: false,
2457+ timestamp: Date.now() + 1,
2458+ };
2459+ const followUpOne = withUsage(
2460+ fauxAssistantMessage(`assistant 1 ${"a".repeat(380)}`),
2461+ api,
2462+ 250,
2463+ );
2464+ const followUpTwo = withUsage(
2465+ fauxAssistantMessage(`assistant 2 ${"b".repeat(380)}`),
2466+ api,
2467+ 250,
2468+ );
2469+ const messages: Message[] = [
2470+ currentUser,
2471+ toolCallMessage,
2472+ toolResultMessage,
2473+ followUpOne,
2474+ followUpTwo,
2475+ ];
2476+
2477+ appendMessage(db, session.id, toolCallMessage, turn);
2478+ appendMessage(db, session.id, toolResultMessage, turn);
2479+ appendMessage(db, session.id, followUpOne, turn);
2480+ appendMessage(db, session.id, followUpTwo, turn);
2481+
2482+ const result = await runAgentLoop({
2483+ db,
2484+ sessionId: session.id,
2485+ turn,
2486+ model,
2487+ systemPrompt: "Test",
2488+ tools: [],
2489+ toolHandlers: new Map(),
2490+ messages,
2491+ cwd: tmp,
2492+ });
2493+
2494+ expect(result.stopReason).toBe("stop");
2495+ expect(compactionRequests.length).toBeGreaterThan(0);
2496+ expect(mainRequests).toHaveLength(1);
2497+ for (const request of [...compactionRequests, ...mainRequests]) {
2498+ expect(isCompleteToolHistory(request)).toBe(true);
2499+ }
2500+ } finally {
2501+ unregisterApiProviders(sourceId);
2502+ }
2503+ });
2504+
23192505 test("context compaction summarizes older messages without re-compacting earlier summaries", async () => {
23202506 const api = "test/context-compaction";
23212507 const sourceId = "test-context-compaction";
@@ -2521,21 +2707,17 @@ describe("agent loop", () => {
25212707 const messages: Message[] = [userMsg];
25222708
25232709 for (let index = 0; index < 6; index += 1) {
2524- const assistantMessage: AssistantMessage = {
2525- ...fauxAssistantMessage(`assistant ${index} ${"a".repeat(380)}`),
2710+ const toolCall = fauxToolCall("shell", {
2711+ command: `echo tool ${index}`,
2712+ });
2713+ const assistantMessage = withUsage(
2714+ fauxAssistantMessage([toolCall], { stopReason: "toolUse" }),
25262715 api,
2527- provider: "test",
2528- model: api,
2529- usage: {
2530- ...ZERO_USAGE,
2531- input: 250,
2532- totalTokens: 250,
2533- cost: { ...ZERO_USAGE.cost },
2534- },
2535- };
2716+ 250,
2717+ );
25362718 const toolResultMessage: Message = {
25372719 role: "toolResult",
2538- toolCallId: `call-${index}`,
2720+ toolCallId: toolCall.id,
25392721 toolName: "shell",
25402722 content: [{ type: "text", text: `tool ${index} ${"t".repeat(380)}` }],
25412723 isError: false,
src/agent.ts+87−1
@@ -524,6 +524,90 @@ function computeCompactionMessageCount(messageCount: number): number {
524524 );
525525 }
526526
527+function advanceCompleteContextSpan(
528+ messages: readonly Message[],
529+ startIndex: number,
530+): number | null {
531+ const message = messages[startIndex];
532+ if (!message) {
533+ return null;
534+ }
535+ if (message.role === "toolResult") {
536+ return null;
537+ }
538+ if (message.role !== "assistant") {
539+ return startIndex + 1;
540+ }
541+
542+ const toolCalls = getAssistantToolCalls(message);
543+ if (toolCalls.length === 0) {
544+ return startIndex + 1;
545+ }
546+
547+ let cursor = startIndex + 1;
548+ const pendingToolCallIds = new Set(toolCalls.map((toolCall) => toolCall.id));
549+ while (pendingToolCallIds.size > 0) {
550+ const nextMessage = messages[cursor];
551+ if (!nextMessage || nextMessage.role !== "toolResult") {
552+ return null;
553+ }
554+ if (!pendingToolCallIds.delete(nextMessage.toolCallId)) {
555+ return null;
556+ }
557+ cursor += 1;
558+ }
559+
560+ return cursor;
561+}
562+
563+function collectCompactionBoundaryCounts(
564+ messages: readonly Message[],
565+): number[] {
566+ const boundaries: number[] = [];
567+ let index = 0;
568+
569+ while (index < messages.length) {
570+ const nextIndex = advanceCompleteContextSpan(messages, index);
571+ if (nextIndex === null) {
572+ return [];
573+ }
574+ index = nextIndex;
575+ if (index < messages.length) {
576+ boundaries.push(index);
577+ }
578+ }
579+
580+ return boundaries;
581+}
582+
583+function computeSafeCompactionMessageCount(
584+ messages: readonly Message[],
585+): number {
586+ const targetCount = computeCompactionMessageCount(messages.length);
587+ if (targetCount === 0) {
588+ return 0;
589+ }
590+
591+ const safeBoundaryCounts = collectCompactionBoundaryCounts(messages);
592+ if (safeBoundaryCounts.length === 0) {
593+ return 0;
594+ }
595+
596+ let nearestLowerBoundary = 0;
597+ for (const boundaryCount of safeBoundaryCounts) {
598+ if (boundaryCount === targetCount) {
599+ return boundaryCount;
600+ }
601+ if (boundaryCount < targetCount) {
602+ nearestLowerBoundary = boundaryCount;
603+ continue;
604+ }
605+ return nearestLowerBoundary > 0 ? nearestLowerBoundary : boundaryCount;
606+ }
607+
608+ return nearestLowerBoundary;
609+}
610+
527611 interface CompactionSummaryResult {
528612 /** Replacement summary text for the compacted context prefix. */
529613 text: string;
@@ -591,7 +675,9 @@ async function maybeCompactContext(
591675 }
592676
593677 const candidateRows = loadUncompactedModelMessages(opts.db, opts.sessionId);
594- const compactCount = computeCompactionMessageCount(candidateRows.length);
678+ const compactCount = computeSafeCompactionMessageCount(
679+ candidateRows.map((row) => row.message),
680+ );
595681 if (compactCount === 0) {
596682 return compactedMessages;
597683 }
src/assistant-output.ts+73−0
@@ -0,0 +1,73 @@
1+/**
2+ * Shared helpers for extracting user-visible assistant output.
3+ *
4+ * @module
5+ */
6+
7+import type { AssistantMessage } from "@mariozechner/pi-ai";
8+import {
9+ collapseWhitespaceToNull,
10+ joinTextBlocks,
11+ truncateText,
12+} from "./text.ts";
13+
14+const ASSISTANT_ACTIVITY_MAX_CHARS = 160;
15+
16+/**
17+ * Extract concatenated text blocks from an assistant message.
18+ *
19+ * @param message - Assistant message to inspect.
20+ * @returns The combined text content, or an empty string when none exists.
21+ */
22+export function extractAssistantText(message: AssistantMessage | null): string {
23+ if (!message) {
24+ return "";
25+ }
26+
27+ return message.content
28+ .filter(
29+ (
30+ block,
31+ ): block is Extract<
32+ AssistantMessage["content"][number],
33+ { type: "text" }
34+ > => {
35+ return block.type === "text";
36+ },
37+ )
38+ .map((block) => block.text)
39+ .join("");
40+}
41+
42+/**
43+ * Extract a short assistant activity snippet from a tool-using message.
44+ *
45+ * @param message - Assistant message to inspect.
46+ * @returns A collapsed activity snippet, or `null` when no snippet applies.
47+ */
48+export function extractAssistantActivitySnippet(
49+ message: AssistantMessage,
50+): string | null {
51+ if (!message.content.some((block) => block.type === "toolCall")) {
52+ return null;
53+ }
54+
55+ const text = collapseWhitespaceToNull(joinTextBlocks(message.content));
56+ return text ? truncateText(text, ASSISTANT_ACTIVITY_MAX_CHARS) : null;
57+}
58+
59+/**
60+ * Extract terminal assistant error text from a failed assistant message.
61+ *
62+ * @param message - Assistant message to inspect.
63+ * @returns Collapsed error text, or `null` when the message is not terminally errored.
64+ */
65+export function extractAssistantErrorText(
66+ message: AssistantMessage | null,
67+): string | null {
68+ if (!message || message.stopReason !== "error" || !message.errorMessage) {
69+ return null;
70+ }
71+
72+ return collapseWhitespaceToNull(message.errorMessage) ?? null;
73+}
src/delegation.test.ts+165−0
@@ -0,0 +1,165 @@
1+import { describe, expect, test } from "bun:test";
2+import {
3+ buildShellDelegationEnv,
4+ countShellDelegationLaunches,
5+ DEFAULT_SHELL_DELEGATION_BUDGET,
6+ readShellDelegationContext,
7+ reserveShellDelegation,
8+ reserveToolDelegation,
9+} from "./delegation.ts";
10+
11+describe("shell delegation safeguards", () => {
12+ test("reads the default root delegation context when env is unset", () => {
13+ expect(readShellDelegationContext({})).toEqual({
14+ depth: 0,
15+ remainingBudget: DEFAULT_SHELL_DELEGATION_BUDGET,
16+ });
17+ });
18+
19+ test("serializes the delegation context back into shell env vars", () => {
20+ expect(
21+ buildShellDelegationEnv({
22+ depth: 1,
23+ remainingBudget: 2,
24+ }),
25+ ).toEqual({
26+ MC_SUBAGENT_DEPTH: "1",
27+ MC_SUBAGENT_BUDGET: "2",
28+ });
29+ });
30+
31+ test("counts likely mc -p launches in supported shell command shapes", () => {
32+ expect(countShellDelegationLaunches('mc -p "review the diff"')).toBe(1);
33+ expect(
34+ countShellDelegationLaunches('command -v mc && mc -p "review the diff"'),
35+ ).toBe(1);
36+ expect(
37+ countShellDelegationLaunches(
38+ 'bun /home/xonecas/.bun/bin/mc -p "review the diff"',
39+ ),
40+ ).toBe(1);
41+ expect(
42+ countShellDelegationLaunches(
43+ 'printf "mc -p should stay literal, not execute"',
44+ ),
45+ ).toBe(0);
46+ });
47+
48+ test("reserving a root shell delegation decrements the remaining budget", () => {
49+ const result = reserveShellDelegation('mc -p "review the diff"', {
50+ depth: 0,
51+ remainingBudget: 3,
52+ });
53+
54+ expect(result).toEqual({
55+ ok: true,
56+ reservation: {
57+ launchCount: 1,
58+ updatedContext: {
59+ depth: 0,
60+ remainingBudget: 2,
61+ },
62+ childContext: {
63+ depth: 1,
64+ remainingBudget: 2,
65+ },
66+ },
67+ });
68+ });
69+
70+ test("reserving a root delegate tool call decrements the remaining budget", () => {
71+ const result = reserveToolDelegation({
72+ depth: 0,
73+ remainingBudget: 3,
74+ });
75+
76+ expect(result).toEqual({
77+ ok: true,
78+ reservation: {
79+ launchCount: 1,
80+ updatedContext: {
81+ depth: 0,
82+ remainingBudget: 2,
83+ },
84+ childContext: {
85+ depth: 1,
86+ remainingBudget: 2,
87+ },
88+ },
89+ });
90+ });
91+
92+ test("blocks nested delegated children from launching more mc -p subagents", () => {
93+ expect(
94+ reserveShellDelegation('mc -p "review again"', {
95+ depth: 1,
96+ remainingBudget: 3,
97+ }),
98+ ).toEqual({
99+ ok: false,
100+ error:
101+ "Shell delegation blocked: delegated `mc -p` runs may not launch more `mc -p` subagents.",
102+ });
103+ });
104+
105+ test("blocks commands that exceed the remaining shell delegation budget", () => {
106+ expect(
107+ reserveShellDelegation('mc -p "one" && mc -p "two"', {
108+ depth: 0,
109+ remainingBudget: 1,
110+ }),
111+ ).toEqual({
112+ ok: false,
113+ error:
114+ "Shell delegation blocked: this command appears to launch more `mc -p` subagents than the remaining delegation budget allows.",
115+ });
116+ });
117+
118+ test("blocks delegate tool calls when no delegation budget remains", () => {
119+ expect(
120+ reserveToolDelegation({
121+ depth: 0,
122+ remainingBudget: 0,
123+ }),
124+ ).toEqual({
125+ ok: false,
126+ error:
127+ "Tool delegation blocked: this run has no remaining `delegate` delegation budget.",
128+ });
129+ });
130+
131+ test("blocks nested delegated children from calling delegate again", () => {
132+ expect(
133+ reserveToolDelegation({
134+ depth: 1,
135+ remainingBudget: 3,
136+ }),
137+ ).toEqual({
138+ ok: false,
139+ error:
140+ "Tool delegation blocked: delegated `delegate` tool runs may not delegate again.",
141+ });
142+ });
143+
144+ test("leaves non-delegating shell commands unchanged", () => {
145+ const result = reserveShellDelegation("bun test src/headless.test.ts", {
146+ depth: 0,
147+ remainingBudget: 4,
148+ });
149+
150+ expect(result).toEqual({
151+ ok: true,
152+ reservation: {
153+ launchCount: 0,
154+ updatedContext: {
155+ depth: 0,
156+ remainingBudget: 4,
157+ },
158+ childContext: {
159+ depth: 0,
160+ remainingBudget: 4,
161+ },
162+ },
163+ });
164+ });
165+});
src/delegation.ts+238−0
@@ -0,0 +1,238 @@
1+/**
2+ * Subagent delegation safeguards.
3+ *
4+ * Tracks a shallow delegation depth plus a small per-run delegation budget so
5+ * first-class `delegate` tool runs and shell-authored `mc -p` child processes
6+ * cannot recurse forever.
7+ *
8+ * @module
9+ */
10+
11+const SHELL_DELEGATION_COMMAND =
12+ /(?:^|[;&|()\s])(?:[^\s;&|()]+\/)?mc\s+(?:-p\b|--prompt(?:\b|=))/g;
13+
14+/** Environment variable carrying the current subagent-delegation depth. */
15+export const SHELL_DELEGATION_DEPTH_ENV = "MC_SUBAGENT_DEPTH";
16+
17+/** Environment variable carrying the remaining subagent-delegation budget. */
18+export const SHELL_DELEGATION_BUDGET_ENV = "MC_SUBAGENT_BUDGET";
19+
20+/** Maximum allowed subagent delegation depth. */
21+export const MAX_SHELL_DELEGATION_DEPTH = 1;
22+
23+/** Default number of delegated subagent launches allowed per agent run. */
24+export const DEFAULT_SHELL_DELEGATION_BUDGET = 4;
25+
26+/** Current subagent-delegation context for one app run. */
27+export interface ShellDelegationContext {
28+ /** Current subagent-delegation depth for this app process. */
29+ depth: number;
30+ /** Remaining delegated-subagent launches available in the active run. */
31+ remainingBudget: number;
32+}
33+
34+/** Result of reserving subagent-delegation budget for one launch. */
35+export interface ShellDelegationReservation {
36+ /** Number of delegated-subagent launches reserved by the request. */
37+ launchCount: number;
38+ /** Updated parent-run context after reserving any delegated launches. */
39+ updatedContext: ShellDelegationContext;
40+ /** Context that delegated child runs should inherit for this request. */
41+ childContext: ShellDelegationContext;
42+}
43+
44+/** Successful or blocked delegation-reservation outcome. */
45+export type ReserveShellDelegationResult =
46+ | {
47+ /** Whether the delegation request may proceed. */
48+ ok: true;
49+ /** Reserved delegation details for the request. */
50+ reservation: ShellDelegationReservation;
51+ }
52+ | {
53+ /** Whether the delegation request may proceed. */
54+ ok: false;
55+ /** Human-readable tool error for the blocked delegation attempt. */
56+ error: string;
57+ };
58+
59+type DelegationReservationError = "nested" | "exhausted" | "over_budget";
60+
61+function readNonNegativeInteger(
62+ value: string | undefined,
63+ fallback: number,
64+): number {
65+ if (value == null || value === "") {
66+ return fallback;
67+ }
68+
69+ const parsed = Number.parseInt(value, 10);
70+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback;
71+}
72+
73+function reserveDelegationBudget(
74+ context: ShellDelegationContext,
75+ launchCount: number,
76+):
77+ | {
78+ ok: true;
79+ reservation: ShellDelegationReservation;
80+ }
81+ | {
82+ ok: false;
83+ reason: DelegationReservationError;
84+ } {
85+ if (launchCount === 0) {
86+ const unchanged = { ...context };
87+ return {
88+ ok: true,
89+ reservation: {
90+ launchCount,
91+ updatedContext: unchanged,
92+ childContext: unchanged,
93+ },
94+ };
95+ }
96+
97+ if (context.depth >= MAX_SHELL_DELEGATION_DEPTH) {
98+ return {
99+ ok: false,
100+ reason: "nested",
101+ };
102+ }
103+
104+ if (context.remainingBudget === 0) {
105+ return {
106+ ok: false,
107+ reason: "exhausted",
108+ };
109+ }
110+
111+ if (launchCount > context.remainingBudget) {
112+ return {
113+ ok: false,
114+ reason: "over_budget",
115+ };
116+ }
117+
118+ const remainingBudget = context.remainingBudget - launchCount;
119+ return {
120+ ok: true,
121+ reservation: {
122+ launchCount,
123+ updatedContext: {
124+ depth: context.depth,
125+ remainingBudget,
126+ },
127+ childContext: {
128+ depth: context.depth + 1,
129+ remainingBudget,
130+ },
131+ },
132+ };
133+}
134+
135+/**
136+ * Read the current subagent-delegation context from environment variables.
137+ *
138+ * Missing or invalid values fall back to the safe root-run defaults.
139+ *
140+ * @param env - Environment variables to inspect.
141+ * @returns The parsed subagent-delegation context.
142+ */
143+export function readShellDelegationContext(
144+ env: Readonly<Record<string, string | undefined>>,
145+): ShellDelegationContext {
146+ return {
147+ depth: readNonNegativeInteger(env[SHELL_DELEGATION_DEPTH_ENV], 0),
148+ remainingBudget: readNonNegativeInteger(
149+ env[SHELL_DELEGATION_BUDGET_ENV],
150+ DEFAULT_SHELL_DELEGATION_BUDGET,
151+ ),
152+ };
153+}
154+
155+/**
156+ * Build the environment-variable overrides for a subagent-delegation context.
157+ *
158+ * @param context - Subagent-delegation context to serialize.
159+ * @returns Environment overrides for child shell processes.
160+ */
161+export function buildShellDelegationEnv(
162+ context: ShellDelegationContext,
163+): Record<string, string> {
164+ return {
165+ [SHELL_DELEGATION_DEPTH_ENV]: String(context.depth),
166+ [SHELL_DELEGATION_BUDGET_ENV]: String(context.remainingBudget),
167+ };
168+}
169+
170+/**
171+ * Count likely shell-authored `mc -p` / `mc --prompt` launches in one command.
172+ *
173+ * The detector is intentionally narrow and optimized for the prompt-guided
174+ * `mc -p "subtask"` pattern mini-coder still supports for CLI-level testing.
175+ *
176+ * @param command - Raw shell command.
177+ * @returns Number of likely `mc -p` launches in the command.
178+ */
179+export function countShellDelegationLaunches(command: string): number {
180+ return command.match(SHELL_DELEGATION_COMMAND)?.length ?? 0;
181+}
182+
183+/**
184+ * Reserve first-class `delegate` tool budget for one delegated subagent run.
185+ *
186+ * @param context - Current subagent-delegation context for the active run.
187+ * @returns Reservation details, or a blocking error when this delegation would
188+ * exceed the allowed subagent-delegation policy.
189+ */
190+export function reserveToolDelegation(
191+ context: ShellDelegationContext,
192+): ReserveShellDelegationResult {
193+ const reservation = reserveDelegationBudget(context, 1);
194+ if (!reservation.ok) {
195+ return {
196+ ok: false,
197+ error:
198+ reservation.reason === "nested"
199+ ? "Tool delegation blocked: delegated `delegate` tool runs may not delegate again."
200+ : "Tool delegation blocked: this run has no remaining `delegate` delegation budget.",
201+ };
202+ }
203+
204+ return reservation;
205+}
206+
207+/**
208+ * Reserve shell-level delegation budget for a command before execution.
209+ *
210+ * Non-delegating commands pass through unchanged. Commands that would exceed
211+ * the per-run delegation budget or the maximum allowed depth are rejected with
212+ * a user-visible tool error.
213+ *
214+ * @param command - Raw shell command to inspect.
215+ * @param context - Current subagent-delegation context for the active run.
216+ * @returns Reservation details, or a blocking error when the command would
217+ * exceed the allowed shell-level delegation policy.
218+ */
219+export function reserveShellDelegation(
220+ command: string,
221+ context: ShellDelegationContext,
222+): ReserveShellDelegationResult {
223+ const launchCount = countShellDelegationLaunches(command);
224+ const reservation = reserveDelegationBudget(context, launchCount);
225+ if (!reservation.ok) {
226+ return {
227+ ok: false,
228+ error:
229+ reservation.reason === "nested"
230+ ? "Shell delegation blocked: delegated `mc -p` runs may not launch more `mc -p` subagents."
231+ : reservation.reason === "exhausted"
232+ ? "Shell delegation blocked: this run has no remaining `mc -p` delegation budget."
233+ : "Shell delegation blocked: this command appears to launch more `mc -p` subagents than the remaining delegation budget allows.",
234+ };
235+ }
236+
237+ return reservation;
238+}
src/headless.test.ts+125−1
@@ -12,7 +12,12 @@ import {
1212 } from "@mariozechner/pi-ai";
1313 import { runHeadlessPrompt, runHeadlessPromptText } from "./headless.ts";
1414 import type { AppState } from "./index.ts";
15-import { listPromptHistory, loadMessages, openDatabase } from "./session.ts";
15+import {
16+ listPromptHistory,
17+ listSessions,
18+ loadMessages,
19+ openDatabase,
20+} from "./session.ts";
1621 import { DEFAULT_THEME } from "./theme.ts";
1722
1823 let tmp: string;
@@ -45,6 +50,9 @@ function createTestState(): AppState {
4550 skills: [],
4651 theme: DEFAULT_THEME,
4752 git: null,
53+ delegationDepth: 0,
54+ delegationBudgetLimit: 4,
55+ delegationBudgetRemaining: 4,
4856 providers: new Map(),
4957 oauthCredentials: {},
5058 settings: {},
@@ -368,4 +376,120 @@ describe("headless", () => {
368376 expect(state.running).toBe(false);
369377 expect(state.abortController).toBeNull();
370378 });
379+
380+ test("runHeadlessPromptText can delegate a bounded subtask without leaving a child session behind", async () => {
381+ faux.setResponses([
382+ fauxAssistantMessage(
383+ [fauxToolCall("delegate", { task: "review the diff" })],
384+ { stopReason: "toolUse" },
385+ ),
386+ fauxAssistantMessage("Subagent review complete."),
387+ fauxAssistantMessage("Used the delegated result."),
388+ ]);
389+ const state = createTestState();
390+ let finalText = "";
391+
392+ const stopReason = await runHeadlessPromptText(state, "delegate once", {
393+ writeActivity: () => {},
394+ writeText: (text) => {
395+ finalText += text;
396+ },
397+ });
398+
399+ expect(stopReason).toBe("stop");
400+ expect(finalText).toBe("Used the delegated result.");
401+
402+ const sessionId = state.session?.id;
403+ if (!sessionId) {
404+ throw new Error("Expected a session to be created");
405+ }
406+
407+ const delegateResult = loadMessages(state.db, sessionId).find(
408+ (message) =>
409+ message.role === "toolResult" && message.toolName === "delegate",
410+ );
411+ if (!delegateResult || delegateResult.role !== "toolResult") {
412+ throw new Error("Expected a delegate tool result");
413+ }
414+ expect(delegateResult.isError).toBe(false);
415+ expect(JSON.stringify(delegateResult.content)).toContain(
416+ "Subagent review complete.",
417+ );
418+ expect(listSessions(state.db, tmp)).toHaveLength(1);
419+ });
420+
421+ test("delegated headless children cannot launch more mc -p subagents", async () => {
422+ faux.setResponses([
423+ fauxAssistantMessage(
424+ [fauxToolCall("shell", { command: 'mc -p "review again"' })],
425+ { stopReason: "toolUse" },
426+ ),
427+ fauxAssistantMessage("Stopped the recursive delegation."),
428+ ]);
429+ const state = createTestState();
430+ state.delegationDepth = 1;
431+
432+ const stopReason = await runHeadlessPromptText(state, "delegate once", {
433+ writeActivity: () => {},
434+ writeText: () => {},
435+ });
436+
437+ expect(stopReason).toBe("stop");
438+
439+ const sessionId = state.session?.id;
440+ if (!sessionId) {
441+ throw new Error("Expected a session to be created");
442+ }
443+
444+ const toolResult = loadMessages(state.db, sessionId).find(
445+ (message) => message.role === "toolResult",
446+ );
447+ if (!toolResult || toolResult.role !== "toolResult") {
448+ throw new Error("Expected a shell tool result");
449+ }
450+ expect(toolResult.isError).toBe(true);
451+ expect(JSON.stringify(toolResult.content)).toContain(
452+ "delegated `mc -p` runs may not launch more `mc -p` subagents",
453+ );
454+ });
455+
456+ test("runHeadlessPrompt blocks mc -p when the shell delegation budget is exhausted", async () => {
457+ faux.setResponses([
458+ fauxAssistantMessage(
459+ [fauxToolCall("shell", { command: 'mc -p "review the diff"' })],
Cut short: this commit's diff is over 1000 lines.
src/headless.ts+5−48
Cut short: this commit's diff is over 1000 lines.
src/index.test.ts+69−0
Cut short: this commit's diff is over 1000 lines.
src/index.ts+191−11
Cut short: this commit's diff is over 1000 lines.
src/prompt.test.ts+15−0
Cut short: this commit's diff is over 1000 lines.
src/prompt.ts+5−1
Cut short: this commit's diff is over 1000 lines.
src/submit.ts+1−0
Cut short: this commit's diff is over 1000 lines.
src/tool-delegate.ts+125−0
Cut short: this commit's diff is over 1000 lines.
src/tool-shell.ts+52−2
Cut short: this commit's diff is over 1000 lines.
src/tools.ts+16−4
Cut short: this commit's diff is over 1000 lines.
src/ui.test.ts+3−0
Cut short: this commit's diff is over 1000 lines.
src/ui/commands.test.ts+3−0
Cut short: this commit's diff is over 1000 lines.