@kolisachint/hoocode-agent 0.4.78 → 0.4.80
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/CHANGELOG.md +40 -0
- package/dist/cli/args.d.ts +2 -0
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +4 -0
- package/dist/cli/args.js.map +1 -1
- package/dist/core/agent-frontmatter.d.ts +5 -7
- package/dist/core/agent-frontmatter.d.ts.map +1 -1
- package/dist/core/agent-frontmatter.js +2 -4
- package/dist/core/agent-frontmatter.js.map +1 -1
- package/dist/core/agent-registry.d.ts +12 -1
- package/dist/core/agent-registry.d.ts.map +1 -1
- package/dist/core/agent-registry.js +38 -3
- package/dist/core/agent-registry.js.map +1 -1
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +7 -3
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/dispatch-evaluator.d.ts +1 -1
- package/dist/core/dispatch-evaluator.d.ts.map +1 -1
- package/dist/core/dispatch-evaluator.js +1 -1
- package/dist/core/dispatch-evaluator.js.map +1 -1
- package/dist/core/messages.d.ts.map +1 -1
- package/dist/core/messages.js +24 -6
- package/dist/core/messages.js.map +1 -1
- package/dist/core/model-categories.d.ts +14 -8
- package/dist/core/model-categories.d.ts.map +1 -1
- package/dist/core/model-categories.js +13 -24
- package/dist/core/model-categories.js.map +1 -1
- package/dist/core/provider-health.d.ts +1 -1
- package/dist/core/provider-health.d.ts.map +1 -1
- package/dist/core/provider-health.js +1 -1
- package/dist/core/provider-health.js.map +1 -1
- package/dist/core/settings-defaults.d.ts +1 -0
- package/dist/core/settings-defaults.d.ts.map +1 -1
- package/dist/core/settings-defaults.js +1 -0
- package/dist/core/settings-defaults.js.map +1 -1
- package/dist/core/settings-manager.d.ts +7 -2
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +9 -0
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/subagent-depth.d.ts +16 -0
- package/dist/core/subagent-depth.d.ts.map +1 -1
- package/dist/core/subagent-depth.js +22 -0
- package/dist/core/subagent-depth.js.map +1 -1
- package/dist/core/subagent-inbox.d.ts +92 -0
- package/dist/core/subagent-inbox.d.ts.map +1 -0
- package/dist/core/subagent-inbox.js +245 -0
- package/dist/core/subagent-inbox.js.map +1 -0
- package/dist/core/subagent-pool.d.ts +14 -7
- package/dist/core/subagent-pool.d.ts.map +1 -1
- package/dist/core/subagent-pool.js +35 -71
- package/dist/core/subagent-pool.js.map +1 -1
- package/dist/core/system-prompt.d.ts +1 -1
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js +8 -8
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/task-store.d.ts +6 -5
- package/dist/core/task-store.d.ts.map +1 -1
- package/dist/core/task-store.js +4 -3
- package/dist/core/task-store.js.map +1 -1
- package/dist/core/tools/index.d.ts +1 -1
- package/dist/core/tools/index.d.ts.map +1 -1
- package/dist/core/tools/index.js +1 -1
- package/dist/core/tools/index.js.map +1 -1
- package/dist/core/tools/subagent.d.ts +23 -20
- package/dist/core/tools/subagent.d.ts.map +1 -1
- package/dist/core/tools/subagent.js +357 -163
- package/dist/core/tools/subagent.js.map +1 -1
- package/dist/core/tools/todo.d.ts.map +1 -1
- package/dist/core/tools/todo.js +10 -6
- package/dist/core/tools/todo.js.map +1 -1
- package/dist/core/warm-subagent-pool-instance.d.ts +23 -0
- package/dist/core/warm-subagent-pool-instance.d.ts.map +1 -0
- package/dist/core/warm-subagent-pool-instance.js +53 -0
- package/dist/core/warm-subagent-pool-instance.js.map +1 -0
- package/dist/core/warm-subagent-pool.d.ts +135 -0
- package/dist/core/warm-subagent-pool.d.ts.map +1 -0
- package/dist/core/warm-subagent-pool.js +383 -0
- package/dist/core/warm-subagent-pool.js.map +1 -0
- package/dist/extensions/core/hoo-core.d.ts.map +1 -1
- package/dist/extensions/core/hoo-core.js +7 -0
- package/dist/extensions/core/hoo-core.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/init-templates.generated.d.ts.map +1 -1
- package/dist/init-templates.generated.js +2 -2
- package/dist/init-templates.generated.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +23 -8
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/task-panel.d.ts.map +1 -1
- package/dist/modes/interactive/components/task-panel.js +26 -3
- package/dist/modes/interactive/components/task-panel.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +1 -1
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/rpc/rpc-client.d.ts +16 -0
- package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client.js +74 -9
- package/dist/modes/rpc/rpc-client.js.map +1 -1
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package.json +1 -1
- package/package.json +4 -4
- package/templates/agents/general-purpose.md +1 -1
- package/templates/agents/plan.md +1 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"subagent-inbox.d.ts","sourceRoot":"","sources":["../../src/core/subagent-inbox.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAGnE,MAAM,MAAM,aAAa,GAAG,SAAS,GAAG,MAAM,GAAG,QAAQ,GAAG,SAAS,GAAG,SAAS,GAAG,WAAW,CAAC;AAEhG,sEAAsE;AACtE,wBAAgB,aAAa,CAAC,SAAS,EAAE,aAAa,GAAG,OAAO,CAE/D;AAED,MAAM,WAAW,WAAW;IAC3B,MAAM,EAAE,MAA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MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,GAAE,aAAwB,GAAG,WAAW,GAAG,SAAS,CAUjG;IAED,wDAAwD;IACxD,GAAG,CAAC,MAAM,EAAE,MAAM,GAAG,WAAW,GAAG,SAAS,CAO3C;IAED;;;;OAIG;IACH,OAAO,CAAC,MAAM,EAAE,MAAM,GAAG;QAAE,MAAM,EAAE,WAAW,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,GAAG,SAAS,CAOzE;IAED,iCAAiC;IACjC,IAAI,IAAI,WAAW,EAAE,CAEpB;IAED,gCAAgC;IAChC,WAAW,IAAI,WAAW,EAAE,CAE3B;IAED,4BAA4B;IAC5B,KAAK,IAAI,IAAI,CAIZ;IAED,mFAAmF;IACnF,OAAO,CAAC,KAAK;CAkBb;AAED,2EAA2E;AAC3E,eAAO,MAAM,aAAa,eAAsB,CAAC","sourcesContent":["/**\n * Subagent inbox: the notify-and-pull bookkeeping behind background `Task`\n * dispatch and the `TaskOutput` tool.\n *\n * Background dispatches don't push their full result into the parent's context.\n * Instead the parent gets a compact notification (\"explore#1 finished\") and the\n * body is retained here, keyed by task id, until the model explicitly pulls it\n * with TaskOutput. This keeps a wide swarm of subagents from flooding the\n * context with N full summaries, and gives the model a queryable liveness view\n * (running / done / failed + last activity) so it can tell a working subagent\n * from a rogue one. The same surface works at every delegation depth.\n *\n * Lifecycle per task:\n * running ──▶ done (body retained) ──collect──▶ collected (body dropped)\n * ├─▶ failed\n * ├─▶ stalled\n * └─▶ timeout\n */\n\nimport type { SubagentPool, TaskResult } from \"./subagent-pool.js\";\nimport type { SubagentResultFile } from \"./subagent-result.js\";\n\nexport type TaskLifecycle = \"running\" | \"done\" | \"failed\" | \"stalled\" | \"timeout\" | \"collected\";\n\n/** A non-terminal task is still doing work; the rest have settled. */\nexport function isOutstanding(lifecycle: TaskLifecycle): boolean {\n\treturn lifecycle === \"running\";\n}\n\nexport interface InboxRecord {\n\ttaskId: string;\n\t/** Friendly handle shown to the model, e.g. \"explore#1\". */\n\tlabel: string;\n\tagentType: string;\n\tlifecycle: TaskLifecycle;\n\tstartedAt: number;\n\tendedAt?: number;\n\t/** Tool the subagent is currently running, from the pool's progress stream. */\n\tlastActivity?: string;\n\t/** First line of the result/summary, kept even after the body is collected. */\n\tsummaryLine?: string;\n\t/** Full subagent summary, retained only while `done` and uncollected. */\n\tbody?: string;\n\t/** Failure reason when the task did not succeed. */\n\terror?: string;\n}\n\n/** Cap on settled (terminal) records kept for late pulls; running records are never pruned. */\nconst MAX_SETTLED = 50;\n\n/** First non-empty line of a block of text, length-capped. */\nfunction firstLine(text: string, max = 120): string {\n\tconst line = (\n\t\ttext\n\t\t\t.trim()\n\t\t\t.split(\"\\n\")\n\t\t\t.find((l) => l.trim()) ?? \"\"\n\t).trim();\n\treturn line.length > max ? `${line.slice(0, max - 1)}…` : line;\n}\n\n/** Map a subagent's terminal `status` onto an inbox lifecycle. */\nfunction failLifecycle(status: string | undefined): TaskLifecycle {\n\tif (status === \"stalled\") return \"stalled\";\n\tif (status === \"timeout\") return \"timeout\";\n\treturn \"failed\";\n}\n\n/** Derive the \"currently running X\" activity label from a forwarded progress event. */\nfunction activityFromEvent(event: Record<string, unknown>): string | undefined {\n\tif (event.type === \"tool_execution_start\" && typeof event.toolName === \"string\") {\n\t\treturn event.toolName;\n\t}\n\tif (event.type === \"turn_end\") return \"thinking\";\n\treturn undefined;\n}\n\nclass SubagentInbox {\n\tprivate records = new Map<string, InboxRecord>();\n\t/** Insertion order of task ids, for stable listing and pruning. */\n\tprivate order: string[] = [];\n\tprivate labelCounters = new Map<string, number>();\n\tprivate observedPools = new WeakSet<SubagentPool>();\n\t/** One-shot callbacks fired after any record settles, for the wait helpers. */\n\tprivate settleListeners = new Set<() => void>();\n\n\tprivate notifySettle(): void {\n\t\tfor (const listener of [...this.settleListeners]) listener();\n\t}\n\n\t/**\n\t * Resolve once the given task settles (or immediately if already settled /\n\t * unknown), bounded by `timeoutMs`. Backs TaskOutput's per-task wait.\n\t */\n\twaitFor(handle: string, timeoutMs: number): Promise<InboxRecord | undefined> {\n\t\tconst current = this.get(handle);\n\t\tif (!current || !isOutstanding(current.lifecycle)) return Promise.resolve(current);\n\t\treturn new Promise((resolve) => {\n\t\t\tconst cleanup = () => {\n\t\t\t\tthis.settleListeners.delete(check);\n\t\t\t\tclearTimeout(timer);\n\t\t\t};\n\t\t\tconst check = () => {\n\t\t\t\tconst rec = this.get(handle);\n\t\t\t\tif (!rec || !isOutstanding(rec.lifecycle)) {\n\t\t\t\t\tcleanup();\n\t\t\t\t\tresolve(rec);\n\t\t\t\t}\n\t\t\t};\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tcleanup();\n\t\t\t\tresolve(this.get(handle));\n\t\t\t}, timeoutMs);\n\t\t\ttimer.unref?.();\n\t\t\tthis.settleListeners.add(check);\n\t\t});\n\t}\n\n\t/** Resolve once nothing is outstanding (the swarm barrier), bounded by `timeoutMs`. */\n\twaitForAll(timeoutMs: number): Promise<void> {\n\t\tif (this.outstanding().length === 0) return Promise.resolve();\n\t\treturn new Promise((resolve) => {\n\t\t\tconst cleanup = () => {\n\t\t\t\tthis.settleListeners.delete(check);\n\t\t\t\tclearTimeout(timer);\n\t\t\t};\n\t\t\tconst check = () => {\n\t\t\t\tif (this.outstanding().length === 0) {\n\t\t\t\t\tcleanup();\n\t\t\t\t\tresolve();\n\t\t\t\t}\n\t\t\t};\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tcleanup();\n\t\t\t\tresolve();\n\t\t\t}, timeoutMs);\n\t\t\ttimer.unref?.();\n\t\t\tthis.settleListeners.add(check);\n\t\t});\n\t}\n\n\t/** Allocate the next friendly label for an agent type (`explore#1`, `explore#2`, …). */\n\tnextLabel(agentType: string): string {\n\t\tconst n = (this.labelCounters.get(agentType) ?? 0) + 1;\n\t\tthis.labelCounters.set(agentType, n);\n\t\treturn `${agentType}#${n}`;\n\t}\n\n\t/**\n\t * Track a pool's `task_progress` events so running records carry a live\n\t * `lastActivity`. Idempotent per pool, so callers can wire it on every dispatch.\n\t */\n\tobserve(pool: SubagentPool): void {\n\t\t// Tolerate a non-EventEmitter stand-in (test fakes): without progress events\n\t\t// records simply carry no live activity.\n\t\tif (typeof (pool as { on?: unknown }).on !== \"function\") return;\n\t\tif (this.observedPools.has(pool)) return;\n\t\tthis.observedPools.add(pool);\n\t\tpool.on(\"task_progress\", (data: { task_id: string; event: Record<string, unknown> }) => {\n\t\t\tconst rec = this.records.get(data.task_id);\n\t\t\tif (!rec || rec.lifecycle !== \"running\") return;\n\t\t\tconst activity = activityFromEvent(data.event);\n\t\t\tif (activity) rec.lastActivity = activity;\n\t\t});\n\t}\n\n\t/** Register a freshly dispatched background task as running. */\n\tstart(taskId: string, label: string, agentType: string): InboxRecord {\n\t\tconst rec: InboxRecord = { taskId, label, agentType, lifecycle: \"running\", startedAt: Date.now() };\n\t\tthis.records.set(taskId, rec);\n\t\tthis.order.push(taskId);\n\t\tthis.prune();\n\t\treturn rec;\n\t}\n\n\t/** Settle a task from its dispatch result: retain the body on success, the reason on failure. */\n\tfinish(taskId: string, result: TaskResult): InboxRecord | undefined {\n\t\tconst rec = this.records.get(taskId);\n\t\tif (!rec) return undefined;\n\t\trec.endedAt = Date.now();\n\t\trec.lastActivity = undefined;\n\t\tconst r = result.result;\n\t\tconst data = r?.result_data as SubagentResultFile | undefined;\n\t\tif (r?.ok) {\n\t\t\trec.lifecycle = \"done\";\n\t\t\trec.body = data?.summary?.trim() || \"(subagent returned no output)\";\n\t\t\trec.summaryLine = firstLine(rec.body);\n\t\t} else {\n\t\t\trec.lifecycle = failLifecycle(r?.status);\n\t\t\trec.error = r?.error ?? (r?.status ? `subagent ${r.status}` : \"unknown error\");\n\t\t\trec.summaryLine = rec.error;\n\t\t}\n\t\tthis.notifySettle();\n\t\treturn rec;\n\t}\n\n\t/** Settle a task that never produced a TaskResult (e.g. a thrown dispatch error). */\n\tfail(taskId: string, reason: string, lifecycle: TaskLifecycle = \"failed\"): InboxRecord | undefined {\n\t\tconst rec = this.records.get(taskId);\n\t\tif (!rec) return undefined;\n\t\trec.endedAt = Date.now();\n\t\trec.lastActivity = undefined;\n\t\trec.lifecycle = lifecycle;\n\t\trec.error = reason;\n\t\trec.summaryLine = reason;\n\t\tthis.notifySettle();\n\t\treturn rec;\n\t}\n\n\t/** Look up a record by task id or by friendly label. */\n\tget(handle: string): InboxRecord | undefined {\n\t\tconst byId = this.records.get(handle);\n\t\tif (byId) return byId;\n\t\tfor (const rec of this.records.values()) {\n\t\t\tif (rec.label === handle) return rec;\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Read a done task's body and mark it collected, dropping the body so it is not\n\t * re-fed to the model. Returns the record (with `body` still populated for this\n\t * one read) or undefined for an unknown handle.\n\t */\n\tcollect(handle: string): { record: InboxRecord; body: string } | undefined {\n\t\tconst rec = this.get(handle);\n\t\tif (!rec || rec.lifecycle !== \"done\" || rec.body === undefined) return undefined;\n\t\tconst body = rec.body;\n\t\trec.lifecycle = \"collected\";\n\t\trec.body = undefined;\n\t\treturn { record: rec, body };\n\t}\n\n\t/** All records, oldest first. */\n\tlist(): InboxRecord[] {\n\t\treturn this.order.map((id) => this.records.get(id)).filter((r): r is InboxRecord => r !== undefined);\n\t}\n\n\t/** Records still doing work. */\n\toutstanding(): InboxRecord[] {\n\t\treturn this.list().filter((r) => isOutstanding(r.lifecycle));\n\t}\n\n\t/** Test/teardown helper. */\n\tclear(): void {\n\t\tthis.records.clear();\n\t\tthis.order = [];\n\t\tthis.labelCounters.clear();\n\t}\n\n\t/** Drop the oldest settled records once past the cap; running records are kept. */\n\tprivate prune(): void {\n\t\tlet settled = this.order.filter((id) => {\n\t\t\tconst r = this.records.get(id);\n\t\t\treturn r !== undefined && !isOutstanding(r.lifecycle);\n\t\t}).length;\n\t\tif (settled <= MAX_SETTLED) return;\n\t\tconst kept: string[] = [];\n\t\tfor (const id of this.order) {\n\t\t\tconst r = this.records.get(id);\n\t\t\tif (r && !isOutstanding(r.lifecycle) && settled > MAX_SETTLED) {\n\t\t\t\tthis.records.delete(id);\n\t\t\t\tsettled--;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tkept.push(id);\n\t\t}\n\t\tthis.order = kept;\n\t}\n}\n\n/** Process-wide subagent inbox shared by the Task and TaskOutput tools. */\nexport const subagentInbox = new SubagentInbox();\n"]}
|
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Subagent inbox: the notify-and-pull bookkeeping behind background `Task`
|
|
3
|
+
* dispatch and the `TaskOutput` tool.
|
|
4
|
+
*
|
|
5
|
+
* Background dispatches don't push their full result into the parent's context.
|
|
6
|
+
* Instead the parent gets a compact notification ("explore#1 finished") and the
|
|
7
|
+
* body is retained here, keyed by task id, until the model explicitly pulls it
|
|
8
|
+
* with TaskOutput. This keeps a wide swarm of subagents from flooding the
|
|
9
|
+
* context with N full summaries, and gives the model a queryable liveness view
|
|
10
|
+
* (running / done / failed + last activity) so it can tell a working subagent
|
|
11
|
+
* from a rogue one. The same surface works at every delegation depth.
|
|
12
|
+
*
|
|
13
|
+
* Lifecycle per task:
|
|
14
|
+
* running ──▶ done (body retained) ──collect──▶ collected (body dropped)
|
|
15
|
+
* ├─▶ failed
|
|
16
|
+
* ├─▶ stalled
|
|
17
|
+
* └─▶ timeout
|
|
18
|
+
*/
|
|
19
|
+
/** A non-terminal task is still doing work; the rest have settled. */
|
|
20
|
+
export function isOutstanding(lifecycle) {
|
|
21
|
+
return lifecycle === "running";
|
|
22
|
+
}
|
|
23
|
+
/** Cap on settled (terminal) records kept for late pulls; running records are never pruned. */
|
|
24
|
+
const MAX_SETTLED = 50;
|
|
25
|
+
/** First non-empty line of a block of text, length-capped. */
|
|
26
|
+
function firstLine(text, max = 120) {
|
|
27
|
+
const line = (text
|
|
28
|
+
.trim()
|
|
29
|
+
.split("\n")
|
|
30
|
+
.find((l) => l.trim()) ?? "").trim();
|
|
31
|
+
return line.length > max ? `${line.slice(0, max - 1)}…` : line;
|
|
32
|
+
}
|
|
33
|
+
/** Map a subagent's terminal `status` onto an inbox lifecycle. */
|
|
34
|
+
function failLifecycle(status) {
|
|
35
|
+
if (status === "stalled")
|
|
36
|
+
return "stalled";
|
|
37
|
+
if (status === "timeout")
|
|
38
|
+
return "timeout";
|
|
39
|
+
return "failed";
|
|
40
|
+
}
|
|
41
|
+
/** Derive the "currently running X" activity label from a forwarded progress event. */
|
|
42
|
+
function activityFromEvent(event) {
|
|
43
|
+
if (event.type === "tool_execution_start" && typeof event.toolName === "string") {
|
|
44
|
+
return event.toolName;
|
|
45
|
+
}
|
|
46
|
+
if (event.type === "turn_end")
|
|
47
|
+
return "thinking";
|
|
48
|
+
return undefined;
|
|
49
|
+
}
|
|
50
|
+
class SubagentInbox {
|
|
51
|
+
records = new Map();
|
|
52
|
+
/** Insertion order of task ids, for stable listing and pruning. */
|
|
53
|
+
order = [];
|
|
54
|
+
labelCounters = new Map();
|
|
55
|
+
observedPools = new WeakSet();
|
|
56
|
+
/** One-shot callbacks fired after any record settles, for the wait helpers. */
|
|
57
|
+
settleListeners = new Set();
|
|
58
|
+
notifySettle() {
|
|
59
|
+
for (const listener of [...this.settleListeners])
|
|
60
|
+
listener();
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Resolve once the given task settles (or immediately if already settled /
|
|
64
|
+
* unknown), bounded by `timeoutMs`. Backs TaskOutput's per-task wait.
|
|
65
|
+
*/
|
|
66
|
+
waitFor(handle, timeoutMs) {
|
|
67
|
+
const current = this.get(handle);
|
|
68
|
+
if (!current || !isOutstanding(current.lifecycle))
|
|
69
|
+
return Promise.resolve(current);
|
|
70
|
+
return new Promise((resolve) => {
|
|
71
|
+
const cleanup = () => {
|
|
72
|
+
this.settleListeners.delete(check);
|
|
73
|
+
clearTimeout(timer);
|
|
74
|
+
};
|
|
75
|
+
const check = () => {
|
|
76
|
+
const rec = this.get(handle);
|
|
77
|
+
if (!rec || !isOutstanding(rec.lifecycle)) {
|
|
78
|
+
cleanup();
|
|
79
|
+
resolve(rec);
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
const timer = setTimeout(() => {
|
|
83
|
+
cleanup();
|
|
84
|
+
resolve(this.get(handle));
|
|
85
|
+
}, timeoutMs);
|
|
86
|
+
timer.unref?.();
|
|
87
|
+
this.settleListeners.add(check);
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
/** Resolve once nothing is outstanding (the swarm barrier), bounded by `timeoutMs`. */
|
|
91
|
+
waitForAll(timeoutMs) {
|
|
92
|
+
if (this.outstanding().length === 0)
|
|
93
|
+
return Promise.resolve();
|
|
94
|
+
return new Promise((resolve) => {
|
|
95
|
+
const cleanup = () => {
|
|
96
|
+
this.settleListeners.delete(check);
|
|
97
|
+
clearTimeout(timer);
|
|
98
|
+
};
|
|
99
|
+
const check = () => {
|
|
100
|
+
if (this.outstanding().length === 0) {
|
|
101
|
+
cleanup();
|
|
102
|
+
resolve();
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
const timer = setTimeout(() => {
|
|
106
|
+
cleanup();
|
|
107
|
+
resolve();
|
|
108
|
+
}, timeoutMs);
|
|
109
|
+
timer.unref?.();
|
|
110
|
+
this.settleListeners.add(check);
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
/** Allocate the next friendly label for an agent type (`explore#1`, `explore#2`, …). */
|
|
114
|
+
nextLabel(agentType) {
|
|
115
|
+
const n = (this.labelCounters.get(agentType) ?? 0) + 1;
|
|
116
|
+
this.labelCounters.set(agentType, n);
|
|
117
|
+
return `${agentType}#${n}`;
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Track a pool's `task_progress` events so running records carry a live
|
|
121
|
+
* `lastActivity`. Idempotent per pool, so callers can wire it on every dispatch.
|
|
122
|
+
*/
|
|
123
|
+
observe(pool) {
|
|
124
|
+
// Tolerate a non-EventEmitter stand-in (test fakes): without progress events
|
|
125
|
+
// records simply carry no live activity.
|
|
126
|
+
if (typeof pool.on !== "function")
|
|
127
|
+
return;
|
|
128
|
+
if (this.observedPools.has(pool))
|
|
129
|
+
return;
|
|
130
|
+
this.observedPools.add(pool);
|
|
131
|
+
pool.on("task_progress", (data) => {
|
|
132
|
+
const rec = this.records.get(data.task_id);
|
|
133
|
+
if (!rec || rec.lifecycle !== "running")
|
|
134
|
+
return;
|
|
135
|
+
const activity = activityFromEvent(data.event);
|
|
136
|
+
if (activity)
|
|
137
|
+
rec.lastActivity = activity;
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
/** Register a freshly dispatched background task as running. */
|
|
141
|
+
start(taskId, label, agentType) {
|
|
142
|
+
const rec = { taskId, label, agentType, lifecycle: "running", startedAt: Date.now() };
|
|
143
|
+
this.records.set(taskId, rec);
|
|
144
|
+
this.order.push(taskId);
|
|
145
|
+
this.prune();
|
|
146
|
+
return rec;
|
|
147
|
+
}
|
|
148
|
+
/** Settle a task from its dispatch result: retain the body on success, the reason on failure. */
|
|
149
|
+
finish(taskId, result) {
|
|
150
|
+
const rec = this.records.get(taskId);
|
|
151
|
+
if (!rec)
|
|
152
|
+
return undefined;
|
|
153
|
+
rec.endedAt = Date.now();
|
|
154
|
+
rec.lastActivity = undefined;
|
|
155
|
+
const r = result.result;
|
|
156
|
+
const data = r?.result_data;
|
|
157
|
+
if (r?.ok) {
|
|
158
|
+
rec.lifecycle = "done";
|
|
159
|
+
rec.body = data?.summary?.trim() || "(subagent returned no output)";
|
|
160
|
+
rec.summaryLine = firstLine(rec.body);
|
|
161
|
+
}
|
|
162
|
+
else {
|
|
163
|
+
rec.lifecycle = failLifecycle(r?.status);
|
|
164
|
+
rec.error = r?.error ?? (r?.status ? `subagent ${r.status}` : "unknown error");
|
|
165
|
+
rec.summaryLine = rec.error;
|
|
166
|
+
}
|
|
167
|
+
this.notifySettle();
|
|
168
|
+
return rec;
|
|
169
|
+
}
|
|
170
|
+
/** Settle a task that never produced a TaskResult (e.g. a thrown dispatch error). */
|
|
171
|
+
fail(taskId, reason, lifecycle = "failed") {
|
|
172
|
+
const rec = this.records.get(taskId);
|
|
173
|
+
if (!rec)
|
|
174
|
+
return undefined;
|
|
175
|
+
rec.endedAt = Date.now();
|
|
176
|
+
rec.lastActivity = undefined;
|
|
177
|
+
rec.lifecycle = lifecycle;
|
|
178
|
+
rec.error = reason;
|
|
179
|
+
rec.summaryLine = reason;
|
|
180
|
+
this.notifySettle();
|
|
181
|
+
return rec;
|
|
182
|
+
}
|
|
183
|
+
/** Look up a record by task id or by friendly label. */
|
|
184
|
+
get(handle) {
|
|
185
|
+
const byId = this.records.get(handle);
|
|
186
|
+
if (byId)
|
|
187
|
+
return byId;
|
|
188
|
+
for (const rec of this.records.values()) {
|
|
189
|
+
if (rec.label === handle)
|
|
190
|
+
return rec;
|
|
191
|
+
}
|
|
192
|
+
return undefined;
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Read a done task's body and mark it collected, dropping the body so it is not
|
|
196
|
+
* re-fed to the model. Returns the record (with `body` still populated for this
|
|
197
|
+
* one read) or undefined for an unknown handle.
|
|
198
|
+
*/
|
|
199
|
+
collect(handle) {
|
|
200
|
+
const rec = this.get(handle);
|
|
201
|
+
if (!rec || rec.lifecycle !== "done" || rec.body === undefined)
|
|
202
|
+
return undefined;
|
|
203
|
+
const body = rec.body;
|
|
204
|
+
rec.lifecycle = "collected";
|
|
205
|
+
rec.body = undefined;
|
|
206
|
+
return { record: rec, body };
|
|
207
|
+
}
|
|
208
|
+
/** All records, oldest first. */
|
|
209
|
+
list() {
|
|
210
|
+
return this.order.map((id) => this.records.get(id)).filter((r) => r !== undefined);
|
|
211
|
+
}
|
|
212
|
+
/** Records still doing work. */
|
|
213
|
+
outstanding() {
|
|
214
|
+
return this.list().filter((r) => isOutstanding(r.lifecycle));
|
|
215
|
+
}
|
|
216
|
+
/** Test/teardown helper. */
|
|
217
|
+
clear() {
|
|
218
|
+
this.records.clear();
|
|
219
|
+
this.order = [];
|
|
220
|
+
this.labelCounters.clear();
|
|
221
|
+
}
|
|
222
|
+
/** Drop the oldest settled records once past the cap; running records are kept. */
|
|
223
|
+
prune() {
|
|
224
|
+
let settled = this.order.filter((id) => {
|
|
225
|
+
const r = this.records.get(id);
|
|
226
|
+
return r !== undefined && !isOutstanding(r.lifecycle);
|
|
227
|
+
}).length;
|
|
228
|
+
if (settled <= MAX_SETTLED)
|
|
229
|
+
return;
|
|
230
|
+
const kept = [];
|
|
231
|
+
for (const id of this.order) {
|
|
232
|
+
const r = this.records.get(id);
|
|
233
|
+
if (r && !isOutstanding(r.lifecycle) && settled > MAX_SETTLED) {
|
|
234
|
+
this.records.delete(id);
|
|
235
|
+
settled--;
|
|
236
|
+
continue;
|
|
237
|
+
}
|
|
238
|
+
kept.push(id);
|
|
239
|
+
}
|
|
240
|
+
this.order = kept;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
/** Process-wide subagent inbox shared by the Task and TaskOutput tools. */
|
|
244
|
+
export const subagentInbox = new SubagentInbox();
|
|
245
|
+
//# sourceMappingURL=subagent-inbox.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"subagent-inbox.js","sourceRoot":"","sources":["../../src/core/subagent-inbox.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAOH,sEAAsE;AACtE,MAAM,UAAU,aAAa,CAAC,SAAwB,EAAW;IAChE,OAAO,SAAS,KAAK,SAAS,CAAC;AAAA,CAC/B;AAoBD,+FAA+F;AAC/F,MAAM,WAAW,GAAG,EAAE,CAAC;AAEvB,8DAA8D;AAC9D,SAAS,SAAS,CAAC,IAAY,EAAE,GAAG,GAAG,GAAG,EAAU;IACnD,MAAM,IAAI,GAAG,CACZ,IAAI;SACF,IAAI,EAAE;SACN,KAAK,CAAC,IAAI,CAAC;SACX,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,IAAI,EAAE,CAC7B,CAAC,IAAI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K,CAAC,MAAM,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC;YACvC,MAAM,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;YAC/B,OAAO,CAAC,KAAK,SAAS,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;QAAA,CACtD,CAAC,CAAC,MAAM,CAAC;QACV,IAAI,OAAO,IAAI,WAAW;YAAE,OAAO;QACnC,MAAM,IAAI,GAAa,EAAE,CAAC;QAC1B,KAAK,MAAM,EAAE,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;YAC7B,MAAM,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;YAC/B,IAAI,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,SAAS,CAAC,IAAI,OAAO,GAAG,WAAW,EAAE,CAAC;gBAC/D,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;gBACxB,OAAO,EAAE,CAAC;gBACV,SAAS;YACV,CAAC;YACD,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QACf,CAAC;QACD,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;IAAA,CAClB;CACD;AAED,2EAA2E;AAC3E,MAAM,CAAC,MAAM,aAAa,GAAG,IAAI,aAAa,EAAE,CAAC","sourcesContent":["/**\n * Subagent inbox: the notify-and-pull bookkeeping behind background `Task`\n * dispatch and the `TaskOutput` tool.\n *\n * Background dispatches don't push their full result into the parent's context.\n * Instead the parent gets a compact notification (\"explore#1 finished\") and the\n * body is retained here, keyed by task id, until the model explicitly pulls it\n * with TaskOutput. This keeps a wide swarm of subagents from flooding the\n * context with N full summaries, and gives the model a queryable liveness view\n * (running / done / failed + last activity) so it can tell a working subagent\n * from a rogue one. The same surface works at every delegation depth.\n *\n * Lifecycle per task:\n * running ──▶ done (body retained) ──collect──▶ collected (body dropped)\n * ├─▶ failed\n * ├─▶ stalled\n * └─▶ timeout\n */\n\nimport type { SubagentPool, TaskResult } from \"./subagent-pool.js\";\nimport type { SubagentResultFile } from \"./subagent-result.js\";\n\nexport type TaskLifecycle = \"running\" | \"done\" | \"failed\" | \"stalled\" | \"timeout\" | \"collected\";\n\n/** A non-terminal task is still doing work; the rest have settled. */\nexport function isOutstanding(lifecycle: TaskLifecycle): boolean {\n\treturn lifecycle === \"running\";\n}\n\nexport interface InboxRecord {\n\ttaskId: string;\n\t/** Friendly handle shown to the model, e.g. \"explore#1\". */\n\tlabel: string;\n\tagentType: string;\n\tlifecycle: TaskLifecycle;\n\tstartedAt: number;\n\tendedAt?: number;\n\t/** Tool the subagent is currently running, from the pool's progress stream. */\n\tlastActivity?: string;\n\t/** First line of the result/summary, kept even after the body is collected. */\n\tsummaryLine?: string;\n\t/** Full subagent summary, retained only while `done` and uncollected. */\n\tbody?: string;\n\t/** Failure reason when the task did not succeed. */\n\terror?: string;\n}\n\n/** Cap on settled (terminal) records kept for late pulls; running records are never pruned. */\nconst MAX_SETTLED = 50;\n\n/** First non-empty line of a block of text, length-capped. */\nfunction firstLine(text: string, max = 120): string {\n\tconst line = (\n\t\ttext\n\t\t\t.trim()\n\t\t\t.split(\"\\n\")\n\t\t\t.find((l) => l.trim()) ?? \"\"\n\t).trim();\n\treturn line.length > max ? `${line.slice(0, max - 1)}…` : line;\n}\n\n/** Map a subagent's terminal `status` onto an inbox lifecycle. */\nfunction failLifecycle(status: string | undefined): TaskLifecycle {\n\tif (status === \"stalled\") return \"stalled\";\n\tif (status === \"timeout\") return \"timeout\";\n\treturn \"failed\";\n}\n\n/** Derive the \"currently running X\" activity label from a forwarded progress event. */\nfunction activityFromEvent(event: Record<string, unknown>): string | undefined {\n\tif (event.type === \"tool_execution_start\" && typeof event.toolName === \"string\") {\n\t\treturn event.toolName;\n\t}\n\tif (event.type === \"turn_end\") return \"thinking\";\n\treturn undefined;\n}\n\nclass SubagentInbox {\n\tprivate records = new Map<string, InboxRecord>();\n\t/** Insertion order of task ids, for stable listing and pruning. */\n\tprivate order: string[] = [];\n\tprivate labelCounters = new Map<string, number>();\n\tprivate observedPools = new WeakSet<SubagentPool>();\n\t/** One-shot callbacks fired after any record settles, for the wait helpers. */\n\tprivate settleListeners = new Set<() => void>();\n\n\tprivate notifySettle(): void {\n\t\tfor (const listener of [...this.settleListeners]) listener();\n\t}\n\n\t/**\n\t * Resolve once the given task settles (or immediately if already settled /\n\t * unknown), bounded by `timeoutMs`. Backs TaskOutput's per-task wait.\n\t */\n\twaitFor(handle: string, timeoutMs: number): Promise<InboxRecord | undefined> {\n\t\tconst current = this.get(handle);\n\t\tif (!current || !isOutstanding(current.lifecycle)) return Promise.resolve(current);\n\t\treturn new Promise((resolve) => {\n\t\t\tconst cleanup = () => {\n\t\t\t\tthis.settleListeners.delete(check);\n\t\t\t\tclearTimeout(timer);\n\t\t\t};\n\t\t\tconst check = () => {\n\t\t\t\tconst rec = this.get(handle);\n\t\t\t\tif (!rec || !isOutstanding(rec.lifecycle)) {\n\t\t\t\t\tcleanup();\n\t\t\t\t\tresolve(rec);\n\t\t\t\t}\n\t\t\t};\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tcleanup();\n\t\t\t\tresolve(this.get(handle));\n\t\t\t}, timeoutMs);\n\t\t\ttimer.unref?.();\n\t\t\tthis.settleListeners.add(check);\n\t\t});\n\t}\n\n\t/** Resolve once nothing is outstanding (the swarm barrier), bounded by `timeoutMs`. */\n\twaitForAll(timeoutMs: number): Promise<void> {\n\t\tif (this.outstanding().length === 0) return Promise.resolve();\n\t\treturn new Promise((resolve) => {\n\t\t\tconst cleanup = () => {\n\t\t\t\tthis.settleListeners.delete(check);\n\t\t\t\tclearTimeout(timer);\n\t\t\t};\n\t\t\tconst check = () => {\n\t\t\t\tif (this.outstanding().length === 0) {\n\t\t\t\t\tcleanup();\n\t\t\t\t\tresolve();\n\t\t\t\t}\n\t\t\t};\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tcleanup();\n\t\t\t\tresolve();\n\t\t\t}, timeoutMs);\n\t\t\ttimer.unref?.();\n\t\t\tthis.settleListeners.add(check);\n\t\t});\n\t}\n\n\t/** Allocate the next friendly label for an agent type (`explore#1`, `explore#2`, …). */\n\tnextLabel(agentType: string): string {\n\t\tconst n = (this.labelCounters.get(agentType) ?? 0) + 1;\n\t\tthis.labelCounters.set(agentType, n);\n\t\treturn `${agentType}#${n}`;\n\t}\n\n\t/**\n\t * Track a pool's `task_progress` events so running records carry a live\n\t * `lastActivity`. Idempotent per pool, so callers can wire it on every dispatch.\n\t */\n\tobserve(pool: SubagentPool): void {\n\t\t// Tolerate a non-EventEmitter stand-in (test fakes): without progress events\n\t\t// records simply carry no live activity.\n\t\tif (typeof (pool as { on?: unknown }).on !== \"function\") return;\n\t\tif (this.observedPools.has(pool)) return;\n\t\tthis.observedPools.add(pool);\n\t\tpool.on(\"task_progress\", (data: { task_id: string; event: Record<string, unknown> }) => {\n\t\t\tconst rec = this.records.get(data.task_id);\n\t\t\tif (!rec || rec.lifecycle !== \"running\") return;\n\t\t\tconst activity = activityFromEvent(data.event);\n\t\t\tif (activity) rec.lastActivity = activity;\n\t\t});\n\t}\n\n\t/** Register a freshly dispatched background task as running. */\n\tstart(taskId: string, label: string, agentType: string): InboxRecord {\n\t\tconst rec: InboxRecord = { taskId, label, agentType, lifecycle: \"running\", startedAt: Date.now() };\n\t\tthis.records.set(taskId, rec);\n\t\tthis.order.push(taskId);\n\t\tthis.prune();\n\t\treturn rec;\n\t}\n\n\t/** Settle a task from its dispatch result: retain the body on success, the reason on failure. */\n\tfinish(taskId: string, result: TaskResult): InboxRecord | undefined {\n\t\tconst rec = this.records.get(taskId);\n\t\tif (!rec) return undefined;\n\t\trec.endedAt = Date.now();\n\t\trec.lastActivity = undefined;\n\t\tconst r = result.result;\n\t\tconst data = r?.result_data as SubagentResultFile | undefined;\n\t\tif (r?.ok) {\n\t\t\trec.lifecycle = \"done\";\n\t\t\trec.body = data?.summary?.trim() || \"(subagent returned no output)\";\n\t\t\trec.summaryLine = firstLine(rec.body);\n\t\t} else {\n\t\t\trec.lifecycle = failLifecycle(r?.status);\n\t\t\trec.error = r?.error ?? (r?.status ? `subagent ${r.status}` : \"unknown error\");\n\t\t\trec.summaryLine = rec.error;\n\t\t}\n\t\tthis.notifySettle();\n\t\treturn rec;\n\t}\n\n\t/** Settle a task that never produced a TaskResult (e.g. a thrown dispatch error). */\n\tfail(taskId: string, reason: string, lifecycle: TaskLifecycle = \"failed\"): InboxRecord | undefined {\n\t\tconst rec = this.records.get(taskId);\n\t\tif (!rec) return undefined;\n\t\trec.endedAt = Date.now();\n\t\trec.lastActivity = undefined;\n\t\trec.lifecycle = lifecycle;\n\t\trec.error = reason;\n\t\trec.summaryLine = reason;\n\t\tthis.notifySettle();\n\t\treturn rec;\n\t}\n\n\t/** Look up a record by task id or by friendly label. */\n\tget(handle: string): InboxRecord | undefined {\n\t\tconst byId = this.records.get(handle);\n\t\tif (byId) return byId;\n\t\tfor (const rec of this.records.values()) {\n\t\t\tif (rec.label === handle) return rec;\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Read a done task's body and mark it collected, dropping the body so it is not\n\t * re-fed to the model. Returns the record (with `body` still populated for this\n\t * one read) or undefined for an unknown handle.\n\t */\n\tcollect(handle: string): { record: InboxRecord; body: string } | undefined {\n\t\tconst rec = this.get(handle);\n\t\tif (!rec || rec.lifecycle !== \"done\" || rec.body === undefined) return undefined;\n\t\tconst body = rec.body;\n\t\trec.lifecycle = \"collected\";\n\t\trec.body = undefined;\n\t\treturn { record: rec, body };\n\t}\n\n\t/** All records, oldest first. */\n\tlist(): InboxRecord[] {\n\t\treturn this.order.map((id) => this.records.get(id)).filter((r): r is InboxRecord => r !== undefined);\n\t}\n\n\t/** Records still doing work. */\n\toutstanding(): InboxRecord[] {\n\t\treturn this.list().filter((r) => isOutstanding(r.lifecycle));\n\t}\n\n\t/** Test/teardown helper. */\n\tclear(): void {\n\t\tthis.records.clear();\n\t\tthis.order = [];\n\t\tthis.labelCounters.clear();\n\t}\n\n\t/** Drop the oldest settled records once past the cap; running records are kept. */\n\tprivate prune(): void {\n\t\tlet settled = this.order.filter((id) => {\n\t\t\tconst r = this.records.get(id);\n\t\t\treturn r !== undefined && !isOutstanding(r.lifecycle);\n\t\t}).length;\n\t\tif (settled <= MAX_SETTLED) return;\n\t\tconst kept: string[] = [];\n\t\tfor (const id of this.order) {\n\t\t\tconst r = this.records.get(id);\n\t\t\tif (r && !isOutstanding(r.lifecycle) && settled > MAX_SETTLED) {\n\t\t\t\tthis.records.delete(id);\n\t\t\t\tsettled--;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tkept.push(id);\n\t\t}\n\t\tthis.order = kept;\n\t}\n}\n\n/** Process-wide subagent inbox shared by the Task and TaskOutput tools. */\nexport const subagentInbox = new SubagentInbox();\n"]}
|
|
@@ -67,6 +67,9 @@ export interface DispatchOptions {
|
|
|
67
67
|
provider?: string;
|
|
68
68
|
/** Explicit session file to persist/continue (used by resume). */
|
|
69
69
|
sessionFile?: string;
|
|
70
|
+
/** Caller-supplied task id. Defaults to a generated `dispatch-…` id. Lets a
|
|
71
|
+
* caller register liveness/inbox state under the id before dispatch resolves. */
|
|
72
|
+
taskId?: string;
|
|
70
73
|
}
|
|
71
74
|
export interface SubagentPoolOptions {
|
|
72
75
|
/** Path to the hoocode executable (or the runtime, e.g. node, when prefixArgs is set). */
|
|
@@ -180,13 +183,6 @@ export declare class SubagentPool extends EventEmitter {
|
|
|
180
183
|
get_status(task_id: string): "running" | "queued" | "done" | "failed" | "stalled" | "timeout" | "unknown";
|
|
181
184
|
/** Wait for a task to complete and return its result. */
|
|
182
185
|
wait_for(task_id: string): Promise<SubagentResult>;
|
|
183
|
-
/**
|
|
184
|
-
* Wait for a task to finish without consuming its result. Returns the result
|
|
185
|
-
* once the task reaches a terminal state, or undefined if the task is not
|
|
186
|
-
* found. Unlike wait_for(), the result remains in the completed map so
|
|
187
|
-
* collect() can still read it afterward.
|
|
188
|
-
*/
|
|
189
|
-
wait_for_completion(task_id: string): Promise<SubagentResult | undefined>;
|
|
190
186
|
/** Number of currently running subagents. */
|
|
191
187
|
running_count(): number;
|
|
192
188
|
/** Number of tasks waiting in the queue. */
|
|
@@ -245,6 +241,17 @@ export declare class SubagentPool extends EventEmitter {
|
|
|
245
241
|
private pull;
|
|
246
242
|
/** Build CLI arguments for a task. */
|
|
247
243
|
private buildArgs;
|
|
244
|
+
/**
|
|
245
|
+
* Environment for a spawned child.
|
|
246
|
+
*
|
|
247
|
+
* Stamps the child's depth (parent depth + 1) so its own guard knows where it
|
|
248
|
+
* sits in the tree; the tree-wide cap (HOOCODE_SUBAGENT_MAX_DEPTH) is inherited
|
|
249
|
+
* via the spread, so at the default cap of 1 the child lands at depth 1 and
|
|
250
|
+
* cannot spawn further subagents. Also flags the child to skip MCP server
|
|
251
|
+
* connection when its tool allowlist is explicit and MCP-free — connecting
|
|
252
|
+
* external servers it can never call is pure boot latency.
|
|
253
|
+
*/
|
|
254
|
+
private childSpawnEnv;
|
|
248
255
|
/** Start a task in a child process, with one retry on failure. */
|
|
249
256
|
private startTask;
|
|
250
257
|
/** Whether a failed built-in subagent should be retried with `model: inherit`. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"subagent-pool.d.ts","sourceRoot":"","sources":["../../src/core/subagent-pool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC3C,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAY3C,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AAWtD,MAAM,WAAW,gBAAgB;IAChC,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,YAAY,CAAC,EAAE,MAAM,CAA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H,OAAO,CAAC,kBAAkB;IAQ1B,+EAA+E;IAC/E,OAAO,IAAI,IAAI,CAyBd;IAED,2DAA2D;IAC3D,OAAO,CAAC,IAAI;IAOZ,sCAAsC;IACtC,OAAO,CAAC,SAAS;IAgGjB,kEAAkE;IAClE,OAAO,CAAC,SAAS;IAoRjB,kFAAkF;IAClF,OAAO,CAAC,6BAA6B;IAiBrC,oFAAoF;IACpF,OAAO,CAAC,6BAA6B;IAQrC,yEAAyE;IACzE,OAAO,CAAC,qBAAqB;IAa7B;;;;OAIG;IACH,OAAO,CAAC,mBAAmB;IAiB3B,OAAO,CAAC,iBAAiB;IAWzB,OAAO,CAAC,aAAa;CAgBrB","sourcesContent":["import { spawn } from \"node:child_process\";\nimport { EventEmitter } from \"node:events\";\nimport { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { getDispatchTaskDir } from \"../config.js\";\nimport { attachJsonlLineReader } from \"../modes/rpc/jsonl.js\";\nimport { waitForChildProcess } from \"../utils/child-process.js\";\nimport { MODEL_INHERIT } from \"./agent-frontmatter.js\";\nimport { type AgentRegistry, loadAgentRegistry } from \"./agent-registry.js\";\nimport { DispatchEvaluator } from \"./dispatch-evaluator.js\";\nimport { SubagentLifeguard } from \"./lifeguard.js\";\nimport { resolveModelReference } from \"./model-categories.js\";\nimport { OutputVerifier } from \"./output-verifier.js\";\nimport type { Settings } from \"./settings-manager.js\";\nimport { currentSubagentDepth, resolveMaxSubagentDepth, SUBAGENT_DEPTH_ENV } from \"./subagent-depth.js\";\nimport { TokenBudget } from \"./token-budget.js\";\n\n/**\n * Provider/model failure signatures where inheriting the parent model can\n * recover. Compiled once at module load instead of on every error check.\n */\nconst INHERITED_MODEL_FALLBACK_ERROR =\n\t/usage[_\\s-]?limit|subscription|quota|rate.?limit|too many requests|429|insufficient|out of credit|credit balance|billing|payment required|402|model[^\\n]*(not found|unavailable|not available|not supported|does not exist|invalid|unsupported)|no api key|no auth configured|authentication|unauthorized|forbidden|permission/i;\n\nexport interface SubagentPoolTask {\n\ttask_id: string;\n\tagent_type: string;\n\ttask: string;\n\tcontext?: string;\n\ttoken_budget?: number;\n\tcwd?: string;\n\tmodel?: string;\n\tprovider?: string;\n\t/**\n\t * Explicit session file for the child to persist/continue. When omitted the\n\t * child uses its own dispatch dir (`<dispatch>/<task_id>/session.jsonl`).\n\t * Resume reuses the original task's session file to continue the transcript.\n\t */\n\tsessionFile?: string;\n\t/** Internal: retry using the caller's model when a built-in agent's preferred model fails. */\n\tuseInheritedModelFallback?: boolean;\n}\n\nexport interface SubagentSlot {\n\tpid: number;\n\tagent_type: string;\n\ttask_id: string;\n\tspawned_at: number;\n\ttoken_budget: number;\n\tprocess: ReturnType<typeof spawn>;\n}\n\nexport interface SubagentResult {\n\ttask_id: string;\n\tok: boolean;\n\tstdout: string;\n\tstderr: string;\n\texit_code: number | null;\n\terror?: string;\n\t/** True when the task exceeded its token budget and was hard-stopped. */\n\tbudget_exceeded?: boolean;\n\t/** Terminal status derived from how the task finished. */\n\tstatus?: \"complete\" | \"partial\" | \"failed\" | \"stalled\" | \"timeout\";\n\t/** Parsed result.json content when available (e.g. on partial completion). */\n\tresult_data?: Record<string, unknown>;\n\t/** True when this run used the inherited-model fallback (preferred model failed first). */\n\tusedInheritedModelFallback?: boolean;\n}\n\nexport interface TaskResult {\n\t/** True when the evaluator decided the task is simple enough for inline handling. */\n\thandled_inline: boolean;\n\t/** Present when the task was delegated. */\n\ttask_id?: string;\n\tagent_type?: string;\n\treason?: string;\n\t/** Subagent result when delegated. */\n\tresult?: SubagentResult;\n\t/** Duration in milliseconds when delegated. */\n\tduration?: number;\n}\n\nexport interface DispatchOptions {\n\t/** Skip evaluation and force this agent type (user/explicit override).\n\t * Accepts any registry-defined agent name, not just the built-in modes. */\n\tforceAgent?: string;\n\t/** Context distilled from the calling agent, passed to the subagent. */\n\tcontext?: string;\n\t/** Model id for the subagent (defaults to the child's configured default). */\n\tmodel?: string;\n\t/** Provider for the subagent. */\n\tprovider?: string;\n\t/** Explicit session file to persist/continue (used by resume). */\n\tsessionFile?: string;\n}\n\nexport interface SubagentPoolOptions {\n\t/** Path to the hoocode executable (or the runtime, e.g. node, when prefixArgs is set). */\n\texecutable: string;\n\t/** Args inserted before task args (e.g. the CLI entry script for node/tsx). */\n\tprefixArgs?: string[];\n\t/** Maximum concurrent child processes. Defaults to 5. */\n\tmaxConcurrency?: number;\n\t/** Working directory for spawned processes. Defaults to process.cwd(). */\n\tcwd?: string;\n\t/** Environment variables. Defaults to process.env. */\n\tenv?: NodeJS.ProcessEnv;\n\t/** Default token budget per task. Defaults to 0. */\n\tdefaultTokenBudget?: number;\n\t/**\n\t * Non-default skill paths to forward to every spawned subagent via --skill.\n\t * Subagents auto-discover skills from standard locations; only paths that\n\t * won't be found by default discovery need to be forwarded here.\n\t */\n\tskillPaths?: string[];\n\t/** Settings for model category resolution. */\n\tsettings?: Settings;\n}\n\n/**\n * Default hard cap on assistant turns for a spawned subagent when its definition\n * does not set `maxTurns`. The token budget is advisory (it warns but never\n * kills), so this turn cap is the guaranteed hard stop for every subagent.\n */\nexport const DEFAULT_SUBAGENT_MAX_TURNS = 50;\n\n/**\n * AgentSession event `type`s forwarded from a subagent's json event stream as\n * `task_progress` events. Deliberately coarse: the child also emits per-delta\n * `message_update` / `tool_execution_update` events (a high-volume firehose) and\n * large `message_*` bodies, which are dropped here to keep the parent's event loop\n * and the task panel from thrashing under concurrent subagents.\n */\nexport const FORWARDED_SUBAGENT_EVENTS: ReadonlySet<string> = new Set([\n\t\"turn_end\",\n\t\"tool_execution_start\",\n\t\"tool_execution_end\",\n]);\n\n/** The action the pool should take for one JSONL line from a subagent's stdout. */\nexport type SubagentStdoutLine =\n\t| { kind: \"heartbeat\" }\n\t| { kind: \"progress\"; event: Record<string, unknown> }\n\t| { kind: \"ignore\" };\n\n/**\n * Classify one JSONL line from a subagent's stdout into the action to take.\n * Pure (no side effects) so the ping/forward/drop policy is unit-testable without\n * spawning a child. Line framing — UTF-8-safe reassembly of chunks split mid-line\n * — is handled upstream by attachJsonlLineReader; this only sees complete lines.\n */\nexport function classifySubagentLine(line: string): SubagentStdoutLine {\n\tconst trimmed = line.trim();\n\tif (!trimmed.startsWith(\"{\")) return { kind: \"ignore\" };\n\tlet parsed: Record<string, unknown>;\n\ttry {\n\t\tparsed = JSON.parse(trimmed) as Record<string, unknown>;\n\t} catch {\n\t\treturn { kind: \"ignore\" };\n\t}\n\tif (parsed.ping === true) return { kind: \"heartbeat\" };\n\tif (typeof parsed.type === \"string\" && FORWARDED_SUBAGENT_EVENTS.has(parsed.type)) {\n\t\treturn { kind: \"progress\", event: parsed };\n\t}\n\treturn { kind: \"ignore\" };\n}\n\n/**\n * Pool for running hoocode subagents as child processes with bounded concurrency,\n * FIFO queuing with priority support, and automatic slot refill.\n *\n * Events:\n * - \"task_done\" – task completed successfully and output was verified\n * - \"task_failed\" – task failed (spawn error, bad exit code, verification failure)\n * - \"task_stalled\" – heartbeat missed past the load-scaled threshold (60s base,\n * widened under concurrency/event-loop lag), process SIGKILLed\n * - \"task_timeout\" – hard timeout exceeded, process was SIGKILLed\n * - \"budget_warning\" – token usage crossed 80% threshold (advisory)\n * - \"budget_exceeded\" – token usage crossed 100% threshold (advisory; never kills)\n * - \"task_progress\" – coarse lifecycle event (turn_end, tool start/end) parsed\n * from the child's json event stream, for live UI updates\n */\nexport class SubagentPool extends EventEmitter {\n\tprivate readonly maxConcurrency: number;\n\tprivate readonly executable: string;\n\tprivate readonly prefixArgs: string[];\n\tprivate readonly cwd: string;\n\tprivate readonly env: NodeJS.ProcessEnv;\n\tprivate readonly defaultTokenBudget: number;\n\t/** Non-default skill paths forwarded to every spawned subagent via --skill. */\n\tprivate skillPaths: string[];\n\n\tprivate slots = new Map<string, SubagentSlot>();\n\tprivate queue: SubagentPoolTask[] = [];\n\tprivate completed = new Map<string, SubagentResult>();\n\tprivate waiters = new Map<string, { resolve: (result: SubagentResult) => void; reject: (err: Error) => void }>();\n\tprivate budgets = new Map<string, TokenBudget>();\n\tprivate verifier = new OutputVerifier();\n\tprivate lifeguard: SubagentLifeguard;\n\tprivate disposed = false;\n\t/** Lazily-loaded agent registry (frontmatter definitions) for this pool's cwd. */\n\tprivate registry?: AgentRegistry;\n\t/** Tracks why a task was killed (stalled / timeout) before exit handler fires. */\n\tprivate killReasons = new Map<string, \"stalled\" | \"timeout\">();\n\t/** Persistent terminal status map, survives wait_for consumption. */\n\tprivate taskStatus = new Map<string, \"done\" | \"failed\" | \"stalled\" | \"timeout\">();\n\t/** Settings for model category resolution. */\n\tprivate readonly settings?: Settings;\n\n\tconstructor(options: SubagentPoolOptions) {\n\t\tsuper();\n\t\tthis.maxConcurrency = options.maxConcurrency ?? 5;\n\t\tthis.executable = options.executable;\n\t\tthis.prefixArgs = options.prefixArgs ?? [];\n\t\tthis.cwd = options.cwd ?? process.cwd();\n\t\tthis.env = options.env ?? process.env;\n\t\tthis.defaultTokenBudget = options.defaultTokenBudget ?? 0;\n\t\tthis.skillPaths = options.skillPaths ? [...options.skillPaths] : [];\n\t\tthis.settings = options.settings;\n\t\tthis.verifier = new OutputVerifier(this.cwd);\n\t\tthis.lifeguard = new SubagentLifeguard(this.cwd);\n\t\tthis.lifeguard.on(\"stalled\", (data: { task_id: string; pid: number }) => {\n\t\t\tthis.killReasons.set(data.task_id, \"stalled\");\n\t\t\tthis.emit(\"task_stalled\", data);\n\t\t});\n\t\tthis.lifeguard.on(\"timeout\", (data: { task_id: string; pid: number }) => {\n\t\t\tthis.killReasons.set(data.task_id, \"timeout\");\n\t\t\tthis.emit(\"task_timeout\", data);\n\t\t});\n\t}\n\n\t/** Update the non-default skill paths forwarded to new subagents. */\n\tupdateSkillPaths(paths: string[]): void {\n\t\tthis.skillPaths = [...paths];\n\t}\n\n\t/**\n\t * Report external in-process load (e.g. the number of background MCP tools\n\t * currently executing in the parent) to the lifeguard. This widens its\n\t * heartbeat/timeout tolerance so monitored subagents aren't false-positive\n\t * reaped when the parent's event loop is busy with concurrent background work.\n\t */\n\tsetExternalLoad(count: number): void {\n\t\tthis.lifeguard.setExternalLoad(count);\n\t}\n\n\t/** Lazily load the agent registry for this pool's cwd. */\n\tprivate getRegistry(): AgentRegistry {\n\t\tif (!this.registry) {\n\t\t\tthis.registry = loadAgentRegistry({ cwd: this.cwd });\n\t\t}\n\t\treturn this.registry;\n\t}\n\n\t/** Priority value: higher numbers run first. */\n\tprivate priorityOf(agent_type: string): number {\n\t\t// Read-only investigation (explore/plan) often unblocks downstream work, so\n\t\t// it runs ahead of other agents.\n\t\treturn agent_type === \"explore\" || agent_type === \"plan\" ? 2 : 1;\n\t}\n\n\t/** Queue a task. It will run when a slot is free. */\n\tspawn(task: SubagentPoolTask): void {\n\t\tif (this.disposed) {\n\t\t\tthrow new Error(\"SubagentPool has been disposed\");\n\t\t}\n\t\tif (\n\t\t\tthis.slots.has(task.task_id) ||\n\t\t\tthis.queue.some((t) => t.task_id === task.task_id) ||\n\t\t\tthis.completed.has(task.task_id)\n\t\t) {\n\t\t\tthrow new Error(`Duplicate task_id: ${task.task_id}`);\n\t\t}\n\n\t\tconst p = this.priorityOf(task.agent_type);\n\t\tconst idx = this.queue.findIndex((t) => this.priorityOf(t.agent_type) < p);\n\t\tif (idx === -1) {\n\t\t\tthis.queue.push(task);\n\t\t} else {\n\t\t\tthis.queue.splice(idx, 0, task);\n\t\t}\n\t\tthis.pull();\n\t}\n\n\t/** Current status of a task. */\n\tget_status(task_id: string): \"running\" | \"queued\" | \"done\" | \"failed\" | \"stalled\" | \"timeout\" | \"unknown\" {\n\t\tif (this.slots.has(task_id)) return \"running\";\n\t\tif (this.queue.some((t) => t.task_id === task_id)) return \"queued\";\n\t\tconst persisted = this.taskStatus.get(task_id);\n\t\tif (persisted) return persisted;\n\t\tconst result = this.completed.get(task_id);\n\t\tif (result) {\n\t\t\tif (result.status === \"stalled\") return \"stalled\";\n\t\t\tif (result.status === \"timeout\") return \"timeout\";\n\t\t\tif (result.ok) return \"done\";\n\t\t\treturn \"failed\";\n\t\t}\n\t\treturn \"unknown\";\n\t}\n\n\t/** Wait for a task to complete and return its result. */\n\twait_for(task_id: string): Promise<SubagentResult> {\n\t\tif (this.disposed) {\n\t\t\treturn Promise.reject(new Error(\"SubagentPool has been disposed\"));\n\t\t}\n\n\t\tconst existing = this.completed.get(task_id);\n\t\tif (existing) {\n\t\t\tthis.completed.delete(task_id);\n\t\t\treturn Promise.resolve(existing);\n\t\t}\n\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tthis.waiters.set(task_id, { resolve, reject });\n\t\t});\n\t}\n\n\t/**\n\t * Wait for a task to finish without consuming its result. Returns the result\n\t * once the task reaches a terminal state, or undefined if the task is not\n\t * found. Unlike wait_for(), the result remains in the completed map so\n\t * collect() can still read it afterward.\n\t */\n\twait_for_completion(task_id: string): Promise<SubagentResult | undefined> {\n\t\tif (this.disposed) {\n\t\t\treturn Promise.reject(new Error(\"SubagentPool has been disposed\"));\n\t\t}\n\n\t\tconst existing = this.completed.get(task_id);\n\t\tif (existing) return Promise.resolve(existing);\n\n\t\tconst persisted = this.taskStatus.get(task_id);\n\t\tif (persisted) {\n\t\t\tconst result = this.completed.get(task_id);\n\t\t\treturn Promise.resolve(result);\n\t\t}\n\n\t\treturn new Promise<SubagentResult | undefined>((resolve) => {\n\t\t\tconst onDone = (data: { task_id: string }) => {\n\t\t\t\tif (data.task_id !== task_id) return;\n\t\t\t\tcleanup();\n\t\t\t\tresolve(this.completed.get(task_id));\n\t\t\t};\n\t\t\tconst onFailed = (data: { task_id: string }) => {\n\t\t\t\tif (data.task_id !== task_id) return;\n\t\t\t\tcleanup();\n\t\t\t\tresolve(this.completed.get(task_id));\n\t\t\t};\n\t\t\tconst onStalled = (data: { task_id: string }) => {\n\t\t\t\tif (data.task_id !== task_id) return;\n\t\t\t\tcleanup();\n\t\t\t\tresolve(this.completed.get(task_id));\n\t\t\t};\n\t\t\tconst onTimeout = (data: { task_id: string }) => {\n\t\t\t\tif (data.task_id !== task_id) return;\n\t\t\t\tcleanup();\n\t\t\t\tresolve(this.completed.get(task_id));\n\t\t\t};\n\t\t\tconst cleanup = () => {\n\t\t\t\tthis.off(\"task_done\", onDone);\n\t\t\t\tthis.off(\"task_failed\", onFailed);\n\t\t\t\tthis.off(\"task_stalled\", onStalled);\n\t\t\t\tthis.off(\"task_timeout\", onTimeout);\n\t\t\t};\n\t\t\tthis.on(\"task_done\", onDone);\n\t\t\tthis.on(\"task_failed\", onFailed);\n\t\t\tthis.on(\"task_stalled\", onStalled);\n\t\t\tthis.on(\"task_timeout\", onTimeout);\n\t\t});\n\t}\n\n\t/** Number of currently running subagents. */\n\trunning_count(): number {\n\t\treturn this.slots.size;\n\t}\n\n\t/** Number of tasks waiting in the queue. */\n\tqueued_count(): number {\n\t\treturn this.queue.length;\n\t}\n\n\t/**\n\t * Dispatch a task through the evaluator.\n\t *\n\t * - If `options.forceAgent` is provided, skip evaluation and spawn directly.\n\t * - Otherwise evaluate the task. If it should be handled inline, return\n\t * `{ handled_inline: true }` immediately.\n\t * - If delegating, spawn the subagent, wait for completion, write\n\t * `output.json`, and return the result.\n\t */\n\tasync dispatch(task: string, options: DispatchOptions = {}): Promise<TaskResult> {\n\t\tif (this.disposed) {\n\t\t\treturn Promise.reject(new Error(\"SubagentPool has been disposed\"));\n\t\t}\n\t\tconst begin = this.beginDispatch(task, options);\n\t\tif (begin.handled_inline) {\n\t\t\treturn { handled_inline: true, reason: begin.reason };\n\t\t}\n\t\tconst result = await this.wait_for(begin.task_id);\n\t\treturn {\n\t\t\thandled_inline: false,\n\t\t\ttask_id: begin.task_id,\n\t\t\tagent_type: begin.agent_type,\n\t\t\treason: begin.reason,\n\t\t\tresult,\n\t\t\tduration: Date.now() - begin.startTime,\n\t\t};\n\t}\n\n\t/**\n\t * Fire-and-forget dispatch for background agents. Spawns the subagent and\n\t * returns its handle immediately; the caller polls get_status()/collect().\n\t */\n\tdispatchDetached(\n\t\ttask: string,\n\t\toptions: DispatchOptions = {},\n\t): { handled_inline: boolean; task_id?: string; agent_type?: string; reason?: string } {\n\t\tif (this.disposed) {\n\t\t\tthrow new Error(\"SubagentPool has been disposed\");\n\t\t}\n\t\tconst begin = this.beginDispatch(task, options);\n\t\tif (begin.handled_inline) {\n\t\t\treturn { handled_inline: true, reason: begin.reason };\n\t\t}\n\t\treturn { handled_inline: false, task_id: begin.task_id, agent_type: begin.agent_type, reason: begin.reason };\n\t}\n\n\t/**\n\t * Evaluate, log, and spawn a task without waiting. Shared by dispatch()\n\t * (blocking) and dispatchDetached() (background).\n\t */\n\tprivate beginDispatch(\n\t\ttask: string,\n\t\toptions: DispatchOptions,\n\t):\n\t\t| { handled_inline: true; reason?: string }\n\t\t| { handled_inline: false; task_id: string; agent_type: string; reason?: string; startTime: number } {\n\t\tconst { forceAgent, context, model, provider, sessionFile } = options;\n\t\tconst evaluator = new DispatchEvaluator();\n\t\tconst analysis = evaluator.evaluate(task);\n\n\t\tif (!forceAgent && !analysis.should_delegate) {\n\t\t\treturn { handled_inline: true, reason: analysis.reason };\n\t\t}\n\n\t\tconst agent_type = forceAgent ?? \"general-purpose\";\n\t\tconst task_id = `dispatch-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;\n\t\tconst reason = forceAgent ? \"user_override\" : analysis.reason;\n\t\tconst complexity = analysis.estimated_complexity;\n\t\t// Depth of the child about to be spawned (this process's depth + 1). Surfaced\n\t\t// so a delegation tree's nesting is visible in logs without extra tooling.\n\t\tconst childDepth = currentSubagentDepth(this.env) + 1;\n\n\t\t// Pre-dispatch logging. Use stderr: stdout is reserved for the JSON event\n\t\t// stream / TUI render and must not be polluted.\n\t\tconsole.error(\n\t\t\t`[DISPATCH] agent=${agent_type} depth=${childDepth} reason=${reason} complexity=${complexity} task_id=${task_id}`,\n\t\t);\n\t\tthis.writeDispatchLog(task_id, agent_type, reason, complexity, task, childDepth);\n\n\t\tconst poolTask: SubagentPoolTask = {\n\t\t\ttask_id,\n\t\t\tagent_type,\n\t\t\ttask,\n\t\t\tcontext,\n\t\t\tmodel,\n\t\t\tprovider,\n\t\t\tsessionFile,\n\t\t\tcwd: this.cwd,\n\t\t};\n\t\tconst startTime = Date.now();\n\t\tthis.spawn(poolTask);\n\t\treturn { handled_inline: false, task_id, agent_type, reason, startTime };\n\t}\n\n\t/**\n\t * Non-destructively read a completed task's result (for background polling).\n\t * Returns undefined while the task is still running/queued, or if its result\n\t * was already consumed via wait_for().\n\t */\n\tcollect(task_id: string): SubagentResult | undefined {\n\t\treturn this.completed.get(task_id);\n\t}\n\n\t/** Absolute path of the persisted session file for a task. */\n\tgetSessionFile(task_id: string, cwd: string = this.cwd): string {\n\t\treturn join(getDispatchTaskDir(cwd, task_id), \"session.jsonl\");\n\t}\n\n\t/**\n\t * Resume a previously dispatched subagent, continuing its persisted session\n\t * with a follow-up prompt. Recovers the original agent type from its dispatch\n\t * log. Rejects if no resumable session exists for the task.\n\t */\n\tasync resume(\n\t\ttask_id: string,\n\t\tprompt: string,\n\t\toptions: Omit<DispatchOptions, \"forceAgent\" | \"sessionFile\"> = {},\n\t): Promise<TaskResult> {\n\t\tif (this.disposed) {\n\t\t\treturn Promise.reject(new Error(\"SubagentPool has been disposed\"));\n\t\t}\n\t\tconst sessionFile = this.getSessionFile(task_id);\n\t\tif (!existsSync(sessionFile)) {\n\t\t\treturn Promise.reject(new Error(`No resumable session for task \"${task_id}\" (expected ${sessionFile}).`));\n\t\t}\n\t\tconst agent_type = this.readDispatchAgentType(task_id) ?? \"general-purpose\";\n\t\treturn this.dispatch(prompt, { ...options, forceAgent: agent_type, sessionFile });\n\t}\n\n\t/** Recover the agent type a task was dispatched with, from its dispatch log. */\n\tprivate readDispatchAgentType(task_id: string): string | undefined {\n\t\tconst path = join(getDispatchTaskDir(this.cwd, task_id), \"dispatch-log.json\");\n\t\tif (!existsSync(path)) return undefined;\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(readFileSync(path, \"utf-8\")) as { agent_type?: string };\n\t\t\treturn typeof parsed.agent_type === \"string\" ? parsed.agent_type : undefined;\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\tprivate writeDispatchLog(\n\t\ttask_id: string,\n\t\tagent_type: string,\n\t\treason: string,\n\t\tcomplexity: string,\n\t\ttask: string,\n\t\tdepth: number,\n\t): void {\n\t\tconst log = {\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\ttask_id,\n\t\t\tagent_type,\n\t\t\tdepth,\n\t\t\treason,\n\t\t\tcomplexity,\n\t\t\ttask,\n\t\t};\n\t\tconst path = join(getDispatchTaskDir(this.cwd, task_id), \"dispatch-log.json\");\n\t\ttry {\n\t\t\tmkdirSync(dirname(path), { recursive: true });\n\t\t\twriteFileSync(path, JSON.stringify(log, null, 2));\n\t\t} catch {\n\t\t\t// Best-effort persistence\n\t\t}\n\t}\n\n\tprivate writeOutputJson(task_id: string, result: SubagentResult): void {\n\t\tconst output = {\n\t\t\ttask_id: result.task_id,\n\t\t\tok: result.ok,\n\t\t\texit_code: result.exit_code,\n\t\t\tstatus: result.status,\n\t\t\tstdout: result.stdout,\n\t\t\tstderr: result.stderr,\n\t\t\terror: result.error,\n\t\t\tbudget_exceeded: result.budget_exceeded,\n\t\t\tresult_data: result.result_data,\n\t\t};\n\t\tconst path = join(getDispatchTaskDir(this.cwd, task_id), \"output.json\");\n\t\ttry {\n\t\t\tmkdirSync(dirname(path), { recursive: true });\n\t\t\twriteFileSync(path, JSON.stringify(output, null, 2));\n\t\t} catch {\n\t\t\t// Best-effort persistence\n\t\t}\n\t}\n\n\t/**\n\t * Remove a task's dispatch dir after a clean, verified success. Best-effort:\n\t * a cleanup failure must never fail an otherwise successful task.\n\t */\n\tprivate cleanupDispatchDir(task_id: string, cwd: string): void {\n\t\ttry {\n\t\t\trmSync(getDispatchTaskDir(cwd, task_id), { recursive: true, force: true });\n\t\t} catch {\n\t\t\t// Best-effort cleanup\n\t\t}\n\t}\n\n\t/** Kill all running processes, clear the queue, and reject pending waiters. */\n\tdispose(): void {\n\t\tif (this.disposed) return;\n\t\tthis.disposed = true;\n\n\t\tfor (const slot of this.slots.values()) {\n\t\t\tif (!slot.process.killed) {\n\t\t\t\tslot.process.kill(\"SIGTERM\");\n\t\t\t}\n\t\t}\n\t\tthis.slots.clear();\n\t\tthis.queue = [];\n\n\t\tfor (const [task_id, waiter] of this.waiters) {\n\t\t\twaiter.reject(new Error(\"SubagentPool disposed\"));\n\t\t\tthis.waiters.delete(task_id);\n\t\t}\n\t\tthis.completed.clear();\n\t\tfor (const budget of this.budgets.values()) {\n\t\t\tbudget.removeAllListeners();\n\t\t}\n\t\tthis.budgets.clear();\n\t\tthis.killReasons.clear();\n\t\tthis.taskStatus.clear();\n\t\tthis.lifeguard.dispose();\n\t\tthis.removeAllListeners();\n\t}\n\n\t/** Pull tasks from the queue while slots are available. */\n\tprivate pull(): void {\n\t\twhile (this.slots.size < this.maxConcurrency && this.queue.length > 0) {\n\t\t\tconst task = this.queue.shift()!;\n\t\t\tthis.startTask(task, false);\n\t\t}\n\t}\n\n\t/** Build CLI arguments for a task. */\n\tprivate buildArgs(task: SubagentPoolTask): string[] {\n\t\t// Persist the child's session so a finished/interrupted subagent can be\n\t\t// resumed later (see resume()). SessionManager.open() creates the file on\n\t\t// first run and continues it on subsequent runs.\n\t\tconst sessionFile = task.sessionFile ?? this.getSessionFile(task.task_id, task.cwd ?? this.cwd);\n\t\tconst args: string[] = [\n\t\t\t...this.prefixArgs,\n\t\t\t\"--mode\",\n\t\t\t\"json\",\n\t\t\t\"--session\",\n\t\t\tsessionFile,\n\t\t\t\"--task-id\",\n\t\t\ttask.task_id,\n\t\t];\n\n\t\t// Prefer the data-driven agent definition from the registry; fall back to the\n\t\t// built-in mode prompt/allowlist for legacy modes not present in the registry.\n\t\tconst def = task.agent_type ? this.getRegistry().get(task.agent_type) : undefined;\n\n\t\tif (task.agent_type) {\n\t\t\tconst systemPrompt = def?.prompt;\n\t\t\tif (systemPrompt) {\n\t\t\t\targs.push(\"--system-prompt\", systemPrompt);\n\t\t\t}\n\n\t\t\t// A `delegate: true` agent may itself dispatch via the ExecuteTask tool, but only\n\t\t\t// while the child it becomes can still nest (childDepth < cap) — so the\n\t\t\t// deepest permitted level cannot delegate further. Gating here keeps the\n\t\t\t// authorization explicit and bounded by the same cap as the depth guard.\n\t\t\tconst childDepth = currentSubagentDepth(this.env) + 1;\n\t\t\tconst canChildDelegate = def?.delegate === true && childDepth < resolveMaxSubagentDepth(undefined, this.env);\n\n\t\t\t// Tool allowlist comes from the agent definition's frontmatter `tools`\n\t\t\t// field (read-only built-ins declare their own sandbox). When omitted, no\n\t\t\t// --tools is passed and the subagent inherits all parent tools (so the Task\n\t\t\t// tool already survives). A delegating agent with an explicit allowlist must\n\t\t\t// have Task/TaskOutput added, or the child would filter them out.\n\t\t\tconst tools = def?.tools ? [...def.tools] : undefined;\n\t\t\tif (canChildDelegate && tools) {\n\t\t\t\tfor (const t of [\"ExecuteTask\", \"TaskOutput\"]) {\n\t\t\t\t\tif (!tools.includes(t)) tools.push(t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (tools && tools.length > 0) {\n\t\t\t\targs.push(\"--tools\", tools.join(\",\"));\n\t\t\t}\n\t\t\tif (def?.disallowedTools && def.disallowedTools.length > 0) {\n\t\t\t\targs.push(\"--disallowed-tools\", def.disallowedTools.join(\",\"));\n\t\t\t}\n\n\t\t\t// Propagate subagent enablement so the child registers the ExecuteTask tool; without\n\t\t\t// this the flag-based enablement would not reach a spawned child.\n\t\t\tif (canChildDelegate) {\n\t\t\t\targs.push(\"--enable-subagents\");\n\t\t\t\t// Scoped delegation: restrict which agent types this child may spawn.\n\t\t\t\tif (def?.delegateTo && def.delegateTo.length > 0) {\n\t\t\t\t\targs.push(\"--delegate-allow\", def.delegateTo.join(\",\"));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Model precedence: a definition's explicit model wins (unless it is the\n\t\t// `inherit` sentinel), otherwise use the caller-provided model. Built-in\n\t\t// agents can retry with the inherited model when their preferred model is\n\t\t// unavailable or quota-limited.\n\t\tconst explicitModel =\n\t\t\t!task.useInheritedModelFallback && def?.model && def.model !== MODEL_INHERIT ? def.model : undefined;\n\t\t// Resolve model categories (fast, standard, capable) to actual model IDs\n\t\tconst rawModel = explicitModel ?? task.model;\n\t\tconst modelToUse = rawModel ? resolveModelReference(rawModel, this.settings) : undefined;\n\t\tif (modelToUse) {\n\t\t\targs.push(\"--model\", modelToUse);\n\t\t}\n\t\tif (task.provider) {\n\t\t\targs.push(\"--provider\", task.provider);\n\t\t}\n\n\t\t// Always give subagents a hard turn cap. With the token budget now advisory\n\t\t// (warn-only), this is the guaranteed hard stop for a runaway subagent.\n\t\tconst maxTurns = def?.maxTurns && def.maxTurns > 0 ? def.maxTurns : DEFAULT_SUBAGENT_MAX_TURNS;\n\t\targs.push(\"--max-turns\", String(maxTurns));\n\n\t\t// Forward non-default skill paths so the subagent has access to all parent skills.\n\t\t// Standard discovery locations (~/.hoocode/, .hoocode/, .claude/) are found automatically.\n\t\tfor (const skillPath of this.skillPaths) {\n\t\t\targs.push(\"--skill\", skillPath);\n\t\t}\n\n\t\tconst prompt = task.context?.trim()\n\t\t\t? `Context from the calling agent:\\n\\n${task.context.trim()}\\n\\nTask: ${task.task.trim()}`\n\t\t\t: `Task: ${task.task.trim()}`;\n\t\targs.push(prompt);\n\n\t\treturn args;\n\t}\n\n\t/** Start a task in a child process, with one retry on failure. */\n\tprivate startTask(task: SubagentPoolTask, isRetry: boolean): void {\n\t\t// Get or create a TokenBudget tracker. On retry, reuse the existing one\n\t\t// so cumulative usage persists across retries.\n\t\tlet budget = this.budgets.get(task.task_id);\n\t\tif (!budget) {\n\t\t\tbudget = new TokenBudget(task.task_id, task.agent_type, {\n\t\t\t\tlimit: task.token_budget,\n\t\t\t\tcwd: task.cwd ?? this.cwd,\n\t\t\t});\n\t\t\tbudget.on(\"budget_warning\", (data: { task_id: string; message: string; used: number; limit: number }) => {\n\t\t\t\tthis.emit(\"budget_warning\", data);\n\t\t\t});\n\t\t\t// The token budget is advisory: surface telemetry but never kill. The\n\t\t\t// guaranteed hard stop is the per-subagent turn cap (--max-turns); see\n\t\t\t// DEFAULT_SUBAGENT_MAX_TURNS.\n\t\t\tbudget.on(\"budget_exceeded\", (data: { task_id: string; used: number; limit: number }) => {\n\t\t\t\tthis.emit(\"budget_exceeded\", data);\n\t\t\t});\n\t\t\tthis.budgets.set(task.task_id, budget);\n\t\t}\n\n\t\tlet proc: ReturnType<typeof spawn>;\n\t\ttry {\n\t\t\tproc = spawn(this.executable, this.buildArgs(task), {\n\t\t\t\tcwd: task.cwd ?? this.cwd,\n\t\t\t\t// Stamp the child's depth (parent depth + 1) so its own guard knows where\n\t\t\t\t// it sits in the tree. The tree-wide cap (HOOCODE_SUBAGENT_MAX_DEPTH) is\n\t\t\t\t// inherited via the spread; at the default cap of 1 the child lands at\n\t\t\t\t// depth 1 and cannot spawn further subagents.\n\t\t\t\tenv: {\n\t\t\t\t\t...this.env,\n\t\t\t\t\t[SUBAGENT_DEPTH_ENV]: String(currentSubagentDepth(this.env) + 1),\n\t\t\t\t},\n\t\t\t\tshell: false,\n\t\t\t\tstdio: [\"ignore\", \"pipe\", \"pipe\"],\n\t\t\t});\n\t\t} catch {\n\t\t\tif (!isRetry) {\n\t\t\t\tthis.startTask(task, true);\n\t\t\t} else {\n\t\t\t\tthis.emit(\"task_failed\", {\n\t\t\t\t\ttask_id: task.task_id,\n\t\t\t\t\terror: \"Spawn failed synchronously\",\n\t\t\t\t});\n\t\t\t\tthis.resolveWaiter(task.task_id, {\n\t\t\t\t\ttask_id: task.task_id,\n\t\t\t\t\tok: false,\n\t\t\t\t\tstdout: \"\",\n\t\t\t\t\tstderr: \"\",\n\t\t\t\t\texit_code: null,\n\t\t\t\t\terror: \"Spawn failed synchronously\",\n\t\t\t\t\tstatus: \"failed\",\n\t\t\t\t});\n\t\t\t\tthis.pull();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tconst slot: SubagentSlot = {\n\t\t\tpid: proc.pid ?? 0,\n\t\t\tagent_type: task.agent_type,\n\t\t\ttask_id: task.task_id,\n\t\t\tspawned_at: Date.now(),\n\t\t\ttoken_budget: task.token_budget ?? this.defaultTokenBudget,\n\t\t\tprocess: proc,\n\t\t};\n\n\t\tthis.slots.set(task.task_id, slot);\n\t\tthis.lifeguard.monitor(task.task_id, task.agent_type, proc);\n\n\t\tlet stdout = \"\";\n\t\tlet stderr = \"\";\n\t\tlet detachStdoutReader: (() => void) | undefined;\n\n\t\tproc.stdout?.on(\"data\", (data: Buffer) => {\n\t\t\tconst chunk = data.toString();\n\t\t\tstdout += chunk;\n\t\t\tbudget.processStdout(chunk);\n\n\t\t\t// Any output proves the child is alive and working, so treat it as a\n\t\t\t// heartbeat. The dedicated {\"ping\":true} line (parsed below via the JSONL\n\t\t\t// reader) still matters for quiet phases (e.g. a long single model turn\n\t\t\t// that emits nothing), but relying on it alone falsely reaps subagents\n\t\t\t// that are busily streaming events while the parent's event loop is\n\t\t\t// starved by concurrent load.\n\t\t\tthis.lifeguard.recordHeartbeat(task.task_id);\n\t\t});\n\n\t\t// Parse the child's newline-delimited JSON event stream with UTF-8-safe,\n\t\t// LF-only framing — multi-byte characters and large events split across pipe\n\t\t// chunks are reassembled before parsing, which the raw handler above cannot do.\n\t\t// Pings refresh the heartbeat; coarse lifecycle events are forwarded for live\n\t\t// UI. Detached when the child exits (see cleanup below).\n\t\tif (proc.stdout) {\n\t\t\tdetachStdoutReader = attachJsonlLineReader(proc.stdout, (line) => {\n\t\t\t\tconst action = classifySubagentLine(line);\n\t\t\t\tif (action.kind === \"heartbeat\") {\n\t\t\t\t\tthis.lifeguard.recordHeartbeat(task.task_id);\n\t\t\t\t} else if (action.kind === \"progress\") {\n\t\t\t\t\tthis.emit(\"task_progress\", {\n\t\t\t\t\t\ttask_id: task.task_id,\n\t\t\t\t\t\tagent_type: task.agent_type,\n\t\t\t\t\t\tevent: action.event,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\tproc.stderr?.on(\"data\", (data: Buffer) => {\n\t\t\tstderr += data.toString();\n\t\t});\n\n\t\twaitForChildProcess(proc)\n\t\t\t.then((code) => {\n\t\t\t\tthis.slots.delete(task.task_id);\n\t\t\t\tdetachStdoutReader?.();\n\t\t\t\tbudget.flush();\n\n\t\t\t\tconst killReason = this.killReasons.get(task.task_id);\n\t\t\t\tthis.killReasons.delete(task.task_id);\n\n\t\t\t\tconst duration = Date.now() - slot.spawned_at;\n\t\t\t\tconst tokens_used = budget.getUsed();\n\t\t\t\tconst budgetExceeded = budget.isExceeded();\n\n\t\t\t\t// A subagent's success is defined by a valid, verified result.json, not by\n\t\t\t\t// its exit code. A child that finished its work and wrote a valid result can\n\t\t\t\t// still be SIGKILLed by the lifeguard before it exits on its own (lingering\n\t\t\t\t// open handles delay a natural exit past the heartbeat threshold), which forces\n\t\t\t\t// exit_code === null. Keying completion off the verified result, not code === 0,\n\t\t\t\t// honors that genuine success instead of discarding it as a false stall.\n\t\t\t\tconst verification = this.verifier.verify(task.task_id, task.cwd ?? this.cwd);\n\t\t\t\t// A well-formed result.json counts as clean completion unless its own\n\t\t\t\t// status field declares failure (e.g. \"failed\" from a provider quota\n\t\t\t\t// error). Without this check the pool would treat a child that wrote a\n\t\t\t\t// valid-but-failed result.json and exited non-zero as a success.\n\t\t\t\tlet cleanlyCompleted = code === 0 || verification.valid;\n\t\t\t\tif (cleanlyCompleted && verification.valid) {\n\t\t\t\t\tconst rd = this.tryReadResultJson(task.task_id, task.cwd ?? this.cwd);\n\t\t\t\t\tif (rd && (rd as Record<string, unknown>).status === \"failed\") {\n\t\t\t\t\t\tcleanlyCompleted = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// If killed by lifeguard before producing a valid result, honor the kill.\n\t\t\t\tif ((killReason === \"stalled\" || killReason === \"timeout\") && !verification.valid) {\n\t\t\t\t\tconst result: SubagentResult = {\n\t\t\t\t\t\ttask_id: task.task_id,\n\t\t\t\t\t\tok: false,\n\t\t\t\t\t\tstdout,\n\t\t\t\t\t\tstderr,\n\t\t\t\t\t\texit_code: code,\n\t\t\t\t\t\tstatus: killReason,\n\t\t\t\t\t};\n\t\t\t\t\tthis.writeOutputJson(task.task_id, result);\n\t\t\t\t\tthis.emit(`task_${killReason}`, {\n\t\t\t\t\t\ttask_id: task.task_id,\n\t\t\t\t\t\tagent_type: task.agent_type,\n\t\t\t\t\t\tduration,\n\t\t\t\t\t\ttokens_used,\n\t\t\t\t\t});\n\t\t\t\t\tthis.resolveWaiter(task.task_id, result);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst result: SubagentResult = {\n\t\t\t\t\ttask_id: task.task_id,\n\t\t\t\t\tok: cleanlyCompleted,\n\t\t\t\t\tstdout,\n\t\t\t\t\tstderr,\n\t\t\t\t\texit_code: code,\n\t\t\t\t\t// Advisory telemetry only: exceeding the budget never fails the task.\n\t\t\t\t\tbudget_exceeded: budgetExceeded,\n\t\t\t\t\tstatus: cleanlyCompleted ? \"complete\" : \"failed\",\n\t\t\t\t\tusedInheritedModelFallback: task.useInheritedModelFallback === true,\n\t\t\t\t};\n\n\t\t\t\tif (result.ok) {\n\t\t\t\t\tif (!verification.valid) {\n\t\t\t\t\t\tresult.ok = false;\n\t\t\t\t\t\tresult.error = verification.reason;\n\t\t\t\t\t\tresult.status = \"failed\";\n\t\t\t\t\t\tthis.writeOutputJson(task.task_id, result);\n\t\t\t\t\t\tthis.emit(\"task_failed\", {\n\t\t\t\t\t\t\ttask_id: task.task_id,\n\t\t\t\t\t\t\tagent_type: task.agent_type,\n\t\t\t\t\t\t\tduration,\n\t\t\t\t\t\t\ttokens_used,\n\t\t\t\t\t\t\terror: verification.reason,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tthis.resolveWaiter(task.task_id, result);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\t// Attach the verified result.json so callers can read the summary\n\t\t\t\t\t// without parsing the raw event stream.\n\t\t\t\t\tresult.result_data = this.tryReadResultJson(task.task_id, task.cwd ?? this.cwd);\n\n\t\t\t\t\t// Clean success: discard the per-task dispatch dir entirely\n\t\t\t\t\t// (session.jsonl, result.json, dispatch-log.json, budget.json). The\n\t\t\t\t\t// in-memory result already carries result_data, so callers lose\n\t\t\t\t\t// nothing. Trade-off: resume() only works for non-successful tasks.\n\t\t\t\t\tthis.cleanupDispatchDir(task.task_id, task.cwd ?? this.cwd);\n\n\t\t\t\t\tthis.emit(\"task_done\", {\n\t\t\t\t\t\ttask_id: task.task_id,\n\t\t\t\t\t\tagent_type: task.agent_type,\n\t\t\t\t\t\tduration,\n\t\t\t\t\t\ttokens_used,\n\t\t\t\t\t\tstatus: \"complete\",\n\t\t\t\t\t});\n\t\t\t\t\tthis.resolveWaiter(task.task_id, result);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// Failure path: keep the dispatch dir for debugging and persist output.\n\t\t\t\t// Attach the child's result.json (if any) and derive a concrete failure\n\t\t\t\t// reason so callers see the real cause (e.g. a provider usage/quota\n\t\t\t\t// error) instead of a generic \"subagent failed\".\n\t\t\t\tresult.result_data = this.tryReadResultJson(task.task_id, task.cwd ?? this.cwd);\n\t\t\t\tif (!result.error) {\n\t\t\t\t\tresult.error = this.deriveFailureReason(result);\n\t\t\t\t}\n\t\t\t\tif (this.shouldRetryWithInheritedModel(task, result)) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t`[DISPATCH] agent=${task.agent_type} task_id=${task.task_id} preferred model failed; retrying with inherited model`,\n\t\t\t\t\t);\n\t\t\t\t\tthis.cleanupRetryArtifacts(task);\n\t\t\t\t\tthis.queue.unshift({ ...task, useInheritedModelFallback: true });\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.writeOutputJson(task.task_id, result);\n\t\t\t\tthis.emit(\"task_failed\", {\n\t\t\t\t\ttask_id: task.task_id,\n\t\t\t\t\tagent_type: task.agent_type,\n\t\t\t\t\tduration,\n\t\t\t\t\ttokens_used,\n\t\t\t\t\terror: result.error ?? `Exited with code ${code}`,\n\t\t\t\t});\n\t\t\t\tthis.resolveWaiter(task.task_id, result);\n\t\t\t})\n\t\t\t.catch((err) => {\n\t\t\t\tthis.slots.delete(task.task_id);\n\t\t\t\tbudget.flush();\n\t\t\t\tconst duration = Date.now() - slot.spawned_at;\n\t\t\t\tconst tokens_used = budget.getUsed();\n\t\t\t\tif (!isRetry) {\n\t\t\t\t\tthis.startTask(task, true);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst error = err instanceof Error ? err.message : String(err);\n\t\t\t\tconst result: SubagentResult = {\n\t\t\t\t\ttask_id: task.task_id,\n\t\t\t\t\tok: false,\n\t\t\t\t\tstdout,\n\t\t\t\t\tstderr,\n\t\t\t\t\texit_code: null,\n\t\t\t\t\terror,\n\t\t\t\t\tstatus: \"failed\",\n\t\t\t\t\tusedInheritedModelFallback: task.useInheritedModelFallback === true,\n\t\t\t\t};\n\t\t\t\tthis.writeOutputJson(task.task_id, result);\n\t\t\t\tthis.emit(\"task_failed\", {\n\t\t\t\t\ttask_id: task.task_id,\n\t\t\t\t\tagent_type: task.agent_type,\n\t\t\t\t\tduration,\n\t\t\t\t\ttokens_used,\n\t\t\t\t\terror,\n\t\t\t\t});\n\t\t\t\tthis.resolveWaiter(task.task_id, result);\n\t\t\t})\n\t\t\t.finally(() => {\n\t\t\t\tbudget.removeAllListeners();\n\t\t\t\tthis.budgets.delete(task.task_id);\n\t\t\t\tthis.pull();\n\t\t\t});\n\t}\n\n\t/** Whether a failed built-in subagent should be retried with `model: inherit`. */\n\tprivate shouldRetryWithInheritedModel(task: SubagentPoolTask, result: SubagentResult): boolean {\n\t\tif (task.useInheritedModelFallback) return false;\n\t\tif (task.sessionFile) return false;\n\t\t// Only the parent model is required: the provider may be unset when the\n\t\t// harness routes through a gateway. The retry inherits the parent model and\n\t\t// lets the child resolve the provider from its own default when none was threaded through.\n\t\tif (!task.model) return false;\n\n\t\tconst def = task.agent_type ? this.getRegistry().get(task.agent_type) : undefined;\n\t\t// Built-in agents always inherit; project agents may pin an explicit model in\n\t\t// frontmatter, so let them fall back too when that model is rejected.\n\t\tif (def?.source !== \"builtin\" && def?.source !== \"project\") return false;\n\t\tif (!def.model || def.model === MODEL_INHERIT) return false;\n\n\t\treturn this.isInheritedModelFallbackError(result);\n\t}\n\n\t/** Detect provider/model failures where inheriting the parent model can recover. */\n\tprivate isInheritedModelFallbackError(result: SubagentResult): boolean {\n\t\tconst text = [result.error, result.stderr, JSON.stringify(result.result_data ?? {})]\n\t\t\t.filter((part): part is string => typeof part === \"string\" && part.length > 0)\n\t\t\t.join(\"\\n\");\n\n\t\treturn INHERITED_MODEL_FALLBACK_ERROR.test(text);\n\t}\n\n\t/** Remove failed attempt artifacts before rerunning the same task id. */\n\tprivate cleanupRetryArtifacts(task: SubagentPoolTask): void {\n\t\tconst cwd = task.cwd ?? this.cwd;\n\t\tconst taskDir = getDispatchTaskDir(cwd, task.task_id);\n\t\tconst sessionFile = task.sessionFile ?? this.getSessionFile(task.task_id, cwd);\n\t\ttry {\n\t\t\trmSync(sessionFile, { force: true });\n\t\t\trmSync(join(taskDir, \"result.json\"), { force: true });\n\t\t\trmSync(join(taskDir, \"output.json\"), { force: true });\n\t\t} catch {\n\t\t\t// Best-effort cleanup; retry can still proceed with existing artifacts.\n\t\t}\n\t}\n\n\t/**\n\t * Best-effort concrete failure reason for a non-zero-exit subagent. Prefers\n\t * the child's result.json summary (which carries the provider/model error\n\t * message on failure), then the tail of stderr, then the exit code.\n\t */\n\tprivate deriveFailureReason(result: SubagentResult): string {\n\t\tconst summary = (result.result_data as { summary?: string } | undefined)?.summary?.trim();\n\t\tif (summary) {\n\t\t\treturn summary;\n\t\t}\n\t\tconst stderrTail = result.stderr\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => line.trim())\n\t\t\t.filter((line) => line.length > 0)\n\t\t\t.slice(-5)\n\t\t\t.join(\"\\n\");\n\t\tif (stderrTail) {\n\t\t\treturn stderrTail;\n\t\t}\n\t\treturn `Exited with code ${result.exit_code}`;\n\t}\n\n\tprivate tryReadResultJson(task_id: string, cwd: string): Record<string, unknown> | undefined {\n\t\tconst path = join(getDispatchTaskDir(cwd, task_id), \"result.json\");\n\t\tif (!existsSync(path)) return undefined;\n\t\ttry {\n\t\t\tconst raw = readFileSync(path, \"utf-8\");\n\t\t\treturn JSON.parse(raw) as Record<string, unknown>;\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\tprivate resolveWaiter(task_id: string, result: SubagentResult): void {\n\t\t// Persist terminal status for get_status() even after wait_for consumes the result\n\t\tif (result.status === \"stalled\") this.taskStatus.set(task_id, \"stalled\");\n\t\telse if (result.status === \"timeout\") this.taskStatus.set(task_id, \"timeout\");\n\t\telse if (result.ok) this.taskStatus.set(task_id, \"done\");\n\t\telse this.taskStatus.set(task_id, \"failed\");\n\n\t\t// Always persist the result so collect() can read it after wait_for() resolves.\n\t\tthis.completed.set(task_id, result);\n\n\t\tconst waiter = this.waiters.get(task_id);\n\t\tif (waiter) {\n\t\t\twaiter.resolve(result);\n\t\t\tthis.waiters.delete(task_id);\n\t\t}\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"subagent-pool.d.ts","sourceRoot":"","sources":["../../src/core/subagent-pool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC3C,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAY3C,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AAiBtD,MAAM,WAAW,gBAAgB;IAChC,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,GAAG,CAAC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AED,2DAA2D;IAC3D,OAAO,CAAC,IAAI;IAOZ,sCAAsC;IACtC,OAAO,CAAC,SAAS;IAkGjB;;;;;;;;;OASG;IACH,OAAO,CAAC,aAAa;IAerB,kEAAkE;IAClE,OAAO,CAAC,SAAS;IA6QjB,kFAAkF;IAClF,OAAO,CAAC,6BAA6B;IAiBrC,oFAAoF;IACpF,OAAO,CAAC,6BAA6B;IAQrC,yEAAyE;IACzE,OAAO,CAAC,qBAAqB;IAa7B;;;;OAIG;IACH,OAAO,CAAC,mBAAmB;IAiB3B,OAAO,CAAC,iBAAiB;IAWzB,OAAO,CAAC,aAAa;CAerB","sourcesContent":["import { spawn } from \"node:child_process\";\nimport { EventEmitter } from \"node:events\";\nimport { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { getDispatchTaskDir } from \"../config.js\";\nimport { attachJsonlLineReader } from \"../modes/rpc/jsonl.js\";\nimport { waitForChildProcess } from \"../utils/child-process.js\";\nimport { MODEL_INHERIT } from \"./agent-frontmatter.js\";\nimport { type AgentRegistry, loadAgentRegistry } from \"./agent-registry.js\";\nimport { DispatchEvaluator } from \"./dispatch-evaluator.js\";\nimport { SubagentLifeguard } from \"./lifeguard.js\";\nimport { resolveModelReference } from \"./model-categories.js\";\nimport { OutputVerifier } from \"./output-verifier.js\";\nimport type { Settings } from \"./settings-manager.js\";\nimport {\n\tcurrentSubagentDepth,\n\tresolveMaxSubagentDepth,\n\tSUBAGENT_DEPTH_ENV,\n\tSUBAGENT_SKIP_MCP_ENV,\n\ttoolAllowlistNeedsMcp,\n} from \"./subagent-depth.js\";\nimport { TokenBudget } from \"./token-budget.js\";\n\n/**\n * Provider/model failure signatures where inheriting the parent model can\n * recover. Compiled once at module load instead of on every error check.\n */\nconst INHERITED_MODEL_FALLBACK_ERROR =\n\t/usage[_\\s-]?limit|subscription|quota|rate.?limit|too many requests|429|insufficient|out of credit|credit balance|billing|payment required|402|model[^\\n]*(not found|unavailable|not available|not supported|does not exist|invalid|unsupported)|no api key|no auth configured|authentication|unauthorized|forbidden|permission/i;\n\nexport interface SubagentPoolTask {\n\ttask_id: string;\n\tagent_type: string;\n\ttask: string;\n\tcontext?: string;\n\ttoken_budget?: number;\n\tcwd?: string;\n\tmodel?: string;\n\tprovider?: string;\n\t/**\n\t * Explicit session file for the child to persist/continue. When omitted the\n\t * child uses its own dispatch dir (`<dispatch>/<task_id>/session.jsonl`).\n\t * Resume reuses the original task's session file to continue the transcript.\n\t */\n\tsessionFile?: string;\n\t/** Internal: retry using the caller's model when a built-in agent's preferred model fails. */\n\tuseInheritedModelFallback?: boolean;\n}\n\nexport interface SubagentSlot {\n\tpid: number;\n\tagent_type: string;\n\ttask_id: string;\n\tspawned_at: number;\n\ttoken_budget: number;\n\tprocess: ReturnType<typeof spawn>;\n}\n\nexport interface SubagentResult {\n\ttask_id: string;\n\tok: boolean;\n\tstdout: string;\n\tstderr: string;\n\texit_code: number | null;\n\terror?: string;\n\t/** True when the task exceeded its token budget and was hard-stopped. */\n\tbudget_exceeded?: boolean;\n\t/** Terminal status derived from how the task finished. */\n\tstatus?: \"complete\" | \"partial\" | \"failed\" | \"stalled\" | \"timeout\";\n\t/** Parsed result.json content when available (e.g. on partial completion). */\n\tresult_data?: Record<string, unknown>;\n\t/** True when this run used the inherited-model fallback (preferred model failed first). */\n\tusedInheritedModelFallback?: boolean;\n}\n\nexport interface TaskResult {\n\t/** True when the evaluator decided the task is simple enough for inline handling. */\n\thandled_inline: boolean;\n\t/** Present when the task was delegated. */\n\ttask_id?: string;\n\tagent_type?: string;\n\treason?: string;\n\t/** Subagent result when delegated. */\n\tresult?: SubagentResult;\n\t/** Duration in milliseconds when delegated. */\n\tduration?: number;\n}\n\nexport interface DispatchOptions {\n\t/** Skip evaluation and force this agent type (user/explicit override).\n\t * Accepts any registry-defined agent name, not just the built-in modes. */\n\tforceAgent?: string;\n\t/** Context distilled from the calling agent, passed to the subagent. */\n\tcontext?: string;\n\t/** Model id for the subagent (defaults to the child's configured default). */\n\tmodel?: string;\n\t/** Provider for the subagent. */\n\tprovider?: string;\n\t/** Explicit session file to persist/continue (used by resume). */\n\tsessionFile?: string;\n\t/** Caller-supplied task id. Defaults to a generated `dispatch-…` id. Lets a\n\t * caller register liveness/inbox state under the id before dispatch resolves. */\n\ttaskId?: string;\n}\n\nexport interface SubagentPoolOptions {\n\t/** Path to the hoocode executable (or the runtime, e.g. node, when prefixArgs is set). */\n\texecutable: string;\n\t/** Args inserted before task args (e.g. the CLI entry script for node/tsx). */\n\tprefixArgs?: string[];\n\t/** Maximum concurrent child processes. Defaults to 5. */\n\tmaxConcurrency?: number;\n\t/** Working directory for spawned processes. Defaults to process.cwd(). */\n\tcwd?: string;\n\t/** Environment variables. Defaults to process.env. */\n\tenv?: NodeJS.ProcessEnv;\n\t/** Default token budget per task. Defaults to 0. */\n\tdefaultTokenBudget?: number;\n\t/**\n\t * Non-default skill paths to forward to every spawned subagent via --skill.\n\t * Subagents auto-discover skills from standard locations; only paths that\n\t * won't be found by default discovery need to be forwarded here.\n\t */\n\tskillPaths?: string[];\n\t/** Settings for model category resolution. */\n\tsettings?: Settings;\n}\n\n/**\n * Default hard cap on assistant turns for a spawned subagent when its definition\n * does not set `maxTurns`. The token budget is advisory (it warns but never\n * kills), so this turn cap is the guaranteed hard stop for every subagent.\n */\nexport const DEFAULT_SUBAGENT_MAX_TURNS = 50;\n\n/**\n * AgentSession event `type`s forwarded from a subagent's json event stream as\n * `task_progress` events. Deliberately coarse: the child also emits per-delta\n * `message_update` / `tool_execution_update` events (a high-volume firehose) and\n * large `message_*` bodies, which are dropped here to keep the parent's event loop\n * and the task panel from thrashing under concurrent subagents.\n */\nexport const FORWARDED_SUBAGENT_EVENTS: ReadonlySet<string> = new Set([\n\t\"turn_end\",\n\t\"tool_execution_start\",\n\t\"tool_execution_end\",\n]);\n\n/** The action the pool should take for one JSONL line from a subagent's stdout. */\nexport type SubagentStdoutLine =\n\t| { kind: \"heartbeat\" }\n\t| { kind: \"progress\"; event: Record<string, unknown> }\n\t| { kind: \"ignore\" };\n\n/**\n * Classify one JSONL line from a subagent's stdout into the action to take.\n * Pure (no side effects) so the ping/forward/drop policy is unit-testable without\n * spawning a child. Line framing — UTF-8-safe reassembly of chunks split mid-line\n * — is handled upstream by attachJsonlLineReader; this only sees complete lines.\n */\nexport function classifySubagentLine(line: string): SubagentStdoutLine {\n\tconst trimmed = line.trim();\n\tif (!trimmed.startsWith(\"{\")) return { kind: \"ignore\" };\n\tlet parsed: Record<string, unknown>;\n\ttry {\n\t\tparsed = JSON.parse(trimmed) as Record<string, unknown>;\n\t} catch {\n\t\treturn { kind: \"ignore\" };\n\t}\n\tif (parsed.ping === true) return { kind: \"heartbeat\" };\n\tif (typeof parsed.type === \"string\" && FORWARDED_SUBAGENT_EVENTS.has(parsed.type)) {\n\t\treturn { kind: \"progress\", event: parsed };\n\t}\n\treturn { kind: \"ignore\" };\n}\n\n/**\n * Pool for running hoocode subagents as child processes with bounded concurrency,\n * FIFO queuing with priority support, and automatic slot refill.\n *\n * Events:\n * - \"task_done\" – task completed successfully and output was verified\n * - \"task_failed\" – task failed (spawn error, bad exit code, verification failure)\n * - \"task_stalled\" – heartbeat missed past the load-scaled threshold (60s base,\n * widened under concurrency/event-loop lag), process SIGKILLed\n * - \"task_timeout\" – hard timeout exceeded, process was SIGKILLed\n * - \"budget_warning\" – token usage crossed 80% threshold (advisory)\n * - \"budget_exceeded\" – token usage crossed 100% threshold (advisory; never kills)\n * - \"task_progress\" – coarse lifecycle event (turn_end, tool start/end) parsed\n * from the child's json event stream, for live UI updates\n */\nexport class SubagentPool extends EventEmitter {\n\tprivate readonly maxConcurrency: number;\n\tprivate readonly executable: string;\n\tprivate readonly prefixArgs: string[];\n\tprivate readonly cwd: string;\n\tprivate readonly env: NodeJS.ProcessEnv;\n\tprivate readonly defaultTokenBudget: number;\n\t/** Non-default skill paths forwarded to every spawned subagent via --skill. */\n\tprivate skillPaths: string[];\n\n\tprivate slots = new Map<string, SubagentSlot>();\n\tprivate queue: SubagentPoolTask[] = [];\n\tprivate completed = new Map<string, SubagentResult>();\n\tprivate waiters = new Map<string, { resolve: (result: SubagentResult) => void; reject: (err: Error) => void }>();\n\tprivate budgets = new Map<string, TokenBudget>();\n\tprivate verifier = new OutputVerifier();\n\tprivate lifeguard: SubagentLifeguard;\n\tprivate disposed = false;\n\t/** Lazily-loaded agent registry (frontmatter definitions) for this pool's cwd. */\n\tprivate registry?: AgentRegistry;\n\t/** Tracks why a task was killed (stalled / timeout) before exit handler fires. */\n\tprivate killReasons = new Map<string, \"stalled\" | \"timeout\">();\n\t/** Persistent terminal status map, survives wait_for consumption. */\n\tprivate taskStatus = new Map<string, \"done\" | \"failed\" | \"stalled\" | \"timeout\">();\n\t/** Settings for model category resolution. */\n\tprivate readonly settings?: Settings;\n\n\tconstructor(options: SubagentPoolOptions) {\n\t\tsuper();\n\t\tthis.maxConcurrency = options.maxConcurrency ?? 5;\n\t\tthis.executable = options.executable;\n\t\tthis.prefixArgs = options.prefixArgs ?? [];\n\t\tthis.cwd = options.cwd ?? process.cwd();\n\t\tthis.env = options.env ?? process.env;\n\t\tthis.defaultTokenBudget = options.defaultTokenBudget ?? 0;\n\t\tthis.skillPaths = options.skillPaths ? [...options.skillPaths] : [];\n\t\tthis.settings = options.settings;\n\t\tthis.verifier = new OutputVerifier(this.cwd);\n\t\tthis.lifeguard = new SubagentLifeguard(this.cwd);\n\t\tthis.lifeguard.on(\"stalled\", (data: { task_id: string; pid: number }) => {\n\t\t\tthis.killReasons.set(data.task_id, \"stalled\");\n\t\t\tthis.emit(\"task_stalled\", data);\n\t\t});\n\t\tthis.lifeguard.on(\"timeout\", (data: { task_id: string; pid: number }) => {\n\t\t\tthis.killReasons.set(data.task_id, \"timeout\");\n\t\t\tthis.emit(\"task_timeout\", data);\n\t\t});\n\t}\n\n\t/** Update the non-default skill paths forwarded to new subagents. */\n\tupdateSkillPaths(paths: string[]): void {\n\t\tthis.skillPaths = [...paths];\n\t}\n\n\t/**\n\t * Report external in-process load (e.g. the number of background MCP tools\n\t * currently executing in the parent) to the lifeguard. This widens its\n\t * heartbeat/timeout tolerance so monitored subagents aren't false-positive\n\t * reaped when the parent's event loop is busy with concurrent background work.\n\t */\n\tsetExternalLoad(count: number): void {\n\t\tthis.lifeguard.setExternalLoad(count);\n\t}\n\n\t/** Lazily load the agent registry for this pool's cwd. */\n\tprivate getRegistry(): AgentRegistry {\n\t\tif (!this.registry) {\n\t\t\tthis.registry = loadAgentRegistry({ cwd: this.cwd });\n\t\t}\n\t\treturn this.registry;\n\t}\n\n\t/** Priority value: higher numbers run first. */\n\tprivate priorityOf(agent_type: string): number {\n\t\t// Read-only investigation (explore/plan) often unblocks downstream work, so\n\t\t// it runs ahead of other agents.\n\t\treturn agent_type === \"explore\" || agent_type === \"plan\" ? 2 : 1;\n\t}\n\n\t/** Queue a task. It will run when a slot is free. */\n\tspawn(task: SubagentPoolTask): void {\n\t\tif (this.disposed) {\n\t\t\tthrow new Error(\"SubagentPool has been disposed\");\n\t\t}\n\t\tif (\n\t\t\tthis.slots.has(task.task_id) ||\n\t\t\tthis.queue.some((t) => t.task_id === task.task_id) ||\n\t\t\tthis.completed.has(task.task_id)\n\t\t) {\n\t\t\tthrow new Error(`Duplicate task_id: ${task.task_id}`);\n\t\t}\n\n\t\tconst p = this.priorityOf(task.agent_type);\n\t\tconst idx = this.queue.findIndex((t) => this.priorityOf(t.agent_type) < p);\n\t\tif (idx === -1) {\n\t\t\tthis.queue.push(task);\n\t\t} else {\n\t\t\tthis.queue.splice(idx, 0, task);\n\t\t}\n\t\tthis.pull();\n\t}\n\n\t/** Current status of a task. */\n\tget_status(task_id: string): \"running\" | \"queued\" | \"done\" | \"failed\" | \"stalled\" | \"timeout\" | \"unknown\" {\n\t\tif (this.slots.has(task_id)) return \"running\";\n\t\tif (this.queue.some((t) => t.task_id === task_id)) return \"queued\";\n\t\tconst persisted = this.taskStatus.get(task_id);\n\t\tif (persisted) return persisted;\n\t\tconst result = this.completed.get(task_id);\n\t\tif (result) {\n\t\t\tif (result.status === \"stalled\") return \"stalled\";\n\t\t\tif (result.status === \"timeout\") return \"timeout\";\n\t\t\tif (result.ok) return \"done\";\n\t\t\treturn \"failed\";\n\t\t}\n\t\treturn \"unknown\";\n\t}\n\n\t/** Wait for a task to complete and return its result. */\n\twait_for(task_id: string): Promise<SubagentResult> {\n\t\tif (this.disposed) {\n\t\t\treturn Promise.reject(new Error(\"SubagentPool has been disposed\"));\n\t\t}\n\n\t\tconst existing = this.completed.get(task_id);\n\t\tif (existing) {\n\t\t\tthis.completed.delete(task_id);\n\t\t\treturn Promise.resolve(existing);\n\t\t}\n\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tthis.waiters.set(task_id, { resolve, reject });\n\t\t});\n\t}\n\n\t/** Number of currently running subagents. */\n\trunning_count(): number {\n\t\treturn this.slots.size;\n\t}\n\n\t/** Number of tasks waiting in the queue. */\n\tqueued_count(): number {\n\t\treturn this.queue.length;\n\t}\n\n\t/**\n\t * Dispatch a task through the evaluator.\n\t *\n\t * - If `options.forceAgent` is provided, skip evaluation and spawn directly.\n\t * - Otherwise evaluate the task. If it should be handled inline, return\n\t * `{ handled_inline: true }` immediately.\n\t * - If delegating, spawn the subagent, wait for completion, write\n\t * `output.json`, and return the result.\n\t */\n\tasync dispatch(task: string, options: DispatchOptions = {}): Promise<TaskResult> {\n\t\tif (this.disposed) {\n\t\t\treturn Promise.reject(new Error(\"SubagentPool has been disposed\"));\n\t\t}\n\t\tconst begin = this.beginDispatch(task, options);\n\t\tif (begin.handled_inline) {\n\t\t\treturn { handled_inline: true, reason: begin.reason };\n\t\t}\n\t\tconst result = await this.wait_for(begin.task_id);\n\t\treturn {\n\t\t\thandled_inline: false,\n\t\t\ttask_id: begin.task_id,\n\t\t\tagent_type: begin.agent_type,\n\t\t\treason: begin.reason,\n\t\t\tresult,\n\t\t\tduration: Date.now() - begin.startTime,\n\t\t};\n\t}\n\n\t/**\n\t * Fire-and-forget dispatch for background agents. Spawns the subagent and\n\t * returns its handle immediately; the caller polls get_status()/collect().\n\t */\n\tdispatchDetached(\n\t\ttask: string,\n\t\toptions: DispatchOptions = {},\n\t): { handled_inline: boolean; task_id?: string; agent_type?: string; reason?: string } {\n\t\tif (this.disposed) {\n\t\t\tthrow new Error(\"SubagentPool has been disposed\");\n\t\t}\n\t\tconst begin = this.beginDispatch(task, options);\n\t\tif (begin.handled_inline) {\n\t\t\treturn { handled_inline: true, reason: begin.reason };\n\t\t}\n\t\treturn { handled_inline: false, task_id: begin.task_id, agent_type: begin.agent_type, reason: begin.reason };\n\t}\n\n\t/**\n\t * Evaluate, log, and spawn a task without waiting. Shared by dispatch()\n\t * (blocking) and dispatchDetached() (background).\n\t */\n\tprivate beginDispatch(\n\t\ttask: string,\n\t\toptions: DispatchOptions,\n\t):\n\t\t| { handled_inline: true; reason?: string }\n\t\t| { handled_inline: false; task_id: string; agent_type: string; reason?: string; startTime: number } {\n\t\tconst { forceAgent, context, model, provider, sessionFile } = options;\n\t\tconst evaluator = new DispatchEvaluator();\n\t\tconst analysis = evaluator.evaluate(task);\n\n\t\tif (!forceAgent && !analysis.should_delegate) {\n\t\t\treturn { handled_inline: true, reason: analysis.reason };\n\t\t}\n\n\t\tconst agent_type = forceAgent ?? \"general-purpose\";\n\t\tconst task_id = options.taskId ?? `dispatch-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;\n\t\tconst reason = forceAgent ? \"user_override\" : analysis.reason;\n\t\tconst complexity = analysis.estimated_complexity;\n\t\t// Depth of the child about to be spawned (this process's depth + 1). Surfaced\n\t\t// so a delegation tree's nesting is visible in logs without extra tooling.\n\t\tconst childDepth = currentSubagentDepth(this.env) + 1;\n\n\t\t// Pre-dispatch logging. Use stderr: stdout is reserved for the JSON event\n\t\t// stream / TUI render and must not be polluted.\n\t\tconsole.error(\n\t\t\t`[DISPATCH] agent=${agent_type} depth=${childDepth} reason=${reason} complexity=${complexity} task_id=${task_id}`,\n\t\t);\n\t\tthis.writeDispatchLog(task_id, agent_type, reason, complexity, task, childDepth);\n\n\t\tconst poolTask: SubagentPoolTask = {\n\t\t\ttask_id,\n\t\t\tagent_type,\n\t\t\ttask,\n\t\t\tcontext,\n\t\t\tmodel,\n\t\t\tprovider,\n\t\t\tsessionFile,\n\t\t\tcwd: this.cwd,\n\t\t};\n\t\tconst startTime = Date.now();\n\t\tthis.spawn(poolTask);\n\t\treturn { handled_inline: false, task_id, agent_type, reason, startTime };\n\t}\n\n\t/**\n\t * Non-destructively read a completed task's result (for background polling).\n\t * Returns undefined while the task is still running/queued, or if its result\n\t * was already consumed via wait_for().\n\t */\n\tcollect(task_id: string): SubagentResult | undefined {\n\t\treturn this.completed.get(task_id);\n\t}\n\n\t/** Absolute path of the persisted session file for a task. */\n\tgetSessionFile(task_id: string, cwd: string = this.cwd): string {\n\t\treturn join(getDispatchTaskDir(cwd, task_id), \"session.jsonl\");\n\t}\n\n\t/**\n\t * Resume a previously dispatched subagent, continuing its persisted session\n\t * with a follow-up prompt. Recovers the original agent type from its dispatch\n\t * log. Rejects if no resumable session exists for the task.\n\t */\n\tasync resume(\n\t\ttask_id: string,\n\t\tprompt: string,\n\t\toptions: Omit<DispatchOptions, \"forceAgent\" | \"sessionFile\"> = {},\n\t): Promise<TaskResult> {\n\t\tif (this.disposed) {\n\t\t\treturn Promise.reject(new Error(\"SubagentPool has been disposed\"));\n\t\t}\n\t\tconst sessionFile = this.getSessionFile(task_id);\n\t\tif (!existsSync(sessionFile)) {\n\t\t\treturn Promise.reject(new Error(`No resumable session for task \"${task_id}\" (expected ${sessionFile}).`));\n\t\t}\n\t\tconst agent_type = this.readDispatchAgentType(task_id) ?? \"general-purpose\";\n\t\treturn this.dispatch(prompt, { ...options, forceAgent: agent_type, sessionFile });\n\t}\n\n\t/** Recover the agent type a task was dispatched with, from its dispatch log. */\n\tprivate readDispatchAgentType(task_id: string): string | undefined {\n\t\tconst path = join(getDispatchTaskDir(this.cwd, task_id), \"dispatch-log.json\");\n\t\tif (!existsSync(path)) return undefined;\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(readFileSync(path, \"utf-8\")) as { agent_type?: string };\n\t\t\treturn typeof parsed.agent_type === \"string\" ? parsed.agent_type : undefined;\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\tprivate writeDispatchLog(\n\t\ttask_id: string,\n\t\tagent_type: string,\n\t\treason: string,\n\t\tcomplexity: string,\n\t\ttask: string,\n\t\tdepth: number,\n\t): void {\n\t\tconst log = {\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\ttask_id,\n\t\t\tagent_type,\n\t\t\tdepth,\n\t\t\treason,\n\t\t\tcomplexity,\n\t\t\ttask,\n\t\t};\n\t\tconst path = join(getDispatchTaskDir(this.cwd, task_id), \"dispatch-log.json\");\n\t\ttry {\n\t\t\tmkdirSync(dirname(path), { recursive: true });\n\t\t\twriteFileSync(path, JSON.stringify(log, null, 2));\n\t\t} catch {\n\t\t\t// Best-effort persistence\n\t\t}\n\t}\n\n\tprivate writeOutputJson(task_id: string, result: SubagentResult): void {\n\t\tconst output = {\n\t\t\ttask_id: result.task_id,\n\t\t\tok: result.ok,\n\t\t\texit_code: result.exit_code,\n\t\t\tstatus: result.status,\n\t\t\tstdout: result.stdout,\n\t\t\tstderr: result.stderr,\n\t\t\terror: result.error,\n\t\t\tbudget_exceeded: result.budget_exceeded,\n\t\t\tresult_data: result.result_data,\n\t\t};\n\t\tconst path = join(getDispatchTaskDir(this.cwd, task_id), \"output.json\");\n\t\ttry {\n\t\t\tmkdirSync(dirname(path), { recursive: true });\n\t\t\twriteFileSync(path, JSON.stringify(output, null, 2));\n\t\t} catch {\n\t\t\t// Best-effort persistence\n\t\t}\n\t}\n\n\t/**\n\t * Remove a task's dispatch dir after a clean, verified success. Best-effort:\n\t * a cleanup failure must never fail an otherwise successful task.\n\t */\n\tprivate cleanupDispatchDir(task_id: string, cwd: string): void {\n\t\ttry {\n\t\t\trmSync(getDispatchTaskDir(cwd, task_id), { recursive: true, force: true });\n\t\t} catch {\n\t\t\t// Best-effort cleanup\n\t\t}\n\t}\n\n\t/** Kill all running processes, clear the queue, and reject pending waiters. */\n\tdispose(): void {\n\t\tif (this.disposed) return;\n\t\tthis.disposed = true;\n\n\t\tfor (const slot of this.slots.values()) {\n\t\t\tif (!slot.process.killed) {\n\t\t\t\tslot.process.kill(\"SIGTERM\");\n\t\t\t}\n\t\t}\n\t\tthis.slots.clear();\n\t\tthis.queue = [];\n\n\t\tfor (const [task_id, waiter] of this.waiters) {\n\t\t\twaiter.reject(new Error(\"SubagentPool disposed\"));\n\t\t\tthis.waiters.delete(task_id);\n\t\t}\n\t\tthis.completed.clear();\n\t\tfor (const budget of this.budgets.values()) {\n\t\t\tbudget.removeAllListeners();\n\t\t}\n\t\tthis.budgets.clear();\n\t\tthis.killReasons.clear();\n\t\tthis.taskStatus.clear();\n\t\tthis.lifeguard.dispose();\n\t\tthis.removeAllListeners();\n\t}\n\n\t/** Pull tasks from the queue while slots are available. */\n\tprivate pull(): void {\n\t\twhile (this.slots.size < this.maxConcurrency && this.queue.length > 0) {\n\t\t\tconst task = this.queue.shift()!;\n\t\t\tthis.startTask(task, false);\n\t\t}\n\t}\n\n\t/** Build CLI arguments for a task. */\n\tprivate buildArgs(task: SubagentPoolTask): string[] {\n\t\t// Persist the child's session so a finished/interrupted subagent can be\n\t\t// resumed later (see resume()). SessionManager.open() creates the file on\n\t\t// first run and continues it on subsequent runs.\n\t\tconst sessionFile = task.sessionFile ?? this.getSessionFile(task.task_id, task.cwd ?? this.cwd);\n\t\tconst args: string[] = [\n\t\t\t...this.prefixArgs,\n\t\t\t\"--mode\",\n\t\t\t\"json\",\n\t\t\t\"--session\",\n\t\t\tsessionFile,\n\t\t\t\"--task-id\",\n\t\t\ttask.task_id,\n\t\t];\n\n\t\t// Prefer the data-driven agent definition from the registry; fall back to the\n\t\t// built-in mode prompt/allowlist for legacy modes not present in the registry.\n\t\tconst def = task.agent_type ? this.getRegistry().get(task.agent_type) : undefined;\n\n\t\tif (task.agent_type) {\n\t\t\tconst systemPrompt = def?.prompt;\n\t\t\tif (systemPrompt) {\n\t\t\t\targs.push(\"--system-prompt\", systemPrompt);\n\t\t\t}\n\n\t\t\t// A `delegate: true` agent may itself dispatch via the Task tool, but only\n\t\t\t// while the child it becomes can still nest (childDepth < cap) — so the\n\t\t\t// deepest permitted level cannot delegate further. Gating here keeps the\n\t\t\t// authorization explicit and bounded by the same cap as the depth guard.\n\t\t\tconst childDepth = currentSubagentDepth(this.env) + 1;\n\t\t\tconst canChildDelegate = def?.delegate === true && childDepth < resolveMaxSubagentDepth(undefined, this.env);\n\n\t\t\t// Tool allowlist comes from the agent definition's frontmatter `tools`\n\t\t\t// field (read-only built-ins declare their own sandbox). When omitted, no\n\t\t\t// --tools is passed and the subagent inherits all parent tools (so the Task\n\t\t\t// tool already survives). A delegating agent with an explicit allowlist must\n\t\t\t// have Task/TaskOutput added, or the child would filter them out.\n\t\t\tconst tools = def?.tools ? [...def.tools] : undefined;\n\t\t\tif (canChildDelegate && tools) {\n\t\t\t\tfor (const t of [\"Task\", \"TaskOutput\"]) {\n\t\t\t\t\tif (!tools.includes(t)) tools.push(t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (tools && tools.length > 0) {\n\t\t\t\targs.push(\"--tools\", tools.join(\",\"));\n\t\t\t}\n\t\t\tif (def?.disallowedTools && def.disallowedTools.length > 0) {\n\t\t\t\targs.push(\"--disallowed-tools\", def.disallowedTools.join(\",\"));\n\t\t\t}\n\n\t\t\t// Propagate subagent enablement so the child registers the Task tool; without\n\t\t\t// this the flag-based enablement would not reach a spawned child.\n\t\t\tif (canChildDelegate) {\n\t\t\t\targs.push(\"--enable-subagents\");\n\t\t\t\t// Scoped delegation: restrict which agent types this child may spawn.\n\t\t\t\tif (def?.delegateTo && def.delegateTo.length > 0) {\n\t\t\t\t\targs.push(\"--delegate-allow\", def.delegateTo.join(\",\"));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Model precedence: a definition's explicit model wins (unless it is the\n\t\t// `inherit` sentinel), otherwise use the caller-provided model. Built-in\n\t\t// agents can retry with the inherited model when their preferred model is\n\t\t// unavailable or quota-limited.\n\t\tconst explicitModel =\n\t\t\t!task.useInheritedModelFallback && def?.model && def.model !== MODEL_INHERIT ? def.model : undefined;\n\t\t// Resolve a model-category reference (fast/standard/capable) to its\n\t\t// configured model id. An unconfigured category resolves to undefined, so no\n\t\t// `--model` is passed and the child keeps its default model.\n\t\tconst rawModel = explicitModel ?? task.model;\n\t\tconst modelToUse = rawModel ? resolveModelReference(rawModel, this.settings) : undefined;\n\t\tif (modelToUse) {\n\t\t\targs.push(\"--model\", modelToUse);\n\t\t}\n\t\tif (task.provider) {\n\t\t\targs.push(\"--provider\", task.provider);\n\t\t}\n\n\t\t// Always give subagents a hard turn cap. With the token budget now advisory\n\t\t// (warn-only), this is the guaranteed hard stop for a runaway subagent.\n\t\tconst maxTurns = def?.maxTurns && def.maxTurns > 0 ? def.maxTurns : DEFAULT_SUBAGENT_MAX_TURNS;\n\t\targs.push(\"--max-turns\", String(maxTurns));\n\n\t\t// Forward non-default skill paths so the subagent has access to all parent skills.\n\t\t// Standard discovery locations (~/.hoocode/, .hoocode/, .claude/) are found automatically.\n\t\tfor (const skillPath of this.skillPaths) {\n\t\t\targs.push(\"--skill\", skillPath);\n\t\t}\n\n\t\tconst prompt = task.context?.trim()\n\t\t\t? `Context from the calling agent:\\n\\n${task.context.trim()}\\n\\nTask: ${task.task.trim()}`\n\t\t\t: `Task: ${task.task.trim()}`;\n\t\targs.push(prompt);\n\n\t\treturn args;\n\t}\n\n\t/**\n\t * Environment for a spawned child.\n\t *\n\t * Stamps the child's depth (parent depth + 1) so its own guard knows where it\n\t * sits in the tree; the tree-wide cap (HOOCODE_SUBAGENT_MAX_DEPTH) is inherited\n\t * via the spread, so at the default cap of 1 the child lands at depth 1 and\n\t * cannot spawn further subagents. Also flags the child to skip MCP server\n\t * connection when its tool allowlist is explicit and MCP-free — connecting\n\t * external servers it can never call is pure boot latency.\n\t */\n\tprivate childSpawnEnv(task: SubagentPoolTask): NodeJS.ProcessEnv {\n\t\tconst env: NodeJS.ProcessEnv = {\n\t\t\t...this.env,\n\t\t\t[SUBAGENT_DEPTH_ENV]: String(currentSubagentDepth(this.env) + 1),\n\t\t};\n\t\t// Use the agent's own frontmatter allowlist (the same source buildArgs passes\n\t\t// via --tools). A delegating child also gets Task/TaskOutput appended there,\n\t\t// but neither is an MCP tool, so the decision is unchanged by that.\n\t\tconst def = task.agent_type ? this.getRegistry().get(task.agent_type) : undefined;\n\t\tif (!toolAllowlistNeedsMcp(def?.tools)) {\n\t\t\tenv[SUBAGENT_SKIP_MCP_ENV] = \"1\";\n\t\t}\n\t\treturn env;\n\t}\n\n\t/** Start a task in a child process, with one retry on failure. */\n\tprivate startTask(task: SubagentPoolTask, isRetry: boolean): void {\n\t\t// Get or create a TokenBudget tracker. On retry, reuse the existing one\n\t\t// so cumulative usage persists across retries.\n\t\tlet budget = this.budgets.get(task.task_id);\n\t\tif (!budget) {\n\t\t\tbudget = new TokenBudget(task.task_id, task.agent_type, {\n\t\t\t\tlimit: task.token_budget,\n\t\t\t\tcwd: task.cwd ?? this.cwd,\n\t\t\t});\n\t\t\tbudget.on(\"budget_warning\", (data: { task_id: string; message: string; used: number; limit: number }) => {\n\t\t\t\tthis.emit(\"budget_warning\", data);\n\t\t\t});\n\t\t\t// The token budget is advisory: surface telemetry but never kill. The\n\t\t\t// guaranteed hard stop is the per-subagent turn cap (--max-turns); see\n\t\t\t// DEFAULT_SUBAGENT_MAX_TURNS.\n\t\t\tbudget.on(\"budget_exceeded\", (data: { task_id: string; used: number; limit: number }) => {\n\t\t\t\tthis.emit(\"budget_exceeded\", data);\n\t\t\t});\n\t\t\tthis.budgets.set(task.task_id, budget);\n\t\t}\n\n\t\tlet proc: ReturnType<typeof spawn>;\n\t\ttry {\n\t\t\tproc = spawn(this.executable, this.buildArgs(task), {\n\t\t\t\tcwd: task.cwd ?? this.cwd,\n\t\t\t\tenv: this.childSpawnEnv(task),\n\t\t\t\tshell: false,\n\t\t\t\tstdio: [\"ignore\", \"pipe\", \"pipe\"],\n\t\t\t});\n\t\t} catch {\n\t\t\tif (!isRetry) {\n\t\t\t\tthis.startTask(task, true);\n\t\t\t} else {\n\t\t\t\tthis.emit(\"task_failed\", {\n\t\t\t\t\ttask_id: task.task_id,\n\t\t\t\t\terror: \"Spawn failed synchronously\",\n\t\t\t\t});\n\t\t\t\tthis.resolveWaiter(task.task_id, {\n\t\t\t\t\ttask_id: task.task_id,\n\t\t\t\t\tok: false,\n\t\t\t\t\tstdout: \"\",\n\t\t\t\t\tstderr: \"\",\n\t\t\t\t\texit_code: null,\n\t\t\t\t\terror: \"Spawn failed synchronously\",\n\t\t\t\t\tstatus: \"failed\",\n\t\t\t\t});\n\t\t\t\tthis.pull();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tconst slot: SubagentSlot = {\n\t\t\tpid: proc.pid ?? 0,\n\t\t\tagent_type: task.agent_type,\n\t\t\ttask_id: task.task_id,\n\t\t\tspawned_at: Date.now(),\n\t\t\ttoken_budget: task.token_budget ?? this.defaultTokenBudget,\n\t\t\tprocess: proc,\n\t\t};\n\n\t\tthis.slots.set(task.task_id, slot);\n\t\tthis.lifeguard.monitor(task.task_id, task.agent_type, proc);\n\n\t\tlet stdout = \"\";\n\t\tlet stderr = \"\";\n\t\tlet detachStdoutReader: (() => void) | undefined;\n\n\t\tproc.stdout?.on(\"data\", (data: Buffer) => {\n\t\t\tconst chunk = data.toString();\n\t\t\tstdout += chunk;\n\t\t\tbudget.processStdout(chunk);\n\n\t\t\t// Any output proves the child is alive and working, so treat it as a\n\t\t\t// heartbeat. The dedicated {\"ping\":true} line (parsed below via the JSONL\n\t\t\t// reader) still matters for quiet phases (e.g. a long single model turn\n\t\t\t// that emits nothing), but relying on it alone falsely reaps subagents\n\t\t\t// that are busily streaming events while the parent's event loop is\n\t\t\t// starved by concurrent load.\n\t\t\tthis.lifeguard.recordHeartbeat(task.task_id);\n\t\t});\n\n\t\t// Parse the child's newline-delimited JSON event stream with UTF-8-safe,\n\t\t// LF-only framing — multi-byte characters and large events split across pipe\n\t\t// chunks are reassembled before parsing, which the raw handler above cannot do.\n\t\t// Pings refresh the heartbeat; coarse lifecycle events are forwarded for live\n\t\t// UI. Detached when the child exits (see cleanup below).\n\t\tif (proc.stdout) {\n\t\t\tdetachStdoutReader = attachJsonlLineReader(proc.stdout, (line) => {\n\t\t\t\tconst action = classifySubagentLine(line);\n\t\t\t\tif (action.kind === \"heartbeat\") {\n\t\t\t\t\tthis.lifeguard.recordHeartbeat(task.task_id);\n\t\t\t\t} else if (action.kind === \"progress\") {\n\t\t\t\t\tthis.emit(\"task_progress\", {\n\t\t\t\t\t\ttask_id: task.task_id,\n\t\t\t\t\t\tagent_type: task.agent_type,\n\t\t\t\t\t\tevent: action.event,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\tproc.stderr?.on(\"data\", (data: Buffer) => {\n\t\t\tstderr += data.toString();\n\t\t});\n\n\t\twaitForChildProcess(proc)\n\t\t\t.then((code) => {\n\t\t\t\tthis.slots.delete(task.task_id);\n\t\t\t\tdetachStdoutReader?.();\n\t\t\t\tbudget.flush();\n\n\t\t\t\tconst killReason = this.killReasons.get(task.task_id);\n\t\t\t\tthis.killReasons.delete(task.task_id);\n\n\t\t\t\tconst duration = Date.now() - slot.spawned_at;\n\t\t\t\tconst tokens_used = budget.getUsed();\n\t\t\t\tconst budgetExceeded = budget.isExceeded();\n\n\t\t\t\t// A subagent's success is defined by a valid, verified result.json, not by\n\t\t\t\t// its exit code. A child that finished its work and wrote a valid result can\n\t\t\t\t// still be SIGKILLed by the lifeguard before it exits on its own (lingering\n\t\t\t\t// open handles delay a natural exit past the heartbeat threshold), which forces\n\t\t\t\t// exit_code === null. Keying completion off the verified result, not code === 0,\n\t\t\t\t// honors that genuine success instead of discarding it as a false stall.\n\t\t\t\tconst verification = this.verifier.verify(task.task_id, task.cwd ?? this.cwd);\n\t\t\t\t// A well-formed result.json counts as clean completion unless its own\n\t\t\t\t// status field declares failure (e.g. \"failed\" from a provider quota\n\t\t\t\t// error). Without this check the pool would treat a child that wrote a\n\t\t\t\t// valid-but-failed result.json and exited non-zero as a success.\n\t\t\t\tlet cleanlyCompleted = code === 0 || verification.valid;\n\t\t\t\tif (cleanlyCompleted && verification.valid) {\n\t\t\t\t\tconst rd = this.tryReadResultJson(task.task_id, task.cwd ?? this.cwd);\n\t\t\t\t\tif (rd && (rd as Record<string, unknown>).status === \"failed\") {\n\t\t\t\t\t\tcleanlyCompleted = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// If killed by lifeguard before producing a valid result, honor the kill.\n\t\t\t\tif ((killReason === \"stalled\" || killReason === \"timeout\") && !verification.valid) {\n\t\t\t\t\tconst result: SubagentResult = {\n\t\t\t\t\t\ttask_id: task.task_id,\n\t\t\t\t\t\tok: false,\n\t\t\t\t\t\tstdout,\n\t\t\t\t\t\tstderr,\n\t\t\t\t\t\texit_code: code,\n\t\t\t\t\t\tstatus: killReason,\n\t\t\t\t\t};\n\t\t\t\t\tthis.writeOutputJson(task.task_id, result);\n\t\t\t\t\tthis.emit(`task_${killReason}`, {\n\t\t\t\t\t\ttask_id: task.task_id,\n\t\t\t\t\t\tagent_type: task.agent_type,\n\t\t\t\t\t\tduration,\n\t\t\t\t\t\ttokens_used,\n\t\t\t\t\t});\n\t\t\t\t\tthis.resolveWaiter(task.task_id, result);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst result: SubagentResult = {\n\t\t\t\t\ttask_id: task.task_id,\n\t\t\t\t\tok: cleanlyCompleted,\n\t\t\t\t\tstdout,\n\t\t\t\t\tstderr,\n\t\t\t\t\texit_code: code,\n\t\t\t\t\t// Advisory telemetry only: exceeding the budget never fails the task.\n\t\t\t\t\tbudget_exceeded: budgetExceeded,\n\t\t\t\t\tstatus: cleanlyCompleted ? \"complete\" : \"failed\",\n\t\t\t\t\tusedInheritedModelFallback: task.useInheritedModelFallback === true,\n\t\t\t\t};\n\n\t\t\t\tif (result.ok) {\n\t\t\t\t\tif (!verification.valid) {\n\t\t\t\t\t\tresult.ok = false;\n\t\t\t\t\t\tresult.error = verification.reason;\n\t\t\t\t\t\tresult.status = \"failed\";\n\t\t\t\t\t\tthis.writeOutputJson(task.task_id, result);\n\t\t\t\t\t\tthis.emit(\"task_failed\", {\n\t\t\t\t\t\t\ttask_id: task.task_id,\n\t\t\t\t\t\t\tagent_type: task.agent_type,\n\t\t\t\t\t\t\tduration,\n\t\t\t\t\t\t\ttokens_used,\n\t\t\t\t\t\t\terror: verification.reason,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tthis.resolveWaiter(task.task_id, result);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\t// Attach the verified result.json so callers can read the summary\n\t\t\t\t\t// without parsing the raw event stream.\n\t\t\t\t\tresult.result_data = this.tryReadResultJson(task.task_id, task.cwd ?? this.cwd);\n\n\t\t\t\t\t// Clean success: discard the per-task dispatch dir entirely\n\t\t\t\t\t// (session.jsonl, result.json, dispatch-log.json, budget.json). The\n\t\t\t\t\t// in-memory result already carries result_data, so callers lose\n\t\t\t\t\t// nothing. Trade-off: resume() only works for non-successful tasks.\n\t\t\t\t\tthis.cleanupDispatchDir(task.task_id, task.cwd ?? this.cwd);\n\n\t\t\t\t\tthis.emit(\"task_done\", {\n\t\t\t\t\t\ttask_id: task.task_id,\n\t\t\t\t\t\tagent_type: task.agent_type,\n\t\t\t\t\t\tduration,\n\t\t\t\t\t\ttokens_used,\n\t\t\t\t\t\tstatus: \"complete\",\n\t\t\t\t\t});\n\t\t\t\t\tthis.resolveWaiter(task.task_id, result);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// Failure path: keep the dispatch dir for debugging and persist output.\n\t\t\t\t// Attach the child's result.json (if any) and derive a concrete failure\n\t\t\t\t// reason so callers see the real cause (e.g. a provider usage/quota\n\t\t\t\t// error) instead of a generic \"subagent failed\".\n\t\t\t\tresult.result_data = this.tryReadResultJson(task.task_id, task.cwd ?? this.cwd);\n\t\t\t\tif (!result.error) {\n\t\t\t\t\tresult.error = this.deriveFailureReason(result);\n\t\t\t\t}\n\t\t\t\tif (this.shouldRetryWithInheritedModel(task, result)) {\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t`[DISPATCH] agent=${task.agent_type} task_id=${task.task_id} preferred model failed; retrying with inherited model`,\n\t\t\t\t\t);\n\t\t\t\t\tthis.cleanupRetryArtifacts(task);\n\t\t\t\t\tthis.queue.unshift({ ...task, useInheritedModelFallback: true });\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthis.writeOutputJson(task.task_id, result);\n\t\t\t\tthis.emit(\"task_failed\", {\n\t\t\t\t\ttask_id: task.task_id,\n\t\t\t\t\tagent_type: task.agent_type,\n\t\t\t\t\tduration,\n\t\t\t\t\ttokens_used,\n\t\t\t\t\terror: result.error ?? `Exited with code ${code}`,\n\t\t\t\t});\n\t\t\t\tthis.resolveWaiter(task.task_id, result);\n\t\t\t})\n\t\t\t.catch((err) => {\n\t\t\t\tthis.slots.delete(task.task_id);\n\t\t\t\tbudget.flush();\n\t\t\t\tconst duration = Date.now() - slot.spawned_at;\n\t\t\t\tconst tokens_used = budget.getUsed();\n\t\t\t\tif (!isRetry) {\n\t\t\t\t\tthis.startTask(task, true);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst error = err instanceof Error ? err.message : String(err);\n\t\t\t\tconst result: SubagentResult = {\n\t\t\t\t\ttask_id: task.task_id,\n\t\t\t\t\tok: false,\n\t\t\t\t\tstdout,\n\t\t\t\t\tstderr,\n\t\t\t\t\texit_code: null,\n\t\t\t\t\terror,\n\t\t\t\t\tstatus: \"failed\",\n\t\t\t\t\tusedInheritedModelFallback: task.useInheritedModelFallback === true,\n\t\t\t\t};\n\t\t\t\tthis.writeOutputJson(task.task_id, result);\n\t\t\t\tthis.emit(\"task_failed\", {\n\t\t\t\t\ttask_id: task.task_id,\n\t\t\t\t\tagent_type: task.agent_type,\n\t\t\t\t\tduration,\n\t\t\t\t\ttokens_used,\n\t\t\t\t\terror,\n\t\t\t\t});\n\t\t\t\tthis.resolveWaiter(task.task_id, result);\n\t\t\t})\n\t\t\t.finally(() => {\n\t\t\t\tbudget.removeAllListeners();\n\t\t\t\tthis.budgets.delete(task.task_id);\n\t\t\t\tthis.pull();\n\t\t\t});\n\t}\n\n\t/** Whether a failed built-in subagent should be retried with `model: inherit`. */\n\tprivate shouldRetryWithInheritedModel(task: SubagentPoolTask, result: SubagentResult): boolean {\n\t\tif (task.useInheritedModelFallback) return false;\n\t\tif (task.sessionFile) return false;\n\t\t// Only the parent model is required: the provider may be unset when the\n\t\t// harness routes through a gateway. The retry inherits the parent model and\n\t\t// lets the child resolve the provider from its own default when none was threaded through.\n\t\tif (!task.model) return false;\n\n\t\tconst def = task.agent_type ? this.getRegistry().get(task.agent_type) : undefined;\n\t\t// Built-in agents always inherit; project agents may pin an explicit model in\n\t\t// frontmatter, so let them fall back too when that model is rejected.\n\t\tif (def?.source !== \"builtin\" && def?.source !== \"project\") return false;\n\t\tif (!def.model || def.model === MODEL_INHERIT) return false;\n\n\t\treturn this.isInheritedModelFallbackError(result);\n\t}\n\n\t/** Detect provider/model failures where inheriting the parent model can recover. */\n\tprivate isInheritedModelFallbackError(result: SubagentResult): boolean {\n\t\tconst text = [result.error, result.stderr, JSON.stringify(result.result_data ?? {})]\n\t\t\t.filter((part): part is string => typeof part === \"string\" && part.length > 0)\n\t\t\t.join(\"\\n\");\n\n\t\treturn INHERITED_MODEL_FALLBACK_ERROR.test(text);\n\t}\n\n\t/** Remove failed attempt artifacts before rerunning the same task id. */\n\tprivate cleanupRetryArtifacts(task: SubagentPoolTask): void {\n\t\tconst cwd = task.cwd ?? this.cwd;\n\t\tconst taskDir = getDispatchTaskDir(cwd, task.task_id);\n\t\tconst sessionFile = task.sessionFile ?? this.getSessionFile(task.task_id, cwd);\n\t\ttry {\n\t\t\trmSync(sessionFile, { force: true });\n\t\t\trmSync(join(taskDir, \"result.json\"), { force: true });\n\t\t\trmSync(join(taskDir, \"output.json\"), { force: true });\n\t\t} catch {\n\t\t\t// Best-effort cleanup; retry can still proceed with existing artifacts.\n\t\t}\n\t}\n\n\t/**\n\t * Best-effort concrete failure reason for a non-zero-exit subagent. Prefers\n\t * the child's result.json summary (which carries the provider/model error\n\t * message on failure), then the tail of stderr, then the exit code.\n\t */\n\tprivate deriveFailureReason(result: SubagentResult): string {\n\t\tconst summary = (result.result_data as { summary?: string } | undefined)?.summary?.trim();\n\t\tif (summary) {\n\t\t\treturn summary;\n\t\t}\n\t\tconst stderrTail = result.stderr\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => line.trim())\n\t\t\t.filter((line) => line.length > 0)\n\t\t\t.slice(-5)\n\t\t\t.join(\"\\n\");\n\t\tif (stderrTail) {\n\t\t\treturn stderrTail;\n\t\t}\n\t\treturn `Exited with code ${result.exit_code}`;\n\t}\n\n\tprivate tryReadResultJson(task_id: string, cwd: string): Record<string, unknown> | undefined {\n\t\tconst path = join(getDispatchTaskDir(cwd, task_id), \"result.json\");\n\t\tif (!existsSync(path)) return undefined;\n\t\ttry {\n\t\t\tconst raw = readFileSync(path, \"utf-8\");\n\t\t\treturn JSON.parse(raw) as Record<string, unknown>;\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\tprivate resolveWaiter(task_id: string, result: SubagentResult): void {\n\t\t// Persist terminal status for get_status() even after wait_for consumes the result\n\t\tif (result.status === \"stalled\") this.taskStatus.set(task_id, \"stalled\");\n\t\telse if (result.status === \"timeout\") this.taskStatus.set(task_id, \"timeout\");\n\t\telse if (result.ok) this.taskStatus.set(task_id, \"done\");\n\t\telse this.taskStatus.set(task_id, \"failed\");\n\n\t\tconst waiter = this.waiters.get(task_id);\n\t\tif (waiter) {\n\t\t\twaiter.resolve(result);\n\t\t\tthis.waiters.delete(task_id);\n\t\t\treturn;\n\t\t}\n\t\tthis.completed.set(task_id, result);\n\t}\n}\n"]}
|