@@ -1,292 +0,0 @@
1-import { resolveProcessScriptPath } from "../internal/runtime/script.ts";
2-import type { SubagentOutput, SubagentSummary } from "../tools/subagent.ts";
3-
4-/**
5- * Resolve the command to invoke a new `mc` subprocess.
6- * - Dev / installed JS: Bun runs a script entrypoint → [bun, script]
7- * - Compiled binary: no script entrypoint is available → [process.execPath]
8- */
9-export function resolveMcCommand(
10- execPath: string,
11- mainModule: string | undefined,
12- argv1: string | undefined,
13-): string[] {
14- const script = resolveProcessScriptPath(mainModule, argv1);
15- if (script) {
16- return [execPath, script];
17- }
18- return [execPath];
19-}
20-
21-function getMcCommand(): string[] {
22- return resolveMcCommand(process.execPath, Bun.main, process.argv[1]);
23-}
24-
25-// Loose recursion cap passed via environment so subprocess chains are bounded
26-// without an in-process depth parameter. Generous enough for real use-cases.
27-const MAX_SUBAGENT_DEPTH = 10;
28-
29-class TailByteBuffer {
30- private readonly ring: Uint8Array;
31- private writePos = 0;
32- private totalSeen = 0;
33-
34- constructor(private readonly maxBytes: number) {
35- this.ring = new Uint8Array(Math.max(0, maxBytes));
36- }
37-
38- push(chunk: Uint8Array): void {
39- if (this.maxBytes <= 0 || chunk.length === 0) return;
40-
41- let offset = 0;
42- while (offset < chunk.length) {
43- const remaining = chunk.length - offset;
44- const writable = Math.min(this.maxBytes - this.writePos, remaining);
45- this.ring.set(chunk.subarray(offset, offset + writable), this.writePos);
46- this.writePos = (this.writePos + writable) % this.maxBytes;
47- offset += writable;
48- this.totalSeen += writable;
49- }
50- }
51-
52- toUint8Array(): Uint8Array {
53- if (this.maxBytes <= 0) return new Uint8Array(0);
54- const kept = Math.min(this.totalSeen, this.maxBytes);
55- if (kept === 0) return new Uint8Array(0);
56- if (this.totalSeen <= this.maxBytes) return this.ring.subarray(0, kept);
57-
58- const out = new Uint8Array(kept);
59- const tailBytes = this.ring.subarray(this.writePos);
60- out.set(tailBytes, 0);
61- out.set(this.ring.subarray(0, this.writePos), tailBytes.length);
62- return out;
63- }
64-}
65-
66-function tailBytesFromChunks(
67- chunks: readonly Uint8Array[],
68- maxBytes: number,
69-): Uint8Array {
70- const buffer = new TailByteBuffer(maxBytes);
71- for (const chunk of chunks) {
72- buffer.push(chunk);
73- }
74- return buffer.toUint8Array();
75-}
76-
77-export function tailTextFromChunks(
78- chunks: readonly Uint8Array[],
79- maxBytes: number,
80-): string {
81- return new TextDecoder().decode(tailBytesFromChunks(chunks, maxBytes));
82-}
83-
84-async function drainTail(
85- stream: ReadableStream | null,
86- maxBytes = 8192,
87-): Promise<string> {
88- if (!stream) return "";
89- const reader = stream.getReader();
90- const buffer = new TailByteBuffer(maxBytes);
91-
92- try {
93- while (true) {
94- const { done, value } = await reader.read();
95- if (done) break;
96- if (value) {
97- buffer.push(value as Uint8Array);
98- }
99- }
100- } finally {
101- reader.releaseLock();
102- }
103-
104- return new TextDecoder().decode(buffer.toUint8Array());
105-}
106-
107-function formatSubagentDiagnostics(stdout: string, stderr: string): string {
108- const lines = [...stderr.split("\n"), ...stdout.split("\n")]
109- .map((line) => line.trim())
110- .filter(Boolean);
111- if (lines.length === 0) return "";
112- const tail = lines.slice(-6).join(" | ");
113- return ` (diagnostics: ${tail.slice(0, 300)})`;
114-}
115-
116-async function resolveDiagnostics(opts: {
117- stdoutTail: Promise<string>;
118- stderrTail: Promise<string>;
119-}): Promise<string> {
120- const [stdout, stderr] = await Promise.all([
121- opts.stdoutTail,
122- opts.stderrTail,
123- ]);
124- return formatSubagentDiagnostics(stdout, stderr);
125-}
126-
127-/**
128- * Parse the structured output from a subagent subprocess.
129- * Returns the parsed summary on success, or an error message string on failure.
130- */
131-export function parseSubagentOutput(
132- rawText: string,
133- exitCode: number | null,
134-): SubagentSummary | string {
135- const trimmed = rawText.trim();
136- if (!trimmed) {
137- return `Subagent subprocess produced no output (exit code ${String(exitCode)})`;
138- }
139-
140- let parsed: SubagentSummary & { error?: string };
141- try {
142- parsed = JSON.parse(trimmed) as SubagentSummary & { error?: string };
143- } catch {
144- return `Subagent subprocess wrote non-JSON output (exit code ${String(exitCode)}): ${trimmed.slice(0, 200)}`;
145- }
146-
147- if (parsed.error) {
148- return `Subagent failed: ${parsed.error}`;
149- }
150- if (exitCode !== 0) {
151- return `Subagent process exited with code ${String(exitCode)}`;
152- }
153-
154- return parsed;
155-}
156-
157-export function createSubagentRunner(
158- cwd: string,
159- getCurrentModel: () => string,
160-) {
161- // Active subprocesses for interrupt cleanup.
162- const activeProcs = new Set<ReturnType<typeof Bun.spawn>>();
163-
164- // Depth is injected by the parent subprocess via MC_SUBAGENT_DEPTH env var.
165- const subagentDepth = Number.parseInt(
166- process.env.MC_SUBAGENT_DEPTH ?? "0",
167- 10,
168- );
169-
170- const runSubagent = async (
171- prompt: string,
172- agentName?: string,
173- modelOverride?: string,
174- abortSignal?: AbortSignal,
175- ): Promise<SubagentOutput> => {
176- if (subagentDepth >= MAX_SUBAGENT_DEPTH) {
177- throw new Error(
178- `Subagent recursion limit reached (depth ${subagentDepth}). ` +
179- `Cannot spawn another subagent.`,
180- );
181- }
182-
183- if (abortSignal?.aborted) {
184- throw new DOMException(
185- "Subagent execution was interrupted",
186- "AbortError",
187- );
188- }
189-
190- const model = modelOverride ?? getCurrentModel();
191- const cmd = [
192- ...getMcCommand(),
193- "--subagent",
194- "--cwd",
195- cwd,
196- "--model",
197- model,
198- "--output-fd",
199- "3",
200- ...(agentName ? ["--agent", agentName] : []),
201- prompt,
202- ];
203-
204- const proc = Bun.spawn({
205- cmd,
206- env: {
207- ...process.env,
208- MC_SUBAGENT_DEPTH: String(subagentDepth + 1),
209- },
210- // Keep subagent stdout/stderr isolated so transient tool errors or warnings
211- // don't leak into the parent UI. We only surface these streams on failure.
212- stdio: ["ignore", "pipe", "pipe", "pipe"],
213- });
214-
215- activeProcs.add(proc);
216-
217- let aborted = false;
218- const onAbort = () => {
219- aborted = true;
220- try {
221- proc.kill("SIGTERM");
222- } catch {
223- /* process may have already exited */
224- }
225- };
226-
227- if (abortSignal) {
228- abortSignal.addEventListener("abort", onAbort);
229- }
230-
231- const stdoutTail = drainTail(proc.stdout).catch(() => "");
232- const stderrTail = drainTail(proc.stderr).catch(() => "");
233-
234- try {
235- const [text] = await Promise.all([
236- Bun.file(proc.stdio[3] as number).text(),
237- proc.exited,
238- ]);
239-
240- if (aborted || abortSignal?.aborted) {
241- throw new DOMException(
242- "Subagent execution was interrupted",
243- "AbortError",
244- );
245- }
246-
247- const parsed = parseSubagentOutput(text, proc.exitCode);
248- if (typeof parsed === "string") {
249- const diagnostics = await resolveDiagnostics({
250- stdoutTail,
251- stderrTail,
252- });
253- throw new Error(`${parsed}${diagnostics}`);
254- }
255-
256- const output: SubagentOutput = {
257- result: parsed.result,
258- inputTokens: parsed.inputTokens,
259- outputTokens: parsed.outputTokens,
260- };
261- if (agentName) output.agentName = agentName;
262-
263- return output;
264- } catch (error) {
265- if (aborted || abortSignal?.aborted) {
266- throw new DOMException(
267- "Subagent execution was interrupted",
268- "AbortError",
269- );
270- }
271- throw error;
272- } finally {
273- if (abortSignal) {
274- abortSignal.removeEventListener("abort", onAbort);
275- }
276- activeProcs.delete(proc);
277- }
278- };
279-
280- return {
281- runSubagent,
282- killAll: () => {
283- for (const proc of activeProcs) {
284- try {
285- proc.kill("SIGTERM");
286- } catch {
287- // Process may have already exited.
288- }
289- }
290- },
291- };
292-}