xonecas.io
64875
Mc

mini-coder / commit d8b26d2

feat: subprocess subagents with worktree isolation (#4)

* fix(interrupt): ESC cancels turn preserving partial response, arrow keys no longer cancel

- ESC during a turn stops the LLM, preserves any partial streamed text in
  history with an interrupt stub appended so the LLM retains context
- Multi-byte ESC sequences (arrow keys, function keys) no longer trigger cancel;
  only a lone ESC byte (0x1B) is treated as cancel
- Ctrl+C always exits the process (never routes through interrupt path)
- SIGINT no longer hijacked by watchForCancel; falls through to the default
  registerCleanup handler (exit 130)
- Ralph mode no longer forcibly disabled on interrupt
- session-runner: removed wasAborted flag, errorStubSaved guard, and all
  abort-specific branching; renderTurn now returns partial messages on abort
  and throws on real errors for a single clean code path
- ESC_BYTE and CTRL_C_BYTE now derived from their string counterparts via
  charCodeAt(0) to make the relationship explicit
- Docs: idea file updated to reflect ESC as cancel key with correct behaviour;
  stale TODO entry removed

* docs: plan subprocess subagents, consolidate TODO items

* docs: revise plan with subprocess details, prompt chain, worktree model

* docs: add phased implementation plan for subprocess subagents

* Phase 1: headless mc mode (--subagent, --agent, --output-fd)

- Add --subagent, --agent <name>, --output-fd <n> CLI flags
- Add HeadlessReporter: no-op AgentReporter that tracks tokens silently
- Add headless path in runAgent: single processUserInput call, returns SubagentSummary
- Define SubagentSummary { result, inputTokens, outputTokens, worktreeBranch? }
- Write SubagentSummary JSON to --output-fd before exit; write { error } on failure
- Extract buildAbortMessages() helper, used by both HeadlessReporter and stream-render

* phase 2: system prompt chain, subagent delegation, HeadlessReporter fix

- loadContextFile split into loadGlobalContextFile (~/.agents/) and
  loadLocalContextFile (.agents/AGENTS.md > CLAUDE.md > AGENTS.md);
  both compose under a single # Project context section, global first
- delegation guideline updated: subagent tool sparingly, prefer direct work
- buildSystemPrompt gains isSubagent param; appends stronger no-delegation
  wording when running as a subprocess
- SessionRunner / agent.ts plumbed through isSubagent (= headless flag)
- getConfigDir unexported (only used internally in connection.ts)
- HeadlessReporter: track text-delta accumulation and pass to
  buildAbortMessages so partial streamed text is not dropped on abort
- Remove dead SubagentSummary.worktreeBranch field (Phase 4 placeholder)
- Unit tests for buildSystemPrompt and loadLocalContextFile (12 tests)

* Phase 3: replace in-process subagent runner with subprocess launcher

- Spawn mc --subagent as a real subprocess instead of running in-process
- Communicate via --output-fd 1 (captured stdout); parse SubagentSummary JSON
- Remove worktree lifecycle, merge lock, depth parameter, and subagent filter
- Add MC_SUBAGENT_DEPTH env-var guard (max 10) to cap runaway recursion
- Guard JSON.parse with a descriptive error including raw subprocess output
- Track active subprocess PIDs for Phase 5 interrupt propagation
- Remove unused formatSubagentLabel export (was only used by old runner)

* Phase 4: new worktree model for subprocess subagents

Subprocess creates and owns its worktree; parent owns all merging.

- Subprocess (index.ts headless mode): on git repos, creates a worktree
  on branch mc-sub-<laneId> before running the agent, removes the
  worktree directory after, and includes worktreeBranch in the fd result.
  SIGTERM handler cleans up both the worktree directory and the branch.

- Parent (subagent-runner.ts): after the subprocess exits, merges the
  reported branch into the parent cwd via a serialising merge lock, cleans
  up the branch on success, or surfaces mergeConflicts on failure.

- SubagentSummary gains worktreeBranch; SubagentOutput replaces the old
  mergeConflict/mergeBlocked structs with a single mergeConflicts field.

* Phase 5: cleanup, output, and ESC propagation

- Subagent tool call display: two lines only
  - tool-call-start: ⇢ [callId] — <prompt ~60 chars>
  - tool-result: ← [callId] done (Nin / Nout tokens)
  - toolCallId threaded through renderToolCall/renderToolResult in stream-render

- ESC interrupt propagation to subprocesses
  - createSubagentRunner returns { runSubagent, killAll }
  - SessionRunner accepts killSubprocesses option, registers abort listener
  - ESC SIGTERMs all active subprocess PIDs before returning to prompt

- Remove execution: inline
  - Removed from docs/custom-commands.md
  - Removed from .agents/commands/release.md

- Remove dead code
  - renderSubagentEvent, renderToolResultInline, stripAnsiSgr,
    normalizeParentLaneLabel, formatSubagentLabel, laneBuffers (tool-render.ts)
  - splitNullSeparated, applyPatch, copyUntrackedPath (worktree.ts)
  - gitStatusLines (worktree.test.ts)
  - _reporter and _getThinkingEffort params from createSubagentRunner
  - currentThinkingEffort local in agent.ts

- Deduplicate assertSubagentMerged into tools/subagent.ts
  (was copy-pasted identically in tools.ts and commands.ts)

* fix: address five subagent subprocess review gaps

Bug 1: remove contradictory delegation guideline
The 'use subagents to achieve this' tail of the guidelines bullet
directly negated the new 'sparingly' directive above it. Removed.

Bug 2: use fd 3 instead of stdout for subprocess communication
Switch Bun.spawn to stdio array so fd 3 is a dedicated pipe.
Parent reads via Bun.file(proc.stdio[3]).text(); subprocess writes
to fd 3. Stdout is now free — an accidental console.log can no
longer silently corrupt the JSON summary.

Bug 3: SIGTERM handler must not delete the branch
The subprocess SIGTERM handler was deleting both the worktree dir
and the branch. Per plan, it should only remove the worktree dir;
the branch is left for the parent to discard.

Bug 4: parent-side cleanup of interrupted branches
Parent now generates the branch name and passes it via
--worktree-branch so it knows what to clean up if the subprocess
is killed. activeProcs (Map<pid, branch>) replaces the old
activePids Set; killAll() calls cleanupBranch() best-effort for
each tracked branch after sending SIGTERM.

Bug 5: test coverage for global+local context composition
Added homeDir param to buildSystemPrompt (forwarded to
loadGlobalContextFile) so tests can inject an isolated home
directory. All existing buildSystemPrompt tests now pass fakeHome
to prevent real ~/.agents from leaking in. Added three new tests:
global only, global+local ordered correctly, neither present.

* fix subagent runner: race in killAll, completion glyph, system prompt wording

- killAll: track proc objects instead of PIDs so branch cleanup can await
  proc.exited before calling git branch -D; previously the branch was still
  checked out when cleanupBranch ran, causing silent git failures and orphaned
  mc-sub-* branches on interrupt
- stdio: keep inherit for stdout/stderr so subprocess crashes surface in the
  parent terminal; silencing them left 'no output' as the only diagnostic
- completion line: use c.cyan('←') + 'subagent done' instead of G.read (wrong
  glyph, dimmed) — matches the plan's intended return-arrow format
- system prompt: add 'that benefit from a fresh context window' to main agent
  guideline; strengthen subagent delegation block to 'you have been given' /
  'unambiguously separable' per plan
- plan: document MC_SUBAGENT_DEPTH cap as an intentional safety rail

xonecas2026-03-10 d8b26d2fe9b2a965d8c7e5df852e4303d261becb parent 12721b7

29 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.

.agents/commands/release.md+0−1
@@ -1,6 +1,5 @@
11 ---
22 description: Create a new tagged npm release (patch/minor/major)
3-execution: inline
43 ---
54
65 Create a new npm release for this repo. The bump type is: $1 (default to "patch" if not provided).
IMPL-subprocess-subagents.md+172−0
@@ -0,0 +1,172 @@
1+# Implementation Plan: Subprocess Subagents
2+
3+> Design spec: `PLAN-subprocess-subagents.md`
4+
5+Five sequential phases. Each phase leaves the repo in a working, tested state.
6+Phases 1, 2, and 5 are good ralph candidates. Phases 3 and 4 touch the core
7+subprocess/worktree boundary and require manual oversight.
8+
9+---
10+
11+## Phase 1 — Headless mc mode
12+
13+**Goal:** `mc` can be launched as a non-interactive subprocess that runs a single
14+prompt and writes a structured result to a file descriptor before exiting.
15+
16+**New CLI flags:**
17+
18+| Flag | Description |
19+|---|---|
20+| `--subagent` | Headless mode: no banner, no interactive loop, no spinner, no status bar |
21+| `--agent <name>` | Load a custom agent config (system prompt + optional model override) |
22+| `--output-fd <n>` | File descriptor to write the JSON result to before exit |
23+
24+`--cwd`, `--model`, and positional prompt already exist and work unchanged.
25+
26+**Changes:**
27+
28+- Add `--subagent`, `--agent`, `--output-fd` to `parseArgs` in `src/index.ts`
29+- Add a `HeadlessReporter` (implements `AgentReporter`) that no-ops all UI methods
30+- When `--subagent` is set: use `HeadlessReporter`, skip banner, skip input loop,
31+ run a single `runner.processUserInput(prompt)` then exit
32+- Before exit, write `SubagentSummary` JSON to the specified fd:
33+ ```ts
34+ interface SubagentSummary {
35+ result: string;
36+ inputTokens: number;
37+ outputTokens: number;
38+ worktreeBranch?: string; // Phase 4
39+ }
40+ ```
41+- `--agent` loads the agent config from `.agents/agents/` (reuse `loadAgents`),
42+ passes its `systemPrompt` and `model` override into `runAgent`
43+
44+**Exit criteria:**
45+- `bun run src/index.ts --subagent --prompt "say hello" --output-fd 1` prints
46+ valid JSON to stdout
47+- All existing tests pass
48+- No interactive mode regressions
49+
50+---
51+
52+## Phase 2 — Prompt chain + system prompt
53+
54+**Goal:** Correct context file composition and balanced delegation language.
55+
56+**Changes:**
57+
58+- Fix `loadContextFile` in `src/agent/system-prompt.ts`:
59+ - Load global (`~/.agents/AGENTS.md` / `CLAUDE.md`) **and** local
60+ (`.agents/AGENTS.md`, `CLAUDE.md`, `AGENTS.md` at repo root) independently
61+ - Compose both into the system prompt in order: global first, then local
62+ - Neither silently shadows the other
63+- Update delegation guidelines in the system prompt:
64+ - Main agent: *"Use the `subagent` tool sparingly — only for clearly separable,
65+ self-contained subtasks. Prefer doing the work directly."*
66+ - Subagent mode (`--subagent` flag): stronger wording appended — *"You are
67+ running as a subagent. Complete the task directly using your tools. Do not
68+ delegate to further subagents unless the subtask is clearly separable and
69+ self-contained."*
70+- Custom agent system prompt (from `--agent`) appended after local context file,
71+ before the user message
72+
73+**Exit criteria:**
74+- Unit tests for `buildSystemPrompt` covering: no context files, global only,
75+ local only, both, and subagent mode
76+- All existing tests pass
77+
78+---
79+
80+## Phase 3 — Subprocess launcher (replaces subagent-runner)
81+
82+**Goal:** The `subagent` tool spawns a real `mc` subprocess instead of running
83+in-process. Worktrees are temporarily disabled in this phase to keep the diff
84+focused. Non-git projects are unaffected.
85+
86+**Changes:**
87+
88+- Replace `src/agent/subagent-runner.ts` with a subprocess launcher:
89+ - Create a pipe pair; pass the write end as `--output-fd <n>` to the child
90+ - Spawn `mc --subagent --cwd <cwd> --model <model> [--agent <name>] <prompt>`
91+ - Read the write end after the child exits; parse `SubagentSummary`
92+ - Return `SubagentOutput` from the parsed summary
93+- Remove `depth` parameter from `runSubagent` signature
94+- Remove `.filter(tool => tool.name !== "subagent")` guard — subagents get the
95+ full tool set
96+- Track active subprocess PIDs for interrupt propagation (Phase 5)
97+- Worktrees: skipped in this phase — subprocess receives the parent `cwd` directly.
98+ Any worktree code in the old runner is removed but not yet replaced.
99+
100+**⚠ Manual phase** — don't ralph this. Verify by running a real subagent task
101+end-to-end and checking the result comes back correctly.
102+
103+**Exit criteria:**
104+- `@writer` (or any custom agent) delegates correctly via subprocess
105+- A custom command runs correctly via subprocess
106+- Token counts are reported in the completion line
107+- All tests pass (worktree-specific tests may need updating/removal)
108+
109+---
110+
111+## Phase 4 — New worktree model
112+
113+**Goal:** Subprocess creates and owns its worktree; parent owns all merging.
114+Fixes the fragile lifecycle that could lose changes.
115+
116+**New model:**
117+1. Subprocess creates a git worktree from `parentCwd` on branch `mc-sub-<laneId>`
118+2. Subprocess works inside the worktree
119+3. Before exit, subprocess removes the worktree *directory* (keeps the branch)
120+ and includes `worktreeBranch` in the fd result
121+4. Parent receives the branch name and merges it into its own working tree
122+5. Parent deletes the branch after a successful merge
123+6. On merge conflict: parent returns conflict file list in the tool result (same
124+ UX as today)
125+7. Merge lock lives in the parent only — sequential per active lane, no lock
126+ needed inside subprocesses
127+
128+**Changes:**
129+
130+- Add worktree lifecycle into the subprocess (create on start, remove dir on exit)
131+- Add `worktreeBranch` to `SubagentSummary`
132+- Move merge + branch cleanup into the subprocess launcher (parent side)
133+- Remove the old merge lock from `subagent-runner.ts` (already gone after Phase 3)
134+- Update `SubagentOutput` — remove `mergeConflict` / `mergeBlocked` structs;
135+ replace with a single `mergeConflicts?: string[]` returned from the parent's
136+ merge call
137+
138+**⚠ Manual phase** — worktree bugs are silent and destructive. Test with a
139+real multi-file edit subagent task and verify changes land in the working tree.
140+
141+**Exit criteria:**
142+- Subagent edits appear in the parent's working tree after the tool call completes
143+- A parallel subagent pair (two concurrent tool calls) both merge cleanly
144+- Merge conflict case surfaces the right file list to the LLM
145+- All tests pass
146+
147+---
148+
149+## Phase 5 — Cleanup, output, and ESC propagation
150+
151+**Goal:** Remove dead code, simplify UI output, wire up interrupt.
152+
153+**Changes:**
154+
155+- **Output**: subagent tool call display becomes two lines only:
156+ - `⇢ subagent [laneId] — <prompt truncated to ~60 chars>`
157+ - `← subagent [laneId] done (Nin / Nout tokens)` or `✖ failed`
158+ - All intermediate subprocess output is suppressed (headless reporter handles this)
159+- **ESC interrupt**: when the user hits ESC during a turn, send `SIGTERM` to all
160+ tracked active subprocess PIDs before returning to the prompt; subprocesses clean
161+ up their worktree directory on receipt
162+- **Remove `execution: inline`**: delete the field from `CustomCommand`, remove
163+ the branch in the command handler, update `loadCustomCommands` and docs
164+- **Remove dead code**: `getSubagentMergeError`, `mergeConflict`/`mergeBlocked`
165+ fields from old `SubagentOutput`, `syncDirtyStateToWorktree` call in old runner
166+
167+**Exit criteria:**
168+- `bun run jscpd && bun run knip && bun run typecheck && bun run format && bun run lint && bun test`
169+ all pass clean
170+- ESC during a subagent task kills the subprocess and returns to prompt without
171+ leaving orphan worktree directories
172+- No `execution: inline` references remain in source or docs
PLAN-subprocess-subagents.md+153−0
@@ -0,0 +1,153 @@
1+# Plan: Subagents as Subprocess mc Sessions
2+
3+## Problem
4+
5+The current in-process subagent runner is a second-class implementation of the agent loop:
6+
7+- Subagents are less capable than the main agent (different system prompt path, tools stripped)
8+- Subagents don't reliably know their working directory — they guess, causing cascading failures
9+- Subagents can't spawn subagents (the tool is stripped at depth > 0)
10+- Ralph mode is broken inside subagents (the loop logic behaves differently in the stripped-down runner)
11+- The runner duplicates agent bootstrap logic: system prompt building, model resolution, tool set assembly
12+- Worktree lifecycle is fragile — changes can be lost when merge or cleanup ordering goes wrong
13+
14+## Goal
15+
16+Replace `subagent-runner.ts` with a subprocess that launches a fresh `mc` process. A subagent becomes a real mini-coder session, not a stripped-down approximation of one.
17+
18+---
19+
20+## Behaviour Changes
21+
22+### What stays the same (user-visible)
23+
24+- `@agent-name` in a prompt delegates to a custom agent — same syntax, same config format
25+- Custom agent frontmatter (`model`, system prompt body) is still respected
26+- Custom commands fan out to subagents
27+- Git isolation per subagent is preserved
28+- Token counts are still aggregated and shown
29+
30+### What improves (user-visible)
31+
32+- **Subagents are fully capable** — same system prompt, same tools, same loop as the main agent
33+- **Subagents can spawn subagents** — no artificial nesting limit
34+- **Working directory is always correct** — the subprocess is launched with an explicit `--cwd`
35+- **Ralph mode works inside subagents** — it's just a full session flag
36+- **ESC kills the whole chain** — the interrupt signal propagates to every active subprocess
37+
38+### What gets removed
39+
40+- `execution: inline` on custom commands — this was a workaround for worktree issues which the new model resolves. All commands run as subprocesses. Community configs that used `execution: inline` will fall back to subprocess execution.
41+
42+---
43+
44+## Prompt Chain
45+
46+Each mc subprocess assembles its system prompt in this order:
47+
48+1. **Internal prompt** — mini-coder's own instructions (tools, guidelines, date/cwd)
49+2. **Global context file** — `~/.agents/AGENTS.md` (or `CLAUDE.md`)
50+3. **Local context file** — `.agents/AGENTS.md` (or `CLAUDE.md`, or `AGENTS.md` at repo root)
51+4. **Custom agent prompt** — the markdown body from the agent config file (if `--agent <name>` was passed)
52+
53+The **command prompt** (expanded template from e.g. `/review` or a custom command) becomes the first user message — it is not part of the system prompt.
54+
55+Note: the current `loadContextFile` only loads the first file it finds. It must be fixed to load both global and local, composing them in order, so project-level context does not silently shadow global context.
56+
57+---
58+
59+## System Prompt: Avoiding Infinite Delegation
60+
61+The current guidelines actively encourage delegation:
62+
63+> "Use subagents for all tasks that require a lot of context..."
64+> "Keep your context clean and focused on the user request, use subagents to achieve this."
65+
66+This causes models to delegate continuously without doing any actual work. The guidelines need to be rebalanced:
67+
68+- **Main agent**: "Use the `subagent` tool sparingly — only for clearly separable, self-contained subtasks that benefit from a fresh context window. Prefer doing the work directly."
69+- **Subagent sessions** (detected via a `--subagent` flag): stronger wording — "You are running as a subagent. Complete the task you have been given directly using your tools. Do not spawn further subagents unless the subtask is unambiguously separable and self-contained."
70+
71+---
72+
73+## Communication Protocol
74+
75+The parent needs structured data back from the subprocess. A **dedicated pipe on fd 3** is used — this keeps stdout/stderr free and avoids temp file lifecycle issues.
76+
77+The parent opens the write end and passes it as fd 3 to the subprocess. Before exiting, the subprocess writes a single JSON line:
78+
79+```ts
80+interface SubagentSummary {
81+ result: string; // final assistant text from the session
82+ inputTokens: number;
83+ outputTokens: number;
84+ worktreeBranch?: string; // git branch the subprocess worked on
85+}
86+```
87+
88+Merge conflict/blocked status is no longer part of the subprocess result — see Worktrees below.
89+
90+---
91+
92+## Output / UI
93+
94+The current subagent output is noisy and not useful. New model:
95+
96+- **On launch**: one line — `⇢ subagent [laneId] — <truncated prompt>`
97+- **While running**: spinner in the parent ("thinking...")
98+- **On completion**: one line — `← subagent [laneId] done (Nin / Nout tokens)`
99+- **Subprocess's own terminal output is suppressed** — the subprocess runs in headless mode (no spinner, no status bar). Its `result` text is returned to the calling LLM via the fd 3 pipe.
100+
101+---
102+
103+## Worktrees
104+
105+### Model
106+
107+Every subprocess creates and owns its own worktree:
108+
109+1. Subprocess is launched with `--cwd <parentCwd>`
110+2. Subprocess creates a git worktree from `parentCwd` on a new branch (`mc-sub-<laneId>`)
111+3. Subprocess does its work inside the worktree
112+4. Before exit, subprocess removes the worktree directory and writes the branch name in the fd 3 summary
113+5. Parent receives the branch name, **merges it into its own working tree**, then deletes the branch
114+
115+The subprocess never merges — it only creates and cleans up its own worktree directory. The parent owns all merging. This eliminates the merge-lock complexity inside subprocesses and makes merge ordering deterministic in the parent.
116+
117+### Merge conflicts
118+
119+If the parent's merge produces conflicts, it surfaces them to the LLM as it does today (conflict file list in the tool result). The LLM can resolve them or report to the user.
120+
121+### Non-git projects
122+
123+Unchanged — no worktree is created and the subprocess works directly on the `cwd`.
124+
125+---
126+
127+## Interrupt Propagation
128+
129+When the user hits `ESC`:
130+
131+- The parent sends `SIGTERM` to all active subprocess PIDs it is tracking
132+- Each subprocess, on receiving `SIGTERM`, cleans up its own worktree directory (branch is left for the parent to handle or discard), then exits
133+- The parent discards any pending merge for interrupted subagents and cleans up their branches
134+
135+---
136+
137+## What Gets Removed
138+
139+| Item | Reason |
140+|---|---|
141+| `subagent-runner.ts` | Replaced by a thin subprocess launcher |
142+| `depth` parameter | No longer needed — subagents are full sessions |
143+| `.filter(tool => tool.name !== "subagent")` guard | Subagents have the full tool set |
144+| Manual `buildSystemPrompt` / `buildToolSet` in runner | Done by the subprocess itself |
145+| Manual model resolution in runner | Passed as `--model` CLI flag |
146+| `execution: inline` in custom commands | Removed — all commands use subprocess execution |
147+| Merge lock in runner | Merges happen in the parent only, sequentially per-lane |
148+
149+---
150+
151+## Recursion Cap
152+
153+An env-var based cap (`MC_SUBAGENT_DEPTH`, max 10) is retained as a safety rail against runaway delegation chains. Unlike the old in-process `depth` parameter it is not a first-class concern of the runner — it is a background guard. Subagents that hit the cap receive a clear error. In practice the cap is generous enough that it should never be reached in normal use.
TODO.md+70−39
@@ -1,45 +1,80 @@
11 # TODO
22
3----
4-
5-## Usbaility issues:
6-
7-- Subagents are way less competent than the main agent
3+## Investigate error:
84
9-
10-- All models: constant reading almost no action, lot's of wasted tokens, using opencode or claude code is a much more action oriented workflow.
11-- Ralph mode is completly broken, most models just exit the loop without completing anything, or after reading the context.
5+```
6+◆ Now add `renderSubagentStart` and `renderSubagentResult` exports, and remove the subagent no-ops from `renderToolResultInline` and `renderToolResult`. Let me find these:
7+ ← read src/cli/tool-render.ts:90+15
8+ · src/cli/tool-render.ts lines 90–104 of 571 (truncated)
9+◆ Now find the subagent no-op in `renderToolResultInline`:
10+ ← read
11+ ✖ Invalid input for tool read: JSON parsing failed: Text: {"path": "src/cli/tool-render.ts", "line"": 210, "count": 20}.
12+⠹ thinking2522 | const responseBody = await response.text();
13+2523 | const responseHeaders = extractResponseHeaders(response);
14+2524 | if (responseBody.trim() === "") {
15+2525 | return {
16+2526 | responseHeaders,
17+2527 | value: new APICallError4({
18+ ^
19+AI_APICallError: Bad Request
20+ cause: undefined,
21+ url: "https://opencode.ai/zen/v1/messages",
22+ requestBodyValues: {
23+ model: "claude-sonnet-4-6",
24+ max_tokens: 128000,
25+ temperature: undefined,
26+ top_k: undefined,
27+ top_p: undefined,
28+ stop_sequences: undefined,
29+ thinking: [Object ...],
30+ output_config: [Object ...],
31+ system: [
32+ [Object ...]
33+ ],
34+ messages: [
35+ [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Objec …
36+ [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...],
37+ ... 35 more items
38+ ],
39+ tools: [
40+ [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...], [Object ...]
41+ ],
42+ tool_choice: [Object ...],
43+ stream: true,
44+},
45+ statusCode: 400,
46+ responseHeaders: {
47+ "cf-ray": "9da4778aca7960ae-ORD",
48+ connection: "keep-alive",
49+ "content-type": "application/json",
50+ date: "Tue, 10 Mar 2026 18:43:47 GMT",
51+ server: "cloudflare",
52+ "transfer-encoding": "chunked",
53+},
54+ responseBody: "",
55+ isRetryable: false,
56+ data: undefined,
57+ vercel.ai.error: true,
58+ vercel.ai.error.AI_APICallError: true,
59+
60+ at /home/xonecas/src/mini-coder/node_modules/@ai-sdk/provider-utils/dist/index.mjs:2527:18
61+ at /home/xonecas/src/mini-coder/node_modules/@ai-sdk/provider-utils/dist/index.mjs:2388:34
62+ at processTicksAndRejections (native:7:39)
63+
64+✖ API error 400
65+ https://opencode.ai/zen/v1/messages
66+✖ API error 400
67+ https://opencode.ai/zen/v1/messages
68+error: script "dev" exited with code 1
69+```
1270
1371 ---
1472
15-## Subagents don't know where they are:
73+## Usbaility issues:
1674
17-Subagents are trying to guess paths, this is terrible... We need to make sure subagents don't make stupid mistakes like this, it breaks trust, and trust in LLM's is already at an all time low.
75+- **Rewrite subagents as subprocess `mc` sessions** — see `PLAN-subprocess-subagents.md`. The in-process runner is a second-class agent: it guesses paths, can't recurse, breaks Ralph mode, and produces lower-quality output than the main agent. Spawning a real `mc` subprocess fixes all of this in one move while keeping custom agent/command configs fully compatible.
1876
19-```
20-▶ @TODO.md let's tackle the first todo and make propper use of shadcn and make a custom theme.
21- ⇢ subagent Read these files and return their full contents:
22-1. ~/src…
23- ⇢ subagent In the directory ~/src/99prompt/web, find and return the …
24-[ff476f3f] ← read ~/src/99prompt/web/idea.md
25-[ff476f3f] ✖ File not found: ~/src/99prompt/web/idea.md
26-[ff476f3f] ← read ~/src/99prompt/web/website.md
27-[ff476f3f] ✖ File not found: ~/src/99prompt/web/website.md
28-[ff476f3f] ← read ~/src/99prompt/web/src/app/globals.css
29-[ff476f3f] ✖ File not found: ~/src/99prompt/web/src/app/globals.css
30-[ff476f3f] ← read ~/src/99prompt/web/components.json
31-[ff476f3f] ✖ File not found: ~/src/99prompt/web/components.json
32-[76f32dc8] ? glob /Users/*/src/99prompt/web/src/components/ui/**/*
33-[76f32dc8] · 1 file
34-[76f32dc8] ? glob /Users/*/src/99prompt/web/src/app/**/layout.tsx
35-[76f32dc8] · 3 files
36-[76f32dc8] ? glob /Users/*/src/99prompt/web/src/app/[locale]/page.tsx
37-[76f32dc8] · no matches
38-[ff476f3f] $ echo $HOME
39-[ff476f3f] ✔ 0
40-[ff476f3f] ← read /Users/seancaetanomartin/src/99prompt/web/idea.md
41-[ff476f3f] · 31 lines
42-```
77+- All models: constant reading almost no action, lot's of wasted tokens, using opencode or claude code is a much more action oriented workflow.
4378
4479 ---
4580
@@ -52,16 +87,12 @@ Subagents are trying to guess paths, this is terrible... We need to make sure su
5287
5388 # Post v1.0.0 work:
5489
55-## Custom commands vs built-in commands vs subagents
56-
57-We currently have a ton of overlap with these features, Commands run within subagents, some commands come from custom configs others are baked in.
90+## Custom commands vs built-in commands
5891
5992 Let's clean things up:
6093
6194 - `/review` command should use the same code as a custom-commands, consolidate the two. We can create the global `/review` command in `~/.agents/commands` at app start if it doesn't exist. That way it can be a pure custom command and the users are encouraged to edit it for their own custom reviews. Never overwrite the file if it exists. Print a line notifying the user that the command was created.
6295
63-- Custom commands and custom subagents: Custom commands just spawn generic subagents with a dedicated prompt, custom agents are just subagents with a dedicated system prompt and a main agent provided prompt. I believe these are already well implemented, and share most of the code.
64-
6596 ---
6697
6798 ## LSP Diagnostics (not very important, with tool-hooks and strong linting, this is not as necessary, but we should implement asap)
docs/custom-commands.md+0−21
@@ -39,7 +39,6 @@ Then in the REPL:
3939 |---|---|---|
4040 | `description` | No | Shown in `/help`. Defaults to the command name. |
4141 | `model` | No | Override the active model for this command (subagent execution). |
42-| `execution` | No | Where the command runs: `subagent` (default) or `inline`. |
4342
4443
4544 ## Arguments
@@ -120,26 +119,6 @@ List each occurrence with file path and line number. No explanations needed.
120119
121120 Large models for deep analysis, small models for search and lookup.
122121
123-## Execution mode
124-
125-By default, commands run with `execution: subagent` (even if `execution`
126-is omitted).
127-
128-Use `execution: inline` to run the command in the main agent context
129-instead of spawning a subagent worktree.
130-
131-```md
132----
133-description: Safe release flow
134-execution: inline
135----
136-
137-Run the release steps in this main repo checkout.
138-```
139-
140-Use `inline` for repo-sensitive workflows (like release flows) where branch
141-context must be exactly the current session branch.
142-
143122
144123 ## Precedence
145124
mini-coder-idea.md+2−1
@@ -27,6 +27,7 @@ conventions and not introduce more specs. (skills.sh installs to `.agents,AGENTS
2727 - Press `ESC` at any point during an assistant response to interrupt it: the partial response is preserved in history with an interrupt stub appended (so the LLM retains context), and the user is returned to the prompt silently. `ctrl+c` exits the app. `ctrl+d` (EOF) also exits.
2828
2929 - `glob`, `grep`, `read`, `replace`,`insert`, `create`, `shell`, and `subagent` tools for LLMs
30+- `subagent` tool spawns a fresh `mc` subprocess — full capability parity with the main agent, correct working directory, and support for recursive subagents. Custom agents (from `.agents/agents/`) and custom commands (from `.agents/commands/`) are fully supported in subagents.
3031 - tool hooks support (do command automatically after certain tools)
3132 - Commands in CLI prompt:
3233 - `/model` command allows the user to pick a model from connected providers. As well as thinking effort for the model if supported. Selection persists accross sessions.
@@ -64,6 +65,6 @@ Core modules:
6465 - `llm-api`: Provides the api to intereact with the provider and process the full conversation turn + tool calling.
6566 - `cli`: Output/UI
6667 - `agent`: Main agent implementation
67-- `tools/subagent`: subagent tool implementation
68+- `tools/subagent`: subagent tool — spawns a fresh `mc` subprocess, handles worktree lifecycle and structured result handback
6869 - `tools/read-write-shell`: all of the tools that use the local filesystem/shell
6970 - `mcp`: handles connecting to mcp servers
src/agent/agent-helpers.ts+19−0
@@ -17,6 +17,25 @@ export function makeInterruptMessage(reason: "user" | "error"): CoreMessage {
1717 return { role: "assistant", content: text };
1818 }
1919
20+export function isAbortError(error: Error): boolean {
21+ return (
22+ error.name === "AbortError" ||
23+ (error.name === "Error" && error.message.toLowerCase().includes("abort"))
24+ );
25+}
26+
27+export function buildAbortMessages(
28+ partialMessages: CoreMessage[],
29+ accumulatedText?: string,
30+): CoreMessage[] {
31+ const stub = makeInterruptMessage("user");
32+ const content = accumulatedText
33+ ? `${accumulatedText}${stub.content}`
34+ : (stub.content as string);
35+ const partialMsg: CoreMessage = { role: "assistant", content };
36+ return [...partialMessages, partialMsg];
37+}
38+
2039 export function extractAssistantText(newMessages: CoreMessage[]): string {
2140 const parts: string[] = [];
2241 for (const msg of newMessages) {
src/agent/agent.ts+23−9
@@ -10,6 +10,7 @@ import {
1010 setPreferredModel,
1111 setPreferredThinkingEffort,
1212 } from "../session/db/index.ts";
13+import type { SubagentSummary } from "../tools/subagent.ts";
1314 import { getGitBranch } from "./agent-helpers.ts";
1415 import { runInputLoop } from "./input-loop.ts";
1516 import type { AgentReporter } from "./reporter.ts";
@@ -25,24 +26,23 @@ interface AgentOptions {
2526 sessionId?: string;
2627 initialPrompt?: string;
2728 reporter: AgentReporter;
29+ headless?: boolean;
30+ agentSystemPrompt?: string;
2831 }
2932
30-export async function runAgent(opts: AgentOptions): Promise<void> {
33+export async function runAgent(
34+ opts: AgentOptions,
35+): Promise<SubagentSummary | undefined> {
3136 const cwd = opts.cwd;
3237 let currentModel = opts.model;
33- let currentThinkingEffort = opts.initialThinkingEffort;
3438
35- const runSubagent = createSubagentRunner(
39+ const { runSubagent, killAll } = createSubagentRunner(
3640 cwd,
37- opts.reporter,
3841 () => currentModel,
39- () => currentThinkingEffort,
4042 );
41-
4243 const agents = loadAgents(cwd);
4344 const tools: ToolDef[] = buildToolSet({
4445 cwd,
45- depth: 0,
4646 runSubagent,
4747 onHook: (tool, path, ok) => opts.reporter.renderHook(tool, path, ok),
4848 availableAgents: agents,
@@ -84,6 +84,9 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
8484 initialModel: currentModel,
8585 initialThinkingEffort: opts.initialThinkingEffort,
8686 sessionId: opts.sessionId,
87+ extraSystemPrompt: opts.agentSystemPrompt,
88+ isSubagent: opts.headless,
89+ killSubprocesses: killAll,
8790 });
8891
8992 const cmdCtx: CommandContext = {
@@ -102,7 +105,6 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
102105 setThinkingEffort: (e) => {
103106 runner.currentThinkingEffort = e;
104107 setPreferredThinkingEffort(e);
105- currentThinkingEffort = e;
106108 },
107109 get planMode() {
108110 return runner.planMode;
@@ -117,7 +119,7 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
117119 runner.planMode = v;
118120 },
119121 cwd,
120- runSubagent: (prompt, model?) => runSubagent(prompt, 0, undefined, model),
122+ runSubagent: (prompt, model?) => runSubagent(prompt, undefined, model),
121123
122124 undoLastTurn: () =>
123125 undoLastTurn({
@@ -156,6 +158,16 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
156158 });
157159 }
158160
161+ if (opts.headless) {
162+ const prompt = opts.initialPrompt ?? "";
163+ const result = await runner.processUserInput(prompt);
164+ return {
165+ result,
166+ inputTokens: runner.totalIn,
167+ outputTokens: runner.totalOut,
168+ };
169+ }
170+
159171 if (opts.initialPrompt) {
160172 await runner.processUserInput(opts.initialPrompt);
161173 }
@@ -167,4 +179,6 @@ export async function runAgent(opts: AgentOptions): Promise<void> {
167179 runner,
168180 renderStatusBar: renderStatusBarForSession,
169181 });
182+
183+ return undefined;
170184 }
src/agent/reporter.ts+0−8
@@ -22,13 +22,6 @@ export interface StatusBarData {
2222 thinkingEffort?: string | null;
2323 }
2424
25-export interface SubagentEventData {
26- laneId: string;
27- parentLabel?: string;
28- hasWorktree?: boolean;
29- activeLanes: Set<string>;
30-}
31-
3225 export interface AgentReporter {
3326 info(msg: string): void;
3427 error(msg: string | Error, hint?: string): void;
@@ -39,7 +32,6 @@ export interface AgentReporter {
3932 stopSpinner(): void;
4033
4134 renderTurn(events: AsyncIterable<TurnEvent>): Promise<TurnResult>;
42- renderSubagentEvent(event: TurnEvent, data: SubagentEventData): void;
4335 renderStatusBar(data: StatusBarData): void;
4436 renderHook(toolName: string, scriptPath: string, success: boolean): void;
4537
src/agent/session-runner.ts+21−1
@@ -35,6 +35,9 @@ interface SessionRunnerOptions {
3535 initialModel: string;
3636 initialThinkingEffort: ThinkingEffort | null;
3737 sessionId?: string | undefined;
38+ extraSystemPrompt?: string | undefined;
39+ isSubagent?: boolean | undefined;
40+ killSubprocesses?: (() => void) | undefined;
3841 }
3942
4043 export class SessionRunner {
@@ -56,6 +59,9 @@ export class SessionRunner {
5659 public totalIn = 0;
5760 public totalOut = 0;
5861 public lastContextTokens = 0;
62+ private extraSystemPrompt: string | undefined;
63+ private isSubagent: boolean | undefined;
64+ private killSubprocesses: (() => void) | undefined;
5965
6066 constructor(opts: SessionRunnerOptions) {
6167 this.cwd = opts.cwd;
@@ -64,6 +70,9 @@ export class SessionRunner {
6470 this.mcpTools = opts.mcpTools;
6571 this.currentModel = opts.initialModel;
6672 this.currentThinkingEffort = opts.initialThinkingEffort;
73+ this.extraSystemPrompt = opts.extraSystemPrompt;
74+ this.isSubagent = opts.isSubagent;
75+ this.killSubprocesses = opts.killSubprocesses;
6776 this.initSession(opts.sessionId);
6877 }
6978
@@ -105,6 +114,12 @@ export class SessionRunner {
105114 const abortController = new AbortController();
106115 const stopWatcher = watchForCancel(abortController);
107116
117+ if (this.killSubprocesses) {
118+ const killSubs = this.killSubprocesses;
119+ abortController.signal.addEventListener("abort", () => {
120+ killSubs();
121+ });
122+ }
108123 const { text: resolvedText, images: refImages } = await resolveFileRefs(
109124 text,
110125 this.cwd,
@@ -140,7 +155,12 @@ export class SessionRunner {
140155 this.coreHistory.push(userMsg);
141156
142157 const llm = resolveModel(this.currentModel);
143- const systemPrompt = buildSystemPrompt(this.cwd, this.currentModel);
158+ const systemPrompt = buildSystemPrompt(
159+ this.cwd,
160+ this.currentModel,
161+ this.extraSystemPrompt,
162+ this.isSubagent,
163+ );
144164
145165 let lastAssistantText = "";
146166
src/agent/subagent-runner.ts+140−153
@@ -1,192 +1,179 @@
1-import { tmpdir } from "node:os";
2-import { join } from "node:path";
3-import { loadAgents } from "../cli/agents.ts";
4-import { formatSubagentLabel } from "../cli/output.ts";
5-import type { ThinkingEffort } from "../llm-api/providers.ts";
6-import { resolveModel } from "../llm-api/providers.ts";
7-import { type CoreMessage, runTurn } from "../llm-api/turn.ts";
8-import type { SubagentOutput } from "../tools/subagent.ts";
1+import type { SubagentOutput, SubagentSummary } from "../tools/subagent.ts";
92 import {
103 cleanupBranch,
11- createWorktree,
12- initializeWorktree,
13- isGitRepo,
144 MergeInProgressError,
155 mergeWorktree,
16- removeWorktree,
17- syncDirtyStateToWorktree,
186 } from "../tools/worktree.ts";
19-import type { AgentReporter } from "./reporter.ts";
20-import { buildSystemPrompt } from "./system-prompt.ts";
21-import { buildToolSet } from "./tools.ts";
227
23-function makeWorktreeBranch(laneId: string): string {
24- return `mc-sub-${laneId}`;
8+/**
9+ * Resolve the command to invoke a new `mc` subprocess.
10+ * - Dev: process.argv[1] ends with ".ts" → [bun, script]
11+ * - Prod: compiled binary → [process.execPath]
12+ */
13+function getMcCommand(): string[] {
14+ const script = process.argv[1];
15+ if (script?.endsWith(".ts")) {
16+ return [process.execPath, script];
17+ }
18+ return [process.execPath];
2519 }
2620
27-function makeWorktreePath(laneId: string): string {
28- return join(tmpdir(), `mc-wt-${laneId}`);
29-}
21+// Loose recursion cap passed via environment so subprocess chains are bounded
22+// without an in-process depth parameter. Generous enough for real use-cases.
23+const MAX_SUBAGENT_DEPTH = 10;
3024
3125 export function createSubagentRunner(
3226 cwd: string,
33- reporter: AgentReporter,
3427 getCurrentModel: () => string,
35- getThinkingEffort: () => ThinkingEffort | null,
3628 ) {
37- const activeLanes = new Set<string>();
38- const worktreesEnabledPromise = isGitRepo(cwd);
39-
40- let mergeLock: Promise<void> = Promise.resolve();
41- const withMergeLock = <T>(fn: () => Promise<T>): Promise<T> => {
42- const task = mergeLock.then(fn, fn);
43- mergeLock = task.then(
44- () => undefined,
45- () => undefined,
46- );
47- return task;
29+ // Active subprocesses — maps proc to branch name (if any) for interrupt cleanup.
30+ const activeProcs = new Map<
31+ ReturnType<typeof Bun.spawn>,
32+ string | undefined
33+ >();
34+
35+ // Depth is injected by the parent subprocess via MC_SUBAGENT_DEPTH env var.
36+ const subagentDepth = parseInt(process.env.MC_SUBAGENT_DEPTH ?? "0", 10);
37+
38+ // Merge lock: serialises merge operations from concurrent subagents.
39+ let mergeLockTail = Promise.resolve();
40+
41+ const mergeSubagentBranch = async (
42+ branch: string,
43+ ): Promise<{ mergeConflicts?: string[] }> => {
44+ const prev = mergeLockTail;
45+ let releaseLock!: () => void;
46+ mergeLockTail = new Promise((resolve) => {
47+ releaseLock = resolve;
48+ });
49+ try {
50+ await prev;
51+ const result = await mergeWorktree(cwd, branch);
52+ if (result.success) {
53+ await cleanupBranch(cwd, branch);
54+ return {};
55+ }
56+ // Merge produced conflicts — leave branch for user to resolve.
57+ return { mergeConflicts: result.conflictFiles };
58+ } catch (err) {
59+ if (err instanceof MergeInProgressError) {
60+ // Another merge is in progress — return its conflict files.
61+ return { mergeConflicts: err.conflictFiles };
62+ }
63+ throw err;
64+ } finally {
65+ releaseLock();
66+ }
4867 };
4968
5069 const runSubagent = async (
5170 prompt: string,
52- depth = 0,
5371 agentName?: string,
5472 modelOverride?: string,
55- parentLabel?: string,
73+ _parentLabel?: string,
5674 ): Promise<SubagentOutput> => {
57- const laneId = crypto.randomUUID().split("-")[0] as string;
58- activeLanes.add(laneId);
75+ if (subagentDepth >= MAX_SUBAGENT_DEPTH) {
76+ throw new Error(
77+ `Subagent recursion limit reached (depth ${subagentDepth}). ` +
78+ `Cannot spawn another subagent.`,
79+ );
80+ }
5981
60- let subagentCwd = cwd;
61- let worktreeBranch: string | undefined;
62- let worktreePath: string | undefined;
63- let preserveBranchOnFailure = false;
82+ const model = modelOverride ?? getCurrentModel();
83+ // Parent generates the branch name so it can clean it up on interrupt.
84+ const laneId = crypto.randomUUID().slice(0, 8);
85+ const worktreeBranch = `mc-sub-${laneId}`;
86+ const cmd = [
87+ ...getMcCommand(),
88+ "--subagent",
89+ "--cwd",
90+ cwd,
91+ "--model",
92+ model,
93+ "--output-fd",
94+ "3",
95+ "--worktree-branch",
96+ worktreeBranch,
97+ ...(agentName ? ["--agent", agentName] : []),
98+ prompt,
99+ ];
100+
101+ const proc = Bun.spawn({
102+ cmd,
103+ env: {
104+ ...process.env,
105+ MC_SUBAGENT_DEPTH: String(subagentDepth + 1),
106+ },
107+ stdio: ["ignore", "inherit", "inherit", "pipe"],
108+ });
109+
110+ activeProcs.set(proc, worktreeBranch);
64111
65112 try {
66- const worktreesEnabled = await worktreesEnabledPromise;
67- if (worktreesEnabled) {
68- const nextBranch = makeWorktreeBranch(laneId);
69- const nextPath = makeWorktreePath(laneId);
70- await createWorktree(cwd, nextBranch, nextPath);
71- worktreeBranch = nextBranch;
72- worktreePath = nextPath;
73- await syncDirtyStateToWorktree(cwd, nextPath);
74- await initializeWorktree(cwd, nextPath);
75- subagentCwd = nextPath;
113+ const [text] = await Promise.all([
114+ Bun.file(proc.stdio[3] as unknown as number).text(),
115+ proc.exited,
116+ ]);
117+
118+ const trimmed = text.trim();
119+ if (!trimmed) {
120+ throw new Error(
121+ `Subagent subprocess produced no output (exit code ${String(proc.exitCode)})`,
122+ );
76123 }
77124
78- const currentModel = getCurrentModel();
79- const allAgents = loadAgents(subagentCwd);
80- const agentConfig = agentName ? allAgents.get(agentName) : undefined;
81- if (agentName && !agentConfig) {
125+ let parsed: SubagentSummary & { error?: string };
126+ try {
127+ parsed = JSON.parse(trimmed) as SubagentSummary & { error?: string };
128+ } catch {
82129 throw new Error(
83- `Unknown agent "${agentName}". Available agents: ${[...allAgents.keys()].join(", ") || "(none)"}`,
130+ `Subagent subprocess wrote non-JSON output (exit code ${String(proc.exitCode)}): ${trimmed.slice(0, 200)}`,
84131 );
85132 }
86133
87- const model = modelOverride ?? agentConfig?.model ?? currentModel;
88- const systemPrompt =
89- agentConfig?.systemPrompt ?? buildSystemPrompt(subagentCwd, model);
90-
91- const subMessages: CoreMessage[] = [{ role: "user", content: prompt }];
92- const laneLabel = formatSubagentLabel(laneId, parentLabel);
93-
94- const subTools = buildToolSet({
95- cwd: subagentCwd,
96- depth,
97- runSubagent,
98- onHook: (tool, path, ok) => reporter.renderHook(tool, path, ok),
99- availableAgents: allAgents,
100- parentLabel: laneLabel,
101- }).filter((tool) => tool.name !== "subagent");
102-
103- const subLlm = resolveModel(model);
104-
105- let result = "";
106- let inputTokens = 0;
107- let outputTokens = 0;
108-
109- const effort = getThinkingEffort();
110- const events = runTurn({
111- model: subLlm,
112- modelString: model,
113- messages: subMessages,
114- tools: subTools,
115- systemPrompt,
116- ...(effort ? { thinkingEffort: effort } : {}),
117- });
118-
119- for await (const event of events) {
120- reporter.stopSpinner();
121- reporter.renderSubagentEvent(event, {
122- laneId,
123- ...(parentLabel ? { parentLabel } : {}),
124- hasWorktree: !!worktreeBranch,
125- activeLanes,
126- });
127- reporter.startSpinner("thinking");
128- if (event.type === "text-delta") result += event.delta;
129- if (event.type === "turn-complete") {
130- inputTokens = event.inputTokens;
131- outputTokens = event.outputTokens;
132- }
134+ if (parsed.error) {
135+ throw new Error(`Subagent failed: ${parsed.error}`);
136+ }
137+ if (proc.exitCode !== 0) {
138+ throw new Error(
139+ `Subagent process exited with code ${String(proc.exitCode)}`,
140+ );
133141 }
134142
135- const baseOutput: SubagentOutput = { result, inputTokens, outputTokens };
136- const branch = worktreeBranch;
137- const path = worktreePath;
138- if (!branch || !path) return baseOutput;
143+ const output: SubagentOutput = {
144+ result: parsed.result,
145+ inputTokens: parsed.inputTokens,
146+ outputTokens: parsed.outputTokens,
147+ };
139148
140- preserveBranchOnFailure = true;
141- return await withMergeLock(async () => {
142- try {
143- const mergeResult = await mergeWorktree(cwd, branch);
144- await removeWorktree(cwd, path);
145- if (mergeResult.success) {
146- await cleanupBranch(cwd, branch);
147- return baseOutput;
148- }
149- return {
150- ...baseOutput,
151- mergeConflict: {
152- branch,
153- conflictFiles: mergeResult.conflictFiles,
154- },
155- };
156- } catch (error) {
157- if (error instanceof MergeInProgressError) {
158- await removeWorktree(cwd, path);
159- return {
160- ...baseOutput,
161- mergeBlocked: {
162- branch,
163- conflictFiles: error.conflictFiles,
164- },
165- };
166- }
167- throw error;
168- }
169- });
170- } catch (error) {
Cut short: this commit's diff is over 1000 lines.
src/agent/system-prompt.test.ts+194−0
Cut short: this commit's diff is over 1000 lines.
src/agent/system-prompt.ts+53−22
Cut short: this commit's diff is over 1000 lines.
src/agent/tools.ts+4−17
Cut short: this commit's diff is over 1000 lines.
src/cli/commands.ts+2−11
Cut short: this commit's diff is over 1000 lines.
src/cli/custom-commands.test.ts+0−11
Cut short: this commit's diff is over 1000 lines.
src/cli/custom-commands.ts+0−3
Cut short: this commit's diff is over 1000 lines.
src/cli/frontmatter.test.ts+1−2
Cut short: this commit's diff is over 1000 lines.
src/cli/frontmatter.ts+0−2
Cut short: this commit's diff is over 1000 lines.
src/cli/headless-reporter.ts+61−0
Cut short: this commit's diff is over 1000 lines.
src/cli/output-reporter.ts+0−6
Cut short: this commit's diff is over 1000 lines.
src/cli/output.ts+1−5
Cut short: this commit's diff is over 1000 lines.
src/cli/stream-render.ts+13−16
Cut short: this commit's diff is over 1000 lines.
src/cli/tool-render.ts+27−207
Cut short: this commit's diff is over 1000 lines.
src/index.ts+122−0
Cut short: this commit's diff is over 1000 lines.
src/session/db/connection.ts+1−1
Cut short: this commit's diff is over 1000 lines.
src/tools/subagent.ts+13−32
Cut short: this commit's diff is over 1000 lines.
src/tools/worktree.test.ts+0−37
Cut short: this commit's diff is over 1000 lines.
src/tools/worktree.ts+1−91
Cut short: this commit's diff is over 1000 lines.