@dreb/coding-agent 2.18.0 → 2.19.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -0
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +3 -2
- package/dist/cli/args.js.map +1 -1
- package/dist/cli/file-processor.d.ts.map +1 -1
- package/dist/cli/file-processor.js +3 -2
- package/dist/cli/file-processor.js.map +1 -1
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +6 -5
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/buddy/buddy-controller.d.ts.map +1 -1
- package/dist/core/buddy/buddy-controller.js +3 -2
- package/dist/core/buddy/buddy-controller.js.map +1 -1
- package/dist/core/event-bus.d.ts.map +1 -1
- package/dist/core/event-bus.js +2 -1
- package/dist/core/event-bus.js.map +1 -1
- package/dist/core/logger.d.ts +29 -0
- package/dist/core/logger.d.ts.map +1 -0
- package/dist/core/logger.js +54 -0
- package/dist/core/logger.js.map +1 -0
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/model-resolver.js +3 -2
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/package-manager.d.ts.map +1 -1
- package/dist/core/package-manager.js +25 -2
- package/dist/core/package-manager.js.map +1 -1
- package/dist/core/stderr-guard.d.ts +37 -0
- package/dist/core/stderr-guard.d.ts.map +1 -0
- package/dist/core/stderr-guard.js +90 -0
- package/dist/core/stderr-guard.js.map +1 -0
- package/dist/core/timings.d.ts.map +1 -1
- package/dist/core/timings.js +5 -4
- package/dist/core/timings.js.map +1 -1
- package/dist/core/tools/subagent.d.ts +38 -1
- package/dist/core/tools/subagent.d.ts.map +1 -1
- package/dist/core/tools/subagent.js +192 -17
- package/dist/core/tools/subagent.js.map +1 -1
- package/dist/core/tools/terminal-render.d.ts.map +1 -1
- package/dist/core/tools/terminal-render.js +2 -1
- package/dist/core/tools/terminal-render.js.map +1 -1
- package/dist/core/tools/web-search-queue.d.ts.map +1 -1
- package/dist/core/tools/web-search-queue.js +2 -1
- package/dist/core/tools/web-search-queue.js.map +1 -1
- package/dist/core/tools/web.d.ts.map +1 -1
- package/dist/core/tools/web.js +6 -5
- package/dist/core/tools/web.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +25 -24
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +5 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +32 -2
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/print-mode.d.ts.map +1 -1
- package/dist/modes/print-mode.js +3 -2
- package/dist/modes/print-mode.js.map +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Stderr interception for interactive TUI mode.
|
|
3
|
+
*
|
|
4
|
+
* When the TUI is active, raw writes to process.stderr would corrupt the
|
|
5
|
+
* differential renderer's state. This module intercepts process.stderr.write
|
|
6
|
+
* and routes all output through a callback instead of letting it hit the terminal.
|
|
7
|
+
*
|
|
8
|
+
* Analogous to output-guard.ts (which handles stdout for non-interactive modes),
|
|
9
|
+
* but specifically for protecting the TUI's display in interactive mode.
|
|
10
|
+
*/
|
|
11
|
+
export type StderrCallback = (message: string, level?: "warn" | "error" | "debug") => void;
|
|
12
|
+
/**
|
|
13
|
+
* Intercept all process.stderr.write calls and route them through the callback.
|
|
14
|
+
* Idempotent — multiple calls are no-ops if already taken over.
|
|
15
|
+
*/
|
|
16
|
+
export declare function takeOverStderr(callback: StderrCallback): void;
|
|
17
|
+
/**
|
|
18
|
+
* Write a message directly through the interceptor callback with level info.
|
|
19
|
+
* Used by the logger to pass severity through without going via process.stderr.write.
|
|
20
|
+
* Falls back to rawStderrWrite if stderr is not taken over.
|
|
21
|
+
*/
|
|
22
|
+
export declare function writeIntercepted(message: string, level: "warn" | "error" | "debug"): void;
|
|
23
|
+
/**
|
|
24
|
+
* Restore the original process.stderr.write behavior.
|
|
25
|
+
*/
|
|
26
|
+
export declare function restoreStderr(): void;
|
|
27
|
+
/**
|
|
28
|
+
* Check whether stderr is currently intercepted.
|
|
29
|
+
*/
|
|
30
|
+
export declare function isStderrTakenOver(): boolean;
|
|
31
|
+
/**
|
|
32
|
+
* Write directly to the real stderr, bypassing interception.
|
|
33
|
+
* Use for intentional writes that must reach the terminal
|
|
34
|
+
* (e.g., fatal errors before exit, post-TUI teardown messages).
|
|
35
|
+
*/
|
|
36
|
+
export declare function writeRawStderr(text: string): void;
|
|
37
|
+
//# sourceMappingURL=stderr-guard.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"stderr-guard.d.ts","sourceRoot":"","sources":["../../src/core/stderr-guard.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,MAAM,MAAM,cAAc,GAAG,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,OAAO,GAAG,OAAO,KAAK,IAAI,CAAC;AAU3F;;;GAGG;AACH,wBAAgB,cAAc,CAAC,QAAQ,EAAE,cAAc,GAAG,IAAI,CAgC7D;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,GAAG,OAAO,GAAG,IAAI,CAUzF;AAED;;GAEG;AACH,wBAAgB,aAAa,IAAI,IAAI,CAOpC;AAED;;GAEG;AACH,wBAAgB,iBAAiB,IAAI,OAAO,CAE3C;AAED;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAMjD","sourcesContent":["/**\n * Stderr interception for interactive TUI mode.\n *\n * When the TUI is active, raw writes to process.stderr would corrupt the\n * differential renderer's state. This module intercepts process.stderr.write\n * and routes all output through a callback instead of letting it hit the terminal.\n *\n * Analogous to output-guard.ts (which handles stdout for non-interactive modes),\n * but specifically for protecting the TUI's display in interactive mode.\n */\n\nexport type StderrCallback = (message: string, level?: \"warn\" | \"error\" | \"debug\") => void;\n\ninterface StderrTakeoverState {\n\trawStderrWrite: (chunk: string, callback?: (error?: Error | null) => void) => boolean;\n\toriginalStderrWrite: typeof process.stderr.write;\n\tcallback: StderrCallback;\n}\n\nlet stderrTakeoverState: StderrTakeoverState | undefined;\n\n/**\n * Intercept all process.stderr.write calls and route them through the callback.\n * Idempotent — multiple calls are no-ops if already taken over.\n */\nexport function takeOverStderr(callback: StderrCallback): void {\n\tif (stderrTakeoverState) {\n\t\treturn;\n\t}\n\n\tconst rawStderrWrite = process.stderr.write.bind(process.stderr) as StderrTakeoverState[\"rawStderrWrite\"];\n\tconst originalStderrWrite = process.stderr.write;\n\n\tprocess.stderr.write = ((\n\t\tchunk: string | Uint8Array,\n\t\tencodingOrCallback?: BufferEncoding | ((error?: Error | null) => void),\n\t\tcallback?: (error?: Error | null) => void,\n\t): boolean => {\n\t\tconst text = typeof chunk === \"string\" ? chunk : Buffer.from(chunk).toString();\n\t\tif (text.length > 0) {\n\t\t\ttry {\n\t\t\t\tstderrTakeoverState?.callback(text);\n\t\t\t} catch {\n\t\t\t\trawStderrWrite(text);\n\t\t\t}\n\t\t}\n\t\t// Signal success to caller — call the callback if provided\n\t\tconst cb = typeof encodingOrCallback === \"function\" ? encodingOrCallback : callback;\n\t\tif (cb) cb(null);\n\t\treturn true;\n\t}) as typeof process.stderr.write;\n\n\tstderrTakeoverState = {\n\t\trawStderrWrite,\n\t\toriginalStderrWrite,\n\t\tcallback,\n\t};\n}\n\n/**\n * Write a message directly through the interceptor callback with level info.\n * Used by the logger to pass severity through without going via process.stderr.write.\n * Falls back to rawStderrWrite if stderr is not taken over.\n */\nexport function writeIntercepted(message: string, level: \"warn\" | \"error\" | \"debug\"): void {\n\tif (stderrTakeoverState) {\n\t\ttry {\n\t\t\tstderrTakeoverState.callback(message, level);\n\t\t} catch {\n\t\t\tstderrTakeoverState.rawStderrWrite(message);\n\t\t}\n\t} else {\n\t\tprocess.stderr.write(`${message}\\n`);\n\t}\n}\n\n/**\n * Restore the original process.stderr.write behavior.\n */\nexport function restoreStderr(): void {\n\tif (!stderrTakeoverState) {\n\t\treturn;\n\t}\n\n\tprocess.stderr.write = stderrTakeoverState.originalStderrWrite;\n\tstderrTakeoverState = undefined;\n}\n\n/**\n * Check whether stderr is currently intercepted.\n */\nexport function isStderrTakenOver(): boolean {\n\treturn stderrTakeoverState !== undefined;\n}\n\n/**\n * Write directly to the real stderr, bypassing interception.\n * Use for intentional writes that must reach the terminal\n * (e.g., fatal errors before exit, post-TUI teardown messages).\n */\nexport function writeRawStderr(text: string): void {\n\tif (stderrTakeoverState) {\n\t\tstderrTakeoverState.rawStderrWrite(text);\n\t\treturn;\n\t}\n\tprocess.stderr.write(text);\n}\n"]}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Stderr interception for interactive TUI mode.
|
|
3
|
+
*
|
|
4
|
+
* When the TUI is active, raw writes to process.stderr would corrupt the
|
|
5
|
+
* differential renderer's state. This module intercepts process.stderr.write
|
|
6
|
+
* and routes all output through a callback instead of letting it hit the terminal.
|
|
7
|
+
*
|
|
8
|
+
* Analogous to output-guard.ts (which handles stdout for non-interactive modes),
|
|
9
|
+
* but specifically for protecting the TUI's display in interactive mode.
|
|
10
|
+
*/
|
|
11
|
+
let stderrTakeoverState;
|
|
12
|
+
/**
|
|
13
|
+
* Intercept all process.stderr.write calls and route them through the callback.
|
|
14
|
+
* Idempotent — multiple calls are no-ops if already taken over.
|
|
15
|
+
*/
|
|
16
|
+
export function takeOverStderr(callback) {
|
|
17
|
+
if (stderrTakeoverState) {
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
const rawStderrWrite = process.stderr.write.bind(process.stderr);
|
|
21
|
+
const originalStderrWrite = process.stderr.write;
|
|
22
|
+
process.stderr.write = ((chunk, encodingOrCallback, callback) => {
|
|
23
|
+
const text = typeof chunk === "string" ? chunk : Buffer.from(chunk).toString();
|
|
24
|
+
if (text.length > 0) {
|
|
25
|
+
try {
|
|
26
|
+
stderrTakeoverState?.callback(text);
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
rawStderrWrite(text);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
// Signal success to caller — call the callback if provided
|
|
33
|
+
const cb = typeof encodingOrCallback === "function" ? encodingOrCallback : callback;
|
|
34
|
+
if (cb)
|
|
35
|
+
cb(null);
|
|
36
|
+
return true;
|
|
37
|
+
});
|
|
38
|
+
stderrTakeoverState = {
|
|
39
|
+
rawStderrWrite,
|
|
40
|
+
originalStderrWrite,
|
|
41
|
+
callback,
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Write a message directly through the interceptor callback with level info.
|
|
46
|
+
* Used by the logger to pass severity through without going via process.stderr.write.
|
|
47
|
+
* Falls back to rawStderrWrite if stderr is not taken over.
|
|
48
|
+
*/
|
|
49
|
+
export function writeIntercepted(message, level) {
|
|
50
|
+
if (stderrTakeoverState) {
|
|
51
|
+
try {
|
|
52
|
+
stderrTakeoverState.callback(message, level);
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
stderrTakeoverState.rawStderrWrite(message);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
else {
|
|
59
|
+
process.stderr.write(`${message}\n`);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Restore the original process.stderr.write behavior.
|
|
64
|
+
*/
|
|
65
|
+
export function restoreStderr() {
|
|
66
|
+
if (!stderrTakeoverState) {
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
process.stderr.write = stderrTakeoverState.originalStderrWrite;
|
|
70
|
+
stderrTakeoverState = undefined;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Check whether stderr is currently intercepted.
|
|
74
|
+
*/
|
|
75
|
+
export function isStderrTakenOver() {
|
|
76
|
+
return stderrTakeoverState !== undefined;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Write directly to the real stderr, bypassing interception.
|
|
80
|
+
* Use for intentional writes that must reach the terminal
|
|
81
|
+
* (e.g., fatal errors before exit, post-TUI teardown messages).
|
|
82
|
+
*/
|
|
83
|
+
export function writeRawStderr(text) {
|
|
84
|
+
if (stderrTakeoverState) {
|
|
85
|
+
stderrTakeoverState.rawStderrWrite(text);
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
process.stderr.write(text);
|
|
89
|
+
}
|
|
90
|
+
//# sourceMappingURL=stderr-guard.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"stderr-guard.js","sourceRoot":"","sources":["../../src/core/stderr-guard.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAUH,IAAI,mBAAoD,CAAC;AAEzD;;;GAGG;AACH,MAAM,UAAU,cAAc,CAAC,QAAwB,EAAQ;IAC9D,IAAI,mBAAmB,EAAE,CAAC;QACzB,OAAO;IACR,CAAC;IAED,MAAM,cAAc,GAAG,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAA0C,CAAC;IAC1G,MAAM,mBAAmB,GAAG,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC;IAEjD,OAAO,CAAC,MAAM,CAAC,KAAK,GAAG,CAAC,CACvB,KAA0B,EAC1B,kBAAsE,EACtE,QAAyC,EAC/B,EAAE,CAAC;QACb,MAAM,IAAI,GAAG,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,QAAQ,EAAE,CAAC;QAC/E,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACrB,IAAI,CAAC;gBACJ,mBAAmB,EAAE,QAAQ,CAAC,IAAI,CAAC,CAAC;YACrC,CAAC;YAAC,M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C,OAAO;IACR,CAAC;IACD,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;AAAA,CAC3B","sourcesContent":["/**\n * Stderr interception for interactive TUI mode.\n *\n * When the TUI is active, raw writes to process.stderr would corrupt the\n * differential renderer's state. This module intercepts process.stderr.write\n * and routes all output through a callback instead of letting it hit the terminal.\n *\n * Analogous to output-guard.ts (which handles stdout for non-interactive modes),\n * but specifically for protecting the TUI's display in interactive mode.\n */\n\nexport type StderrCallback = (message: string, level?: \"warn\" | \"error\" | \"debug\") => void;\n\ninterface StderrTakeoverState {\n\trawStderrWrite: (chunk: string, callback?: (error?: Error | null) => void) => boolean;\n\toriginalStderrWrite: typeof process.stderr.write;\n\tcallback: StderrCallback;\n}\n\nlet stderrTakeoverState: StderrTakeoverState | undefined;\n\n/**\n * Intercept all process.stderr.write calls and route them through the callback.\n * Idempotent — multiple calls are no-ops if already taken over.\n */\nexport function takeOverStderr(callback: StderrCallback): void {\n\tif (stderrTakeoverState) {\n\t\treturn;\n\t}\n\n\tconst rawStderrWrite = process.stderr.write.bind(process.stderr) as StderrTakeoverState[\"rawStderrWrite\"];\n\tconst originalStderrWrite = process.stderr.write;\n\n\tprocess.stderr.write = ((\n\t\tchunk: string | Uint8Array,\n\t\tencodingOrCallback?: BufferEncoding | ((error?: Error | null) => void),\n\t\tcallback?: (error?: Error | null) => void,\n\t): boolean => {\n\t\tconst text = typeof chunk === \"string\" ? chunk : Buffer.from(chunk).toString();\n\t\tif (text.length > 0) {\n\t\t\ttry {\n\t\t\t\tstderrTakeoverState?.callback(text);\n\t\t\t} catch {\n\t\t\t\trawStderrWrite(text);\n\t\t\t}\n\t\t}\n\t\t// Signal success to caller — call the callback if provided\n\t\tconst cb = typeof encodingOrCallback === \"function\" ? encodingOrCallback : callback;\n\t\tif (cb) cb(null);\n\t\treturn true;\n\t}) as typeof process.stderr.write;\n\n\tstderrTakeoverState = {\n\t\trawStderrWrite,\n\t\toriginalStderrWrite,\n\t\tcallback,\n\t};\n}\n\n/**\n * Write a message directly through the interceptor callback with level info.\n * Used by the logger to pass severity through without going via process.stderr.write.\n * Falls back to rawStderrWrite if stderr is not taken over.\n */\nexport function writeIntercepted(message: string, level: \"warn\" | \"error\" | \"debug\"): void {\n\tif (stderrTakeoverState) {\n\t\ttry {\n\t\t\tstderrTakeoverState.callback(message, level);\n\t\t} catch {\n\t\t\tstderrTakeoverState.rawStderrWrite(message);\n\t\t}\n\t} else {\n\t\tprocess.stderr.write(`${message}\\n`);\n\t}\n}\n\n/**\n * Restore the original process.stderr.write behavior.\n */\nexport function restoreStderr(): void {\n\tif (!stderrTakeoverState) {\n\t\treturn;\n\t}\n\n\tprocess.stderr.write = stderrTakeoverState.originalStderrWrite;\n\tstderrTakeoverState = undefined;\n}\n\n/**\n * Check whether stderr is currently intercepted.\n */\nexport function isStderrTakenOver(): boolean {\n\treturn stderrTakeoverState !== undefined;\n}\n\n/**\n * Write directly to the real stderr, bypassing interception.\n * Use for intentional writes that must reach the terminal\n * (e.g., fatal errors before exit, post-TUI teardown messages).\n */\nexport function writeRawStderr(text: string): void {\n\tif (stderrTakeoverState) {\n\t\tstderrTakeoverState.rawStderrWrite(text);\n\t\treturn;\n\t}\n\tprocess.stderr.write(text);\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"timings.d.ts","sourceRoot":"","sources":["../../src/core/timings.ts"],"names":[],"mappings":"AAAA;;;GAGG;
|
|
1
|
+
{"version":3,"file":"timings.d.ts","sourceRoot":"","sources":["../../src/core/timings.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAQH,wBAAgB,YAAY,IAAI,IAAI,CAInC;AAED,wBAAgB,IAAI,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAKxC;AAED,wBAAgB,YAAY,IAAI,IAAI,CAQnC","sourcesContent":["/**\n * Central timing instrumentation for startup profiling.\n * Enable with DREB_TIMING=1 environment variable.\n */\n\nimport { log } from \"./logger.js\";\n\nconst ENABLED = process.env.DREB_TIMING === \"1\";\nconst timings: Array<{ label: string; ms: number }> = [];\nlet lastTime = Date.now();\n\nexport function resetTimings(): void {\n\tif (!ENABLED) return;\n\ttimings.length = 0;\n\tlastTime = Date.now();\n}\n\nexport function time(label: string): void {\n\tif (!ENABLED) return;\n\tconst now = Date.now();\n\ttimings.push({ label, ms: now - lastTime });\n\tlastTime = now;\n}\n\nexport function printTimings(): void {\n\tif (!ENABLED || timings.length === 0) return;\n\tlog.debug(\"\\n--- Startup Timings ---\");\n\tfor (const t of timings) {\n\t\tlog.debug(` ${t.label}: ${t.ms}ms`);\n\t}\n\tlog.debug(` TOTAL: ${timings.reduce((a, b) => a + b.ms, 0)}ms`);\n\tlog.debug(\"------------------------\\n\");\n}\n"]}
|
package/dist/core/timings.js
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
* Central timing instrumentation for startup profiling.
|
|
3
3
|
* Enable with DREB_TIMING=1 environment variable.
|
|
4
4
|
*/
|
|
5
|
+
import { log } from "./logger.js";
|
|
5
6
|
const ENABLED = process.env.DREB_TIMING === "1";
|
|
6
7
|
const timings = [];
|
|
7
8
|
let lastTime = Date.now();
|
|
@@ -21,11 +22,11 @@ export function time(label) {
|
|
|
21
22
|
export function printTimings() {
|
|
22
23
|
if (!ENABLED || timings.length === 0)
|
|
23
24
|
return;
|
|
24
|
-
|
|
25
|
+
log.debug("\n--- Startup Timings ---");
|
|
25
26
|
for (const t of timings) {
|
|
26
|
-
|
|
27
|
+
log.debug(` ${t.label}: ${t.ms}ms`);
|
|
27
28
|
}
|
|
28
|
-
|
|
29
|
-
|
|
29
|
+
log.debug(` TOTAL: ${timings.reduce((a, b) => a + b.ms, 0)}ms`);
|
|
30
|
+
log.debug("------------------------\n");
|
|
30
31
|
}
|
|
31
32
|
//# sourceMappingURL=timings.js.map
|
package/dist/core/timings.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"timings.js","sourceRoot":"","sources":["../../src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AED,MAAM,UAAU,IAAI,CAAC,KAAa,EAAQ;IACzC,IAAI,CAAC,OAAO;QAAE,OAAO;IACrB,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;IACvB,OAAO,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,GAAG,GAAG,QAAQ,EAAE,CAAC,CAAC;IAC5C,QAAQ,GAAG,GAAG,CAAC;AAAA,CACf;AAED,MAAM,UAAU,YAAY,GAAS;IACpC,IAAI,CAAC,OAAO,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO;IAC7C,GAAG,CAAC,KAAK,CAAC,2BAA2B,CAAC,CAAC;IACvC,KAAK,MAAM,CAAC,IAAI,OAAO,EAAE,CAAC;QACzB,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,KAAK,KAAK,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC;IACtC,CAAC;IACD,GAAG,CAAC,KAAK,CAAC,YAAY,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC;IACjE,GAAG,CAAC,KAAK,CAAC,4BAA4B,CAAC,CAAC;AAAA,CACxC","sourcesContent":["/**\n * Central timing instrumentation for startup profiling.\n * Enable with DREB_TIMING=1 environment variable.\n */\n\nimport { log } from \"./logger.js\";\n\nconst ENABLED = process.env.DREB_TIMING === \"1\";\nconst timings: Array<{ label: string; ms: number }> = [];\nlet lastTime = Date.now();\n\nexport function resetTimings(): void {\n\tif (!ENABLED) return;\n\ttimings.length = 0;\n\tlastTime = Date.now();\n}\n\nexport function time(label: string): void {\n\tif (!ENABLED) return;\n\tconst now = Date.now();\n\ttimings.push({ label, ms: now - lastTime });\n\tlastTime = now;\n}\n\nexport function printTimings(): void {\n\tif (!ENABLED || timings.length === 0) return;\n\tlog.debug(\"\\n--- Startup Timings ---\");\n\tfor (const t of timings) {\n\t\tlog.debug(` ${t.label}: ${t.ms}ms`);\n\t}\n\tlog.debug(` TOTAL: ${timings.reduce((a, b) => a + b.ms, 0)}ms`);\n\tlog.debug(\"------------------------\\n\");\n}\n"]}
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import type { AgentTool } from "@dreb/agent-core";
|
|
2
|
+
import { type Api, type Model } from "@dreb/ai";
|
|
2
3
|
import { type Static } from "@sinclair/typebox";
|
|
3
4
|
import type { ToolDefinition } from "../extensions/types.js";
|
|
4
5
|
import type { ModelRegistry } from "../model-registry.js";
|
|
5
6
|
import { type TruncationResult } from "./truncate.js";
|
|
6
|
-
interface AgentTypeConfig {
|
|
7
|
+
export interface AgentTypeConfig {
|
|
7
8
|
name: string;
|
|
8
9
|
description: string;
|
|
9
10
|
tools?: string;
|
|
@@ -63,6 +64,42 @@ export declare function resolveModelStringSingle(modelStr: string, parentProvide
|
|
|
63
64
|
ok: false;
|
|
64
65
|
error: string;
|
|
65
66
|
};
|
|
67
|
+
export interface ProbeModelAvailabilityOptions {
|
|
68
|
+
/** Parent/tool abort signal. A 10s probe timeout is layered on top. */
|
|
69
|
+
signal?: AbortSignal;
|
|
70
|
+
/** Model registry used to resolve provider API keys for the probe call. */
|
|
71
|
+
registry?: ModelRegistry;
|
|
72
|
+
/** Override the default 10s probe timeout; primarily useful for tests. */
|
|
73
|
+
timeoutMs?: number;
|
|
74
|
+
}
|
|
75
|
+
export type ProbeModelAvailabilityResult = {
|
|
76
|
+
ok: true;
|
|
77
|
+
} | {
|
|
78
|
+
ok: false;
|
|
79
|
+
reason: string;
|
|
80
|
+
aborted?: boolean;
|
|
81
|
+
};
|
|
82
|
+
export declare function isRuntimeUnavailableError(value: unknown): boolean;
|
|
83
|
+
export declare function probeModelAvailability(model: Model<Api>, options?: ProbeModelAvailabilityOptions): Promise<ProbeModelAvailabilityResult>;
|
|
84
|
+
export interface SkippedFallbackModel {
|
|
85
|
+
model: string;
|
|
86
|
+
reason: string;
|
|
87
|
+
}
|
|
88
|
+
export type SubagentModelResolution = {
|
|
89
|
+
ok: true;
|
|
90
|
+
modelId: string;
|
|
91
|
+
provider?: string;
|
|
92
|
+
warning?: string;
|
|
93
|
+
skippedModels: SkippedFallbackModel[];
|
|
94
|
+
} | {
|
|
95
|
+
ok: false;
|
|
96
|
+
error: string;
|
|
97
|
+
skippedModels: SkippedFallbackModel[];
|
|
98
|
+
};
|
|
99
|
+
export declare function resolveModelForSubagentSpawn(models: string | string[], parentProvider: string | undefined, registry: ModelRegistry | undefined, parentModel?: string, signal?: AbortSignal): Promise<SubagentModelResolution>;
|
|
100
|
+
export declare function formatModelFallbackSummary(skippedModels: SkippedFallbackModel[], selectedModel: string | undefined): string | undefined;
|
|
101
|
+
export declare function prependModelFallbackSummary(output: string, skippedModels: SkippedFallbackModel[], selectedModel: string | undefined): string;
|
|
102
|
+
export declare function executeSingle(agents: Map<string, AgentTypeConfig>, agentName: string | undefined, task: string, cwd: string, signal?: AbortSignal, onProgress?: (event: string) => void, modelOverride?: string, parentProvider?: string, registry?: ModelRegistry, sessionDir?: string, parentModel?: string): Promise<SubagentResult>;
|
|
66
103
|
export interface BackgroundAgentInfo {
|
|
67
104
|
agentId: string;
|
|
68
105
|
agentType: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"subagent.d.ts","sourceRoot":"","sources":["../../../src/core/tools/subagent.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAElD,OAAO,EAAE,KAAK,MAAM,EAAQ,MAAM,mBAAmB,CAAC;AAItD,OAAO,KAAK,EAAE,cAAc,EAA2B,MAAM,wBAAwB,CAAC;AACtF,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAI1D,OAAO,EAAiC,KAAK,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAMrF,UAAU,eAAe;IACxB,IAAI,EAAE,MAAM,CAAC;IACb,W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AM,GAAG,SAAS,CAAC;IAC1C,kKAAkK;IAClK,WAAW,CAAC,EAAE,MAAM,MAAM,GAAG,SAAS,CAAC;IACvC,iFAAiF;IACjF,aAAa,CAAC,EAAE,aAAa,CAAC;CAC9B;AAkBD,QAAA,MAAM,cAAc;;;;;;;;;;;;;;;;;EA2BlB,CAAC;AAEH,MAAM,MAAM,iBAAiB,GAAG,MAAM,CAAC,OAAO,cAAc,CAAC,CAAC;AAE9D,MAAM,WAAW,mBAAmB;IACnC,UAAU,CAAC,EAAE,gBAAgB,CAAC;IAC9B,IAAI,EAAE,QAAQ,GAAG,UAAU,GAAG,OAAO,CAAC;IACtC,UAAU,EAAE,MAAM,CAAC;CACnB;AAiGD,wBAAgB,4BAA4B,CAC3C,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,mBAAmB,GAC3B,cAAc,CAAC,OAAO,cAAc,EAAE,mBAAmB,GAAG,SAAS,CAAC,CA0UxE;AAED,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,mBAAmB,GAAG,SAAS,CAAC,OAAO,cAAc,CAAC,CAE/G;AAED,eAAO,MAAM,sBAAsB;;;;;;;;;;;;;;;;;yCAA8C,CAAC;AAClF,eAAO,MAAM,YAAY;;;;;;;;;;;;;;;;;QAAoC,CAAC","sourcesContent":["import { type ChildProcess, spawn } from \"node:child_process\";\nimport { randomBytes } from \"node:crypto\";\nimport { existsSync, readdirSync, readFileSync, statSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join, resolve } from \"node:path\";\nimport type { AgentTool } from \"@dreb/agent-core\";\nimport { Text } from \"@dreb/tui\";\nimport { type Static, Type } from \"@sinclair/typebox\";\nimport { CONFIG_DIR_NAME, getPackageDir, getSubagentSessionsDir } from \"../../config.js\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.js\";\nimport { attachJsonlLineReader } from \"../../modes/rpc/jsonl.js\";\nimport type { ToolDefinition, ToolRenderResultOptions } from \"../extensions/types.js\";\nimport type { ModelRegistry } from \"../model-registry.js\";\nimport { resolveCliModel } from \"../model-resolver.js\";\nimport { getTextOutput, invalidArgText, str } from \"./render-utils.js\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.js\";\nimport { DEFAULT_MAX_BYTES, formatSize, type TruncationResult } from \"./truncate.js\";\n\n// ---------------------------------------------------------------------------\n// Agent type system\n// ---------------------------------------------------------------------------\n\ninterface AgentTypeConfig {\n\tname: string;\n\tdescription: string;\n\ttools?: string;\n\t/** Single model ID or ordered fallback list. First resolvable model wins. */\n\tmodel?: string | string[];\n\tsystemPrompt: string;\n}\n\nconst DEFAULT_AGENT = \"Explore\";\n\nexport function parseAgentFrontmatter(\n\tcontent: string,\n): { ok: true; config: AgentTypeConfig } | { ok: false; error: string } {\n\tconst fmMatch = content.match(/^---\\n([\\s\\S]*?)\\n---\\n?([\\s\\S]*)$/);\n\tif (!fmMatch) return { ok: false, error: \"missing --- frontmatter delimiters\" };\n\n\tconst frontmatter = fmMatch[1];\n\tconst body = fmMatch[2].trim();\n\n\tconst get = (key: string): string | undefined => {\n\t\tconst match = frontmatter.match(new RegExp(`^${key}:\\\\s*(.+)$`, \"m\"));\n\t\treturn match?.[1].trim();\n\t};\n\n\t/** Parse `model` field — supports single string, comma-separated, or YAML list syntax. */\n\tconst getModel = (): string | string[] | undefined => {\n\t\t// First check for YAML list syntax (indented lines starting with \"- \")\n\t\tconst listMatch = frontmatter.match(/^model:\\s*\\n((?:\\s+-\\s+.+\\n?)+)/m);\n\t\tif (listMatch) {\n\t\t\tconst items = listMatch[1]\n\t\t\t\t.split(\"\\n\")\n\t\t\t\t.map((line) => line.replace(/^\\s+-\\s+/, \"\").trim())\n\t\t\t\t.filter(Boolean);\n\t\t\treturn items.length > 1 ? items : items[0];\n\t\t}\n\t\t// Inline value — check for comma-separated list\n\t\tconst value = get(\"model\");\n\t\tif (!value) return undefined;\n\t\tif (value.includes(\",\")) {\n\t\t\tconst items = value\n\t\t\t\t.split(\",\")\n\t\t\t\t.map((s) => s.trim())\n\t\t\t\t.filter(Boolean);\n\t\t\treturn items.length > 1 ? items : items[0];\n\t\t}\n\t\treturn value;\n\t};\n\n\tconst name = get(\"name\");\n\tif (!name) return { ok: false, error: \"missing required 'name' field in frontmatter\" };\n\n\treturn {\n\t\tok: true,\n\t\tconfig: {\n\t\t\tname,\n\t\t\tdescription: get(\"description\") || \"\",\n\t\t\ttools: get(\"tools\"),\n\t\t\tmodel: getModel(),\n\t\t\tsystemPrompt: body,\n\t\t},\n\t};\n}\n\nfunction discoverAgentTypes(cwd: string): Map<string, AgentTypeConfig> {\n\tconst agents = new Map<string, AgentTypeConfig>();\n\n\t// Package-bundled agents (shipped with dreb — the canonical source of truth for built-in agents)\n\tconst packageAgentsDir = join(getPackageDir(), \"agents\");\n\tloadAgentsFromDir(packageAgentsDir, agents);\n\n\t// User-level agents (~/.dreb/agents/*.md)\n\tconst userDir = join(homedir(), CONFIG_DIR_NAME, \"agents\");\n\tloadAgentsFromDir(userDir, agents);\n\n\t// Project-level agents (.dreb/agents/*.md)\n\t// TODO: Security gate — prompt user for confirmation before loading agents from untrusted repos\n\tconst projectDir = join(cwd, \".dreb\", \"agents\");\n\tloadAgentsFromDir(projectDir, agents);\n\n\treturn agents;\n}\n\nfunction loadAgentsFromDir(dir: string, agents: Map<string, AgentTypeConfig>): void {\n\tif (!existsSync(dir)) return;\n\ttry {\n\t\tfor (const file of readdirSync(dir)) {\n\t\t\tif (!file.endsWith(\".md\")) continue;\n\t\t\ttry {\n\t\t\t\tconst content = readFileSync(join(dir, file), \"utf-8\");\n\t\t\t\tconst parsed = parseAgentFrontmatter(content);\n\t\t\t\tif (!parsed.ok) {\n\t\t\t\t\tconsole.error(`[subagent] Skipping agent file ${join(dir, file)}: ${parsed.error}`);\n\t\t\t\t} else {\n\t\t\t\t\tagents.set(parsed.config.name, parsed.config);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tconsole.error(\n\t\t\t\t\t`[subagent] Could not read agent file ${join(dir, file)}: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t} catch (err) {\n\t\tif ((err as NodeJS.ErrnoException).code !== \"ENOENT\") {\n\t\t\tconsole.error(\n\t\t\t\t`[subagent] Could not read agents directory ${dir}: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t);\n\t\t}\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Subagent process spawning\n// ---------------------------------------------------------------------------\n\nexport interface SubagentResult {\n\tagent: string;\n\ttask: string;\n\tmodel?: string;\n\texitCode: number;\n\toutput: string;\n\tstderr: string;\n\terrorMessage: string | null;\n\t/** Path to the persisted session JSONL file, if available */\n\tsessionFile?: string;\n}\n\n// Capture at module load before process.title overwrites argv memory on Linux.\n// After process.title = \"dreb\" (in cli.ts), the original argv area is overwritten\n// and process.argv[1] may return corrupted or truncated data.\nconst DREB_SCRIPT = process.argv[1] || \"dreb\";\nconst NODE_EXEC = process.execPath;\n\n// Tools that must never be available to subagents — wait (subagents should\n// never no-op; they have a task to complete) and subagent (no recursive spawning).\nconst SUBAGENT_EXCLUDED_TOOLS = [\"wait\", \"subagent\"] as const;\n\n// Default standard tools for subagents when no tools are specified in the agent\n// definition. This is the set passed via --tools to the child process.\n//\n// NOTE: Always-active tools (search, skill, tasks_update, suggest_next) are NOT\n// listed here — the child process adds them unconditionally regardless of --tools.\n// Internal tools (tmp_read) are also excluded.\nconst SUBAGENT_DEFAULT_TOOLS = [\"read\", \"bash\", \"edit\", \"write\", \"grep\", \"find\", \"ls\", \"web_search\", \"web_fetch\"];\n\n/**\n * Filter a comma-separated tools string, removing any tools in SUBAGENT_EXCLUDED_TOOLS.\n * Returns the filtered tools as a comma-separated string (always non-empty — falls\n * back to SUBAGENT_DEFAULT_TOOLS if all specified tools were excluded).\n */\nexport function filterSubagentTools(tools: string | undefined): string {\n\tif (!tools) return SUBAGENT_DEFAULT_TOOLS.join(\",\");\n\tconst filtered = tools\n\t\t.split(\",\")\n\t\t.map((t) => t.trim())\n\t\t.filter((t) => !(SUBAGENT_EXCLUDED_TOOLS as readonly string[]).includes(t))\n\t\t.join(\",\");\n\treturn filtered || SUBAGENT_DEFAULT_TOOLS.join(\",\");\n}\n\n// TODO: Support PATH-based binary discovery.\n// Currently returns the captured argv[1].\nfunction findDrebBinary(): string {\n\treturn DREB_SCRIPT;\n}\n\nasync function spawnSubagent(\n\tagentConfig: AgentTypeConfig,\n\ttask: string,\n\tcwd: string,\n\tsignal?: AbortSignal,\n\tonProgress?: (event: string) => void,\n\tparentProvider?: string,\n\tsessionDir?: string,\n): Promise<SubagentResult> {\n\tconst drebBin = findDrebBinary();\n\tconsole.error(`[subagent] spawn: agent=${agentConfig.name} cwd=${cwd}`);\n\n\t// Validate cwd exists — spawn() throws a misleading ENOENT blaming the\n\t// binary when the cwd is invalid, making the real cause hard to diagnose\n\tif (!existsSync(cwd)) {\n\t\treturn {\n\t\t\tagent: agentConfig.name,\n\t\t\ttask,\n\t\t\texitCode: 1,\n\t\t\toutput: \"\",\n\t\t\tstderr: \"\",\n\t\t\terrorMessage: `Working directory does not exist: ${cwd}`,\n\t\t};\n\t}\n\n\tconst args: string[] = [\"--mode\", \"json\", \"--ui\", \"agent\"];\n\tif (sessionDir) {\n\t\targs.push(\"--session-dir\", sessionDir);\n\t} else {\n\t\targs.push(\"--no-session\");\n\t}\n\t// By spawn time, model should be a resolved single string (fallback resolution\n\t// happens in executeSingle). Handle string[] defensively by taking the first entry.\n\tconst modelStr = Array.isArray(agentConfig.model) ? agentConfig.model[0] : agentConfig.model;\n\tif (modelStr) {\n\t\targs.push(\"--model\", modelStr);\n\t\t// When the model string doesn't already specify a provider (no \"/\"),\n\t\t// inherit the parent's provider to prevent fuzzy matching from picking\n\t\t// an unauthenticated provider (e.g. Bedrock instead of Anthropic).\n\t\tif (parentProvider && !modelStr.includes(\"/\")) {\n\t\t\targs.push(\"--provider\", parentProvider);\n\t\t}\n\t}\n\t// Always pass --tools to ensure wait/subagent are excluded from child processes.\n\t// filterSubagentTools always returns a non-empty string.\n\targs.push(\"--tools\", filterSubagentTools(agentConfig.tools));\n\tif (agentConfig.systemPrompt) {\n\t\targs.push(\"--append-system-prompt\", agentConfig.systemPrompt);\n\t}\n\t// Pass agent type metadata so the child session can record it in its JSONL header\n\targs.push(\"--agent-type\", agentConfig.name);\n\targs.push(\"-p\", task);\n\n\t// Early abort check — if the signal is already aborted (e.g. queued task whose\n\t// AbortController was aborted while waiting on bgAcquire), bail out before\n\t// spawning a child process that can never be killed. addEventListener(\"abort\")\n\t// on an already-aborted signal does NOT fire the callback in Node.js.\n\tif (signal?.aborted) {\n\t\treturn {\n\t\t\tagent: agentConfig.name,\n\t\t\ttask,\n\t\t\texitCode: 1,\n\t\t\toutput: \"\",\n\t\t\tstderr: \"\",\n\t\t\terrorMessage: \"Aborted before spawn\",\n\t\t};\n\t}\n\n\treturn new Promise<SubagentResult>((resolvePromise, rejectPromise) => {\n\t\tlet proc: ChildProcess;\n\t\ttry {\n\t\t\tproc = spawn(NODE_EXEC, [drebBin, ...args], {\n\t\t\t\tcwd,\n\t\t\t\tstdio: [\"ignore\", \"pipe\", \"pipe\"],\n\t\t\t\tenv: { ...process.env },\n\t\t\t});\n\t\t} catch (err) {\n\t\t\trejectPromise(new Error(`Failed to spawn subagent: ${err instanceof Error ? err.message : String(err)}`));\n\t\t\treturn;\n\t\t}\n\n\t\tlet settled = false;\n\t\tlet killTimer: ReturnType<typeof setTimeout> | null = null;\n\t\tconst collectedMessages: Array<{ role: string; content: any[] }> = [];\n\t\tconst stderrChunks: string[] = [];\n\t\tlet stderrSize = 0;\n\t\tconst MAX_STDERR_BYTES = 8192;\n\t\tconst plainStdoutLines: string[] = [];\n\t\tlet lastToolName = \"\";\n\t\tlet resolvedModel: string | undefined;\n\n\t\t// Drain stderr concurrently to avoid pipe deadlock (capped to prevent OOM from verbose subagents)\n\t\tproc.stderr?.on(\"data\", (chunk: Buffer) => {\n\t\t\tif (stderrSize < MAX_STDERR_BYTES) {\n\t\t\t\tconst str = chunk.toString();\n\t\t\t\tstderrChunks.push(str);\n\t\t\t\tstderrSize += str.length;\n\t\t\t}\n\t\t});\n\t\tproc.stderr?.on(\"error\", (err) => {\n\t\t\tconsole.error(`[subagent] stderr stream error (agent=${agentConfig.name}): ${err.message}`);\n\t\t});\n\n\t\t// Parse JSONL events from stdout\n\t\tif (proc.stdout) {\n\t\t\tproc.stdout.on(\"error\", (err) => {\n\t\t\t\tconsole.error(`[subagent] stdout stream error (agent=${agentConfig.name}): ${err.message}`);\n\t\t\t});\n\t\t\tattachJsonlLineReader(proc.stdout, (line) => {\n\t\t\t\tif (!line.trim()) return;\n\t\t\t\t// Separate JSON.parse from event handling so only parse failures\n\t\t\t\t// are caught as non-JSON lines — errors in handling propagate normally\n\t\t\t\tlet event: any;\n\t\t\t\ttry {\n\t\t\t\t\tevent = JSON.parse(line);\n\t\t\t\t} catch {\n\t\t\t\t\t// Capture non-JSON lines — on failure these often contain the real error\n\t\t\t\t\t// (e.g. startup errors printed before JSONL mode begins)\n\t\t\t\t\tplainStdoutLines.push(line.trim());\n\t\t\t\t\tif (line.trim().startsWith(\"{\")) {\n\t\t\t\t\t\tconsole.error(`[subagent] Failed to parse JSONL event: ${line.slice(0, 200)}`);\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (event.type === \"agent_start\" && event.model) {\n\t\t\t\t\tresolvedModel = event.model.id;\n\t\t\t\t}\n\t\t\t\tif (event.type === \"message_end\" && event.message?.role === \"assistant\") {\n\t\t\t\t\tcollectedMessages.push(event.message);\n\t\t\t\t}\n\t\t\t\tif (event.type === \"tool_execution_start\" && onProgress) {\n\t\t\t\t\tlastToolName = event.toolName || \"\";\n\t\t\t\t\tonProgress(`Using ${lastToolName}...`);\n\t\t\t\t}\n\t\t\t\tif (event.type === \"tool_execution_end\" && onProgress) {\n\t\t\t\t\tonProgress(`${lastToolName} done`);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\t// Handle abort signal (guard kill() against ESRCH race if process already exited)\n\t\tconst onAbort = () => {\n\t\t\ttry {\n\t\t\t\tproc.kill(\"SIGTERM\");\n\t\t\t} catch {\n\t\t\t\t/* process already exited */\n\t\t\t}\n\t\t\tkillTimer = setTimeout(() => {\n\t\t\t\ttry {\n\t\t\t\t\tif (!proc.killed) proc.kill(\"SIGKILL\");\n\t\t\t\t} catch {\n\t\t\t\t\t/* process already exited */\n\t\t\t\t}\n\t\t\t}, 5000);\n\t\t};\n\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\n\t\tproc.on(\"error\", (err) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tif (killTimer) clearTimeout(killTimer);\n\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\trejectPromise(new Error(`Subagent process error: ${err.message}`));\n\t\t});\n\n\t\tproc.on(\"close\", (code) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tif (killTimer) clearTimeout(killTimer);\n\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\tconst exitCode = code ?? 1;\n\t\t\tconst stderr = stderrChunks.join(\"\");\n\t\t\tconsole.error(\n\t\t\t\t`[subagent] close: agent=${agentConfig.name} exit=${exitCode} messages=${collectedMessages.length}${exitCode !== 0 ? ` stderr=${stderr.slice(0, 200)} stdout=${plainStdoutLines.join(\"|\").slice(0, 200)}` : \"\"}`,\n\t\t\t);\n\n\t\t\t// Extract final text output from collected assistant messages\n\t\t\tconst outputParts: string[] = [];\n\t\t\tfor (const msg of collectedMessages) {\n\t\t\t\tif (Array.isArray(msg.content)) {\n\t\t\t\t\tfor (const part of msg.content) {\n\t\t\t\t\t\tif (part.type === \"text\" && part.text) {\n\t\t\t\t\t\t\toutputParts.push(part.text);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst output = outputParts.join(\"\\n\\n\");\n\n\t\t\t// Build error message from best available source: stderr, plain stdout lines, or generic\n\t\t\tlet errorMessage: string | null = null;\n\t\t\tif (exitCode !== 0) {\n\t\t\t\tconst stderrTrimmed = stderr.trim();\n\t\t\t\tconst plainOutput = plainStdoutLines.join(\"\\n\").trim();\n\t\t\t\terrorMessage =\n\t\t\t\t\tstderrTrimmed.slice(0, 500) || plainOutput.slice(0, 500) || `Subagent exited with code ${exitCode}`;\n\t\t\t}\n\n\t\t\t// Discover the session file written by the child process\n\t\t\tconst sessionFile = sessionDir ? discoverSessionFile(sessionDir, agentConfig.name) : undefined;\n\n\t\t\tresolvePromise({\n\t\t\t\tagent: agentConfig.name,\n\t\t\t\ttask,\n\t\t\t\tmodel:\n\t\t\t\t\tresolvedModel ??\n\t\t\t\t\t(exitCode === 0\n\t\t\t\t\t\t? Array.isArray(agentConfig.model)\n\t\t\t\t\t\t\t? agentConfig.model[0]\n\t\t\t\t\t\t\t: agentConfig.model\n\t\t\t\t\t\t: undefined),\n\t\t\t\texitCode,\n\t\t\t\toutput,\n\t\t\t\tstderr: stderr.slice(0, 2000), // cap stderr\n\t\t\t\terrorMessage,\n\t\t\t\tsessionFile,\n\t\t\t});\n\t\t});\n\t});\n}\n\n// ---------------------------------------------------------------------------\n// Session file discovery and cleanup\n// ---------------------------------------------------------------------------\n\n/**\n * Find the most recently modified .jsonl file in a session directory.\n * Returns the full path, or undefined if no session file was written\n * (e.g., subagent was killed before the first assistant message).\n */\nexport function discoverSessionFile(sessionDir: string, agentName: string): string | undefined {\n\ttry {\n\t\tif (!existsSync(sessionDir)) return undefined;\n\t\tconst files = readdirSync(sessionDir).filter((f) => f.endsWith(\".jsonl\"));\n\t\tif (files.length === 0) return undefined;\n\t\t// Pick the most recently modified file (typically there's only one per subagent dir)\n\t\tlet best: { path: string; mtime: number } | undefined;\n\t\tfor (const f of files) {\n\t\t\ttry {\n\t\t\t\tconst fullPath = join(sessionDir, f);\n\t\t\t\tconst mtime = statSync(fullPath).mtime.getTime();\n\t\t\t\tif (!best || mtime > best.mtime) {\n\t\t\t\t\tbest = { path: fullPath, mtime };\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// File disappeared or is a bad symlink — skip it, keep any valid candidate\n\t\t\t}\n\t\t}\n\t\tif (best) {\n\t\t\tconsole.error(`[subagent] session file: ${best.path} (agent=${agentName})`);\n\t\t\treturn best.path;\n\t\t}\n\t} catch (err) {\n\t\tconsole.error(\n\t\t\t`[subagent] failed to discover session file (agent=${agentName}): ${err instanceof Error ? err.message : String(err)}`,\n\t\t);\n\t}\n\treturn undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Execution modes\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve a model fallback list against the registry. Tries each model in order,\n * returns the first one that resolves successfully. If all fail, returns the\n * last error. Single strings are treated as a one-element list.\n */\nexport function resolveModelWithFallbacks(\n\tmodels: string | string[],\n\tparentProvider: string | undefined,\n\tregistry: ModelRegistry | undefined,\n\tparentModel?: string,\n): { ok: true; modelId: string; provider?: string; warning?: string } | { ok: false; error: string } {\n\tconst modelList = Array.isArray(models) ? models : [models];\n\tlet lastError = \"\";\n\tfor (const modelStr of modelList) {\n\t\tconst result = resolveModelStringSingle(modelStr, parentProvider, registry);\n\t\tif (result.ok) return result;\n\t\tlastError = result.error;\n\t}\n\t// After all configured fallbacks are exhausted, try the parent model as a last resort\n\tif (parentModel) {\n\t\tconst result = resolveModelStringSingle(parentModel, parentProvider, registry);\n\t\tif (result.ok) {\n\t\t\treturn {\n\t\t\t\t...result,\n\t\t\t\twarning: `Agent preferred models were unavailable. Falling back to parent model \"${result.modelId}\".`,\n\t\t\t};\n\t\t}\n\t\tlastError = result.error;\n\t}\n\tif (modelList.length > 1 || parentModel) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `None of the fallback models resolved: ${[...modelList, ...(parentModel ? [parentModel] : [])].join(\", \")}. Last error: ${lastError}`,\n\t\t};\n\t}\n\treturn { ok: false, error: lastError };\n}\n\nexport function resolveModelStringSingle(\n\tmodelStr: string,\n\tparentProvider: string | undefined,\n\tregistry: ModelRegistry | undefined,\n): { ok: true; modelId: string; provider?: string } | { ok: false; error: string } {\n\tif (!registry) {\n\t\treturn { ok: true, modelId: modelStr };\n\t}\n\n\t// If the model string contains \"/\" the user already specified a provider\n\tconst hasProvider = modelStr.includes(\"/\");\n\tconst resolved = resolveCliModel({\n\t\tcliProvider: hasProvider ? undefined : parentProvider,\n\t\tcliModel: modelStr,\n\t\tmodelRegistry: registry,\n\t});\n\n\tif (resolved.error) {\n\t\treturn { ok: false, error: resolved.error };\n\t}\n\tif (!resolved.model) {\n\t\treturn { ok: false, error: `Model \"${modelStr}\" not found. Use --list-models to see available models.` };\n\t}\n\n\t// resolveCliModel creates a synthetic model for any unknown ID when a\n\t// provider is specified (designed for custom/self-hosted models like Ollama).\n\t// For subagents this causes silent failures — reject synthetic fallbacks\n\t// so the next model in the fallback list is tried instead.\n\tif (resolved.isSyntheticFallback) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `Model \"${modelStr}\" not found for provider \"${resolved.model.provider}\". Use --list-models to see available models.`,\n\t\t};\n\t}\n\n\t// Verify the resolved provider has authentication configured.\n\t// resolveCliModel uses getAll() (all models, not just authenticated ones)\n\t// so a model can resolve successfully to a provider with no API key.\n\t// Reject early so the fallback list can continue to the next model.\n\tif (!registry.authStorage.hasAuth(resolved.model.provider)) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `No authentication configured for provider \"${resolved.model.provider}\". Model \"${modelStr}\" cannot be used.`,\n\t\t};\n\t}\n\n\treturn { ok: true, modelId: resolved.model.id, provider: resolved.model.provider };\n}\n\nconst MAX_PARALLEL_TASKS = 8;\nconst MAX_CONCURRENCY = 4;\nconst MAX_TASK_LENGTH = 32_768; // 32 KB — prevent E2BIG from oversized argv\n\n// Semaphore for background task concurrency — shared across all background launches\nlet bgRunning = 0;\nconst bgWaiters: Array<() => void> = [];\n\nasync function bgAcquire(): Promise<void> {\n\tif (bgRunning < MAX_CONCURRENCY) {\n\t\tbgRunning++;\n\t\treturn;\n\t}\n\treturn new Promise<void>((resolve) => {\n\t\tbgWaiters.push(() => {\n\t\t\tbgRunning++;\n\t\t\tresolve();\n\t\t});\n\t});\n}\n\nfunction bgRelease(): void {\n\tbgRunning--;\n\tconst next = bgWaiters.shift();\n\tif (next) next();\n}\n\n/**\n * Resolve a per-task cwd relative to the parent cwd.\n * Rejects absolute paths and relative paths that escape the parent directory.\n * Returns a result object with ok=false and an error string on rejection, so callers can surface it to the model.\n */\nfunction clampCwd(defaultCwd: string, itemCwd?: string): { ok: true; cwd: string } | { ok: false; error: string } {\n\tif (!itemCwd) return { ok: true, cwd: defaultCwd };\n\tif (itemCwd.startsWith(\"/\")) {\n\t\treturn { ok: false, error: `Rejected absolute cwd \"${itemCwd}\" — must be relative to parent cwd` };\n\t}\n\tconst resolved = resolve(defaultCwd, itemCwd);\n\tif (resolved !== defaultCwd && !resolved.startsWith(`${defaultCwd}/`)) {\n\t\treturn { ok: false, error: `Rejected cwd \"${itemCwd}\" — resolves outside parent cwd` };\n\t}\n\treturn { ok: true, cwd: resolved };\n}\n\nasync function executeSingle(\n\tagents: Map<string, AgentTypeConfig>,\n\tagentName: string | undefined,\n\ttask: string,\n\tcwd: string,\n\tsignal?: AbortSignal,\n\tonProgress?: (event: string) => void,\n\tmodelOverride?: string,\n\tparentProvider?: string,\n\tregistry?: ModelRegistry,\n\tsessionDir?: string,\n\tparentModel?: string,\n): Promise<SubagentResult> {\n\tconst name = agentName || DEFAULT_AGENT;\n\tconst config = agents.get(name);\n\tif (!config) {\n\t\treturn {\n\t\t\tagent: name,\n\t\t\ttask,\n\t\t\texitCode: 1,\n\t\t\toutput: \"\",\n\t\t\tstderr: \"\",\n\t\t\terrorMessage: `Unknown agent type \"${name}\". Available: ${[...agents.keys()].join(\", \")}. If you expected \"${name}\" to exist, check the .md file in ~/.dreb/agents/ or .dreb/agents/ for syntax errors.`,\n\t\t};\n\t}\n\t// Validate task length for all modes (single, parallel items, chain steps)\n\tif (task.length > MAX_TASK_LENGTH) {\n\t\treturn {\n\t\t\tagent: name,\n\t\t\ttask: `${task.slice(0, 200)}...`,\n\t\t\texitCode: 1,\n\t\t\toutput: \"\",\n\t\t\tstderr: \"\",\n\t\t\terrorMessage: `Task prompt too long (${task.length} chars, max ${MAX_TASK_LENGTH}). Shorten the prompt.`,\n\t\t};\n\t}\n\t// Per-invocation model override takes precedence over agent definition model.\n\t// Override is always a single string; agent config may be a string or fallback list.\n\tconst modelSpec = modelOverride || config.model;\n\tlet effectiveConfig: AgentTypeConfig = modelOverride ? { ...config, model: modelOverride } : config;\n\tlet resolvedProvider = parentProvider;\n\tlet warning: string | undefined;\n\n\t// Resolve and validate the model against the registry before spawning.\n\t// This catches typos and invalid model names immediately instead of failing\n\t// silently in the child process. Also passes the canonical model ID to the\n\t// child, avoiding fuzzy matching entirely.\n\tif (modelSpec) {\n\t\tconst resolved = resolveModelWithFallbacks(modelSpec, parentProvider, registry, parentModel);\n\t\tif (!resolved.ok) {\n\t\t\treturn {\n\t\t\t\tagent: name,\n\t\t\t\ttask,\n\t\t\t\texitCode: 1,\n\t\t\t\toutput: \"\",\n\t\t\t\tstderr: \"\",\n\t\t\t\terrorMessage: resolved.error,\n\t\t\t};\n\t\t}\n\t\teffectiveConfig = { ...effectiveConfig, model: resolved.modelId };\n\t\tif (resolved.provider) {\n\t\t\tresolvedProvider = resolved.provider;\n\t\t}\n\t\twarning = resolved.warning;\n\t}\n\n\tonProgress?.(`Running ${name} agent...`);\n\tconst result = await spawnSubagent(effectiveConfig, task, cwd, signal, onProgress, resolvedProvider, sessionDir);\n\tif (warning) {\n\t\tresult.output = `[WARNING: ${warning}]\\n\\n${result.output}`;\n\t}\n\treturn result;\n}\n\nasync function executeChain(\n\tagents: Map<string, AgentTypeConfig>,\n\tchain: Array<{ agent?: string; task: string; cwd?: string; model?: string }>,\n\tdefaultCwd: string,\n\tsignal?: AbortSignal,\n\tonProgress?: (event: string) => void,\n\tparentProvider?: string,\n\tregistry?: ModelRegistry,\n\tsessionBaseDir?: string,\n\tdefaultAgent?: string,\n\tdefaultModel?: string,\n\tparentModel?: string,\n): Promise<SubagentResult[]> {\n\tconst results: SubagentResult[] = [];\n\tlet previousOutput = \"\";\n\n\tfor (let i = 0; i < chain.length; i++) {\n\t\tif (signal?.aborted) break;\n\t\tconst step = chain[i];\n\t\tconst task = step.task.replace(/\\{previous\\}/g, previousOutput);\n\t\tonProgress?.(`Chain step ${i + 1}/${chain.length}`);\n\n\t\t// Validate task length after {previous} substitution (can compound across steps)\n\t\tif (task.length > MAX_TASK_LENGTH) {\n\t\t\tresults.push({\n\t\t\t\tagent: step.agent || defaultAgent || DEFAULT_AGENT,\n\t\t\t\ttask: `${task.slice(0, 200)}...`,\n\t\t\t\texitCode: 1,\n\t\t\t\toutput: \"\",\n\t\t\t\tstderr: \"\",\n\t\t\t\terrorMessage: `Task prompt too long after {previous} substitution (${task.length} chars, max ${MAX_TASK_LENGTH}). Shorten the prompt or summarize previous output.`,\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\n\t\tconst cwdResult = clampCwd(defaultCwd, step.cwd);\n\t\tif (!cwdResult.ok) {\n\t\t\tresults.push({\n\t\t\t\tagent: step.agent || defaultAgent || DEFAULT_AGENT,\n\t\t\t\ttask,\n\t\t\t\texitCode: 1,\n\t\t\t\toutput: \"\",\n\t\t\t\tstderr: \"\",\n\t\t\t\terrorMessage: cwdResult.error,\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\n\t\t// Each chain step gets its own session subdirectory\n\t\tconst stepSessionDir = sessionBaseDir ? join(sessionBaseDir, `step-${i + 1}`) : undefined;\n\t\tconst result = await executeSingle(\n\t\t\tagents,\n\t\t\tstep.agent || defaultAgent,\n\t\t\ttask,\n\t\t\tcwdResult.cwd,\n\t\t\tsignal,\n\t\t\tonProgress,\n\t\t\tstep.model || defaultModel,\n\t\t\tparentProvider,\n\t\t\tregistry,\n\t\t\tstepSessionDir,\n\t\t\tparentModel,\n\t\t);\n\t\tresults.push(result);\n\n\t\tif (result.exitCode !== 0) {\n\t\t\tbreak; // stop chain on error\n\t\t}\n\t\tpreviousOutput = result.output;\n\t}\n\n\treturn results;\n}\n\n// ---------------------------------------------------------------------------\n// Background execution\n// ---------------------------------------------------------------------------\n\nfunction generateAgentId(): string {\n\treturn randomBytes(6).toString(\"hex\");\n}\n\n// ---------------------------------------------------------------------------\n// Background agent registry — queryable by TUI / Telegram frontends\n// ---------------------------------------------------------------------------\n\nexport interface BackgroundAgentInfo {\n\tagentId: string;\n\tagentType: string;\n\ttaskSummary: string;\n\tstartedAt: number;\n\tstatus: \"running\" | \"completed\" | \"failed\";\n}\n\nconst backgroundAgentRegistry = new Map<string, BackgroundAgentInfo>();\nconst backgroundAbortControllers = new Map<string, AbortController>();\n\n/** Get a snapshot of all tracked background agents (running and recently completed). Returns readonly clones. */\nexport function getBackgroundAgents(): readonly Readonly<BackgroundAgentInfo>[] {\n\treturn [...backgroundAgentRegistry.values()].map((a) => ({ ...a }));\n}\n\n/** Get only currently running background agents. Returns readonly clones. */\nexport function getRunningBackgroundAgents(): readonly Readonly<BackgroundAgentInfo>[] {\n\treturn [...backgroundAgentRegistry.values()].filter((a) => a.status === \"running\").map((a) => ({ ...a }));\n}\n\n/** Abort all running background agents. */\nexport function abortBackgroundAgents(): void {\n\tfor (const [id, controller] of backgroundAbortControllers) {\n\t\tcontroller.abort();\n\t\tconst entry = backgroundAgentRegistry.get(id);\n\t\tif (entry && entry.status === \"running\") {\n\t\t\tentry.status = \"failed\";\n\t\t}\n\t}\n\tbackgroundAbortControllers.clear();\n}\n\n/** Remove completed/failed entries older than the given age (ms). Default: 5 minutes. */\nexport function pruneBackgroundAgents(maxAgeMs = 5 * 60 * 1000): void {\n\tconst now = Date.now();\n\tfor (const [id, info] of backgroundAgentRegistry) {\n\t\tif (info.status !== \"running\" && now - info.startedAt > maxAgeMs) {\n\t\t\tbackgroundAgentRegistry.delete(id);\n\t\t\tbackgroundAbortControllers.delete(id);\n\t\t}\n\t}\n}\n\nexport interface SubagentToolOptions {\n\t/** Called when a background subagent starts. Used by TUI to show status indicators. */\n\tonBackgroundStart?: (agentId: string, agentType: string, taskSummary: string) => void;\n\t/** Called when a background subagent completes with its result. `cancelled` is true if the user aborted it. */\n\tonBackgroundComplete?: (agentId: string, result: SubagentResult, cancelled: boolean) => void;\n\t/** Parent session's current provider (e.g. \"anthropic\"). Called at each invocation to get the live value after mid-session model switches. */\n\tparentProvider?: () => string | undefined;\n\t/** Parent session's current model ID. Used as a final fallback when all subagent-configured models fail to resolve. Called at each invocation for fresh value. */\n\tparentModel?: () => string | undefined;\n\t/** Model registry for validating model names before spawning child processes. */\n\tmodelRegistry?: ModelRegistry;\n}\n\n// ---------------------------------------------------------------------------\n// Tool schema and definition\n// ---------------------------------------------------------------------------\n\nconst taskItemSchema = Type.Object({\n\tagent: Type.Optional(Type.String({ description: \"Agent type name (default: 'Explore')\" })),\n\ttask: Type.String({ description: \"The task prompt for this subagent\" }),\n\tcwd: Type.Optional(Type.String({ description: \"Working directory (defaults to parent's cwd)\" })),\n\tmodel: Type.Optional(\n\t\tType.String({\n\t\t\tdescription:\n\t\t\t\t\"Model override for this task. Takes precedence over agent definition model. Note: a single-string override discards the agent's fallback list.\",\n\t\t}),\n\t),\n});\n\nconst subagentSchema = Type.Object({\n\tagent: Type.Optional(Type.String({ description: \"Agent type name (default: 'Explore')\" })),\n\ttask: Type.Optional(Type.String({ description: \"Task prompt (single mode)\", minLength: 1 })),\n\tmodel: Type.Optional(\n\t\tType.String({\n\t\t\tdescription:\n\t\t\t\t\"Model override. Takes precedence over agent definition model. Note: a single-string override discards the agent's fallback list. For parallel/chain, set per-task instead.\",\n\t\t}),\n\t),\n\ttasks: Type.Optional(\n\t\tType.Array(taskItemSchema, {\n\t\t\tdescription: \"Array of tasks to run in parallel (max 8)\",\n\t\t\tminItems: 1,\n\t\t\tmaxItems: MAX_PARALLEL_TASKS,\n\t\t}),\n\t),\n\tchain: Type.Optional(\n\t\tType.Array(taskItemSchema, {\n\t\t\tdescription: \"Sequential pipeline — each step can use {previous} for prior output\",\n\t\t\tminItems: 1,\n\t\t}),\n\t),\n\t// background parameter removed — all subagents run in background mode.\n\t// Kept in schema for backward compatibility (silently ignored if passed).\n\tbackground: Type.Optional(\n\t\tType.Boolean({ description: \"Deprecated — all subagents run in background mode. This parameter is ignored.\" }),\n\t),\n});\n\nexport type SubagentToolInput = Static<typeof subagentSchema>;\n\nexport interface SubagentToolDetails {\n\ttruncation?: TruncationResult;\n\tmode: \"single\" | \"parallel\" | \"chain\";\n\tagentCount: number;\n}\n\nfunction formatSubagentCall(\n\targs: SubagentToolInput | undefined,\n\ttheme: typeof import(\"../../modes/interactive/theme/theme.js\").theme,\n\targsComplete = true,\n): string {\n\tconst invalidArg = invalidArgText(theme);\n\n\tif (args?.tasks) {\n\t\t// Show agent type(s) in the parallel label\n\t\tconst agentCounts = new Map<string, number>();\n\t\tfor (const t of args.tasks) {\n\t\t\tconst name = t.agent || args.agent || DEFAULT_AGENT;\n\t\t\tagentCounts.set(name, (agentCounts.get(name) || 0) + 1);\n\t\t}\n\t\tlet typeLabel: string;\n\t\tif (agentCounts.size === 1) {\n\t\t\tconst [name] = [...agentCounts.keys()];\n\t\t\ttypeLabel = `${args.tasks.length} ${name} tasks`;\n\t\t} else {\n\t\t\tconst parts = [...agentCounts.entries()].map(([name, count]) => `${count} ${name}`);\n\t\t\ttypeLabel = `${args.tasks.length} tasks: ${parts.join(\", \")}`;\n\t\t}\n\t\treturn `${theme.fg(\"toolTitle\", theme.bold(\"subagent\"))} ${theme.fg(\"accent\", `parallel (${typeLabel})`)}`;\n\t}\n\tif (args?.chain) {\n\t\tconst agentName = str(args.agent) || args.chain[0]?.agent || DEFAULT_AGENT;\n\t\treturn `${theme.fg(\"toolTitle\", theme.bold(\"subagent\"))} ${theme.fg(\"accent\", `chain (${agentName}, ${args.chain.length} steps)`)}`;\n\t}\n\n\tconst agent = str(args?.agent) || DEFAULT_AGENT;\n\tconst model = str(args?.model);\n\tconst task = str(args?.task);\n\tconst taskPreview = task ? (task.length > 60 ? `${task.slice(0, 57)}...` : task) : null;\n\tconst modelSuffix = model ? ` ${theme.fg(\"muted\", `(${model})`)}` : \"\";\n\treturn (\n\t\ttheme.fg(\"toolTitle\", theme.bold(\"subagent\")) +\n\t\t\" \" +\n\t\ttheme.fg(\"accent\", agent) +\n\t\tmodelSuffix +\n\t\t\" \" +\n\t\t(taskPreview === null\n\t\t\t? argsComplete\n\t\t\t\t? invalidArg\n\t\t\t\t: theme.fg(\"muted\", \"…\")\n\t\t\t: theme.fg(\"toolOutput\", `\"${taskPreview}\"`))\n\t);\n}\n\nfunction formatSubagentResult(\n\tresult: {\n\t\tcontent: Array<{ type: string; text?: string }>;\n\t\tdetails?: SubagentToolDetails;\n\t},\n\toptions: ToolRenderResultOptions,\n\ttheme: typeof import(\"../../modes/interactive/theme/theme.js\").theme,\n\tshowImages: boolean,\n): string {\n\tconst output = getTextOutput(result, showImages).trim();\n\tlet text = \"\";\n\tif (output) {\n\t\tconst lines = output.split(\"\\n\");\n\t\tconst maxLines = options.expanded ? lines.length : 25;\n\t\tconst displayLines = lines.slice(0, maxLines);\n\t\tconst remaining = lines.length - maxLines;\n\t\ttext += `\\n${displayLines.map((line) => theme.fg(\"toolOutput\", line)).join(\"\\n\")}`;\n\t\tif (remaining > 0) {\n\t\t\ttext += `${theme.fg(\"muted\", `\\n... (${remaining} more lines,`)} ${keyHint(\"app.tools.expand\", \"to expand\")})`;\n\t\t}\n\t}\n\tconst truncation = result.details?.truncation;\n\tif (truncation?.truncated) {\n\t\ttext += `\\n${theme.fg(\"warning\", `[Truncated: ${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit]`)}`;\n\t}\n\treturn text;\n}\n\nfunction formatSingleResult(result: SubagentResult): string {\n\tlet text = `## Agent: ${result.agent}${result.model ? ` (model: ${result.model})` : \"\"}\\n`;\n\tif (result.exitCode !== 0) {\n\t\ttext += `**Error** (exit ${result.exitCode}): ${result.errorMessage || \"Unknown error\"}\\n`;\n\t\tif (result.stderr) {\n\t\t\ttext += `\\nStderr:\\n${result.stderr}\\n`;\n\t\t}\n\t}\n\tif (result.output) {\n\t\ttext += `\\n${result.output}`;\n\t} else if (result.exitCode === 0) {\n\t\ttext += \"\\n(No output)\";\n\t}\n\tif (result.sessionFile) {\n\t\ttext += `\\n\\nSession log: ${result.sessionFile}`;\n\t}\n\treturn text;\n}\n\nexport function createSubagentToolDefinition(\n\tcwd: string,\n\toptions?: SubagentToolOptions,\n): ToolDefinition<typeof subagentSchema, SubagentToolDetails | undefined> {\n\tconst onBackgroundStart = options?.onBackgroundStart;\n\tconst onBackgroundComplete = options?.onBackgroundComplete;\n\tconst getParentProvider = options?.parentProvider ?? (() => undefined);\n\tconst getParentModel = options?.parentModel ?? (() => undefined);\n\tconst modelRegistry = options?.modelRegistry;\n\n\t// Discover agents at definition time to build the prompt guidelines.\n\t// This is cheap (reads .md files) and the same call happens on every execute().\n\tconst knownAgents = discoverAgentTypes(cwd);\n\tconst agentListParts: string[] = [];\n\tfor (const [name, config] of knownAgents) {\n\t\tconst defaultTag = name === DEFAULT_AGENT ? \" (default)\" : \"\";\n\t\tconst desc = config.description || name;\n\t\tagentListParts.push(`'${name}'${defaultTag} — ${desc}`);\n\t}\n\tconst builtInAgentsLine = `Built-in agents: ${agentListParts.join(\"; \")}`;\n\n\treturn {\n\t\tname: \"subagent\",\n\t\tlabel: \"subagent\",\n\t\tdescription:\n\t\t\t\"Delegate tasks to independent subagents (Explore for codebase research, Sandbox for isolated /tmp-only analysis). \" +\n\t\t\t\"Supports single task, parallel (up to 8, max 4 concurrent), \" +\n\t\t\t\"and chain (sequential pipeline with {previous} substitution) modes. \" +\n\t\t\t\"All subagents run in background — returns immediately, notifies on completion.\",\n\t\tpromptSnippet: \"Delegate tasks to independent subagents\",\n\t\tpromptGuidelines: [\n\t\t\t\"Use `subagent` to delegate focused, independent tasks to child agents\",\n\t\t\t\"Available agent types can be discovered from ~/.dreb/agents/ and .dreb/agents/ markdown files\",\n\t\t\tbuiltInAgentsLine,\n\t\t\t\"Use parallel mode for independent tasks that can run concurrently\",\n\t\t\t\"Use chain mode when each step depends on the previous step's output (reference with {previous})\",\n\t\t\t\"All subagents run in background — the tool returns immediately and you are notified when each agent completes.\",\n\t\t\t\"Subagents have their own context window — provide enough context in the task prompt\",\n\t\t\t\"Each agent notifies independently when done — completion messages include a list of any still-running agents. If you need their results before proceeding, end your current turn with no tool calls (as if you were asking the user a question and waiting for their reply). This emits `agent_end` and lets the framework deliver the completion as a new message that resumes your turn automatically. Do not call `sleep` or any other waiting action, and do not launch filler work.\",\n\t\t\t\"Agent definitions specify a `model` field with a provider fallback list (comma-separated or YAML list). The spawner tries each in order and uses the first one that resolves for the current provider. This makes agents portable across providers.\",\n\t\t\t\"Per-invocation `model` overrides take precedence but **discard the entire fallback list** — if the single override model isn't available on the current provider, the agent fails. Only override when you have a specific reason (e.g. escalating to a stronger tier for a complex task).\",\n\t\t\t\"**Model routing** — agent definitions already specify the right tier for their role. Most subagent tasks (exploration, file discovery, grep, navigation, summarization) are handled well by the defaults. Do not override the model unless the task genuinely requires a different capability tier than what the agent definition provides.\",\n\t\t],\n\t\tparameters: subagentSchema,\n\n\t\tasync execute(_toolCallId, params: SubagentToolInput, _signal, _onUpdate) {\n\t\t\tconst agents = discoverAgentTypes(cwd);\n\n\t\t\t// Determine mode\n\t\t\tconst modeCount = (params.task ? 1 : 0) + (params.tasks ? 1 : 0) + (params.chain ? 1 : 0);\n\t\t\tif (modeCount === 0) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{ type: \"text\", text: \"Error: provide one of `task` (single), `tasks` (parallel), or `chain`.\" },\n\t\t\t\t\t],\n\t\t\t\t\tdetails: undefined,\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (modeCount > 1) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: \"Error: modes are mutually exclusive — provide only one of `task`, `tasks`, or `chain`.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tdetails: undefined,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// All subagents run in background mode — return immediately, notify on completion\n\t\t\t{\n\t\t\t\tif (!onBackgroundComplete) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: \"Subagent execution requires background support, which is not available in this session.\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tdetails: undefined,\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\t/**\n\t\t\t\t * Shared lifecycle for all background launches: generates agent ID,\n\t\t\t\t * sets up registry/abort/notification, gates on the concurrency\n\t\t\t\t * semaphore, and handles errors. The caller provides the actual\n\t\t\t\t * work via `runFn(signal)` which must return a SubagentResult.\n\t\t\t\t */\n\t\t\t\tconst launchBackgroundLifecycle = (\n\t\t\t\t\tagentName: string,\n\t\t\t\t\ttaskSummary: string,\n\t\t\t\t\trunFn: (signal: AbortSignal) => Promise<SubagentResult>,\n\t\t\t\t): string => {\n\t\t\t\t\tconst agentId = generateAgentId();\n\t\t\t\t\tconst bgAbort = new AbortController();\n\t\t\t\t\tbackgroundAgentRegistry.set(agentId, {\n\t\t\t\t\t\tagentId,\n\t\t\t\t\t\tagentType: agentName,\n\t\t\t\t\t\ttaskSummary,\n\t\t\t\t\t\tstartedAt: Date.now(),\n\t\t\t\t\t\tstatus: \"running\",\n\t\t\t\t\t});\n\t\t\t\t\tbackgroundAbortControllers.set(agentId, bgAbort);\n\t\t\t\t\tonBackgroundStart?.(agentId, agentName, taskSummary);\n\n\t\t\t\t\tconst bgSignal = bgAbort.signal;\n\n\t\t\t\t\tconst safeNotify = (result: SubagentResult) => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tonBackgroundComplete(agentId, result, bgSignal.aborted);\n\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\t\t`[subagent] onBackgroundComplete threw for agent ${agentId}: ${err instanceof Error ? err.message : String(err)}. Background result lost.`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\n\t\t\t\t\tconst run = async () => {\n\t\t\t\t\t\tawait bgAcquire();\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst result = await runFn(bgSignal);\n\t\t\t\t\t\t\tconst entry = backgroundAgentRegistry.get(agentId);\n\t\t\t\t\t\t\tif (entry && !bgSignal.aborted) entry.status = result.exitCode === 0 ? \"completed\" : \"failed\";\n\t\t\t\t\t\t\tbackgroundAbortControllers.delete(agentId);\n\t\t\t\t\t\t\tsafeNotify(result);\n\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\tconst entry = backgroundAgentRegistry.get(agentId);\n\t\t\t\t\t\t\tif (entry && !bgSignal.aborted) entry.status = \"failed\";\n\t\t\t\t\t\t\tbackgroundAbortControllers.delete(agentId);\n\t\t\t\t\t\t\tsafeNotify({\n\t\t\t\t\t\t\t\tagent: agentName,\n\t\t\t\t\t\t\t\ttask: taskSummary,\n\t\t\t\t\t\t\t\texitCode: 1,\n\t\t\t\t\t\t\t\toutput: \"\",\n\t\t\t\t\t\t\t\tstderr: \"\",\n\t\t\t\t\t\t\t\terrorMessage: err instanceof Error ? err.message : String(err),\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\tbgRelease();\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t\trun().catch((err) => {\n\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\t`[subagent] Unhandled background error (${agentId}): ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst entry = backgroundAgentRegistry.get(agentId);\n\t\t\t\t\t\tif (entry && entry.status === \"running\") entry.status = \"failed\";\n\t\t\t\t\t\tbackgroundAbortControllers.delete(agentId);\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tonBackgroundComplete(\n\t\t\t\t\t\t\t\tagentId,\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tagent: agentName,\n\t\t\t\t\t\t\t\t\ttask: taskSummary,\n\t\t\t\t\t\t\t\t\texitCode: 1,\n\t\t\t\t\t\t\t\t\toutput: \"\",\n\t\t\t\t\t\t\t\t\tstderr: \"\",\n\t\t\t\t\t\t\t\t\terrorMessage: `Internal error: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tbgSignal.aborted,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t} catch (notifyErr) {\n\t\t\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\t\t`[subagent] CRITICAL: Last-resort notification failed for ${agentId}: ${notifyErr instanceof Error ? notifyErr.message : String(notifyErr)}`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\n\t\t\t\t\treturn agentId;\n\t\t\t\t};\n\n\t\t\t\t// Helper to launch a single background task\n\t\t\t\tconst subagentSessionsBase = getSubagentSessionsDir();\n\t\t\t\tconst launchBackgroundTask = (\n\t\t\t\t\tagentName: string,\n\t\t\t\t\ttask: string,\n\t\t\t\t\ttaskLabel: string,\n\t\t\t\t\ttaskCwd?: string,\n\t\t\t\t\tmodelOverride?: string,\n\t\t\t\t) => {\n\t\t\t\t\tconst resolvedCwd = taskCwd ?? cwd;\n\t\t\t\t\t// Each background agent gets its own session subdirectory\n\t\t\t\t\tconst sessionId = generateAgentId();\n\t\t\t\t\tconst sessionDir = join(subagentSessionsBase, sessionId);\n\t\t\t\t\treturn launchBackgroundLifecycle(agentName, taskLabel, (signal) =>\n\t\t\t\t\t\texecuteSingle(\n\t\t\t\t\t\t\tagents,\n\t\t\t\t\t\t\tagentName === DEFAULT_AGENT ? undefined : agentName,\n\t\t\t\t\t\t\ttask,\n\t\t\t\t\t\t\tresolvedCwd,\n\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t\tundefined,\n\t\t\t\t\t\t\tmodelOverride,\n\t\t\t\t\t\t\tgetParentProvider(),\n\t\t\t\t\t\t\tmodelRegistry,\n\t\t\t\t\t\t\tsessionDir,\n\t\t\t\t\t\t\tgetParentModel(),\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t};\n\n\t\t\t\tif (params.task) {\n\t\t\t\t\t// Single background task\n\t\t\t\t\tconst agentName = params.agent || DEFAULT_AGENT;\n\t\t\t\t\tconst agentId = launchBackgroundTask(\n\t\t\t\t\t\tagentName,\n\t\t\t\t\t\tparams.task,\n\t\t\t\t\t\t`${agentName} task`,\n\t\t\t\t\t\tundefined,\n\t\t\t\t\t\tparams.model,\n\t\t\t\t\t);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: `Background agent ${agentId} started (${agentName}). You will be notified when it completes.`,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tdetails: { mode: \"single\", agentCount: 1 } as SubagentToolDetails,\n\t\t\t\t\t\tendTurn: true,\n\t\t\t\t\t};\n\t\t\t\t} else if (params.tasks) {\n\t\t\t\t\t// Parallel background tasks — each gets its own agent ID and notifies independently\n\t\t\t\t\tconst launched: Array<{ id: string; agentName: string; taskText: string }> = [];\n\t\t\t\t\tconst skipped: Array<{ taskText: string; error: string }> = [];\n\t\t\t\t\tfor (let i = 0; i < params.tasks.length; i++) {\n\t\t\t\t\t\tconst item = params.tasks[i];\n\t\t\t\t\t\tconst agentName = item.agent || params.agent || DEFAULT_AGENT;\n\t\t\t\t\t\tconst cwdResult = clampCwd(cwd, item.cwd);\n\t\t\t\t\t\tif (!cwdResult.ok) {\n\t\t\t\t\t\t\tskipped.push({ taskText: item.task, error: cwdResult.error });\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst agentId = launchBackgroundTask(\n\t\t\t\t\t\t\tagentName,\n\t\t\t\t\t\t\titem.task,\n\t\t\t\t\t\t\t`${agentName} task ${i + 1}/${params.tasks.length}`,\n\t\t\t\t\t\t\tcwdResult.cwd,\n\t\t\t\t\t\t\titem.model || params.model,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tlaunched.push({ id: agentId, agentName, taskText: item.task });\n\t\t\t\t\t}\n\t\t\t\t\tconst listing = launched\n\t\t\t\t\t\t.map(({ id, agentName, taskText }) => ` ${id} (${agentName}): ${taskText.slice(0, 80)}`)\n\t\t\t\t\t\t.join(\"\\n\");\n\t\t\t\t\tconst skippedListing = skipped\n\t\t\t\t\t\t.map(({ taskText, error }) => ` SKIPPED: ${taskText.slice(0, 60)} — ${error}`)\n\t\t\t\t\t\t.join(\"\\n\");\n\t\t\t\t\tconst parts = [`${launched.length} background agents started:\\n${listing}`];\n\t\t\t\t\tif (skipped.length > 0) {\n\t\t\t\t\t\tparts.push(`\\n${skipped.length} task(s) failed to launch:\\n${skippedListing}`);\n\t\t\t\t\t}\n\t\t\t\t\tif (launched.length > 0) {\n\t\t\t\t\t\tparts.push(\"\\nEach will notify independently when complete.\");\n\t\t\t\t\t} else {\n\t\t\t\t\t\tparts.push(\"\\nNo agents were launched.\");\n\t\t\t\t\t}\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: parts.join(\"\\n\"),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tdetails: { mode: \"parallel\", agentCount: launched.length } as SubagentToolDetails,\n\t\t\t\t\t\tendTurn: launched.length > 0,\n\t\t\t\t\t};\n\t\t\t\t} else {\n\t\t\t\t\t// Chain mode — sequential, stays as one agent since steps depend on each other\n\t\t\t\t\tconst agentName = params.agent || params.chain![0].agent || DEFAULT_AGENT;\n\t\t\t\t\tconst taskSummary = `${params.chain!.length}-step chain`;\n\t\t\t\t\tconst chainSteps = params.chain!;\n\n\t\t\t\t\tconst chainSessionDir = join(subagentSessionsBase, `chain-${generateAgentId()}`);\n\t\t\t\t\tconst agentId = launchBackgroundLifecycle(agentName, taskSummary, async (signal) => {\n\t\t\t\t\t\tconst results = await executeChain(\n\t\t\t\t\t\t\tagents,\n\t\t\t\t\t\t\tchainSteps,\n\t\t\t\t\t\t\tcwd,\n\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t\tundefined,\n\t\t\t\t\t\t\tgetParentProvider(),\n\t\t\t\t\t\t\tmodelRegistry,\n\t\t\t\t\t\t\tchainSessionDir,\n\t\t\t\t\t\t\tparams.agent,\n\t\t\t\t\t\t\tparams.model,\n\t\t\t\t\t\t\tgetParentModel(),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst resultText = results\n\t\t\t\t\t\t\t.map((r, i) => `### Step ${i + 1}\\n${formatSingleResult(r)}`)\n\t\t\t\t\t\t\t.join(\"\\n\\n---\\n\\n\");\n\t\t\t\t\t\tconst failed = results.filter((r) => r.exitCode !== 0);\n\t\t\t\t\t\t// Per-step session logs are already embedded in resultText via formatSingleResult\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tagent: agentName,\n\t\t\t\t\t\t\ttask: taskSummary,\n\t\t\t\t\t\t\texitCode: failed.length > 0 ? 1 : 0,\n\t\t\t\t\t\t\toutput: resultText,\n\t\t\t\t\t\t\tstderr: \"\",\n\t\t\t\t\t\t\terrorMessage:\n\t\t\t\t\t\t\t\tfailed.length > 0\n\t\t\t\t\t\t\t\t\t? `Chain stopped at step ${results.length} of ${chainSteps.length}: ${results[results.length - 1]?.errorMessage}`\n\t\t\t\t\t\t\t\t\t: null,\n\t\t\t\t\t\t};\n\t\t\t\t\t});\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: `Background chain ${agentId} started (${taskSummary}). You will be notified when it completes.`,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tdetails: { mode: \"chain\", agentCount: chainSteps.length } as SubagentToolDetails,\n\t\t\t\t\t\tendTurn: true,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\n\t\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatSubagentCall(args, theme, context.argsComplete));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatSubagentResult(result as any, options, theme, context.showImages));\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createSubagentTool(cwd: string, options?: SubagentToolOptions): AgentTool<typeof subagentSchema> {\n\treturn wrapToolDefinition(createSubagentToolDefinition(cwd, options));\n}\n\nexport const subagentToolDefinition = createSubagentToolDefinition(process.cwd());\nexport const subagentTool = createSubagentTool(process.cwd());\n"]}
|
|
1
|
+
{"version":3,"file":"subagent.d.ts","sourceRoot":"","sources":["../../../src/core/tools/subagent.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,KAAK,GAAG,EAAiD,KAAK,KAAK,EAAE,MAAM,UAAU,CAAC;AAE/F,OAAO,EAAE,KAAK,MAAM,EAAQ,MAAM,mBAAmB,CAAC;AAItD,OAAO,KAAK,EAAE,cAAc,EAA2B,MAAM,wBAAwB,CAAC;AAEtF,OAAO,KAAK,EAAE,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AO,CAAC;IACtC,UAAU,EAAE,MAAM,CAAC;CACnB;AAiGD,wBAAgB,4BAA4B,CAC3C,GAAG,EAAE,MAAM,EACX,OAAO,CAAC,EAAE,mBAAmB,GAC3B,cAAc,CAAC,OAAO,cAAc,EAAE,mBAAmB,GAAG,SAAS,CAAC,CA0UxE;AAED,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,mBAAmB,GAAG,SAAS,CAAC,OAAO,cAAc,CAAC,CAE/G;AAED,eAAO,MAAM,sBAAsB;;;;;;;;;;;;;;;;;yCAA8C,CAAC;AAClF,eAAO,MAAM,YAAY;;;;;;;;;;;;;;;;;QAAoC,CAAC","sourcesContent":["import { type ChildProcess, spawn } from \"node:child_process\";\nimport { randomBytes } from \"node:crypto\";\nimport { existsSync, readdirSync, readFileSync, statSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join, resolve } from \"node:path\";\nimport type { AgentTool } from \"@dreb/agent-core\";\nimport { type Api, type AssistantMessage, type Context, complete, type Model } from \"@dreb/ai\";\nimport { Text } from \"@dreb/tui\";\nimport { type Static, Type } from \"@sinclair/typebox\";\nimport { CONFIG_DIR_NAME, getPackageDir, getSubagentSessionsDir } from \"../../config.js\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.js\";\nimport { attachJsonlLineReader } from \"../../modes/rpc/jsonl.js\";\nimport type { ToolDefinition, ToolRenderResultOptions } from \"../extensions/types.js\";\nimport { log } from \"../logger.js\";\nimport type { ModelRegistry } from \"../model-registry.js\";\nimport { resolveCliModel } from \"../model-resolver.js\";\nimport { getTextOutput, invalidArgText, str } from \"./render-utils.js\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.js\";\nimport { DEFAULT_MAX_BYTES, formatSize, type TruncationResult } from \"./truncate.js\";\n\n// ---------------------------------------------------------------------------\n// Agent type system\n// ---------------------------------------------------------------------------\n\nexport interface AgentTypeConfig {\n\tname: string;\n\tdescription: string;\n\ttools?: string;\n\t/** Single model ID or ordered fallback list. First resolvable model wins. */\n\tmodel?: string | string[];\n\tsystemPrompt: string;\n}\n\nconst DEFAULT_AGENT = \"Explore\";\n\nexport function parseAgentFrontmatter(\n\tcontent: string,\n): { ok: true; config: AgentTypeConfig } | { ok: false; error: string } {\n\tconst fmMatch = content.match(/^---\\n([\\s\\S]*?)\\n---\\n?([\\s\\S]*)$/);\n\tif (!fmMatch) return { ok: false, error: \"missing --- frontmatter delimiters\" };\n\n\tconst frontmatter = fmMatch[1];\n\tconst body = fmMatch[2].trim();\n\n\tconst get = (key: string): string | undefined => {\n\t\tconst match = frontmatter.match(new RegExp(`^${key}:\\\\s*(.+)$`, \"m\"));\n\t\treturn match?.[1].trim();\n\t};\n\n\t/** Parse `model` field — supports single string, comma-separated, or YAML list syntax. */\n\tconst getModel = (): string | string[] | undefined => {\n\t\t// First check for YAML list syntax (indented lines starting with \"- \")\n\t\tconst listMatch = frontmatter.match(/^model:\\s*\\n((?:\\s+-\\s+.+\\n?)+)/m);\n\t\tif (listMatch) {\n\t\t\tconst items = listMatch[1]\n\t\t\t\t.split(\"\\n\")\n\t\t\t\t.map((line) => line.replace(/^\\s+-\\s+/, \"\").trim())\n\t\t\t\t.filter(Boolean);\n\t\t\treturn items.length > 1 ? items : items[0];\n\t\t}\n\t\t// Inline value — check for comma-separated list\n\t\tconst value = get(\"model\");\n\t\tif (!value) return undefined;\n\t\tif (value.includes(\",\")) {\n\t\t\tconst items = value\n\t\t\t\t.split(\",\")\n\t\t\t\t.map((s) => s.trim())\n\t\t\t\t.filter(Boolean);\n\t\t\treturn items.length > 1 ? items : items[0];\n\t\t}\n\t\treturn value;\n\t};\n\n\tconst name = get(\"name\");\n\tif (!name) return { ok: false, error: \"missing required 'name' field in frontmatter\" };\n\n\treturn {\n\t\tok: true,\n\t\tconfig: {\n\t\t\tname,\n\t\t\tdescription: get(\"description\") || \"\",\n\t\t\ttools: get(\"tools\"),\n\t\t\tmodel: getModel(),\n\t\t\tsystemPrompt: body,\n\t\t},\n\t};\n}\n\nfunction discoverAgentTypes(cwd: string): Map<string, AgentTypeConfig> {\n\tconst agents = new Map<string, AgentTypeConfig>();\n\n\t// Package-bundled agents (shipped with dreb — the canonical source of truth for built-in agents)\n\tconst packageAgentsDir = join(getPackageDir(), \"agents\");\n\tloadAgentsFromDir(packageAgentsDir, agents);\n\n\t// User-level agents (~/.dreb/agents/*.md)\n\tconst userDir = join(homedir(), CONFIG_DIR_NAME, \"agents\");\n\tloadAgentsFromDir(userDir, agents);\n\n\t// Project-level agents (.dreb/agents/*.md)\n\t// TODO: Security gate — prompt user for confirmation before loading agents from untrusted repos\n\tconst projectDir = join(cwd, \".dreb\", \"agents\");\n\tloadAgentsFromDir(projectDir, agents);\n\n\treturn agents;\n}\n\nfunction loadAgentsFromDir(dir: string, agents: Map<string, AgentTypeConfig>): void {\n\tif (!existsSync(dir)) return;\n\ttry {\n\t\tfor (const file of readdirSync(dir)) {\n\t\t\tif (!file.endsWith(\".md\")) continue;\n\t\t\ttry {\n\t\t\t\tconst content = readFileSync(join(dir, file), \"utf-8\");\n\t\t\t\tconst parsed = parseAgentFrontmatter(content);\n\t\t\t\tif (!parsed.ok) {\n\t\t\t\t\tlog.warn(`[subagent] Skipping agent file ${join(dir, file)}: ${parsed.error}`);\n\t\t\t\t} else {\n\t\t\t\t\tagents.set(parsed.config.name, parsed.config);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tlog.warn(\n\t\t\t\t\t`[subagent] Could not read agent file ${join(dir, file)}: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t} catch (err) {\n\t\tif ((err as NodeJS.ErrnoException).code !== \"ENOENT\") {\n\t\t\tlog.warn(\n\t\t\t\t`[subagent] Could not read agents directory ${dir}: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t);\n\t\t}\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Subagent process spawning\n// ---------------------------------------------------------------------------\n\nexport interface SubagentResult {\n\tagent: string;\n\ttask: string;\n\tmodel?: string;\n\texitCode: number;\n\toutput: string;\n\tstderr: string;\n\terrorMessage: string | null;\n\t/** Path to the persisted session JSONL file, if available */\n\tsessionFile?: string;\n}\n\n// Capture at module load before process.title overwrites argv memory on Linux.\n// After process.title = \"dreb\" (in cli.ts), the original argv area is overwritten\n// and process.argv[1] may return corrupted or truncated data.\nconst DREB_SCRIPT = process.argv[1] || \"dreb\";\nconst NODE_EXEC = process.execPath;\n\n// Tools that must never be available to subagents — wait (subagents should\n// never no-op; they have a task to complete) and subagent (no recursive spawning).\nconst SUBAGENT_EXCLUDED_TOOLS = [\"wait\", \"subagent\"] as const;\n\n// Default standard tools for subagents when no tools are specified in the agent\n// definition. This is the set passed via --tools to the child process.\n//\n// NOTE: Always-active tools (search, skill, tasks_update, suggest_next) are NOT\n// listed here — the child process adds them unconditionally regardless of --tools.\n// Internal tools (tmp_read) are also excluded.\nconst SUBAGENT_DEFAULT_TOOLS = [\"read\", \"bash\", \"edit\", \"write\", \"grep\", \"find\", \"ls\", \"web_search\", \"web_fetch\"];\n\n/**\n * Filter a comma-separated tools string, removing any tools in SUBAGENT_EXCLUDED_TOOLS.\n * Returns the filtered tools as a comma-separated string (always non-empty — falls\n * back to SUBAGENT_DEFAULT_TOOLS if all specified tools were excluded).\n */\nexport function filterSubagentTools(tools: string | undefined): string {\n\tif (!tools) return SUBAGENT_DEFAULT_TOOLS.join(\",\");\n\tconst filtered = tools\n\t\t.split(\",\")\n\t\t.map((t) => t.trim())\n\t\t.filter((t) => !(SUBAGENT_EXCLUDED_TOOLS as readonly string[]).includes(t))\n\t\t.join(\",\");\n\treturn filtered || SUBAGENT_DEFAULT_TOOLS.join(\",\");\n}\n\n// TODO: Support PATH-based binary discovery.\n// Currently returns the captured argv[1].\nfunction findDrebBinary(): string {\n\treturn DREB_SCRIPT;\n}\n\nasync function spawnSubagent(\n\tagentConfig: AgentTypeConfig,\n\ttask: string,\n\tcwd: string,\n\tsignal?: AbortSignal,\n\tonProgress?: (event: string) => void,\n\tparentProvider?: string,\n\tsessionDir?: string,\n): Promise<SubagentResult> {\n\tconst drebBin = findDrebBinary();\n\tlog.debug(`[subagent] spawn: agent=${agentConfig.name} cwd=${cwd}`);\n\n\t// Validate cwd exists — spawn() throws a misleading ENOENT blaming the\n\t// binary when the cwd is invalid, making the real cause hard to diagnose\n\tif (!existsSync(cwd)) {\n\t\treturn {\n\t\t\tagent: agentConfig.name,\n\t\t\ttask,\n\t\t\texitCode: 1,\n\t\t\toutput: \"\",\n\t\t\tstderr: \"\",\n\t\t\terrorMessage: `Working directory does not exist: ${cwd}`,\n\t\t};\n\t}\n\n\tconst args: string[] = [\"--mode\", \"json\", \"--ui\", \"agent\"];\n\tif (sessionDir) {\n\t\targs.push(\"--session-dir\", sessionDir);\n\t} else {\n\t\targs.push(\"--no-session\");\n\t}\n\t// By spawn time, model should be a resolved single string (fallback resolution\n\t// happens in executeSingle). Handle string[] defensively by taking the first entry.\n\tconst modelStr = Array.isArray(agentConfig.model) ? agentConfig.model[0] : agentConfig.model;\n\tif (modelStr) {\n\t\targs.push(\"--model\", modelStr);\n\t\t// When the model string doesn't already specify a provider (no \"/\"),\n\t\t// inherit the parent's provider to prevent fuzzy matching from picking\n\t\t// an unauthenticated provider (e.g. Bedrock instead of Anthropic).\n\t\tif (parentProvider && !modelStr.includes(\"/\")) {\n\t\t\targs.push(\"--provider\", parentProvider);\n\t\t}\n\t}\n\t// Always pass --tools to ensure wait/subagent are excluded from child processes.\n\t// filterSubagentTools always returns a non-empty string.\n\targs.push(\"--tools\", filterSubagentTools(agentConfig.tools));\n\tif (agentConfig.systemPrompt) {\n\t\targs.push(\"--append-system-prompt\", agentConfig.systemPrompt);\n\t}\n\t// Pass agent type metadata so the child session can record it in its JSONL header\n\targs.push(\"--agent-type\", agentConfig.name);\n\targs.push(\"-p\", task);\n\n\t// Early abort check — if the signal is already aborted (e.g. queued task whose\n\t// AbortController was aborted while waiting on bgAcquire), bail out before\n\t// spawning a child process that can never be killed. addEventListener(\"abort\")\n\t// on an already-aborted signal does NOT fire the callback in Node.js.\n\tif (signal?.aborted) {\n\t\treturn {\n\t\t\tagent: agentConfig.name,\n\t\t\ttask,\n\t\t\texitCode: 1,\n\t\t\toutput: \"\",\n\t\t\tstderr: \"\",\n\t\t\terrorMessage: \"Aborted before spawn\",\n\t\t};\n\t}\n\n\treturn new Promise<SubagentResult>((resolvePromise, rejectPromise) => {\n\t\tlet proc: ChildProcess;\n\t\ttry {\n\t\t\tproc = spawn(NODE_EXEC, [drebBin, ...args], {\n\t\t\t\tcwd,\n\t\t\t\tstdio: [\"ignore\", \"pipe\", \"pipe\"],\n\t\t\t\tenv: { ...process.env },\n\t\t\t});\n\t\t} catch (err) {\n\t\t\trejectPromise(new Error(`Failed to spawn subagent: ${err instanceof Error ? err.message : String(err)}`));\n\t\t\treturn;\n\t\t}\n\n\t\tlet settled = false;\n\t\tlet killTimer: ReturnType<typeof setTimeout> | null = null;\n\t\tconst collectedMessages: Array<{ role: string; content: any[] }> = [];\n\t\tconst stderrChunks: string[] = [];\n\t\tlet stderrSize = 0;\n\t\tconst MAX_STDERR_BYTES = 8192;\n\t\tconst plainStdoutLines: string[] = [];\n\t\tlet lastToolName = \"\";\n\t\tlet resolvedModel: string | undefined;\n\n\t\t// Drain stderr concurrently to avoid pipe deadlock (capped to prevent OOM from verbose subagents)\n\t\tproc.stderr?.on(\"data\", (chunk: Buffer) => {\n\t\t\tif (stderrSize < MAX_STDERR_BYTES) {\n\t\t\t\tconst str = chunk.toString();\n\t\t\t\tstderrChunks.push(str);\n\t\t\t\tstderrSize += str.length;\n\t\t\t}\n\t\t});\n\t\tproc.stderr?.on(\"error\", (err) => {\n\t\t\tlog.warn(`[subagent] stderr stream error (agent=${agentConfig.name}): ${err.message}`);\n\t\t});\n\n\t\t// Parse JSONL events from stdout\n\t\tif (proc.stdout) {\n\t\t\tproc.stdout.on(\"error\", (err) => {\n\t\t\t\tlog.warn(`[subagent] stdout stream error (agent=${agentConfig.name}): ${err.message}`);\n\t\t\t});\n\t\t\tattachJsonlLineReader(proc.stdout, (line) => {\n\t\t\t\tif (!line.trim()) return;\n\t\t\t\t// Separate JSON.parse from event handling so only parse failures\n\t\t\t\t// are caught as non-JSON lines — errors in handling propagate normally\n\t\t\t\tlet event: any;\n\t\t\t\ttry {\n\t\t\t\t\tevent = JSON.parse(line);\n\t\t\t\t} catch {\n\t\t\t\t\t// Capture non-JSON lines — on failure these often contain the real error\n\t\t\t\t\t// (e.g. startup errors printed before JSONL mode begins)\n\t\t\t\t\tplainStdoutLines.push(line.trim());\n\t\t\t\t\tif (line.trim().startsWith(\"{\")) {\n\t\t\t\t\t\tlog.warn(`[subagent] Failed to parse JSONL event: ${line.slice(0, 200)}`);\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (event.type === \"agent_start\" && event.model) {\n\t\t\t\t\tresolvedModel = event.model.id;\n\t\t\t\t}\n\t\t\t\tif (event.type === \"message_end\" && event.message?.role === \"assistant\") {\n\t\t\t\t\tcollectedMessages.push(event.message);\n\t\t\t\t}\n\t\t\t\tif (event.type === \"tool_execution_start\" && onProgress) {\n\t\t\t\t\tlastToolName = event.toolName || \"\";\n\t\t\t\t\tonProgress(`Using ${lastToolName}...`);\n\t\t\t\t}\n\t\t\t\tif (event.type === \"tool_execution_end\" && onProgress) {\n\t\t\t\t\tonProgress(`${lastToolName} done`);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\t// Handle abort signal (guard kill() against ESRCH race if process already exited)\n\t\tconst onAbort = () => {\n\t\t\ttry {\n\t\t\t\tproc.kill(\"SIGTERM\");\n\t\t\t} catch {\n\t\t\t\t/* process already exited */\n\t\t\t}\n\t\t\tkillTimer = setTimeout(() => {\n\t\t\t\ttry {\n\t\t\t\t\tif (!proc.killed) proc.kill(\"SIGKILL\");\n\t\t\t\t} catch {\n\t\t\t\t\t/* process already exited */\n\t\t\t\t}\n\t\t\t}, 5000);\n\t\t};\n\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\n\t\tproc.on(\"error\", (err) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tif (killTimer) clearTimeout(killTimer);\n\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\trejectPromise(new Error(`Subagent process error: ${err.message}`));\n\t\t});\n\n\t\tproc.on(\"close\", (code) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tif (killTimer) clearTimeout(killTimer);\n\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\tconst exitCode = code ?? 1;\n\t\t\tconst stderr = stderrChunks.join(\"\");\n\t\t\tlog.debug(\n\t\t\t\t`[subagent] close: agent=${agentConfig.name} exit=${exitCode} messages=${collectedMessages.length}${exitCode !== 0 ? ` stderr=${stderr.slice(0, 200)} stdout=${plainStdoutLines.join(\"|\").slice(0, 200)}` : \"\"}`,\n\t\t\t);\n\n\t\t\t// Extract final text output from collected assistant messages\n\t\t\tconst outputParts: string[] = [];\n\t\t\tfor (const msg of collectedMessages) {\n\t\t\t\tif (Array.isArray(msg.content)) {\n\t\t\t\t\tfor (const part of msg.content) {\n\t\t\t\t\t\tif (part.type === \"text\" && part.text) {\n\t\t\t\t\t\t\toutputParts.push(part.text);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst output = outputParts.join(\"\\n\\n\");\n\n\t\t\t// Build error message from best available source: stderr, plain stdout lines, or generic\n\t\t\tlet errorMessage: string | null = null;\n\t\t\tif (exitCode !== 0) {\n\t\t\t\tconst stderrTrimmed = stderr.trim();\n\t\t\t\tconst plainOutput = plainStdoutLines.join(\"\\n\").trim();\n\t\t\t\terrorMessage =\n\t\t\t\t\tstderrTrimmed.slice(0, 500) || plainOutput.slice(0, 500) || `Subagent exited with code ${exitCode}`;\n\t\t\t}\n\n\t\t\t// Discover the session file written by the child process\n\t\t\tconst sessionFile = sessionDir ? discoverSessionFile(sessionDir, agentConfig.name) : undefined;\n\n\t\t\tresolvePromise({\n\t\t\t\tagent: agentConfig.name,\n\t\t\t\ttask,\n\t\t\t\tmodel:\n\t\t\t\t\tresolvedModel ??\n\t\t\t\t\t(exitCode === 0\n\t\t\t\t\t\t? Array.isArray(agentConfig.model)\n\t\t\t\t\t\t\t? agentConfig.model[0]\n\t\t\t\t\t\t\t: agentConfig.model\n\t\t\t\t\t\t: undefined),\n\t\t\t\texitCode,\n\t\t\t\toutput,\n\t\t\t\tstderr: stderr.slice(0, 2000), // cap stderr\n\t\t\t\terrorMessage,\n\t\t\t\tsessionFile,\n\t\t\t});\n\t\t});\n\t});\n}\n\n// ---------------------------------------------------------------------------\n// Session file discovery and cleanup\n// ---------------------------------------------------------------------------\n\n/**\n * Find the most recently modified .jsonl file in a session directory.\n * Returns the full path, or undefined if no session file was written\n * (e.g., subagent was killed before the first assistant message).\n */\nexport function discoverSessionFile(sessionDir: string, agentName: string): string | undefined {\n\ttry {\n\t\tif (!existsSync(sessionDir)) return undefined;\n\t\tconst files = readdirSync(sessionDir).filter((f) => f.endsWith(\".jsonl\"));\n\t\tif (files.length === 0) return undefined;\n\t\t// Pick the most recently modified file (typically there's only one per subagent dir)\n\t\tlet best: { path: string; mtime: number } | undefined;\n\t\tfor (const f of files) {\n\t\t\ttry {\n\t\t\t\tconst fullPath = join(sessionDir, f);\n\t\t\t\tconst mtime = statSync(fullPath).mtime.getTime();\n\t\t\t\tif (!best || mtime > best.mtime) {\n\t\t\t\t\tbest = { path: fullPath, mtime };\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// File disappeared or is a bad symlink — skip it, keep any valid candidate\n\t\t\t}\n\t\t}\n\t\tif (best) {\n\t\t\tlog.debug(`[subagent] session file: ${best.path} (agent=${agentName})`);\n\t\t\treturn best.path;\n\t\t}\n\t} catch (err) {\n\t\tlog.warn(\n\t\t\t`[subagent] failed to discover session file (agent=${agentName}): ${err instanceof Error ? err.message : String(err)}`,\n\t\t);\n\t}\n\treturn undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Execution modes\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve a model fallback list against the registry. Tries each model in order,\n * returns the first one that resolves successfully. If all fail, returns the\n * last error. Single strings are treated as a one-element list.\n */\nexport function resolveModelWithFallbacks(\n\tmodels: string | string[],\n\tparentProvider: string | undefined,\n\tregistry: ModelRegistry | undefined,\n\tparentModel?: string,\n): { ok: true; modelId: string; provider?: string; warning?: string } | { ok: false; error: string } {\n\tconst modelList = Array.isArray(models) ? models : [models];\n\tlet lastError = \"\";\n\tfor (const modelStr of modelList) {\n\t\tconst result = resolveModelStringSingle(modelStr, parentProvider, registry);\n\t\tif (result.ok) return result;\n\t\tlastError = result.error;\n\t}\n\t// After all configured fallbacks are exhausted, try the parent model as a last resort\n\tif (parentModel) {\n\t\tconst result = resolveModelStringSingle(parentModel, parentProvider, registry);\n\t\tif (result.ok) {\n\t\t\treturn {\n\t\t\t\t...result,\n\t\t\t\twarning: `Agent preferred models were unavailable. Falling back to parent model \"${result.modelId}\".`,\n\t\t\t};\n\t\t}\n\t\tlastError = result.error;\n\t}\n\tif (modelList.length > 1 || parentModel) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `None of the fallback models resolved: ${[...modelList, ...(parentModel ? [parentModel] : [])].join(\", \")}. Last error: ${lastError}`,\n\t\t};\n\t}\n\treturn { ok: false, error: lastError };\n}\n\nexport function resolveModelStringSingle(\n\tmodelStr: string,\n\tparentProvider: string | undefined,\n\tregistry: ModelRegistry | undefined,\n): { ok: true; modelId: string; provider?: string } | { ok: false; error: string } {\n\tif (!registry) {\n\t\treturn { ok: true, modelId: modelStr };\n\t}\n\n\t// If the model string contains \"/\" the user already specified a provider\n\tconst hasProvider = modelStr.includes(\"/\");\n\tconst resolved = resolveCliModel({\n\t\tcliProvider: hasProvider ? undefined : parentProvider,\n\t\tcliModel: modelStr,\n\t\tmodelRegistry: registry,\n\t});\n\n\tif (resolved.error) {\n\t\treturn { ok: false, error: resolved.error };\n\t}\n\tif (!resolved.model) {\n\t\treturn { ok: false, error: `Model \"${modelStr}\" not found. Use --list-models to see available models.` };\n\t}\n\n\t// resolveCliModel creates a synthetic model for any unknown ID when a\n\t// provider is specified (designed for custom/self-hosted models like Ollama).\n\t// For subagents this causes silent failures — reject synthetic fallbacks\n\t// so the next model in the fallback list is tried instead.\n\tif (resolved.isSyntheticFallback) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `Model \"${modelStr}\" not found for provider \"${resolved.model.provider}\". Use --list-models to see available models.`,\n\t\t};\n\t}\n\n\t// Verify the resolved provider has authentication configured.\n\t// resolveCliModel uses getAll() (all models, not just authenticated ones)\n\t// so a model can resolve successfully to a provider with no API key.\n\t// Reject early so the fallback list can continue to the next model.\n\tif (!registry.authStorage.hasAuth(resolved.model.provider)) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `No authentication configured for provider \"${resolved.model.provider}\". Model \"${modelStr}\" cannot be used.`,\n\t\t};\n\t}\n\n\treturn { ok: true, modelId: resolved.model.id, provider: resolved.model.provider };\n}\n\nexport interface ProbeModelAvailabilityOptions {\n\t/** Parent/tool abort signal. A 10s probe timeout is layered on top. */\n\tsignal?: AbortSignal;\n\t/** Model registry used to resolve provider API keys for the probe call. */\n\tregistry?: ModelRegistry;\n\t/** Override the default 10s probe timeout; primarily useful for tests. */\n\ttimeoutMs?: number;\n}\n\nexport type ProbeModelAvailabilityResult = { ok: true } | { ok: false; reason: string; aborted?: boolean };\n\nfunction compactErrorReason(reason: string): string {\n\tconst singleLine = reason.replace(/\\s+/g, \" \").trim();\n\treturn singleLine.length > 180 ? `${singleLine.slice(0, 177)}...` : singleLine || \"unknown error\";\n}\n\nfunction reasonFromRuntimeError(value: unknown): string {\n\tif (value instanceof Error) return value.message;\n\tif (typeof value === \"string\") return value;\n\tif (value && typeof value === \"object\") {\n\t\tconst maybeMessage = value as Partial<AssistantMessage> & { message?: unknown };\n\t\tif (typeof maybeMessage.errorMessage === \"string\") return maybeMessage.errorMessage;\n\t\tif (typeof maybeMessage.message === \"string\") return maybeMessage.message;\n\t}\n\treturn String(value);\n}\n\nexport function isRuntimeUnavailableError(value: unknown): boolean {\n\tif (value instanceof Error || typeof value === \"string\") return true;\n\tif (value && typeof value === \"object\") {\n\t\tconst maybeMessage = value as Partial<AssistantMessage>;\n\t\treturn maybeMessage.stopReason === \"error\" || maybeMessage.stopReason === \"aborted\";\n\t}\n\treturn false;\n}\n\nfunction makeProbeSignal(\n\tparentSignal: AbortSignal | undefined,\n\ttimeoutMs: number,\n): { signal: AbortSignal; timeoutPromise: Promise<never>; cleanup: () => void } {\n\tconst controller = new AbortController();\n\tconst timeoutError = new Error(`Model availability probe timed out after ${timeoutMs}ms`);\n\tlet timeout: ReturnType<typeof setTimeout>;\n\tconst timeoutPromise = new Promise<never>((_, reject) => {\n\t\ttimeout = setTimeout(() => {\n\t\t\tcontroller.abort(timeoutError);\n\t\t\treject(timeoutError);\n\t\t}, timeoutMs);\n\t});\n\tconst parentAbortHandler = () => controller.abort(parentSignal?.reason);\n\tparentSignal?.addEventListener(\"abort\", parentAbortHandler, { once: true });\n\tif (parentSignal?.aborted) controller.abort(parentSignal.reason);\n\n\treturn {\n\t\tsignal: controller.signal,\n\t\ttimeoutPromise,\n\t\tcleanup: () => {\n\t\t\tclearTimeout(timeout);\n\t\t\tparentSignal?.removeEventListener(\"abort\", parentAbortHandler);\n\t\t},\n\t};\n}\n\nexport async function probeModelAvailability(\n\tmodel: Model<Api>,\n\toptions: ProbeModelAvailabilityOptions = {},\n): Promise<ProbeModelAvailabilityResult> {\n\tconst { signal, registry, timeoutMs = 10_000 } = options;\n\tif (signal?.aborted) return { ok: false, reason: \"Aborted before spawn\", aborted: true };\n\n\tconst probeSignal = makeProbeSignal(signal, timeoutMs);\n\ttry {\n\t\tconst context: Context = {\n\t\t\tsystemPrompt: \"You are a model availability probe. Reply briefly.\",\n\t\t\tmessages: [{ role: \"user\", content: \"hi\", timestamp: Date.now() }],\n\t\t};\n\t\tconst apiKey = await Promise.race([\n\t\t\tregistry ? registry.getApiKey(model) : Promise.resolve(undefined),\n\t\t\tprobeSignal.timeoutPromise,\n\t\t]);\n\t\tif (signal?.aborted) return { ok: false, reason: \"Aborted before spawn\", aborted: true };\n\t\tconst result = await Promise.race([\n\t\t\tcomplete(model, context, {\n\t\t\t\tapiKey,\n\t\t\t\tmaxRetryDelayMs: 0,\n\t\t\t\tmaxTokens: 1,\n\t\t\t\tsignal: probeSignal.signal,\n\t\t\t}),\n\t\t\tprobeSignal.timeoutPromise,\n\t\t]);\n\t\tif (signal?.aborted) return { ok: false, reason: \"Aborted before spawn\", aborted: true };\n\t\tif (isRuntimeUnavailableError(result)) {\n\t\t\treturn { ok: false, reason: compactErrorReason(reasonFromRuntimeError(result)) };\n\t\t}\n\t\treturn { ok: true };\n\t} catch (err) {\n\t\tif (signal?.aborted) return { ok: false, reason: \"Aborted before spawn\", aborted: true };\n\t\treturn { ok: false, reason: compactErrorReason(reasonFromRuntimeError(err)) };\n\t} finally {\n\t\tprobeSignal.cleanup();\n\t}\n}\n\nexport interface SkippedFallbackModel {\n\tmodel: string;\n\treason: string;\n}\n\nexport type SubagentModelResolution =\n\t| {\n\t\t\tok: true;\n\t\t\tmodelId: string;\n\t\t\tprovider?: string;\n\t\t\twarning?: string;\n\t\t\tskippedModels: SkippedFallbackModel[];\n\t }\n\t| { ok: false; error: string; skippedModels: SkippedFallbackModel[] };\n\nexport async function resolveModelForSubagentSpawn(\n\tmodels: string | string[],\n\tparentProvider: string | undefined,\n\tregistry: ModelRegistry | undefined,\n\tparentModel?: string,\n\tsignal?: AbortSignal,\n): Promise<SubagentModelResolution> {\n\tif (signal?.aborted) return { ok: false, error: \"Aborted before spawn\", skippedModels: [] };\n\n\t// Runtime probing only applies to agent definition fallback lists. Single\n\t// models, per-invocation overrides, and registry-less environments keep the\n\t// existing spawn-time resolution behavior exactly.\n\tif (!Array.isArray(models) || !registry) {\n\t\tconst resolved = resolveModelWithFallbacks(models, parentProvider, registry, parentModel);\n\t\treturn { ...resolved, skippedModels: [] };\n\t}\n\n\tconst skippedModels: SkippedFallbackModel[] = [];\n\tlet lastError = \"\";\n\n\tfor (const modelStr of models) {\n\t\tif (signal?.aborted) return { ok: false, error: \"Aborted before spawn\", skippedModels };\n\n\t\tconst resolved = resolveModelStringSingle(modelStr, parentProvider, registry);\n\t\tif (!resolved.ok) {\n\t\t\tlastError = resolved.error;\n\t\t\tconst reason = compactErrorReason(resolved.error);\n\t\t\tskippedModels.push({ model: modelStr, reason });\n\t\t\tlog.warn(`[subagent] Model \"${modelStr}\" unavailable (${reason}). Trying next fallback...`);\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst modelObj = resolved.provider ? registry.find(resolved.provider, resolved.modelId) : undefined;\n\t\tif (modelObj) {\n\t\t\tconst probe = await probeModelAvailability(modelObj, { signal, registry });\n\t\t\tif (!probe.ok && probe.aborted) {\n\t\t\t\treturn { ok: false, error: \"Aborted before spawn\", skippedModels };\n\t\t\t}\n\t\t\tif (signal?.aborted) return { ok: false, error: \"Aborted before spawn\", skippedModels };\n\t\t\tif (!probe.ok) {\n\t\t\t\tlastError = probe.reason;\n\t\t\t\tskippedModels.push({ model: modelStr, reason: probe.reason });\n\t\t\t\tlog.warn(`[subagent] Model \"${modelStr}\" failed probe (${probe.reason}). Trying next fallback...`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tlog.debug(`[subagent] Using model \"${resolved.modelId}\" for subagent.`);\n\t\treturn { ...resolved, skippedModels };\n\t}\n\n\tif (signal?.aborted) return { ok: false, error: \"Aborted before spawn\", skippedModels };\n\n\tif (parentModel) {\n\t\tconst parentResolved = resolveModelStringSingle(parentModel, parentProvider, registry);\n\t\tif (parentResolved.ok) {\n\t\t\tconst warning = `Agent preferred models were unavailable. Falling back to parent model \"${parentResolved.modelId}\".`;\n\t\t\tlog.warn(`[subagent] ${warning}`);\n\t\t\treturn { ...parentResolved, warning, skippedModels };\n\t\t}\n\t\tlastError = parentResolved.error;\n\t}\n\n\treturn {\n\t\tok: false,\n\t\tskippedModels,\n\t\terror: `None of the fallback models passed availability checks: ${[\n\t\t\t...models,\n\t\t\t...(parentModel ? [parentModel] : []),\n\t\t].join(\", \")}. Last error: ${lastError || \"all probes failed\"}`,\n\t};\n}\n\nexport function formatModelFallbackSummary(\n\tskippedModels: SkippedFallbackModel[],\n\tselectedModel: string | undefined,\n): string | undefined {\n\tif (skippedModels.length === 0) return undefined;\n\tconst skipped = skippedModels.map((s) => `- ${s.model}: ${s.reason}`).join(\"\\n\");\n\treturn `[MODEL FALLBACK: skipped ${skippedModels.length} unavailable model(s); using \"${selectedModel ?? \"unknown\"}\".]\\n${skipped}`;\n}\n\nexport function prependModelFallbackSummary(\n\toutput: string,\n\tskippedModels: SkippedFallbackModel[],\n\tselectedModel: string | undefined,\n): string {\n\tconst fallbackSummary = formatModelFallbackSummary(skippedModels, selectedModel);\n\treturn fallbackSummary ? `${fallbackSummary}\\n\\n${output}` : output;\n}\n\nfunction formatSkippedModelFailureDetails(skippedModels: SkippedFallbackModel[]): string | undefined {\n\tif (skippedModels.length === 0) return undefined;\n\treturn `Skipped models:\\n${skippedModels.map((s) => `- ${s.model}: ${s.reason}`).join(\"\\n\")}`;\n}\n\nconst MAX_PARALLEL_TASKS = 8;\nconst MAX_CONCURRENCY = 4;\nconst MAX_TASK_LENGTH = 32_768; // 32 KB — prevent E2BIG from oversized argv\n\n// Semaphore for background task concurrency — shared across all background launches\nlet bgRunning = 0;\nconst bgWaiters: Array<() => void> = [];\n\nasync function bgAcquire(): Promise<void> {\n\tif (bgRunning < MAX_CONCURRENCY) {\n\t\tbgRunning++;\n\t\treturn;\n\t}\n\treturn new Promise<void>((resolve) => {\n\t\tbgWaiters.push(() => {\n\t\t\tbgRunning++;\n\t\t\tresolve();\n\t\t});\n\t});\n}\n\nfunction bgRelease(): void {\n\tbgRunning--;\n\tconst next = bgWaiters.shift();\n\tif (next) next();\n}\n\n/**\n * Resolve a per-task cwd relative to the parent cwd.\n * Rejects absolute paths and relative paths that escape the parent directory.\n * Returns a result object with ok=false and an error string on rejection, so callers can surface it to the model.\n */\nfunction clampCwd(defaultCwd: string, itemCwd?: string): { ok: true; cwd: string } | { ok: false; error: string } {\n\tif (!itemCwd) return { ok: true, cwd: defaultCwd };\n\tif (itemCwd.startsWith(\"/\")) {\n\t\treturn { ok: false, error: `Rejected absolute cwd \"${itemCwd}\" — must be relative to parent cwd` };\n\t}\n\tconst resolved = resolve(defaultCwd, itemCwd);\n\tif (resolved !== defaultCwd && !resolved.startsWith(`${defaultCwd}/`)) {\n\t\treturn { ok: false, error: `Rejected cwd \"${itemCwd}\" — resolves outside parent cwd` };\n\t}\n\treturn { ok: true, cwd: resolved };\n}\n\nexport async function executeSingle(\n\tagents: Map<string, AgentTypeConfig>,\n\tagentName: string | undefined,\n\ttask: string,\n\tcwd: string,\n\tsignal?: AbortSignal,\n\tonProgress?: (event: string) => void,\n\tmodelOverride?: string,\n\tparentProvider?: string,\n\tregistry?: ModelRegistry,\n\tsessionDir?: string,\n\tparentModel?: string,\n): Promise<SubagentResult> {\n\tconst name = agentName || DEFAULT_AGENT;\n\tconst config = agents.get(name);\n\tif (!config) {\n\t\treturn {\n\t\t\tagent: name,\n\t\t\ttask,\n\t\t\texitCode: 1,\n\t\t\toutput: \"\",\n\t\t\tstderr: \"\",\n\t\t\terrorMessage: `Unknown agent type \"${name}\". Available: ${[...agents.keys()].join(\", \")}. If you expected \"${name}\" to exist, check the .md file in ~/.dreb/agents/ or .dreb/agents/ for syntax errors.`,\n\t\t};\n\t}\n\t// Validate task length for all modes (single, parallel items, chain steps)\n\tif (task.length > MAX_TASK_LENGTH) {\n\t\treturn {\n\t\t\tagent: name,\n\t\t\ttask: `${task.slice(0, 200)}...`,\n\t\t\texitCode: 1,\n\t\t\toutput: \"\",\n\t\t\tstderr: \"\",\n\t\t\terrorMessage: `Task prompt too long (${task.length} chars, max ${MAX_TASK_LENGTH}). Shorten the prompt.`,\n\t\t};\n\t}\n\t// Per-invocation model override takes precedence over agent definition model.\n\t// Override is always a single string; agent config may be a string or fallback list.\n\tconst modelSpec = modelOverride || config.model;\n\tlet effectiveConfig: AgentTypeConfig = modelOverride ? { ...config, model: modelOverride } : config;\n\tlet resolvedProvider = parentProvider;\n\tlet warning: string | undefined;\n\tlet skippedModels: SkippedFallbackModel[] = [];\n\n\t// Resolve and validate the model against the registry before spawning.\n\t// This catches typos and invalid model names immediately instead of failing\n\t// silently in the child process. Also passes the canonical model ID to the\n\t// child, avoiding fuzzy matching entirely. Agent definition fallback lists get\n\t// an additional best-effort 1-token probe before spawn so runtime-unavailable\n\t// models are skipped before committing to a child process.\n\tif (modelSpec) {\n\t\tconst resolved = await resolveModelForSubagentSpawn(modelSpec, parentProvider, registry, parentModel, signal);\n\t\tskippedModels = resolved.skippedModels;\n\t\tif (!resolved.ok) {\n\t\t\tconst skippedDetails = formatSkippedModelFailureDetails(skippedModels);\n\t\t\treturn {\n\t\t\t\tagent: name,\n\t\t\t\ttask,\n\t\t\t\texitCode: 1,\n\t\t\t\toutput: \"\",\n\t\t\t\tstderr: \"\",\n\t\t\t\terrorMessage: skippedDetails ? `${resolved.error}\\n\\n${skippedDetails}` : resolved.error,\n\t\t\t};\n\t\t}\n\t\teffectiveConfig = { ...effectiveConfig, model: resolved.modelId };\n\t\tif (resolved.provider) {\n\t\t\tresolvedProvider = resolved.provider;\n\t\t}\n\t\twarning = resolved.warning;\n\t}\n\n\tonProgress?.(`Running ${name} agent...`);\n\tconst result = await spawnSubagent(effectiveConfig, task, cwd, signal, onProgress, resolvedProvider, sessionDir);\n\tresult.output = prependModelFallbackSummary(\n\t\tresult.output,\n\t\tskippedModels,\n\t\tresult.model ?? effectiveConfig.model?.toString(),\n\t);\n\tif (warning) {\n\t\tresult.output = `[WARNING: ${warning}]\\n\\n${result.output}`;\n\t}\n\treturn result;\n}\n\nasync function executeChain(\n\tagents: Map<string, AgentTypeConfig>,\n\tchain: Array<{ agent?: string; task: string; cwd?: string; model?: string }>,\n\tdefaultCwd: string,\n\tsignal?: AbortSignal,\n\tonProgress?: (event: string) => void,\n\tparentProvider?: string,\n\tregistry?: ModelRegistry,\n\tsessionBaseDir?: string,\n\tdefaultAgent?: string,\n\tdefaultModel?: string,\n\tparentModel?: string,\n): Promise<SubagentResult[]> {\n\tconst results: SubagentResult[] = [];\n\tlet previousOutput = \"\";\n\n\tfor (let i = 0; i < chain.length; i++) {\n\t\tif (signal?.aborted) break;\n\t\tconst step = chain[i];\n\t\tconst task = step.task.replace(/\\{previous\\}/g, previousOutput);\n\t\tonProgress?.(`Chain step ${i + 1}/${chain.length}`);\n\n\t\t// Validate task length after {previous} substitution (can compound across steps)\n\t\tif (task.length > MAX_TASK_LENGTH) {\n\t\t\tresults.push({\n\t\t\t\tagent: step.agent || defaultAgent || DEFAULT_AGENT,\n\t\t\t\ttask: `${task.slice(0, 200)}...`,\n\t\t\t\texitCode: 1,\n\t\t\t\toutput: \"\",\n\t\t\t\tstderr: \"\",\n\t\t\t\terrorMessage: `Task prompt too long after {previous} substitution (${task.length} chars, max ${MAX_TASK_LENGTH}). Shorten the prompt or summarize previous output.`,\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\n\t\tconst cwdResult = clampCwd(defaultCwd, step.cwd);\n\t\tif (!cwdResult.ok) {\n\t\t\tresults.push({\n\t\t\t\tagent: step.agent || defaultAgent || DEFAULT_AGENT,\n\t\t\t\ttask,\n\t\t\t\texitCode: 1,\n\t\t\t\toutput: \"\",\n\t\t\t\tstderr: \"\",\n\t\t\t\terrorMessage: cwdResult.error,\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\n\t\t// Each chain step gets its own session subdirectory\n\t\tconst stepSessionDir = sessionBaseDir ? join(sessionBaseDir, `step-${i + 1}`) : undefined;\n\t\tconst result = await executeSingle(\n\t\t\tagents,\n\t\t\tstep.agent || defaultAgent,\n\t\t\ttask,\n\t\t\tcwdResult.cwd,\n\t\t\tsignal,\n\t\t\tonProgress,\n\t\t\tstep.model || defaultModel,\n\t\t\tparentProvider,\n\t\t\tregistry,\n\t\t\tstepSessionDir,\n\t\t\tparentModel,\n\t\t);\n\t\tresults.push(result);\n\n\t\tif (result.exitCode !== 0) {\n\t\t\tbreak; // stop chain on error\n\t\t}\n\t\tpreviousOutput = result.output;\n\t}\n\n\treturn results;\n}\n\n// ---------------------------------------------------------------------------\n// Background execution\n// ---------------------------------------------------------------------------\n\nfunction generateAgentId(): string {\n\treturn randomBytes(6).toString(\"hex\");\n}\n\n// ---------------------------------------------------------------------------\n// Background agent registry — queryable by TUI / Telegram frontends\n// ---------------------------------------------------------------------------\n\nexport interface BackgroundAgentInfo {\n\tagentId: string;\n\tagentType: string;\n\ttaskSummary: string;\n\tstartedAt: number;\n\tstatus: \"running\" | \"completed\" | \"failed\";\n}\n\nconst backgroundAgentRegistry = new Map<string, BackgroundAgentInfo>();\nconst backgroundAbortControllers = new Map<string, AbortController>();\n\n/** Get a snapshot of all tracked background agents (running and recently completed). Returns readonly clones. */\nexport function getBackgroundAgents(): readonly Readonly<BackgroundAgentInfo>[] {\n\treturn [...backgroundAgentRegistry.values()].map((a) => ({ ...a }));\n}\n\n/** Get only currently running background agents. Returns readonly clones. */\nexport function getRunningBackgroundAgents(): readonly Readonly<BackgroundAgentInfo>[] {\n\treturn [...backgroundAgentRegistry.values()].filter((a) => a.status === \"running\").map((a) => ({ ...a }));\n}\n\n/** Abort all running background agents. */\nexport function abortBackgroundAgents(): void {\n\tfor (const [id, controller] of backgroundAbortControllers) {\n\t\tcontroller.abort();\n\t\tconst entry = backgroundAgentRegistry.get(id);\n\t\tif (entry && entry.status === \"running\") {\n\t\t\tentry.status = \"failed\";\n\t\t}\n\t}\n\tbackgroundAbortControllers.clear();\n}\n\n/** Remove completed/failed entries older than the given age (ms). Default: 5 minutes. */\nexport function pruneBackgroundAgents(maxAgeMs = 5 * 60 * 1000): void {\n\tconst now = Date.now();\n\tfor (const [id, info] of backgroundAgentRegistry) {\n\t\tif (info.status !== \"running\" && now - info.startedAt > maxAgeMs) {\n\t\t\tbackgroundAgentRegistry.delete(id);\n\t\t\tbackgroundAbortControllers.delete(id);\n\t\t}\n\t}\n}\n\nexport interface SubagentToolOptions {\n\t/** Called when a background subagent starts. Used by TUI to show status indicators. */\n\tonBackgroundStart?: (agentId: string, agentType: string, taskSummary: string) => void;\n\t/** Called when a background subagent completes with its result. `cancelled` is true if the user aborted it. */\n\tonBackgroundComplete?: (agentId: string, result: SubagentResult, cancelled: boolean) => void;\n\t/** Parent session's current provider (e.g. \"anthropic\"). Called at each invocation to get the live value after mid-session model switches. */\n\tparentProvider?: () => string | undefined;\n\t/** Parent session's current model ID. Used as a final fallback when all subagent-configured models fail to resolve. Called at each invocation for fresh value. */\n\tparentModel?: () => string | undefined;\n\t/** Model registry for validating model names before spawning child processes. */\n\tmodelRegistry?: ModelRegistry;\n}\n\n// ---------------------------------------------------------------------------\n// Tool schema and definition\n// ---------------------------------------------------------------------------\n\nconst taskItemSchema = Type.Object({\n\tagent: Type.Optional(Type.String({ description: \"Agent type name (default: 'Explore')\" })),\n\ttask: Type.String({ description: \"The task prompt for this subagent\" }),\n\tcwd: Type.Optional(Type.String({ description: \"Working directory (defaults to parent's cwd)\" })),\n\tmodel: Type.Optional(\n\t\tType.String({\n\t\t\tdescription:\n\t\t\t\t\"Model override for this task. Takes precedence over agent definition model. Note: a single-string override discards the agent's fallback list.\",\n\t\t}),\n\t),\n});\n\nconst subagentSchema = Type.Object({\n\tagent: Type.Optional(Type.String({ description: \"Agent type name (default: 'Explore')\" })),\n\ttask: Type.Optional(Type.String({ description: \"Task prompt (single mode)\", minLength: 1 })),\n\tmodel: Type.Optional(\n\t\tType.String({\n\t\t\tdescription:\n\t\t\t\t\"Model override. Takes precedence over agent definition model. Note: a single-string override discards the agent's fallback list. For parallel/chain, set per-task instead.\",\n\t\t}),\n\t),\n\ttasks: Type.Optional(\n\t\tType.Array(taskItemSchema, {\n\t\t\tdescription: \"Array of tasks to run in parallel (max 8)\",\n\t\t\tminItems: 1,\n\t\t\tmaxItems: MAX_PARALLEL_TASKS,\n\t\t}),\n\t),\n\tchain: Type.Optional(\n\t\tType.Array(taskItemSchema, {\n\t\t\tdescription: \"Sequential pipeline — each step can use {previous} for prior output\",\n\t\t\tminItems: 1,\n\t\t}),\n\t),\n\t// background parameter removed — all subagents run in background mode.\n\t// Kept in schema for backward compatibility (silently ignored if passed).\n\tbackground: Type.Optional(\n\t\tType.Boolean({ description: \"Deprecated — all subagents run in background mode. This parameter is ignored.\" }),\n\t),\n});\n\nexport type SubagentToolInput = Static<typeof subagentSchema>;\n\nexport interface SubagentToolDetails {\n\ttruncation?: TruncationResult;\n\tmode: \"single\" | \"parallel\" | \"chain\";\n\tagentCount: number;\n}\n\nfunction formatSubagentCall(\n\targs: SubagentToolInput | undefined,\n\ttheme: typeof import(\"../../modes/interactive/theme/theme.js\").theme,\n\targsComplete = true,\n): string {\n\tconst invalidArg = invalidArgText(theme);\n\n\tif (args?.tasks) {\n\t\t// Show agent type(s) in the parallel label\n\t\tconst agentCounts = new Map<string, number>();\n\t\tfor (const t of args.tasks) {\n\t\t\tconst name = t.agent || args.agent || DEFAULT_AGENT;\n\t\t\tagentCounts.set(name, (agentCounts.get(name) || 0) + 1);\n\t\t}\n\t\tlet typeLabel: string;\n\t\tif (agentCounts.size === 1) {\n\t\t\tconst [name] = [...agentCounts.keys()];\n\t\t\ttypeLabel = `${args.tasks.length} ${name} tasks`;\n\t\t} else {\n\t\t\tconst parts = [...agentCounts.entries()].map(([name, count]) => `${count} ${name}`);\n\t\t\ttypeLabel = `${args.tasks.length} tasks: ${parts.join(\", \")}`;\n\t\t}\n\t\treturn `${theme.fg(\"toolTitle\", theme.bold(\"subagent\"))} ${theme.fg(\"accent\", `parallel (${typeLabel})`)}`;\n\t}\n\tif (args?.chain) {\n\t\tconst agentName = str(args.agent) || args.chain[0]?.agent || DEFAULT_AGENT;\n\t\treturn `${theme.fg(\"toolTitle\", theme.bold(\"subagent\"))} ${theme.fg(\"accent\", `chain (${agentName}, ${args.chain.length} steps)`)}`;\n\t}\n\n\tconst agent = str(args?.agent) || DEFAULT_AGENT;\n\tconst model = str(args?.model);\n\tconst task = str(args?.task);\n\tconst taskPreview = task ? (task.length > 60 ? `${task.slice(0, 57)}...` : task) : null;\n\tconst modelSuffix = model ? ` ${theme.fg(\"muted\", `(${model})`)}` : \"\";\n\treturn (\n\t\ttheme.fg(\"toolTitle\", theme.bold(\"subagent\")) +\n\t\t\" \" +\n\t\ttheme.fg(\"accent\", agent) +\n\t\tmodelSuffix +\n\t\t\" \" +\n\t\t(taskPreview === null\n\t\t\t? argsComplete\n\t\t\t\t? invalidArg\n\t\t\t\t: theme.fg(\"muted\", \"…\")\n\t\t\t: theme.fg(\"toolOutput\", `\"${taskPreview}\"`))\n\t);\n}\n\nfunction formatSubagentResult(\n\tresult: {\n\t\tcontent: Array<{ type: string; text?: string }>;\n\t\tdetails?: SubagentToolDetails;\n\t},\n\toptions: ToolRenderResultOptions,\n\ttheme: typeof import(\"../../modes/interactive/theme/theme.js\").theme,\n\tshowImages: boolean,\n): string {\n\tconst output = getTextOutput(result, showImages).trim();\n\tlet text = \"\";\n\tif (output) {\n\t\tconst lines = output.split(\"\\n\");\n\t\tconst maxLines = options.expanded ? lines.length : 25;\n\t\tconst displayLines = lines.slice(0, maxLines);\n\t\tconst remaining = lines.length - maxLines;\n\t\ttext += `\\n${displayLines.map((line) => theme.fg(\"toolOutput\", line)).join(\"\\n\")}`;\n\t\tif (remaining > 0) {\n\t\t\ttext += `${theme.fg(\"muted\", `\\n... (${remaining} more lines,`)} ${keyHint(\"app.tools.expand\", \"to expand\")})`;\n\t\t}\n\t}\n\tconst truncation = result.details?.truncation;\n\tif (truncation?.truncated) {\n\t\ttext += `\\n${theme.fg(\"warning\", `[Truncated: ${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit]`)}`;\n\t}\n\treturn text;\n}\n\nfunction formatSingleResult(result: SubagentResult): string {\n\tlet text = `## Agent: ${result.agent}${result.model ? ` (model: ${result.model})` : \"\"}\\n`;\n\tif (result.exitCode !== 0) {\n\t\ttext += `**Error** (exit ${result.exitCode}): ${result.errorMessage || \"Unknown error\"}\\n`;\n\t\tif (result.stderr) {\n\t\t\ttext += `\\nStderr:\\n${result.stderr}\\n`;\n\t\t}\n\t}\n\tif (result.output) {\n\t\ttext += `\\n${result.output}`;\n\t} else if (result.exitCode === 0) {\n\t\ttext += \"\\n(No output)\";\n\t}\n\tif (result.sessionFile) {\n\t\ttext += `\\n\\nSession log: ${result.sessionFile}`;\n\t}\n\treturn text;\n}\n\nexport function createSubagentToolDefinition(\n\tcwd: string,\n\toptions?: SubagentToolOptions,\n): ToolDefinition<typeof subagentSchema, SubagentToolDetails | undefined> {\n\tconst onBackgroundStart = options?.onBackgroundStart;\n\tconst onBackgroundComplete = options?.onBackgroundComplete;\n\tconst getParentProvider = options?.parentProvider ?? (() => undefined);\n\tconst getParentModel = options?.parentModel ?? (() => undefined);\n\tconst modelRegistry = options?.modelRegistry;\n\n\t// Discover agents at definition time to build the prompt guidelines.\n\t// This is cheap (reads .md files) and the same call happens on every execute().\n\tconst knownAgents = discoverAgentTypes(cwd);\n\tconst agentListParts: string[] = [];\n\tfor (const [name, config] of knownAgents) {\n\t\tconst defaultTag = name === DEFAULT_AGENT ? \" (default)\" : \"\";\n\t\tconst desc = config.description || name;\n\t\tagentListParts.push(`'${name}'${defaultTag} — ${desc}`);\n\t}\n\tconst builtInAgentsLine = `Built-in agents: ${agentListParts.join(\"; \")}`;\n\n\treturn {\n\t\tname: \"subagent\",\n\t\tlabel: \"subagent\",\n\t\tdescription:\n\t\t\t\"Delegate tasks to independent subagents (Explore for codebase research, Sandbox for isolated /tmp-only analysis). \" +\n\t\t\t\"Supports single task, parallel (up to 8, max 4 concurrent), \" +\n\t\t\t\"and chain (sequential pipeline with {previous} substitution) modes. \" +\n\t\t\t\"All subagents run in background — returns immediately, notifies on completion.\",\n\t\tpromptSnippet: \"Delegate tasks to independent subagents\",\n\t\tpromptGuidelines: [\n\t\t\t\"Use `subagent` to delegate focused, independent tasks to child agents\",\n\t\t\t\"Available agent types can be discovered from ~/.dreb/agents/ and .dreb/agents/ markdown files\",\n\t\t\tbuiltInAgentsLine,\n\t\t\t\"Use parallel mode for independent tasks that can run concurrently\",\n\t\t\t\"Use chain mode when each step depends on the previous step's output (reference with {previous})\",\n\t\t\t\"All subagents run in background — the tool returns immediately and you are notified when each agent completes.\",\n\t\t\t\"Subagents have their own context window — provide enough context in the task prompt\",\n\t\t\t\"Each agent notifies independently when done — completion messages include a list of any still-running agents. If you need their results before proceeding, end your current turn with no tool calls (as if you were asking the user a question and waiting for their reply). This emits `agent_end` and lets the framework deliver the completion as a new message that resumes your turn automatically. Do not call `sleep` or any other waiting action, and do not launch filler work.\",\n\t\t\t\"Agent definitions specify a `model` field with a provider fallback list (comma-separated or YAML list). The spawner tries each in order and uses the first one that resolves for the current provider. This makes agents portable across providers.\",\n\t\t\t\"Per-invocation `model` overrides take precedence but **discard the entire fallback list** — if the single override model isn't available on the current provider, the agent fails. Only override when you have a specific reason (e.g. escalating to a stronger tier for a complex task).\",\n\t\t\t\"**Model routing** — agent definitions already specify the right tier for their role. Most subagent tasks (exploration, file discovery, grep, navigation, summarization) are handled well by the defaults. Do not override the model unless the task genuinely requires a different capability tier than what the agent definition provides.\",\n\t\t],\n\t\tparameters: subagentSchema,\n\n\t\tasync execute(_toolCallId, params: SubagentToolInput, _signal, _onUpdate) {\n\t\t\tconst agents = discoverAgentTypes(cwd);\n\n\t\t\t// Determine mode\n\t\t\tconst modeCount = (params.task ? 1 : 0) + (params.tasks ? 1 : 0) + (params.chain ? 1 : 0);\n\t\t\tif (modeCount === 0) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{ type: \"text\", text: \"Error: provide one of `task` (single), `tasks` (parallel), or `chain`.\" },\n\t\t\t\t\t],\n\t\t\t\t\tdetails: undefined,\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (modeCount > 1) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: \"Error: modes are mutually exclusive — provide only one of `task`, `tasks`, or `chain`.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tdetails: undefined,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// All subagents run in background mode — return immediately, notify on completion\n\t\t\t{\n\t\t\t\tif (!onBackgroundComplete) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: \"Subagent execution requires background support, which is not available in this session.\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tdetails: undefined,\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\t/**\n\t\t\t\t * Shared lifecycle for all background launches: generates agent ID,\n\t\t\t\t * sets up registry/abort/notification, gates on the concurrency\n\t\t\t\t * semaphore, and handles errors. The caller provides the actual\n\t\t\t\t * work via `runFn(signal)` which must return a SubagentResult.\n\t\t\t\t */\n\t\t\t\tconst launchBackgroundLifecycle = (\n\t\t\t\t\tagentName: string,\n\t\t\t\t\ttaskSummary: string,\n\t\t\t\t\trunFn: (signal: AbortSignal) => Promise<SubagentResult>,\n\t\t\t\t): string => {\n\t\t\t\t\tconst agentId = generateAgentId();\n\t\t\t\t\tconst bgAbort = new AbortController();\n\t\t\t\t\tbackgroundAgentRegistry.set(agentId, {\n\t\t\t\t\t\tagentId,\n\t\t\t\t\t\tagentType: agentName,\n\t\t\t\t\t\ttaskSummary,\n\t\t\t\t\t\tstartedAt: Date.now(),\n\t\t\t\t\t\tstatus: \"running\",\n\t\t\t\t\t});\n\t\t\t\t\tbackgroundAbortControllers.set(agentId, bgAbort);\n\t\t\t\t\tonBackgroundStart?.(agentId, agentName, taskSummary);\n\n\t\t\t\t\tconst bgSignal = bgAbort.signal;\n\n\t\t\t\t\tconst safeNotify = (result: SubagentResult) => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tonBackgroundComplete(agentId, result, bgSignal.aborted);\n\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\tlog.warn(\n\t\t\t\t\t\t\t\t`[subagent] onBackgroundComplete threw for agent ${agentId}: ${err instanceof Error ? err.message : String(err)}. Background result lost.`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\n\t\t\t\t\tconst run = async () => {\n\t\t\t\t\t\tawait bgAcquire();\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst result = await runFn(bgSignal);\n\t\t\t\t\t\t\tconst entry = backgroundAgentRegistry.get(agentId);\n\t\t\t\t\t\t\tif (entry && !bgSignal.aborted) entry.status = result.exitCode === 0 ? \"completed\" : \"failed\";\n\t\t\t\t\t\t\tbackgroundAbortControllers.delete(agentId);\n\t\t\t\t\t\t\tsafeNotify(result);\n\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\tconst entry = backgroundAgentRegistry.get(agentId);\n\t\t\t\t\t\t\tif (entry && !bgSignal.aborted) entry.status = \"failed\";\n\t\t\t\t\t\t\tbackgroundAbortControllers.delete(agentId);\n\t\t\t\t\t\t\tsafeNotify({\n\t\t\t\t\t\t\t\tagent: agentName,\n\t\t\t\t\t\t\t\ttask: taskSummary,\n\t\t\t\t\t\t\t\texitCode: 1,\n\t\t\t\t\t\t\t\toutput: \"\",\n\t\t\t\t\t\t\t\tstderr: \"\",\n\t\t\t\t\t\t\t\terrorMessage: err instanceof Error ? err.message : String(err),\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\tbgRelease();\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t\trun().catch((err) => {\n\t\t\t\t\t\tlog.warn(\n\t\t\t\t\t\t\t`[subagent] Unhandled background error (${agentId}): ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst entry = backgroundAgentRegistry.get(agentId);\n\t\t\t\t\t\tif (entry && entry.status === \"running\") entry.status = \"failed\";\n\t\t\t\t\t\tbackgroundAbortControllers.delete(agentId);\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tonBackgroundComplete(\n\t\t\t\t\t\t\t\tagentId,\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tagent: agentName,\n\t\t\t\t\t\t\t\t\ttask: taskSummary,\n\t\t\t\t\t\t\t\t\texitCode: 1,\n\t\t\t\t\t\t\t\t\toutput: \"\",\n\t\t\t\t\t\t\t\t\tstderr: \"\",\n\t\t\t\t\t\t\t\t\terrorMessage: `Internal error: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tbgSignal.aborted,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t} catch (notifyErr) {\n\t\t\t\t\t\t\tlog.error(\n\t\t\t\t\t\t\t\t`[subagent] CRITICAL: Last-resort notification failed for ${agentId}: ${notifyErr instanceof Error ? notifyErr.message : String(notifyErr)}`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\n\t\t\t\t\treturn agentId;\n\t\t\t\t};\n\n\t\t\t\t// Helper to launch a single background task\n\t\t\t\tconst subagentSessionsBase = getSubagentSessionsDir();\n\t\t\t\tconst launchBackgroundTask = (\n\t\t\t\t\tagentName: string,\n\t\t\t\t\ttask: string,\n\t\t\t\t\ttaskLabel: string,\n\t\t\t\t\ttaskCwd?: string,\n\t\t\t\t\tmodelOverride?: string,\n\t\t\t\t) => {\n\t\t\t\t\tconst resolvedCwd = taskCwd ?? cwd;\n\t\t\t\t\t// Each background agent gets its own session subdirectory\n\t\t\t\t\tconst sessionId = generateAgentId();\n\t\t\t\t\tconst sessionDir = join(subagentSessionsBase, sessionId);\n\t\t\t\t\treturn launchBackgroundLifecycle(agentName, taskLabel, (signal) =>\n\t\t\t\t\t\texecuteSingle(\n\t\t\t\t\t\t\tagents,\n\t\t\t\t\t\t\tagentName === DEFAULT_AGENT ? undefined : agentName,\n\t\t\t\t\t\t\ttask,\n\t\t\t\t\t\t\tresolvedCwd,\n\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t\tundefined,\n\t\t\t\t\t\t\tmodelOverride,\n\t\t\t\t\t\t\tgetParentProvider(),\n\t\t\t\t\t\t\tmodelRegistry,\n\t\t\t\t\t\t\tsessionDir,\n\t\t\t\t\t\t\tgetParentModel(),\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t};\n\n\t\t\t\tif (params.task) {\n\t\t\t\t\t// Single background task\n\t\t\t\t\tconst agentName = params.agent || DEFAULT_AGENT;\n\t\t\t\t\tconst agentId = launchBackgroundTask(\n\t\t\t\t\t\tagentName,\n\t\t\t\t\t\tparams.task,\n\t\t\t\t\t\t`${agentName} task`,\n\t\t\t\t\t\tundefined,\n\t\t\t\t\t\tparams.model,\n\t\t\t\t\t);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: `Background agent ${agentId} started (${agentName}). You will be notified when it completes.`,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tdetails: { mode: \"single\", agentCount: 1 } as SubagentToolDetails,\n\t\t\t\t\t\tendTurn: true,\n\t\t\t\t\t};\n\t\t\t\t} else if (params.tasks) {\n\t\t\t\t\t// Parallel background tasks — each gets its own agent ID and notifies independently\n\t\t\t\t\tconst launched: Array<{ id: string; agentName: string; taskText: string }> = [];\n\t\t\t\t\tconst skipped: Array<{ taskText: string; error: string }> = [];\n\t\t\t\t\tfor (let i = 0; i < params.tasks.length; i++) {\n\t\t\t\t\t\tconst item = params.tasks[i];\n\t\t\t\t\t\tconst agentName = item.agent || params.agent || DEFAULT_AGENT;\n\t\t\t\t\t\tconst cwdResult = clampCwd(cwd, item.cwd);\n\t\t\t\t\t\tif (!cwdResult.ok) {\n\t\t\t\t\t\t\tskipped.push({ taskText: item.task, error: cwdResult.error });\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst agentId = launchBackgroundTask(\n\t\t\t\t\t\t\tagentName,\n\t\t\t\t\t\t\titem.task,\n\t\t\t\t\t\t\t`${agentName} task ${i + 1}/${params.tasks.length}`,\n\t\t\t\t\t\t\tcwdResult.cwd,\n\t\t\t\t\t\t\titem.model || params.model,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tlaunched.push({ id: agentId, agentName, taskText: item.task });\n\t\t\t\t\t}\n\t\t\t\t\tconst listing = launched\n\t\t\t\t\t\t.map(({ id, agentName, taskText }) => ` ${id} (${agentName}): ${taskText.slice(0, 80)}`)\n\t\t\t\t\t\t.join(\"\\n\");\n\t\t\t\t\tconst skippedListing = skipped\n\t\t\t\t\t\t.map(({ taskText, error }) => ` SKIPPED: ${taskText.slice(0, 60)} — ${error}`)\n\t\t\t\t\t\t.join(\"\\n\");\n\t\t\t\t\tconst parts = [`${launched.length} background agents started:\\n${listing}`];\n\t\t\t\t\tif (skipped.length > 0) {\n\t\t\t\t\t\tparts.push(`\\n${skipped.length} task(s) failed to launch:\\n${skippedListing}`);\n\t\t\t\t\t}\n\t\t\t\t\tif (launched.length > 0) {\n\t\t\t\t\t\tparts.push(\"\\nEach will notify independently when complete.\");\n\t\t\t\t\t} else {\n\t\t\t\t\t\tparts.push(\"\\nNo agents were launched.\");\n\t\t\t\t\t}\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: parts.join(\"\\n\"),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tdetails: { mode: \"parallel\", agentCount: launched.length } as SubagentToolDetails,\n\t\t\t\t\t\tendTurn: launched.length > 0,\n\t\t\t\t\t};\n\t\t\t\t} else {\n\t\t\t\t\t// Chain mode — sequential, stays as one agent since steps depend on each other\n\t\t\t\t\tconst agentName = params.agent || params.chain![0].agent || DEFAULT_AGENT;\n\t\t\t\t\tconst taskSummary = `${params.chain!.length}-step chain`;\n\t\t\t\t\tconst chainSteps = params.chain!;\n\n\t\t\t\t\tconst chainSessionDir = join(subagentSessionsBase, `chain-${generateAgentId()}`);\n\t\t\t\t\tconst agentId = launchBackgroundLifecycle(agentName, taskSummary, async (signal) => {\n\t\t\t\t\t\tconst results = await executeChain(\n\t\t\t\t\t\t\tagents,\n\t\t\t\t\t\t\tchainSteps,\n\t\t\t\t\t\t\tcwd,\n\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t\tundefined,\n\t\t\t\t\t\t\tgetParentProvider(),\n\t\t\t\t\t\t\tmodelRegistry,\n\t\t\t\t\t\t\tchainSessionDir,\n\t\t\t\t\t\t\tparams.agent,\n\t\t\t\t\t\t\tparams.model,\n\t\t\t\t\t\t\tgetParentModel(),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst resultText = results\n\t\t\t\t\t\t\t.map((r, i) => `### Step ${i + 1}\\n${formatSingleResult(r)}`)\n\t\t\t\t\t\t\t.join(\"\\n\\n---\\n\\n\");\n\t\t\t\t\t\tconst failed = results.filter((r) => r.exitCode !== 0);\n\t\t\t\t\t\t// Per-step session logs are already embedded in resultText via formatSingleResult\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tagent: agentName,\n\t\t\t\t\t\t\ttask: taskSummary,\n\t\t\t\t\t\t\texitCode: failed.length > 0 ? 1 : 0,\n\t\t\t\t\t\t\toutput: resultText,\n\t\t\t\t\t\t\tstderr: \"\",\n\t\t\t\t\t\t\terrorMessage:\n\t\t\t\t\t\t\t\tfailed.length > 0\n\t\t\t\t\t\t\t\t\t? `Chain stopped at step ${results.length} of ${chainSteps.length}: ${results[results.length - 1]?.errorMessage}`\n\t\t\t\t\t\t\t\t\t: null,\n\t\t\t\t\t\t};\n\t\t\t\t\t});\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: `Background chain ${agentId} started (${taskSummary}). You will be notified when it completes.`,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tdetails: { mode: \"chain\", agentCount: chainSteps.length } as SubagentToolDetails,\n\t\t\t\t\t\tendTurn: true,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\n\t\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatSubagentCall(args, theme, context.argsComplete));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0);\n\t\t\ttext.setText(formatSubagentResult(result as any, options, theme, context.showImages));\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createSubagentTool(cwd: string, options?: SubagentToolOptions): AgentTool<typeof subagentSchema> {\n\treturn wrapToolDefinition(createSubagentToolDefinition(cwd, options));\n}\n\nexport const subagentToolDefinition = createSubagentToolDefinition(process.cwd());\nexport const subagentTool = createSubagentTool(process.cwd());\n"]}
|