@kolisachint/hoocode-agent 0.4.111 → 0.4.113

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.
Files changed (75) hide show
  1. package/CHANGELOG.md +73 -0
  2. package/dist/cli/args.d.ts +1 -0
  3. package/dist/cli/args.d.ts.map +1 -1
  4. package/dist/cli/args.js +8 -3
  5. package/dist/cli/args.js.map +1 -1
  6. package/dist/core/extensions/loader.d.ts +10 -1
  7. package/dist/core/extensions/loader.d.ts.map +1 -1
  8. package/dist/core/extensions/loader.js +17 -2
  9. package/dist/core/extensions/loader.js.map +1 -1
  10. package/dist/core/extensions/plugins/marketplace.d.ts +36 -5
  11. package/dist/core/extensions/plugins/marketplace.d.ts.map +1 -1
  12. package/dist/core/extensions/plugins/marketplace.js +63 -17
  13. package/dist/core/extensions/plugins/marketplace.js.map +1 -1
  14. package/dist/core/scheduler.d.ts +8 -2
  15. package/dist/core/scheduler.d.ts.map +1 -1
  16. package/dist/core/scheduler.js +9 -3
  17. package/dist/core/scheduler.js.map +1 -1
  18. package/dist/core/settings-defaults.d.ts +1 -1
  19. package/dist/core/settings-defaults.d.ts.map +1 -1
  20. package/dist/core/settings-defaults.js +2 -2
  21. package/dist/core/settings-defaults.js.map +1 -1
  22. package/dist/core/settings-types.d.ts.map +1 -1
  23. package/dist/core/settings-types.js.map +1 -1
  24. package/dist/core/subagent-events.d.ts +21 -0
  25. package/dist/core/subagent-events.d.ts.map +1 -0
  26. package/dist/core/subagent-events.js +25 -0
  27. package/dist/core/subagent-events.js.map +1 -0
  28. package/dist/core/subagent-pool.d.ts +5 -4
  29. package/dist/core/subagent-pool.d.ts.map +1 -1
  30. package/dist/core/subagent-pool.js +7 -9
  31. package/dist/core/subagent-pool.js.map +1 -1
  32. package/dist/core/tools/subagent.d.ts +15 -3
  33. package/dist/core/tools/subagent.d.ts.map +1 -1
  34. package/dist/core/tools/subagent.js +27 -14
  35. package/dist/core/tools/subagent.js.map +1 -1
  36. package/dist/extensions/core/loop.d.ts.map +1 -1
  37. package/dist/extensions/core/loop.js +4 -1
  38. package/dist/extensions/core/loop.js.map +1 -1
  39. package/dist/extensions/core/marketplace.d.ts +5 -3
  40. package/dist/extensions/core/marketplace.d.ts.map +1 -1
  41. package/dist/extensions/core/marketplace.js +37 -15
  42. package/dist/extensions/core/marketplace.js.map +1 -1
  43. package/dist/modes/interactive/components/assistant-message.d.ts +27 -1
  44. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  45. package/dist/modes/interactive/components/assistant-message.js +150 -7
  46. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  47. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
  48. package/dist/modes/interactive/components/custom-editor.js +18 -0
  49. package/dist/modes/interactive/components/custom-editor.js.map +1 -1
  50. package/dist/modes/interactive/components/task-panel.d.ts.map +1 -1
  51. package/dist/modes/interactive/components/task-panel.js +5 -2
  52. package/dist/modes/interactive/components/task-panel.js.map +1 -1
  53. package/dist/modes/interactive/components/tool-execution.d.ts +17 -0
  54. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  55. package/dist/modes/interactive/components/tool-execution.js +78 -5
  56. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  57. package/dist/modes/interactive/components/user-message.d.ts +4 -0
  58. package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
  59. package/dist/modes/interactive/components/user-message.js +12 -3
  60. package/dist/modes/interactive/components/user-message.js.map +1 -1
  61. package/dist/modes/interactive/interactive-mode.d.ts +12 -0
  62. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  63. package/dist/modes/interactive/interactive-mode.js +75 -4
  64. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  65. package/dist/modes/interactive/voice/voice-controller.d.ts.map +1 -1
  66. package/dist/modes/interactive/voice/voice-controller.js +9 -5
  67. package/dist/modes/interactive/voice/voice-controller.js.map +1 -1
  68. package/dist/modes/print-mode.d.ts.map +1 -1
  69. package/dist/modes/print-mode.js +10 -3
  70. package/dist/modes/print-mode.js.map +1 -1
  71. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  72. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  73. package/examples/extensions/sandbox/package.json +1 -1
  74. package/examples/extensions/with-deps/package.json +1 -1
  75. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"scheduler.js","sourceRoot":"","sources":["../../src/core/scheduler.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC7E,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAepC,oEAAoE;AACpE,SAAS,UAAU,CAAC,KAAa,EAAE,GAAW,EAAE,GAAW,EAA8B;IACxF,IAAI,KAAK,KAAK,GAAG;QAAE,OAAO,GAAG,EAAE,CAAC,IAAI,CAAC;IAErC,MAAM,OAAO,GAAG,IAAI,GAAG,EAAU,CAAC;IAClC,KAAK,MAAM,IAAI,IAAI,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC;QACrC,4BAA4B;QAC5B,MAAM,CAAC,KAAK,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QACzC,MAAM,IAAI,GAAG,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QACxD,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,IAAI,GAAG,CAAC;YAAE,SAAS;QAEjD,IAAI,EAAE,GAAG,GAAG,CAAC;QACb,IAAI,EAAE,GAAG,GAAG,CAAC;QACb,IAAI,KAAK,IAAI,KAAK,KAAK,GAAG,EAAE,CAAC;YAC5B,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,GAAG,KAA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ler — cron-driven recurring/one-shot prompts.\n *\n * Backs the `/loop` command and the Cron* tools. Tasks are matched against a\n * standard 5-field cron expression (minute hour day-of-month month day-of-week)\n * in local time and fired by re-submitting their prompt as a user message.\n * Firing is idle-gated so a task never interrupts an in-flight turn; a task due\n * while the agent is busy is picked up on a later tick within the same minute.\n *\n * Recurring tasks persist; one-shot tasks delete themselves after firing.\n */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\n\nexport interface ScheduledTask {\n\tid: string;\n\t/** 5-field cron expression in local time. */\n\tcron: string;\n\t/** Prompt re-submitted on each fire. */\n\tprompt: string;\n\t/** Recurring (fire on every match) vs one-shot (fire once, then delete). */\n\trecurring: boolean;\n\tcreatedAt: number;\n\t/** Minute-bucket key of the last fire, to avoid double-firing within a minute. */\n\tlastRunMinute?: number;\n}\n\n/** Parse one cron field into a predicate over its numeric value. */\nfunction parseField(field: string, min: number, max: number): (value: number) => boolean {\n\tif (field === \"*\") return () => true;\n\n\tconst allowed = new Set<number>();\n\tfor (const part of field.split(\",\")) {\n\t\t// step: */n or a-b/n or a/n\n\t\tconst [range, stepStr] = part.split(\"/\");\n\t\tconst step = stepStr ? Number.parseInt(stepStr, 10) : 1;\n\t\tif (!Number.isFinite(step) || step < 1) continue;\n\n\t\tlet lo = min;\n\t\tlet hi = max;\n\t\tif (range && range !== \"*\") {\n\t\t\tconst [a, b] = range.split(\"-\");\n\t\t\tlo = Number.parseInt(a, 10);\n\t\t\thi = b !== undefined ? Number.parseInt(b, 10) : lo;\n\t\t\tif (!Number.isFinite(lo) || !Number.isFinite(hi)) continue;\n\t\t}\n\t\tfor (let v = lo; v <= hi; v += step) {\n\t\t\tif (v >= min && v <= max) allowed.add(v);\n\t\t}\n\t}\n\treturn (value: number) => allowed.has(value);\n}\n\n/** True when `date` matches the 5-field cron expression. Invalid expressions never match. */\nexport function matchesCron(expr: string, date: Date): boolean {\n\tconst fields = expr.trim().split(/\\s+/);\n\tif (fields.length !== 5) return false;\n\n\tconst [m, h, dom, mon, dow] = fields;\n\tconst minute = parseField(m, 0, 59)(date.getMinutes());\n\tconst hour = parseField(h, 0, 23)(date.getHours());\n\tconst month = parseField(mon, 1, 12)(date.getMonth() + 1);\n\t// day-of-week: cron allows 0 or 7 for Sunday; normalize 7→0.\n\tconst dowVal = date.getDay();\n\tconst domField = parseField(dom, 1, 31);\n\tconst dowField = parseField(dow.replace(/7/g, \"0\"), 0, 6);\n\n\tif (!(minute && hour && month)) return false;\n\n\t// Standard cron semantics: when both DOM and DOW are restricted, match either.\n\tconst domRestricted = dom !== \"*\";\n\tconst dowRestricted = dow !== \"*\";\n\tif (domRestricted && dowRestricted) {\n\t\treturn domField(date.getDate()) || dowField(dowVal);\n\t}\n\treturn domField(date.getDate()) && dowField(dowVal);\n}\n\nlet idCounter = 0;\nfunction newId(): string {\n\tidCounter += 1;\n\treturn `task_${Date.now().toString(36)}${idCounter.toString(36)}`;\n}\n\nexport interface TaskSchedulerOptions {\n\t/** Path to the durable JSON store. */\n\tstorePath: string;\n\t/** Submit a due task's prompt (e.g. via sendUserMessage). */\n\tfire: (prompt: string) => void;\n\t/** Whether the agent is idle; tasks only fire when true. Defaults to always-idle. */\n\tisIdle?: () => boolean;\n\t/** Tick interval in ms. Defaults to 30s. */\n\tintervalMs?: number;\n}\n\nexport class TaskScheduler {\n\tprivate tasks: ScheduledTask[] = [];\n\tprivate timer: ReturnType<typeof setInterval> | undefined;\n\tprivate readonly opts: Required<Pick<TaskSchedulerOptions, \"storePath\" | \"fire\">> &\n\t\tPick<TaskSchedulerOptions, \"isIdle\" | \"intervalMs\">;\n\n\tconstructor(opts: TaskSchedulerOptions) {\n\t\tthis.opts = opts;\n\t\tthis.load();\n\t}\n\n\t/** Load persisted tasks from disk (best-effort). */\n\tload(): void {\n\t\ttry {\n\t\t\tif (existsSync(this.opts.storePath)) {\n\t\t\t\tconst parsed = JSON.parse(readFileSync(this.opts.storePath, \"utf8\")) as { tasks?: ScheduledTask[] };\n\t\t\t\tthis.tasks = Array.isArray(parsed.tasks) ? parsed.tasks : [];\n\t\t\t}\n\t\t} catch {\n\t\t\tthis.tasks = [];\n\t\t}\n\t}\n\n\tprivate persist(): void {\n\t\ttry {\n\t\t\tmkdirSync(dirname(this.opts.storePath), { recursive: true });\n\t\t\twriteFileSync(this.opts.storePath, `${JSON.stringify({ tasks: this.tasks }, null, 2)}\\n`, \"utf8\");\n\t\t} catch {\n\t\t\t// best-effort persistence\n\t\t}\n\t}\n\n\t/** Begin the tick loop. Safe to call once. */\n\tstart(): void {\n\t\tif (this.timer) return;\n\t\tthis.timer = setInterval(() => this.tick(new Date()), this.opts.intervalMs ?? 30_000);\n\t\tthis.timer.unref?.();\n\t}\n\n\tstop(): void {\n\t\tif (this.timer) {\n\t\t\tclearInterval(this.timer);\n\t\t\tthis.timer = undefined;\n\t\t}\n\t}\n\n\tcreate(input: { cron: string; prompt: string; recurring?: boolean }): ScheduledTask {\n\t\tconst task: ScheduledTask = {\n\t\t\tid: newId(),\n\t\t\tcron: input.cron,\n\t\t\tprompt: input.prompt,\n\t\t\trecurring: input.recurring ?? true,\n\t\t\tcreatedAt: Date.now(),\n\t\t};\n\t\tthis.tasks.push(task);\n\t\tthis.persist();\n\t\treturn task;\n\t}\n\n\tlist(): ScheduledTask[] {\n\t\treturn [...this.tasks];\n\t}\n\n\tdelete(id: string): boolean {\n\t\tconst before = this.tasks.length;\n\t\tthis.tasks = this.tasks.filter((t) => t.id !== id);\n\t\tconst removed = this.tasks.length < before;\n\t\tif (removed) this.persist();\n\t\treturn removed;\n\t}\n\n\tclear(): void {\n\t\tif (this.tasks.length === 0) return;\n\t\tthis.tasks = [];\n\t\tthis.persist();\n\t}\n\n\t/** Evaluate all tasks against `now` and fire those that are due (when idle). */\n\ttick(now: Date): void {\n\t\tconst idle = this.opts.isIdle ? this.opts.isIdle() : true;\n\t\tif (!idle) return;\n\n\t\tconst minuteKey = Math.floor(now.getTime() / 60_000);\n\t\tlet mutated = false;\n\t\tconst toDelete: string[] = [];\n\n\t\tfor (const task of this.tasks) {\n\t\t\tif (task.lastRunMinute === minuteKey) continue;\n\t\t\tif (!matchesCron(task.cron, now)) continue;\n\n\t\t\ttask.lastRunMinute = minuteKey;\n\t\t\tmutated = true;\n\t\t\tthis.opts.fire(task.prompt);\n\t\t\tif (!task.recurring) toDelete.push(task.id);\n\t\t}\n\n\t\tif (toDelete.length > 0) {\n\t\t\tthis.tasks = this.tasks.filter((t) => !toDelete.includes(t.id));\n\t\t}\n\t\tif (mutated || toDelete.length > 0) this.persist();\n\t}\n}\n"]}
1
+ {"version":3,"file":"scheduler.js","sourceRoot":"","sources":["../../src/core/scheduler.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC7E,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAepC,oEAAoE;AACpE,SAAS,UAAU,CAAC,KAAa,EAAE,GAAW,EAAE,GAAW,EAA8B;IACxF,IAAI,KAAK,KAAK,GAAG;QAAE,OAAO,GAAG,EAAE,CAAC,IAAI,CAAC;IAErC,MAAM,OAAO,GAAG,IAAI,GAAG,EAAU,CAAC;IAClC,KAAK,MAAM,IAAI,IAAI,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC;QACrC,4BAA4B;QAC5B,MAAM,CAAC,KAAK,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QACzC,MAAM,IAAI,GAAG,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,QAAQ,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QACxD,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,IAAI,GAAG,CAAC;YAAE,SAAS;QAEjD,IAAI,EAAE,GAAG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C,SAAS;gBAAE,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QAC7C,CAAC;QAED,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACzB,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;QACjE,CAAC;QACD,IAAI,OAAO,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC;YAAE,IAAI,CAAC,OAAO,EAAE,CAAC;IAAA,CACnD;CACD","sourcesContent":["/**\n * Task scheduler — cron-driven recurring/one-shot prompts.\n *\n * Backs the `/loop` command and the Cron* tools. Tasks are matched against a\n * standard 5-field cron expression (minute hour day-of-month month day-of-week)\n * in local time and fired by re-submitting their prompt as a user message.\n * Firing is idle-gated so a task never interrupts an in-flight turn; a task due\n * while the agent is busy is picked up on a later tick within the same minute.\n *\n * Recurring tasks persist; one-shot tasks delete themselves after firing.\n */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\n\nexport interface ScheduledTask {\n\tid: string;\n\t/** 5-field cron expression in local time. */\n\tcron: string;\n\t/** Prompt re-submitted on each fire. */\n\tprompt: string;\n\t/** Recurring (fire on every match) vs one-shot (fire once, then delete). */\n\trecurring: boolean;\n\tcreatedAt: number;\n\t/** Minute-bucket key of the last fire, to avoid double-firing within a minute. */\n\tlastRunMinute?: number;\n}\n\n/** Parse one cron field into a predicate over its numeric value. */\nfunction parseField(field: string, min: number, max: number): (value: number) => boolean {\n\tif (field === \"*\") return () => true;\n\n\tconst allowed = new Set<number>();\n\tfor (const part of field.split(\",\")) {\n\t\t// step: */n or a-b/n or a/n\n\t\tconst [range, stepStr] = part.split(\"/\");\n\t\tconst step = stepStr ? Number.parseInt(stepStr, 10) : 1;\n\t\tif (!Number.isFinite(step) || step < 1) continue;\n\n\t\tlet lo = min;\n\t\tlet hi = max;\n\t\tif (range && range !== \"*\") {\n\t\t\tconst [a, b] = range.split(\"-\");\n\t\t\tlo = Number.parseInt(a, 10);\n\t\t\thi = b !== undefined ? Number.parseInt(b, 10) : lo;\n\t\t\tif (!Number.isFinite(lo) || !Number.isFinite(hi)) continue;\n\t\t}\n\t\tfor (let v = lo; v <= hi; v += step) {\n\t\t\tif (v >= min && v <= max) allowed.add(v);\n\t\t}\n\t}\n\treturn (value: number) => allowed.has(value);\n}\n\n/** True when `date` matches the 5-field cron expression. Invalid expressions never match. */\nexport function matchesCron(expr: string, date: Date): boolean {\n\tconst fields = expr.trim().split(/\\s+/);\n\tif (fields.length !== 5) return false;\n\n\tconst [m, h, dom, mon, dow] = fields;\n\tconst minute = parseField(m, 0, 59)(date.getMinutes());\n\tconst hour = parseField(h, 0, 23)(date.getHours());\n\tconst month = parseField(mon, 1, 12)(date.getMonth() + 1);\n\t// day-of-week: cron allows 0 or 7 for Sunday; normalize 7→0.\n\tconst dowVal = date.getDay();\n\tconst domField = parseField(dom, 1, 31);\n\tconst dowField = parseField(dow.replace(/7/g, \"0\"), 0, 6);\n\n\tif (!(minute && hour && month)) return false;\n\n\t// Standard cron semantics: when both DOM and DOW are restricted, match either.\n\tconst domRestricted = dom !== \"*\";\n\tconst dowRestricted = dow !== \"*\";\n\tif (domRestricted && dowRestricted) {\n\t\treturn domField(date.getDate()) || dowField(dowVal);\n\t}\n\treturn domField(date.getDate()) && dowField(dowVal);\n}\n\nlet idCounter = 0;\nfunction newId(): string {\n\tidCounter += 1;\n\treturn `task_${Date.now().toString(36)}${idCounter.toString(36)}`;\n}\n\nexport interface TaskSchedulerOptions {\n\t/** Path to the durable JSON store (written on every mutation). */\n\tstorePath: string;\n\t/**\n\t * Legacy store path read only when {@link storePath} does not yet exist, so\n\t * tasks scheduled under an older location migrate forward on first persist.\n\t */\n\tlegacyStorePath?: string;\n\t/** Submit a due task's prompt (e.g. via sendUserMessage). */\n\tfire: (prompt: string) => void;\n\t/** Whether the agent is idle; tasks only fire when true. Defaults to always-idle. */\n\tisIdle?: () => boolean;\n\t/** Tick interval in ms. Defaults to 30s. */\n\tintervalMs?: number;\n}\n\nexport class TaskScheduler {\n\tprivate tasks: ScheduledTask[] = [];\n\tprivate timer: ReturnType<typeof setInterval> | undefined;\n\tprivate readonly opts: Required<Pick<TaskSchedulerOptions, \"storePath\" | \"fire\">> &\n\t\tPick<TaskSchedulerOptions, \"isIdle\" | \"intervalMs\" | \"legacyStorePath\">;\n\n\tconstructor(opts: TaskSchedulerOptions) {\n\t\tthis.opts = opts;\n\t\tthis.load();\n\t}\n\n\t/** Load persisted tasks from disk (best-effort). Falls back to the legacy\n\t * store path when the primary one does not exist yet. */\n\tload(): void {\n\t\tconst source =\n\t\t\texistsSync(this.opts.storePath) || !this.opts.legacyStorePath\n\t\t\t\t? this.opts.storePath\n\t\t\t\t: existsSync(this.opts.legacyStorePath)\n\t\t\t\t\t? this.opts.legacyStorePath\n\t\t\t\t\t: this.opts.storePath;\n\t\ttry {\n\t\t\tif (existsSync(source)) {\n\t\t\t\tconst parsed = JSON.parse(readFileSync(source, \"utf8\")) as { tasks?: ScheduledTask[] };\n\t\t\t\tthis.tasks = Array.isArray(parsed.tasks) ? parsed.tasks : [];\n\t\t\t}\n\t\t} catch {\n\t\t\tthis.tasks = [];\n\t\t}\n\t}\n\n\tprivate persist(): void {\n\t\ttry {\n\t\t\tmkdirSync(dirname(this.opts.storePath), { recursive: true });\n\t\t\twriteFileSync(this.opts.storePath, `${JSON.stringify({ tasks: this.tasks }, null, 2)}\\n`, \"utf8\");\n\t\t} catch {\n\t\t\t// best-effort persistence\n\t\t}\n\t}\n\n\t/** Begin the tick loop. Safe to call once. */\n\tstart(): void {\n\t\tif (this.timer) return;\n\t\tthis.timer = setInterval(() => this.tick(new Date()), this.opts.intervalMs ?? 30_000);\n\t\tthis.timer.unref?.();\n\t}\n\n\tstop(): void {\n\t\tif (this.timer) {\n\t\t\tclearInterval(this.timer);\n\t\t\tthis.timer = undefined;\n\t\t}\n\t}\n\n\tcreate(input: { cron: string; prompt: string; recurring?: boolean }): ScheduledTask {\n\t\tconst task: ScheduledTask = {\n\t\t\tid: newId(),\n\t\t\tcron: input.cron,\n\t\t\tprompt: input.prompt,\n\t\t\trecurring: input.recurring ?? true,\n\t\t\tcreatedAt: Date.now(),\n\t\t};\n\t\tthis.tasks.push(task);\n\t\tthis.persist();\n\t\treturn task;\n\t}\n\n\tlist(): ScheduledTask[] {\n\t\treturn [...this.tasks];\n\t}\n\n\tdelete(id: string): boolean {\n\t\tconst before = this.tasks.length;\n\t\tthis.tasks = this.tasks.filter((t) => t.id !== id);\n\t\tconst removed = this.tasks.length < before;\n\t\tif (removed) this.persist();\n\t\treturn removed;\n\t}\n\n\tclear(): void {\n\t\tif (this.tasks.length === 0) return;\n\t\tthis.tasks = [];\n\t\tthis.persist();\n\t}\n\n\t/** Evaluate all tasks against `now` and fire those that are due (when idle). */\n\ttick(now: Date): void {\n\t\tconst idle = this.opts.isIdle ? this.opts.isIdle() : true;\n\t\tif (!idle) return;\n\n\t\tconst minuteKey = Math.floor(now.getTime() / 60_000);\n\t\tlet mutated = false;\n\t\tconst toDelete: string[] = [];\n\n\t\tfor (const task of this.tasks) {\n\t\t\tif (task.lastRunMinute === minuteKey) continue;\n\t\t\tif (!matchesCron(task.cron, now)) continue;\n\n\t\t\ttask.lastRunMinute = minuteKey;\n\t\t\tmutated = true;\n\t\t\tthis.opts.fire(task.prompt);\n\t\t\tif (!task.recurring) toDelete.push(task.id);\n\t\t}\n\n\t\tif (toDelete.length > 0) {\n\t\t\tthis.tasks = this.tasks.filter((t) => !toDelete.includes(t.id));\n\t\t}\n\t\tif (mutated || toDelete.length > 0) this.persist();\n\t}\n}\n"]}
@@ -24,7 +24,7 @@ export declare const DEFAULT_SETTINGS: {
24
24
  collapseChangelog: false;
25
25
  enableInstallTelemetry: true;
26
26
  enableSkillCommands: true;
27
- enableSubagent: false;
27
+ enableSubagent: true;
28
28
  warmSubagents: false;
29
29
  maxSubagentDepth: number;
30
30
  nestedSubagentConcurrency: number;
@@ -1 +1 @@
1
- {"version":3,"file":"settings-defaults.d.ts","sourceRoot":"","sources":["../../src/core/settings-defaults.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6DT,CAAC","sourcesContent":["import type { Settings } from \"./settings-manager.js\";\n\nexport const DEFAULT_SETTINGS = {\n\ttransport: \"auto\",\n\tsteeringMode: \"one-at-a-time\",\n\tfollowUpMode: \"one-at-a-time\",\n\tcompaction: {\n\t\tenabled: true,\n\t\treserveTokens: 16384,\n\t\tkeepRecentTokens: 20000,\n\t},\n\tbranchSummary: {\n\t\treserveTokens: 16384,\n\t\tskipPrompt: false,\n\t},\n\tretry: {\n\t\tenabled: true,\n\t\tmaxRetries: 3,\n\t\tbaseDelayMs: 2000,\n\t\tprovider: {\n\t\t\tmaxRetryDelayMs: 60000,\n\t\t},\n\t},\n\thideThinkingBlock: false,\n\tquietStartup: false,\n\tcollapseChangelog: false,\n\tenableInstallTelemetry: true,\n\tenableSkillCommands: true,\n\tenableSubagent: false,\n\twarmSubagents: false,\n\tmaxSubagentDepth: 1,\n\tnestedSubagentConcurrency: 2,\n\tenableTodoWrite: true,\n\tenableWebTools: false,\n\tenableBrowserTools: false,\n\tenableBrowserLivePreview: false,\n\tenableFileTools: false,\n\tterminal: {\n\t\tshowImages: true,\n\t\timageWidthCells: 60,\n\t\tclearOnShrink: false,\n\t\tshowTerminalProgress: false,\n\t},\n\timages: {\n\t\tautoResize: true,\n\t\tblockImages: false,\n\t},\n\tdoubleEscapeAction: \"tree\",\n\ttreeFilterMode: \"default\",\n\teditorPaddingX: 0,\n\tautocompleteMaxVisible: 5,\n\tmarkdown: {\n\t\tcodeBlockIndent: \" \",\n\t},\n\twarnings: {\n\t\tanthropicExtraUsage: true,\n\t},\n\tpackages: [],\n\textensions: [],\n\tskills: [],\n\tprompts: [],\n\tslashCommands: [],\n\tthemes: [],\n} satisfies Settings;\n"]}
1
+ {"version":3,"file":"settings-defaults.d.ts","sourceRoot":"","sources":["../../src/core/settings-defaults.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6DT,CAAC","sourcesContent":["import type { Settings } from \"./settings-manager.js\";\n\nexport const DEFAULT_SETTINGS = {\n\ttransport: \"auto\",\n\tsteeringMode: \"one-at-a-time\",\n\tfollowUpMode: \"one-at-a-time\",\n\tcompaction: {\n\t\tenabled: true,\n\t\treserveTokens: 16384,\n\t\tkeepRecentTokens: 20000,\n\t},\n\tbranchSummary: {\n\t\treserveTokens: 16384,\n\t\tskipPrompt: false,\n\t},\n\tretry: {\n\t\tenabled: true,\n\t\tmaxRetries: 3,\n\t\tbaseDelayMs: 2000,\n\t\tprovider: {\n\t\t\tmaxRetryDelayMs: 60000,\n\t\t},\n\t},\n\thideThinkingBlock: false,\n\tquietStartup: false,\n\tcollapseChangelog: false,\n\tenableInstallTelemetry: true,\n\tenableSkillCommands: true,\n\tenableSubagent: true,\n\twarmSubagents: false,\n\tmaxSubagentDepth: 2,\n\tnestedSubagentConcurrency: 2,\n\tenableTodoWrite: true,\n\tenableWebTools: false,\n\tenableBrowserTools: false,\n\tenableBrowserLivePreview: false,\n\tenableFileTools: false,\n\tterminal: {\n\t\tshowImages: true,\n\t\timageWidthCells: 60,\n\t\tclearOnShrink: false,\n\t\tshowTerminalProgress: false,\n\t},\n\timages: {\n\t\tautoResize: true,\n\t\tblockImages: false,\n\t},\n\tdoubleEscapeAction: \"tree\",\n\ttreeFilterMode: \"default\",\n\teditorPaddingX: 0,\n\tautocompleteMaxVisible: 5,\n\tmarkdown: {\n\t\tcodeBlockIndent: \" \",\n\t},\n\twarnings: {\n\t\tanthropicExtraUsage: true,\n\t},\n\tpackages: [],\n\textensions: [],\n\tskills: [],\n\tprompts: [],\n\tslashCommands: [],\n\tthemes: [],\n} satisfies Settings;\n"]}
@@ -24,9 +24,9 @@ export const DEFAULT_SETTINGS = {
24
24
  collapseChangelog: false,
25
25
  enableInstallTelemetry: true,
26
26
  enableSkillCommands: true,
27
- enableSubagent: false,
27
+ enableSubagent: true,
28
28
  warmSubagents: false,
29
- maxSubagentDepth: 1,
29
+ maxSubagentDepth: 2,
30
30
  nestedSubagentConcurrency: 2,
31
31
  enableTodoWrite: true,
32
32
  enableWebTools: false,
@@ -1 +1 @@
1
- {"version":3,"file":"settings-defaults.js","sourceRoot":"","sources":["../../src/core/settings-defaults.ts"],"names":[],"mappings":"AAEA,MAAM,CAAC,MAAM,gBAAgB,GAAG;IAC/B,SAAS,EAAE,MAAM;IACjB,YAAY,EAAE,eAAe;IAC7B,YAAY,EAAE,eAAe;IAC7B,UAAU,EAAE;QACX,OAAO,EAAE,IAAI;QACb,aAAa,EAAE,KAAK;QACpB,gBAAgB,EAAE,KAAK;KACvB;IACD,aAAa,EAAE;QACd,aAAa,EAAE,KAAK;QACpB,UAAU,EAAE,KAAK;KACjB;IACD,KAAK,EAAE;QACN,OAAO,EAAE,IAAI;QACb,UAAU,EAAE,CAAC;QACb,WAAW,EAAE,IAAI;QACjB,QAAQ,EAAE;YACT,eAAe,EAAE,KAAK;SACtB;KACD;IACD,iBAAiB,EAAE,KAAK;IACxB,YAAY,EAAE,KAAK;IACnB,iBAAiB,EAAE,KAAK;IACxB,sBAAsB,EAAE,IAAI;IAC5B,mBAAmB,EAAE,IAAI;IACzB,cAAc,EAAE,KAAK;IACrB,aAAa,EAAE,KAAK;IACpB,gBAAgB,EAAE,CAAC;IACnB,yBAAyB,EAAE,CAAC;IAC5B,eAAe,EAAE,IAAI;IACrB,cAAc,EAAE,KAAK;IACrB,kBAAkB,EAAE,KAAK;IACzB,wBAAwB,EAAE,KAAK;IAC/B,eAAe,EAAE,KAAK;IACtB,QAAQ,EAAE;QACT,UAAU,EAAE,IAAI;QAChB,eAAe,EAAE,EAAE;QACnB,aAAa,EAAE,KAAK;QACpB,oBAAoB,EAAE,KAAK;KAC3B;IACD,MAAM,EAAE;QACP,UAAU,EAAE,IAAI;QAChB,WAAW,EAAE,KAAK;KAClB;IACD,kBAAkB,EAAE,MAAM;IAC1B,cAAc,EAAE,SAAS;IACzB,cAAc,EAAE,CAAC;IACjB,sBAAsB,EAAE,CAAC;IACzB,QAAQ,EAAE;QACT,eAAe,EAAE,IAAI;KACrB;IACD,QAAQ,EAAE;QACT,mBAAmB,EAAE,IAAI;KACzB;IACD,QAAQ,EAAE,EAAE;IACZ,UAAU,EAAE,EAAE;IACd,MAAM,EAAE,EAAE;IACV,OAAO,EAAE,EAAE;IACX,aAAa,EAAE,EAAE;IACjB,MAAM,EAAE,EAAE;CACS,CAAC","sourcesContent":["import type { Settings } from \"./settings-manager.js\";\n\nexport const DEFAULT_SETTINGS = {\n\ttransport: \"auto\",\n\tsteeringMode: \"one-at-a-time\",\n\tfollowUpMode: \"one-at-a-time\",\n\tcompaction: {\n\t\tenabled: true,\n\t\treserveTokens: 16384,\n\t\tkeepRecentTokens: 20000,\n\t},\n\tbranchSummary: {\n\t\treserveTokens: 16384,\n\t\tskipPrompt: false,\n\t},\n\tretry: {\n\t\tenabled: true,\n\t\tmaxRetries: 3,\n\t\tbaseDelayMs: 2000,\n\t\tprovider: {\n\t\t\tmaxRetryDelayMs: 60000,\n\t\t},\n\t},\n\thideThinkingBlock: false,\n\tquietStartup: false,\n\tcollapseChangelog: false,\n\tenableInstallTelemetry: true,\n\tenableSkillCommands: true,\n\tenableSubagent: false,\n\twarmSubagents: false,\n\tmaxSubagentDepth: 1,\n\tnestedSubagentConcurrency: 2,\n\tenableTodoWrite: true,\n\tenableWebTools: false,\n\tenableBrowserTools: false,\n\tenableBrowserLivePreview: false,\n\tenableFileTools: false,\n\tterminal: {\n\t\tshowImages: true,\n\t\timageWidthCells: 60,\n\t\tclearOnShrink: false,\n\t\tshowTerminalProgress: false,\n\t},\n\timages: {\n\t\tautoResize: true,\n\t\tblockImages: false,\n\t},\n\tdoubleEscapeAction: \"tree\",\n\ttreeFilterMode: \"default\",\n\teditorPaddingX: 0,\n\tautocompleteMaxVisible: 5,\n\tmarkdown: {\n\t\tcodeBlockIndent: \" \",\n\t},\n\twarnings: {\n\t\tanthropicExtraUsage: true,\n\t},\n\tpackages: [],\n\textensions: [],\n\tskills: [],\n\tprompts: [],\n\tslashCommands: [],\n\tthemes: [],\n} satisfies Settings;\n"]}
1
+ {"version":3,"file":"settings-defaults.js","sourceRoot":"","sources":["../../src/core/settings-defaults.ts"],"names":[],"mappings":"AAEA,MAAM,CAAC,MAAM,gBAAgB,GAAG;IAC/B,SAAS,EAAE,MAAM;IACjB,YAAY,EAAE,eAAe;IAC7B,YAAY,EAAE,eAAe;IAC7B,UAAU,EAAE;QACX,OAAO,EAAE,IAAI;QACb,aAAa,EAAE,KAAK;QACpB,gBAAgB,EAAE,KAAK;KACvB;IACD,aAAa,EAAE;QACd,aAAa,EAAE,KAAK;QACpB,UAAU,EAAE,KAAK;KACjB;IACD,KAAK,EAAE;QACN,OAAO,EAAE,IAAI;QACb,UAAU,EAAE,CAAC;QACb,WAAW,EAAE,IAAI;QACjB,QAAQ,EAAE;YACT,eAAe,EAAE,KAAK;SACtB;KACD;IACD,iBAAiB,EAAE,KAAK;IACxB,YAAY,EAAE,KAAK;IACnB,iBAAiB,EAAE,KAAK;IACxB,sBAAsB,EAAE,IAAI;IAC5B,mBAAmB,EAAE,IAAI;IACzB,cAAc,EAAE,IAAI;IACpB,aAAa,EAAE,KAAK;IACpB,gBAAgB,EAAE,CAAC;IACnB,yBAAyB,EAAE,CAAC;IAC5B,eAAe,EAAE,IAAI;IACrB,cAAc,EAAE,KAAK;IACrB,kBAAkB,EAAE,KAAK;IACzB,wBAAwB,EAAE,KAAK;IAC/B,eAAe,EAAE,KAAK;IACtB,QAAQ,EAAE;QACT,UAAU,EAAE,IAAI;QAChB,eAAe,EAAE,EAAE;QACnB,aAAa,EAAE,KAAK;QACpB,oBAAoB,EAAE,KAAK;KAC3B;IACD,MAAM,EAAE;QACP,UAAU,EAAE,IAAI;QAChB,WAAW,EAAE,KAAK;KAClB;IACD,kBAAkB,EAAE,MAAM;IAC1B,cAAc,EAAE,SAAS;IACzB,cAAc,EAAE,CAAC;IACjB,sBAAsB,EAAE,CAAC;IACzB,QAAQ,EAAE;QACT,eAAe,EAAE,IAAI;KACrB;IACD,QAAQ,EAAE;QACT,mBAAmB,EAAE,IAAI;KACzB;IACD,QAAQ,EAAE,EAAE;IACZ,UAAU,EAAE,EAAE;IACd,MAAM,EAAE,EAAE;IACV,OAAO,EAAE,EAAE;IACX,aAAa,EAAE,EAAE;IACjB,MAAM,EAAE,EAAE;CACS,CAAC","sourcesContent":["import type { Settings } from \"./settings-manager.js\";\n\nexport const DEFAULT_SETTINGS = {\n\ttransport: \"auto\",\n\tsteeringMode: \"one-at-a-time\",\n\tfollowUpMode: \"one-at-a-time\",\n\tcompaction: {\n\t\tenabled: true,\n\t\treserveTokens: 16384,\n\t\tkeepRecentTokens: 20000,\n\t},\n\tbranchSummary: {\n\t\treserveTokens: 16384,\n\t\tskipPrompt: false,\n\t},\n\tretry: {\n\t\tenabled: true,\n\t\tmaxRetries: 3,\n\t\tbaseDelayMs: 2000,\n\t\tprovider: {\n\t\t\tmaxRetryDelayMs: 60000,\n\t\t},\n\t},\n\thideThinkingBlock: false,\n\tquietStartup: false,\n\tcollapseChangelog: false,\n\tenableInstallTelemetry: true,\n\tenableSkillCommands: true,\n\tenableSubagent: true,\n\twarmSubagents: false,\n\tmaxSubagentDepth: 2,\n\tnestedSubagentConcurrency: 2,\n\tenableTodoWrite: true,\n\tenableWebTools: false,\n\tenableBrowserTools: false,\n\tenableBrowserLivePreview: false,\n\tenableFileTools: false,\n\tterminal: {\n\t\tshowImages: true,\n\t\timageWidthCells: 60,\n\t\tclearOnShrink: false,\n\t\tshowTerminalProgress: false,\n\t},\n\timages: {\n\t\tautoResize: true,\n\t\tblockImages: false,\n\t},\n\tdoubleEscapeAction: \"tree\",\n\ttreeFilterMode: \"default\",\n\teditorPaddingX: 0,\n\tautocompleteMaxVisible: 5,\n\tmarkdown: {\n\t\tcodeBlockIndent: \" \",\n\t},\n\twarnings: {\n\t\tanthropicExtraUsage: true,\n\t},\n\tpackages: [],\n\textensions: [],\n\tskills: [],\n\tprompts: [],\n\tslashCommands: [],\n\tthemes: [],\n} satisfies Settings;\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"settings-types.d.ts","sourceRoot":"","sources":["../../src/core/settings-types.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AAEzD,MAAM,WAAW,kBAAkB;IAClC,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC1B;AAED,MAAM,WAAW,qBAAqB;IACrC,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,UAAU,CAAC,EAAE,OAAO,CAAC;CACrB;AAED,MAAM,WAAW,qBAAqB;IACrC,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,eAAe,CAAC,EAAE,MAAM,CAAC;CACzB;AAED,MAAM,WAAW,aAAa;IAC7B,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,EAAE,qBAAqB,CAAC;CACjC;AAED,MAAM,WAAW,gBAAgB;IAChC,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,oBAA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MAAM,CAAC,EAAE,aAAa,CAAC;IACvB,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;IACzB,kBAAkB,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,CAAC;IAC9C,cAAc,CAAC,EAAE,SAAS,GAAG,UAAU,GAAG,WAAW,GAAG,cAAc,GAAG,KAAK,CAAC;IAC/E,eAAe,CAAC,EAAE,uBAAuB,CAAC;IAC1C,eAAe,CAAC,EAAE,YAAY,GAAG,SAAS,CAAC;IAC3C,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAC7B,QAAQ,CAAC,EAAE,gBAAgB,CAAC;IAC5B,QAAQ,CAAC,EAAE,eAAe,CAAC;IAC3B,UAAU,CAAC,EAAE,MAAM,CAAC;CACpB","sourcesContent":["/**\n * Settings schema shared across the app.\n *\n * The `Settings` interface and its nested option groups describe the on-disk\n * global/project settings.json shape. Extracted from settings-manager.ts so the\n * schema can be imported without pulling in the manager implementation.\n */\n\nimport type { Transport } from \"@kolisachint/hoocode-ai\";\n\nexport interface CompactionSettings {\n\tenabled?: boolean; // default: true\n\treserveTokens?: number; // default: 16384\n\tkeepRecentTokens?: number; // default: 20000\n}\n\nexport interface BranchSummarySettings {\n\treserveTokens?: number; // default: 16384 (tokens reserved for prompt + LLM response)\n\tskipPrompt?: boolean; // default: false - when true, skips \"Summarize branch?\" prompt and defaults to no summary\n}\n\nexport interface ProviderRetrySettings {\n\ttimeoutMs?: number; // SDK/provider request timeout in milliseconds\n\tmaxRetries?: number; // SDK/provider retry attempts\n\tmaxRetryDelayMs?: number; // default: 60000 (max server-requested delay before failing)\n}\n\nexport interface RetrySettings {\n\tenabled?: boolean; // default: true\n\tmaxRetries?: number; // default: 3\n\tbaseDelayMs?: number; // default: 2000 (exponential backoff: 2s, 4s, 8s)\n\tprovider?: ProviderRetrySettings;\n}\n\nexport interface TerminalSettings {\n\tshowImages?: boolean; // default: true (only relevant if terminal supports images)\n\timageWidthCells?: number; // default: 60 (preferred inline image width in terminal cells)\n\tclearOnShrink?: boolean; // default: false (clear empty rows when content shrinks)\n\tshowTerminalProgress?: boolean; // default: false (OSC 9;4 terminal progress indicators)\n}\n\nexport interface ImageSettings {\n\tautoResize?: boolean; // default: true (resize images to 2000x2000 max for better model compatibility)\n\tblockImages?: boolean; // default: false - when true, prevents all images from being sent to LLM providers\n}\n\nexport interface ThinkingBudgetsSettings {\n\tminimal?: number;\n\tlow?: number;\n\tmedium?: number;\n\thigh?: number;\n}\n\nexport interface MarkdownSettings {\n\tcodeBlockIndent?: string; // default: \" \"\n}\n\nexport interface WarningSettings {\n\tanthropicExtraUsage?: boolean; // default: true\n}\n\n/**\n * Model categories for subagent model selection.\n * Categories map to explicit model IDs (e.g., \"<provider>/<model-id>\").\n * When a category is not configured, no override is applied and the agent's or\n * parent's default model is used.\n */\nexport interface ModelCategories {\n\t/** Quick, cheap models for read-only exploration (grep, find, file discovery) */\n\tfast?: string;\n\t/** Balanced models for general work (planning, moderate complexity) */\n\tstandard?: string;\n\t/** Most capable models for complex reasoning (multi-file refactors) */\n\tcapable?: string;\n}\n\nexport type TransportSetting = Transport;\n\n/**\n * Package source for npm/git packages.\n * - String form: load all resources from the package\n * - Object form: filter which resources to load\n */\nexport type PackageSource =\n\t| string\n\t| {\n\t\t\tsource: string;\n\t\t\textensions?: string[];\n\t\t\tskills?: string[];\n\t\t\tprompts?: string[];\n\t\t\tthemes?: string[];\n\t };\n\nexport interface Settings {\n\tlastChangelogVersion?: string;\n\tdefaultProvider?: string;\n\tdefaultModel?: string;\n\tdefaultThinkingLevel?: \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\";\n\tmodelCategories?: ModelCategories; // Model categories for subagent model selection (fast, standard, capable)\n\ttransport?: TransportSetting; // default: \"auto\"\n\tsteeringMode?: \"all\" | \"one-at-a-time\";\n\tfollowUpMode?: \"all\" | \"one-at-a-time\";\n\ttheme?: string;\n\tcompaction?: CompactionSettings;\n\tbranchSummary?: BranchSummarySettings;\n\tretry?: RetrySettings;\n\thideThinkingBlock?: boolean;\n\tshellPath?: string; // Custom shell path (e.g., for Cygwin users on Windows)\n\tquietStartup?: boolean;\n\tshellCommandPrefix?: string; // Prefix prepended to every bash command (e.g., \"shopt -s expand_aliases\" for alias support)\n\tnpmCommand?: string[]; // Command used for npm package lookup/install operations, argv-style (e.g., [\"mise\", \"exec\", \"node@20\", \"--\", \"npm\"])\n\tcollapseChangelog?: boolean; // Show condensed changelog after update (use /changelog for full)\n\tenableInstallTelemetry?: boolean; // default: true - anonymous version/update ping after changelog-detected updates\n\tpackages?: PackageSource[]; // Array of npm/git package sources (string or object with filtering)\n\textensions?: string[]; // Array of local extension file paths or directories\n\tskills?: string[]; // Array of local skill file paths or directories\n\tprompts?: string[]; // Array of local prompt template paths or directories\n\tslashCommands?: string[]; // Array of local slash-command paths or directories\n\tthemes?: string[]; // Array of local theme file paths or directories\n\tenableSkillCommands?: boolean; // default: true - register skills as /skill:name commands\n\tenableSubagent?: boolean; // default: false - enable the subagent tool (delegate tasks to isolated agent loops)\n\twarmSubagents?: boolean; // default: false - dispatch eligible subagents on reused warm RPC workers (experimental)\n\tmaxSubagentDepth?: number; // default: 1 - tree-wide subagent nesting cap (1 = subagents cannot spawn subagents)\n\tnestedSubagentConcurrency?: number; // default: 2 - max concurrent subagents per pool at nesting depth >= 1\n\tenableTodoWrite?: boolean; // default: true - enable the TodoWrite tool (maintain a live todo list in the task panel)\n\tenableWebTools?: boolean; // default: false - enable the webfetch + websearch tools (network access)\n\tenableBrowserTools?: boolean; // default: false - enable the browser_run + browser_continue tools (browsertools engine)\n\tenableBrowserLivePreview?: boolean; // default: false - default the live viewer on for browser_run runs and auto-open it\n\tenableFileTools?: boolean; // default: false - enable the document tools: DocRead/DocEdit/DocWrite + DocScan/DocGrep/DocPeek (filetools binary)\n\tterminal?: TerminalSettings;\n\timages?: ImageSettings;\n\tenabledModels?: string[]; // Model patterns for cycling (same format as --models CLI flag)\n\tdoubleEscapeAction?: \"fork\" | \"tree\" | \"none\"; // Action for double-escape with empty editor (default: \"tree\")\n\ttreeFilterMode?: \"default\" | \"no-tools\" | \"user-only\" | \"labeled-only\" | \"all\"; // Default filter when opening /tree\n\tthinkingBudgets?: ThinkingBudgetsSettings; // Custom token budgets for thinking levels\n\tthinkingDisplay?: \"summarized\" | \"omitted\"; // How adaptive-thinking models return thinking content. Opus 4.8 defaults to \"omitted\" (faster tool use); set \"summarized\" to surface thinking text.\n\teditorPaddingX?: number; // Horizontal padding for input editor (default: 0)\n\tautocompleteMaxVisible?: number; // Max visible items in autocomplete dropdown (default: 5)\n\tshowHardwareCursor?: boolean; // Show terminal cursor while still positioning it for IME\n\tmarkdown?: MarkdownSettings;\n\twarnings?: WarningSettings;\n\tsessionDir?: string; // Custom session storage directory (same format as --session-dir CLI flag)\n}\n"]}
1
+ {"version":3,"file":"settings-types.d.ts","sourceRoot":"","sources":["../../src/core/settings-types.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AAEzD,MAAM,WAAW,kBAAkB;IAClC,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC1B;AAED,MAAM,WAAW,qBAAqB;IACrC,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,UAAU,CAAC,EAAE,OAAO,CAAC;CACrB;AAED,MAAM,WAAW,qBAAqB;IACrC,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,eAAe,CAAC,EAAE,MAAM,CAAC;CACzB;AAED,MAAM,WAAW,aAAa;IAC7B,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,WAAW,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E,OAAO,CAAC;IAC1B,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAC7B,wBAAwB,CAAC,EAAE,OAAO,CAAC;IACnC,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,QAAQ,CAAC,EAAE,gBAAgB,CAAC;IAC5B,MAAM,CAAC,EAAE,aAAa,CAAC;IACvB,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;IACzB,kBAAkB,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,CAAC;IAC9C,cAAc,CAAC,EAAE,SAAS,GAAG,UAAU,GAAG,WAAW,GAAG,cAAc,GAAG,KAAK,CAAC;IAC/E,eAAe,CAAC,EAAE,uBAAuB,CAAC;IAC1C,eAAe,CAAC,EAAE,YAAY,GAAG,SAAS,CAAC;IAC3C,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAC7B,QAAQ,CAAC,EAAE,gBAAgB,CAAC;IAC5B,QAAQ,CAAC,EAAE,eAAe,CAAC;IAC3B,UAAU,CAAC,EAAE,MAAM,CAAC;CACpB","sourcesContent":["/**\n * Settings schema shared across the app.\n *\n * The `Settings` interface and its nested option groups describe the on-disk\n * global/project settings.json shape. Extracted from settings-manager.ts so the\n * schema can be imported without pulling in the manager implementation.\n */\n\nimport type { Transport } from \"@kolisachint/hoocode-ai\";\n\nexport interface CompactionSettings {\n\tenabled?: boolean; // default: true\n\treserveTokens?: number; // default: 16384\n\tkeepRecentTokens?: number; // default: 20000\n}\n\nexport interface BranchSummarySettings {\n\treserveTokens?: number; // default: 16384 (tokens reserved for prompt + LLM response)\n\tskipPrompt?: boolean; // default: false - when true, skips \"Summarize branch?\" prompt and defaults to no summary\n}\n\nexport interface ProviderRetrySettings {\n\ttimeoutMs?: number; // SDK/provider request timeout in milliseconds\n\tmaxRetries?: number; // SDK/provider retry attempts\n\tmaxRetryDelayMs?: number; // default: 60000 (max server-requested delay before failing)\n}\n\nexport interface RetrySettings {\n\tenabled?: boolean; // default: true\n\tmaxRetries?: number; // default: 3\n\tbaseDelayMs?: number; // default: 2000 (exponential backoff: 2s, 4s, 8s)\n\tprovider?: ProviderRetrySettings;\n}\n\nexport interface TerminalSettings {\n\tshowImages?: boolean; // default: true (only relevant if terminal supports images)\n\timageWidthCells?: number; // default: 60 (preferred inline image width in terminal cells)\n\tclearOnShrink?: boolean; // default: false (clear empty rows when content shrinks)\n\tshowTerminalProgress?: boolean; // default: false (OSC 9;4 terminal progress indicators)\n}\n\nexport interface ImageSettings {\n\tautoResize?: boolean; // default: true (resize images to 2000x2000 max for better model compatibility)\n\tblockImages?: boolean; // default: false - when true, prevents all images from being sent to LLM providers\n}\n\nexport interface ThinkingBudgetsSettings {\n\tminimal?: number;\n\tlow?: number;\n\tmedium?: number;\n\thigh?: number;\n}\n\nexport interface MarkdownSettings {\n\tcodeBlockIndent?: string; // default: \" \"\n}\n\nexport interface WarningSettings {\n\tanthropicExtraUsage?: boolean; // default: true\n}\n\n/**\n * Model categories for subagent model selection.\n * Categories map to explicit model IDs (e.g., \"<provider>/<model-id>\").\n * When a category is not configured, no override is applied and the agent's or\n * parent's default model is used.\n */\nexport interface ModelCategories {\n\t/** Quick, cheap models for read-only exploration (grep, find, file discovery) */\n\tfast?: string;\n\t/** Balanced models for general work (planning, moderate complexity) */\n\tstandard?: string;\n\t/** Most capable models for complex reasoning (multi-file refactors) */\n\tcapable?: string;\n}\n\nexport type TransportSetting = Transport;\n\n/**\n * Package source for npm/git packages.\n * - String form: load all resources from the package\n * - Object form: filter which resources to load\n */\nexport type PackageSource =\n\t| string\n\t| {\n\t\t\tsource: string;\n\t\t\textensions?: string[];\n\t\t\tskills?: string[];\n\t\t\tprompts?: string[];\n\t\t\tthemes?: string[];\n\t };\n\nexport interface Settings {\n\tlastChangelogVersion?: string;\n\tdefaultProvider?: string;\n\tdefaultModel?: string;\n\tdefaultThinkingLevel?: \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\";\n\tmodelCategories?: ModelCategories; // Model categories for subagent model selection (fast, standard, capable)\n\ttransport?: TransportSetting; // default: \"auto\"\n\tsteeringMode?: \"all\" | \"one-at-a-time\";\n\tfollowUpMode?: \"all\" | \"one-at-a-time\";\n\ttheme?: string;\n\tcompaction?: CompactionSettings;\n\tbranchSummary?: BranchSummarySettings;\n\tretry?: RetrySettings;\n\thideThinkingBlock?: boolean;\n\tshellPath?: string; // Custom shell path (e.g., for Cygwin users on Windows)\n\tquietStartup?: boolean;\n\tshellCommandPrefix?: string; // Prefix prepended to every bash command (e.g., \"shopt -s expand_aliases\" for alias support)\n\tnpmCommand?: string[]; // Command used for npm package lookup/install operations, argv-style (e.g., [\"mise\", \"exec\", \"node@20\", \"--\", \"npm\"])\n\tcollapseChangelog?: boolean; // Show condensed changelog after update (use /changelog for full)\n\tenableInstallTelemetry?: boolean; // default: true - anonymous version/update ping after changelog-detected updates\n\tpackages?: PackageSource[]; // Array of npm/git package sources (string or object with filtering)\n\textensions?: string[]; // Array of local extension file paths or directories\n\tskills?: string[]; // Array of local skill file paths or directories\n\tprompts?: string[]; // Array of local prompt template paths or directories\n\tslashCommands?: string[]; // Array of local slash-command paths or directories\n\tthemes?: string[]; // Array of local theme file paths or directories\n\tenableSkillCommands?: boolean; // default: true - register skills as /skill:name commands\n\tenableSubagent?: boolean; // default: true - enable the subagent tool (delegate tasks to isolated agent loops); set false to disable\n\twarmSubagents?: boolean; // default: false - dispatch eligible subagents on reused warm RPC workers (experimental)\n\tmaxSubagentDepth?: number; // default: 2 - tree-wide subagent nesting cap (2 = a subagent may spawn one more level; 1 = no nesting)\n\tnestedSubagentConcurrency?: number; // default: 2 - max concurrent subagents per pool at nesting depth >= 1\n\tenableTodoWrite?: boolean; // default: true - enable the TodoWrite tool (maintain a live todo list in the task panel)\n\tenableWebTools?: boolean; // default: false - enable the webfetch + websearch tools (network access)\n\tenableBrowserTools?: boolean; // default: false - enable the browser_run + browser_continue tools (browsertools engine)\n\tenableBrowserLivePreview?: boolean; // default: false - default the live viewer on for browser_run runs and auto-open it\n\tenableFileTools?: boolean; // default: false - enable the document tools: DocRead/DocEdit/DocWrite + DocScan/DocGrep/DocPeek (filetools binary)\n\tterminal?: TerminalSettings;\n\timages?: ImageSettings;\n\tenabledModels?: string[]; // Model patterns for cycling (same format as --models CLI flag)\n\tdoubleEscapeAction?: \"fork\" | \"tree\" | \"none\"; // Action for double-escape with empty editor (default: \"tree\")\n\ttreeFilterMode?: \"default\" | \"no-tools\" | \"user-only\" | \"labeled-only\" | \"all\"; // Default filter when opening /tree\n\tthinkingBudgets?: ThinkingBudgetsSettings; // Custom token budgets for thinking levels\n\tthinkingDisplay?: \"summarized\" | \"omitted\"; // How adaptive-thinking models return thinking content. Opus 4.8 defaults to \"omitted\" (faster tool use); set \"summarized\" to surface thinking text.\n\teditorPaddingX?: number; // Horizontal padding for input editor (default: 0)\n\tautocompleteMaxVisible?: number; // Max visible items in autocomplete dropdown (default: 5)\n\tshowHardwareCursor?: boolean; // Show terminal cursor while still positioning it for IME\n\tmarkdown?: MarkdownSettings;\n\twarnings?: WarningSettings;\n\tsessionDir?: string; // Custom session storage directory (same format as --session-dir CLI flag)\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"settings-types.js","sourceRoot":"","sources":["../../src/core/settings-types.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG","sourcesContent":["/**\n * Settings schema shared across the app.\n *\n * The `Settings` interface and its nested option groups describe the on-disk\n * global/project settings.json shape. Extracted from settings-manager.ts so the\n * schema can be imported without pulling in the manager implementation.\n */\n\nimport type { Transport } from \"@kolisachint/hoocode-ai\";\n\nexport interface CompactionSettings {\n\tenabled?: boolean; // default: true\n\treserveTokens?: number; // default: 16384\n\tkeepRecentTokens?: number; // default: 20000\n}\n\nexport interface BranchSummarySettings {\n\treserveTokens?: number; // default: 16384 (tokens reserved for prompt + LLM response)\n\tskipPrompt?: boolean; // default: false - when true, skips \"Summarize branch?\" prompt and defaults to no summary\n}\n\nexport interface ProviderRetrySettings {\n\ttimeoutMs?: number; // SDK/provider request timeout in milliseconds\n\tmaxRetries?: number; // SDK/provider retry attempts\n\tmaxRetryDelayMs?: number; // default: 60000 (max server-requested delay before failing)\n}\n\nexport interface RetrySettings {\n\tenabled?: boolean; // default: true\n\tmaxRetries?: number; // default: 3\n\tbaseDelayMs?: number; // default: 2000 (exponential backoff: 2s, 4s, 8s)\n\tprovider?: ProviderRetrySettings;\n}\n\nexport interface TerminalSettings {\n\tshowImages?: boolean; // default: true (only relevant if terminal supports images)\n\timageWidthCells?: number; // default: 60 (preferred inline image width in terminal cells)\n\tclearOnShrink?: boolean; // default: false (clear empty rows when content shrinks)\n\tshowTerminalProgress?: boolean; // default: false (OSC 9;4 terminal progress indicators)\n}\n\nexport interface ImageSettings {\n\tautoResize?: boolean; // default: true (resize images to 2000x2000 max for better model compatibility)\n\tblockImages?: boolean; // default: false - when true, prevents all images from being sent to LLM providers\n}\n\nexport interface ThinkingBudgetsSettings {\n\tminimal?: number;\n\tlow?: number;\n\tmedium?: number;\n\thigh?: number;\n}\n\nexport interface MarkdownSettings {\n\tcodeBlockIndent?: string; // default: \" \"\n}\n\nexport interface WarningSettings {\n\tanthropicExtraUsage?: boolean; // default: true\n}\n\n/**\n * Model categories for subagent model selection.\n * Categories map to explicit model IDs (e.g., \"<provider>/<model-id>\").\n * When a category is not configured, no override is applied and the agent's or\n * parent's default model is used.\n */\nexport interface ModelCategories {\n\t/** Quick, cheap models for read-only exploration (grep, find, file discovery) */\n\tfast?: string;\n\t/** Balanced models for general work (planning, moderate complexity) */\n\tstandard?: string;\n\t/** Most capable models for complex reasoning (multi-file refactors) */\n\tcapable?: string;\n}\n\nexport type TransportSetting = Transport;\n\n/**\n * Package source for npm/git packages.\n * - String form: load all resources from the package\n * - Object form: filter which resources to load\n */\nexport type PackageSource =\n\t| string\n\t| {\n\t\t\tsource: string;\n\t\t\textensions?: string[];\n\t\t\tskills?: string[];\n\t\t\tprompts?: string[];\n\t\t\tthemes?: string[];\n\t };\n\nexport interface Settings {\n\tlastChangelogVersion?: string;\n\tdefaultProvider?: string;\n\tdefaultModel?: string;\n\tdefaultThinkingLevel?: \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\";\n\tmodelCategories?: ModelCategories; // Model categories for subagent model selection (fast, standard, capable)\n\ttransport?: TransportSetting; // default: \"auto\"\n\tsteeringMode?: \"all\" | \"one-at-a-time\";\n\tfollowUpMode?: \"all\" | \"one-at-a-time\";\n\ttheme?: string;\n\tcompaction?: CompactionSettings;\n\tbranchSummary?: BranchSummarySettings;\n\tretry?: RetrySettings;\n\thideThinkingBlock?: boolean;\n\tshellPath?: string; // Custom shell path (e.g., for Cygwin users on Windows)\n\tquietStartup?: boolean;\n\tshellCommandPrefix?: string; // Prefix prepended to every bash command (e.g., \"shopt -s expand_aliases\" for alias support)\n\tnpmCommand?: string[]; // Command used for npm package lookup/install operations, argv-style (e.g., [\"mise\", \"exec\", \"node@20\", \"--\", \"npm\"])\n\tcollapseChangelog?: boolean; // Show condensed changelog after update (use /changelog for full)\n\tenableInstallTelemetry?: boolean; // default: true - anonymous version/update ping after changelog-detected updates\n\tpackages?: PackageSource[]; // Array of npm/git package sources (string or object with filtering)\n\textensions?: string[]; // Array of local extension file paths or directories\n\tskills?: string[]; // Array of local skill file paths or directories\n\tprompts?: string[]; // Array of local prompt template paths or directories\n\tslashCommands?: string[]; // Array of local slash-command paths or directories\n\tthemes?: string[]; // Array of local theme file paths or directories\n\tenableSkillCommands?: boolean; // default: true - register skills as /skill:name commands\n\tenableSubagent?: boolean; // default: false - enable the subagent tool (delegate tasks to isolated agent loops)\n\twarmSubagents?: boolean; // default: false - dispatch eligible subagents on reused warm RPC workers (experimental)\n\tmaxSubagentDepth?: number; // default: 1 - tree-wide subagent nesting cap (1 = subagents cannot spawn subagents)\n\tnestedSubagentConcurrency?: number; // default: 2 - max concurrent subagents per pool at nesting depth >= 1\n\tenableTodoWrite?: boolean; // default: true - enable the TodoWrite tool (maintain a live todo list in the task panel)\n\tenableWebTools?: boolean; // default: false - enable the webfetch + websearch tools (network access)\n\tenableBrowserTools?: boolean; // default: false - enable the browser_run + browser_continue tools (browsertools engine)\n\tenableBrowserLivePreview?: boolean; // default: false - default the live viewer on for browser_run runs and auto-open it\n\tenableFileTools?: boolean; // default: false - enable the document tools: DocRead/DocEdit/DocWrite + DocScan/DocGrep/DocPeek (filetools binary)\n\tterminal?: TerminalSettings;\n\timages?: ImageSettings;\n\tenabledModels?: string[]; // Model patterns for cycling (same format as --models CLI flag)\n\tdoubleEscapeAction?: \"fork\" | \"tree\" | \"none\"; // Action for double-escape with empty editor (default: \"tree\")\n\ttreeFilterMode?: \"default\" | \"no-tools\" | \"user-only\" | \"labeled-only\" | \"all\"; // Default filter when opening /tree\n\tthinkingBudgets?: ThinkingBudgetsSettings; // Custom token budgets for thinking levels\n\tthinkingDisplay?: \"summarized\" | \"omitted\"; // How adaptive-thinking models return thinking content. Opus 4.8 defaults to \"omitted\" (faster tool use); set \"summarized\" to surface thinking text.\n\teditorPaddingX?: number; // Horizontal padding for input editor (default: 0)\n\tautocompleteMaxVisible?: number; // Max visible items in autocomplete dropdown (default: 5)\n\tshowHardwareCursor?: boolean; // Show terminal cursor while still positioning it for IME\n\tmarkdown?: MarkdownSettings;\n\twarnings?: WarningSettings;\n\tsessionDir?: string; // Custom session storage directory (same format as --session-dir CLI flag)\n}\n"]}
1
+ {"version":3,"file":"settings-types.js","sourceRoot":"","sources":["../../src/core/settings-types.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG","sourcesContent":["/**\n * Settings schema shared across the app.\n *\n * The `Settings` interface and its nested option groups describe the on-disk\n * global/project settings.json shape. Extracted from settings-manager.ts so the\n * schema can be imported without pulling in the manager implementation.\n */\n\nimport type { Transport } from \"@kolisachint/hoocode-ai\";\n\nexport interface CompactionSettings {\n\tenabled?: boolean; // default: true\n\treserveTokens?: number; // default: 16384\n\tkeepRecentTokens?: number; // default: 20000\n}\n\nexport interface BranchSummarySettings {\n\treserveTokens?: number; // default: 16384 (tokens reserved for prompt + LLM response)\n\tskipPrompt?: boolean; // default: false - when true, skips \"Summarize branch?\" prompt and defaults to no summary\n}\n\nexport interface ProviderRetrySettings {\n\ttimeoutMs?: number; // SDK/provider request timeout in milliseconds\n\tmaxRetries?: number; // SDK/provider retry attempts\n\tmaxRetryDelayMs?: number; // default: 60000 (max server-requested delay before failing)\n}\n\nexport interface RetrySettings {\n\tenabled?: boolean; // default: true\n\tmaxRetries?: number; // default: 3\n\tbaseDelayMs?: number; // default: 2000 (exponential backoff: 2s, 4s, 8s)\n\tprovider?: ProviderRetrySettings;\n}\n\nexport interface TerminalSettings {\n\tshowImages?: boolean; // default: true (only relevant if terminal supports images)\n\timageWidthCells?: number; // default: 60 (preferred inline image width in terminal cells)\n\tclearOnShrink?: boolean; // default: false (clear empty rows when content shrinks)\n\tshowTerminalProgress?: boolean; // default: false (OSC 9;4 terminal progress indicators)\n}\n\nexport interface ImageSettings {\n\tautoResize?: boolean; // default: true (resize images to 2000x2000 max for better model compatibility)\n\tblockImages?: boolean; // default: false - when true, prevents all images from being sent to LLM providers\n}\n\nexport interface ThinkingBudgetsSettings {\n\tminimal?: number;\n\tlow?: number;\n\tmedium?: number;\n\thigh?: number;\n}\n\nexport interface MarkdownSettings {\n\tcodeBlockIndent?: string; // default: \" \"\n}\n\nexport interface WarningSettings {\n\tanthropicExtraUsage?: boolean; // default: true\n}\n\n/**\n * Model categories for subagent model selection.\n * Categories map to explicit model IDs (e.g., \"<provider>/<model-id>\").\n * When a category is not configured, no override is applied and the agent's or\n * parent's default model is used.\n */\nexport interface ModelCategories {\n\t/** Quick, cheap models for read-only exploration (grep, find, file discovery) */\n\tfast?: string;\n\t/** Balanced models for general work (planning, moderate complexity) */\n\tstandard?: string;\n\t/** Most capable models for complex reasoning (multi-file refactors) */\n\tcapable?: string;\n}\n\nexport type TransportSetting = Transport;\n\n/**\n * Package source for npm/git packages.\n * - String form: load all resources from the package\n * - Object form: filter which resources to load\n */\nexport type PackageSource =\n\t| string\n\t| {\n\t\t\tsource: string;\n\t\t\textensions?: string[];\n\t\t\tskills?: string[];\n\t\t\tprompts?: string[];\n\t\t\tthemes?: string[];\n\t };\n\nexport interface Settings {\n\tlastChangelogVersion?: string;\n\tdefaultProvider?: string;\n\tdefaultModel?: string;\n\tdefaultThinkingLevel?: \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\";\n\tmodelCategories?: ModelCategories; // Model categories for subagent model selection (fast, standard, capable)\n\ttransport?: TransportSetting; // default: \"auto\"\n\tsteeringMode?: \"all\" | \"one-at-a-time\";\n\tfollowUpMode?: \"all\" | \"one-at-a-time\";\n\ttheme?: string;\n\tcompaction?: CompactionSettings;\n\tbranchSummary?: BranchSummarySettings;\n\tretry?: RetrySettings;\n\thideThinkingBlock?: boolean;\n\tshellPath?: string; // Custom shell path (e.g., for Cygwin users on Windows)\n\tquietStartup?: boolean;\n\tshellCommandPrefix?: string; // Prefix prepended to every bash command (e.g., \"shopt -s expand_aliases\" for alias support)\n\tnpmCommand?: string[]; // Command used for npm package lookup/install operations, argv-style (e.g., [\"mise\", \"exec\", \"node@20\", \"--\", \"npm\"])\n\tcollapseChangelog?: boolean; // Show condensed changelog after update (use /changelog for full)\n\tenableInstallTelemetry?: boolean; // default: true - anonymous version/update ping after changelog-detected updates\n\tpackages?: PackageSource[]; // Array of npm/git package sources (string or object with filtering)\n\textensions?: string[]; // Array of local extension file paths or directories\n\tskills?: string[]; // Array of local skill file paths or directories\n\tprompts?: string[]; // Array of local prompt template paths or directories\n\tslashCommands?: string[]; // Array of local slash-command paths or directories\n\tthemes?: string[]; // Array of local theme file paths or directories\n\tenableSkillCommands?: boolean; // default: true - register skills as /skill:name commands\n\tenableSubagent?: boolean; // default: true - enable the subagent tool (delegate tasks to isolated agent loops); set false to disable\n\twarmSubagents?: boolean; // default: false - dispatch eligible subagents on reused warm RPC workers (experimental)\n\tmaxSubagentDepth?: number; // default: 2 - tree-wide subagent nesting cap (2 = a subagent may spawn one more level; 1 = no nesting)\n\tnestedSubagentConcurrency?: number; // default: 2 - max concurrent subagents per pool at nesting depth >= 1\n\tenableTodoWrite?: boolean; // default: true - enable the TodoWrite tool (maintain a live todo list in the task panel)\n\tenableWebTools?: boolean; // default: false - enable the webfetch + websearch tools (network access)\n\tenableBrowserTools?: boolean; // default: false - enable the browser_run + browser_continue tools (browsertools engine)\n\tenableBrowserLivePreview?: boolean; // default: false - default the live viewer on for browser_run runs and auto-open it\n\tenableFileTools?: boolean; // default: false - enable the document tools: DocRead/DocEdit/DocWrite + DocScan/DocGrep/DocPeek (filetools binary)\n\tterminal?: TerminalSettings;\n\timages?: ImageSettings;\n\tenabledModels?: string[]; // Model patterns for cycling (same format as --models CLI flag)\n\tdoubleEscapeAction?: \"fork\" | \"tree\" | \"none\"; // Action for double-escape with empty editor (default: \"tree\")\n\ttreeFilterMode?: \"default\" | \"no-tools\" | \"user-only\" | \"labeled-only\" | \"all\"; // Default filter when opening /tree\n\tthinkingBudgets?: ThinkingBudgetsSettings; // Custom token budgets for thinking levels\n\tthinkingDisplay?: \"summarized\" | \"omitted\"; // How adaptive-thinking models return thinking content. Opus 4.8 defaults to \"omitted\" (faster tool use); set \"summarized\" to surface thinking text.\n\teditorPaddingX?: number; // Horizontal padding for input editor (default: 0)\n\tautocompleteMaxVisible?: number; // Max visible items in autocomplete dropdown (default: 5)\n\tshowHardwareCursor?: boolean; // Show terminal cursor while still positioning it for IME\n\tmarkdown?: MarkdownSettings;\n\twarnings?: WarningSettings;\n\tsessionDir?: string; // Custom session storage directory (same format as --session-dir CLI flag)\n}\n"]}
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Canonical set of AgentSession event `type`s that a spawned subagent writes to
3
+ * its stdout JSON stream, shared so the child emitter (print-mode) and the
4
+ * parent consumer (SubagentPool) cannot drift apart.
5
+ *
6
+ * A subagent child otherwise emits the full per-delta event firehose
7
+ * (`message_update`, `tool_execution_update`, `message_start`, …). The parent
8
+ * only ever consumes:
9
+ * - the progress events below, forwarded to the UI as `task_progress`, and
10
+ * - `message_end`, whose usage the parent's TokenBudget accumulates.
11
+ * Everything else is dropped at the source so the firehose never crosses the
12
+ * pipe (and is never framed/parsed on the parent's UI event loop). The child's
13
+ * authoritative result travels via `result.json`, not this stream, and liveness
14
+ * travels via a separate periodic `ping`, so this filtering is lossless for the
15
+ * parent.
16
+ */
17
+ export declare const SUBAGENT_PROGRESS_EVENTS: ReadonlySet<string>;
18
+ /** Superset the child actually writes: progress events plus `message_end` (token
19
+ * usage for the parent budget). */
20
+ export declare const SUBAGENT_STDOUT_EVENT_TYPES: ReadonlySet<string>;
21
+ //# sourceMappingURL=subagent-events.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"subagent-events.d.ts","sourceRoot":"","sources":["../../src/core/subagent-events.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,wBAAwB,EAAE,WAAW,CAAC,MAAM,CAIvD,CAAC;AAEH;mCACmC;AACnC,eAAO,MAAM,2BAA2B,EAAE,WAAW,CAAC,MAAM,CAAyD,CAAC","sourcesContent":["/**\n * Canonical set of AgentSession event `type`s that a spawned subagent writes to\n * its stdout JSON stream, shared so the child emitter (print-mode) and the\n * parent consumer (SubagentPool) cannot drift apart.\n *\n * A subagent child otherwise emits the full per-delta event firehose\n * (`message_update`, `tool_execution_update`, `message_start`, …). The parent\n * only ever consumes:\n * - the progress events below, forwarded to the UI as `task_progress`, and\n * - `message_end`, whose usage the parent's TokenBudget accumulates.\n * Everything else is dropped at the source so the firehose never crosses the\n * pipe (and is never framed/parsed on the parent's UI event loop). The child's\n * authoritative result travels via `result.json`, not this stream, and liveness\n * travels via a separate periodic `ping`, so this filtering is lossless for the\n * parent.\n */\nexport const SUBAGENT_PROGRESS_EVENTS: ReadonlySet<string> = new Set([\n\t\"turn_end\",\n\t\"tool_execution_start\",\n\t\"tool_execution_end\",\n]);\n\n/** Superset the child actually writes: progress events plus `message_end` (token\n * usage for the parent budget). */\nexport const SUBAGENT_STDOUT_EVENT_TYPES: ReadonlySet<string> = new Set([...SUBAGENT_PROGRESS_EVENTS, \"message_end\"]);\n"]}
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Canonical set of AgentSession event `type`s that a spawned subagent writes to
3
+ * its stdout JSON stream, shared so the child emitter (print-mode) and the
4
+ * parent consumer (SubagentPool) cannot drift apart.
5
+ *
6
+ * A subagent child otherwise emits the full per-delta event firehose
7
+ * (`message_update`, `tool_execution_update`, `message_start`, …). The parent
8
+ * only ever consumes:
9
+ * - the progress events below, forwarded to the UI as `task_progress`, and
10
+ * - `message_end`, whose usage the parent's TokenBudget accumulates.
11
+ * Everything else is dropped at the source so the firehose never crosses the
12
+ * pipe (and is never framed/parsed on the parent's UI event loop). The child's
13
+ * authoritative result travels via `result.json`, not this stream, and liveness
14
+ * travels via a separate periodic `ping`, so this filtering is lossless for the
15
+ * parent.
16
+ */
17
+ export const SUBAGENT_PROGRESS_EVENTS = new Set([
18
+ "turn_end",
19
+ "tool_execution_start",
20
+ "tool_execution_end",
21
+ ]);
22
+ /** Superset the child actually writes: progress events plus `message_end` (token
23
+ * usage for the parent budget). */
24
+ export const SUBAGENT_STDOUT_EVENT_TYPES = new Set([...SUBAGENT_PROGRESS_EVENTS, "message_end"]);
25
+ //# sourceMappingURL=subagent-events.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"subagent-events.js","sourceRoot":"","sources":["../../src/core/subagent-events.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,MAAM,CAAC,MAAM,wBAAwB,GAAwB,IAAI,GAAG,CAAC;IACpE,UAAU;IACV,sBAAsB;IACtB,oBAAoB;CACpB,CAAC,CAAC;AAEH;mCACmC;AACnC,MAAM,CAAC,MAAM,2BAA2B,GAAwB,IAAI,GAAG,CAAC,CAAC,GAAG,wBAAwB,EAAE,aAAa,CAAC,CAAC,CAAC","sourcesContent":["/**\n * Canonical set of AgentSession event `type`s that a spawned subagent writes to\n * its stdout JSON stream, shared so the child emitter (print-mode) and the\n * parent consumer (SubagentPool) cannot drift apart.\n *\n * A subagent child otherwise emits the full per-delta event firehose\n * (`message_update`, `tool_execution_update`, `message_start`, …). The parent\n * only ever consumes:\n * - the progress events below, forwarded to the UI as `task_progress`, and\n * - `message_end`, whose usage the parent's TokenBudget accumulates.\n * Everything else is dropped at the source so the firehose never crosses the\n * pipe (and is never framed/parsed on the parent's UI event loop). The child's\n * authoritative result travels via `result.json`, not this stream, and liveness\n * travels via a separate periodic `ping`, so this filtering is lossless for the\n * parent.\n */\nexport const SUBAGENT_PROGRESS_EVENTS: ReadonlySet<string> = new Set([\n\t\"turn_end\",\n\t\"tool_execution_start\",\n\t\"tool_execution_end\",\n]);\n\n/** Superset the child actually writes: progress events plus `message_end` (token\n * usage for the parent budget). */\nexport const SUBAGENT_STDOUT_EVENT_TYPES: ReadonlySet<string> = new Set([...SUBAGENT_PROGRESS_EVENTS, \"message_end\"]);\n"]}
@@ -101,10 +101,11 @@ export interface SubagentPoolOptions {
101
101
  export declare const DEFAULT_SUBAGENT_MAX_TURNS = 50;
102
102
  /**
103
103
  * AgentSession event `type`s forwarded from a subagent's json event stream as
104
- * `task_progress` events. Deliberately coarse: the child also emits per-delta
105
- * `message_update` / `tool_execution_update` events (a high-volume firehose) and
106
- * large `message_*` bodies, which are dropped here to keep the parent's event loop
107
- * and the task panel from thrashing under concurrent subagents.
104
+ * `task_progress` events. Deliberately coarse; the child now also filters its
105
+ * stdout to this set plus `message_end` at the source (see
106
+ * SUBAGENT_STDOUT_EVENT_TYPES), so the per-delta firehose no longer crosses the
107
+ * pipe. Re-exported from the shared module so the child emitter and this
108
+ * consumer stay in lockstep.
108
109
  */
109
110
  export declare const FORWARDED_SUBAGENT_EVENTS: ReadonlySet<string>;
110
111
  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AM,CAAC;QAAC,UAAU,CAAC,EAAE,MAAM,CAAC;QAAC,MAAM,CAAC,EAAE,MAAM,CAAA;KAAE,CASrF;IAED;;;OAGG;IACH,OAAO,CAAC,aAAa;IA4CrB;;;;OAIG;IACH,OAAO,CAAC,OAAO,EAAE,MAAM,GAAG,cAAc,GAAG,SAAS,CAEnD;IAED,8DAA8D;IAC9D,cAAc,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,GAAE,MAAiB,GAAG,MAAM,CAE9D;IAED;;;;OAIG;IACG,MAAM,CACX,OAAO,EAAE,MAAM,EACf,MAAM,EAAE,MAAM,EACd,OAAO,GAAE,IAAI,CAAC,eAAe,EAAE,YAAY,GAAG,aAAa,CAAM,GAC/D,OAAO,CAAC,UAAU,CAAC,CAUrB;IAED,gFAAgF;IAChF,OAAO,CAAC,qBAAqB;IAW7B,OAAO,CAAC,gBAAgB;IA0BxB,OAAO,CAAC,eAAe;IAsBvB;;;OAGG;IACH,OAAO,CAAC,kBAAkB;IAQ1B,+EAA+E;IAC/E,OAAO,IAAI,IAAI,CA8Bd;IAED,2DAA2D;IAC3D,OAAO,CAAC,IAAI;IAOZ,sCAAsC;IACtC,OAAO,CAAC,SAAS;IAkGjB;;;;;;;;;OASG;IACH,OAAO,CAAC,aAAa;IAerB,kEAAkE;IAClE,OAAO,CAAC,SAAS;IA4SjB,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 { writeFileAtomicSync } from \"../utils/atomic-file.js\";\nimport { waitForChildProcess } from \"../utils/child-process.js\";\nimport { killProcessTree } from \"../utils/shell.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\" | \"cancelled\";\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/**\n * Cap on the captured stdout/stderr text kept per task (tail-truncated). The\n * capture exists for diagnostics (failure reasons, output.json), so keeping the\n * most recent tail is enough; without a cap a chatty child could grow the\n * parent's memory without bound across a long swarm.\n */\nexport const MAX_CAPTURED_STREAM_CHARS = 256 * 1024;\n\n/**\n * Cap on a single un-terminated JSONL line buffered from a child's stdout. The\n * forwarded events are small; anything approaching this is a runaway writer,\n * and the reader drops the line rather than buffering toward OOM.\n */\nexport const MAX_SUBAGENT_EVENT_LINE_CHARS = 8 * 1024 * 1024;\n\n/** Append a chunk to a capped capture buffer, keeping the most recent tail. */\nfunction appendTail(current: string, chunk: string, cap: number = MAX_CAPTURED_STREAM_CHARS): string {\n\tconst next = current + chunk;\n\treturn next.length > cap ? next.slice(next.length - cap) : next;\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 * - \"task_cancelled\" – user-initiated cancel (see cancel()); process tree killed\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 / user cancel) before exit handler fires. */\n\tprivate killReasons = new Map<string, \"stalled\" | \"timeout\" | \"cancelled\">();\n\t/** Persistent terminal status map, survives wait_for consumption. */\n\tprivate taskStatus = new Map<string, \"done\" | \"failed\" | \"stalled\" | \"timeout\" | \"cancelled\">();\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(\n\t\ttask_id: string,\n\t): \"running\" | \"queued\" | \"done\" | \"failed\" | \"stalled\" | \"timeout\" | \"cancelled\" | \"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.status === \"cancelled\") return \"cancelled\";\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/**\n\t * Cancel a task on the user's behalf (Esc/abort mid-turn). A queued task is\n\t * removed and settles immediately; a running task's whole process tree is\n\t * killed and settles with status \"cancelled\" when its exit is observed\n\t * (unless it already wrote a valid result.json — completed work is honored).\n\t * Returns false for unknown/settled task ids.\n\t */\n\tcancel(task_id: string): boolean {\n\t\tconst queued = this.queue.findIndex((t) => t.task_id === task_id);\n\t\tif (queued !== -1) {\n\t\t\tthis.queue.splice(queued, 1);\n\t\t\tconst result: SubagentResult = {\n\t\t\t\ttask_id,\n\t\t\t\tok: false,\n\t\t\t\tstdout: \"\",\n\t\t\t\tstderr: \"\",\n\t\t\t\texit_code: null,\n\t\t\t\terror: \"cancelled before start\",\n\t\t\t\tstatus: \"cancelled\",\n\t\t\t};\n\t\t\tthis.emit(\"task_cancelled\", { task_id });\n\t\t\tthis.resolveWaiter(task_id, result);\n\t\t\treturn true;\n\t\t}\n\t\tconst slot = this.slots.get(task_id);\n\t\tif (!slot) return false;\n\t\tthis.killReasons.set(task_id, \"cancelled\");\n\t\tif (slot.pid > 0) {\n\t\t\tkillProcessTree(slot.pid);\n\t\t} else if (!slot.process.killed) {\n\t\t\tslot.process.kill(\"SIGKILL\");\n\t\t}\n\t\treturn true;\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\t// Atomic like result.json: background pollers may read output.json while\n\t\t\t// it is being (re)written.\n\t\t\twriteFileAtomicSync(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\t// Kill the whole process group/tree, not just the direct child: a\n\t\t\t// subagent's own children (bash commands, nested subagents) must not\n\t\t\t// outlive the pool.\n\t\t\tif (slot.pid > 0) {\n\t\t\t\tkillProcessTree(slot.pid);\n\t\t\t} else if (!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\t// POSIX: the child leads its own process group so a kill can reach its\n\t\t\t\t// whole tree (see lifeguard/dispose). A single-PID SIGKILL orphans any\n\t\t\t\t// grandchildren the subagent spawned (its own bash commands, nested\n\t\t\t\t// subagents), which kept burning CPU after their parent was reaped.\n\t\t\t\tdetached: process.platform !== \"win32\",\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\t// Capture (tail-capped) for diagnostics, and treat any output as a\n\t\t\t// heartbeat: a child busily streaming events is alive even when the\n\t\t\t// parent's starved event loop hasn't parsed its {\"ping\":true} line yet.\n\t\t\t// All *parsing* happens in the single JSONL reader below.\n\t\t\tstdout = appendTail(stdout, data.toString());\n\t\t\tthis.lifeguard.recordHeartbeat(task.task_id);\n\t\t});\n\n\t\t// The one parser on the child's stdout: UTF-8-safe, LF-only framing —\n\t\t// multi-byte characters and large events split across pipe chunks are\n\t\t// reassembled before parsing. Each complete line feeds the token budget\n\t\t// (usage telemetry) and the ping/forward/drop classifier; previously the\n\t\t// budget ran its own naive chunk-splitting parser on the same stream, which\n\t\t// corrupted lines split mid-character. The line buffer is capped so a\n\t\t// runaway writer cannot OOM the parent. Detached when the child exits (see\n\t\t// cleanup below); the reader also self-detaches on stream error/close.\n\t\tif (proc.stdout) {\n\t\t\tdetachStdoutReader = attachJsonlLineReader(\n\t\t\t\tproc.stdout,\n\t\t\t\t(line) => {\n\t\t\t\t\tbudget.processLine(line);\n\t\t\t\t\tconst action = classifySubagentLine(line);\n\t\t\t\t\tif (action.kind === \"heartbeat\") {\n\t\t\t\t\t\tthis.lifeguard.recordHeartbeat(task.task_id);\n\t\t\t\t\t} else if (action.kind === \"progress\") {\n\t\t\t\t\t\tthis.emit(\"task_progress\", {\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\tevent: action.event,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{ maxBuffer: MAX_SUBAGENT_EVENT_LINE_CHARS },\n\t\t\t);\n\t\t}\n\t\tproc.stderr?.on(\"data\", (data: Buffer) => {\n\t\t\tstderr = appendTail(stderr, data.toString());\n\t\t});\n\n\t\t// True when this attempt scheduled another run of the same task id (spawn\n\t\t// retry or inherited-model fallback). The retry reuses the task's TokenBudget\n\t\t// so usage accumulates across attempts; the .finally below must then leave\n\t\t// the budget (and its listeners) alone instead of tearing it down under the\n\t\t// retry's feet.\n\t\tlet retryScheduled = false;\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\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 (lifeguard reap or user cancel) before producing a valid\n\t\t\t\t// result, honor the kill; a child that already wrote a verified\n\t\t\t\t// result.json completed its work and settles as a success below.\n\t\t\t\tif (killReason !== undefined && !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\tretryScheduled = true;\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\t// The retry (started synchronously here) looks the budget up from\n\t\t\t\t\t// this.budgets and reuses it; flag it so the .finally below doesn't\n\t\t\t\t\t// strip the budget's listeners or delete the entry the retry now owns.\n\t\t\t\t\tretryScheduled = true;\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\t// Runs on success AND failure: the stdout reader used to be detached only\n\t\t\t\t// on the success path, leaking listeners (and their buffers) whenever a\n\t\t\t\t// child failed or the wait rejected.\n\t\t\t\tdetachStdoutReader?.();\n\t\t\t\tproc.stdout?.removeAllListeners(\"data\");\n\t\t\t\tproc.stderr?.removeAllListeners(\"data\");\n\t\t\t\tproc.stdout?.destroy();\n\t\t\t\tproc.stderr?.destroy();\n\t\t\t\tif (!retryScheduled) {\n\t\t\t\t\tbudget.removeAllListeners();\n\t\t\t\t\tthis.budgets.delete(task.task_id);\n\t\t\t\t}\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.status === \"cancelled\") this.taskStatus.set(task_id, \"cancelled\");\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"]}
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,EAA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G,SAAS,CAEnD;IAED,8DAA8D;IAC9D,cAAc,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,GAAE,MAAiB,GAAG,MAAM,CAE9D;IAED;;;;OAIG;IACG,MAAM,CACX,OAAO,EAAE,MAAM,EACf,MAAM,EAAE,MAAM,EACd,OAAO,GAAE,IAAI,CAAC,eAAe,EAAE,YAAY,GAAG,aAAa,CAAM,GAC/D,OAAO,CAAC,UAAU,CAAC,CAUrB;IAED,gFAAgF;IAChF,OAAO,CAAC,qBAAqB;IAW7B,OAAO,CAAC,gBAAgB;IA0BxB,OAAO,CAAC,eAAe;IAsBvB;;;OAGG;IACH,OAAO,CAAC,kBAAkB;IAQ1B,+EAA+E;IAC/E,OAAO,IAAI,IAAI,CA8Bd;IAED,2DAA2D;IAC3D,OAAO,CAAC,IAAI;IAOZ,sCAAsC;IACtC,OAAO,CAAC,SAAS;IAkGjB;;;;;;;;;OASG;IACH,OAAO,CAAC,aAAa;IAerB,kEAAkE;IAClE,OAAO,CAAC,SAAS;IA4SjB,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 { writeFileAtomicSync } from \"../utils/atomic-file.js\";\nimport { waitForChildProcess } from \"../utils/child-process.js\";\nimport { killProcessTree } from \"../utils/shell.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 { SUBAGENT_PROGRESS_EVENTS } from \"./subagent-events.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\" | \"cancelled\";\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 now also filters its\n * stdout to this set plus `message_end` at the source (see\n * SUBAGENT_STDOUT_EVENT_TYPES), so the per-delta firehose no longer crosses the\n * pipe. Re-exported from the shared module so the child emitter and this\n * consumer stay in lockstep.\n */\nexport const FORWARDED_SUBAGENT_EVENTS = SUBAGENT_PROGRESS_EVENTS;\n\n/**\n * Cap on the captured stdout/stderr text kept per task (tail-truncated). The\n * capture exists for diagnostics (failure reasons, output.json), so keeping the\n * most recent tail is enough; without a cap a chatty child could grow the\n * parent's memory without bound across a long swarm.\n */\nexport const MAX_CAPTURED_STREAM_CHARS = 256 * 1024;\n\n/**\n * Cap on a single un-terminated JSONL line buffered from a child's stdout. The\n * forwarded events are small; anything approaching this is a runaway writer,\n * and the reader drops the line rather than buffering toward OOM.\n */\nexport const MAX_SUBAGENT_EVENT_LINE_CHARS = 8 * 1024 * 1024;\n\n/** Append a chunk to a capped capture buffer, keeping the most recent tail. */\nfunction appendTail(current: string, chunk: string, cap: number = MAX_CAPTURED_STREAM_CHARS): string {\n\tconst next = current + chunk;\n\treturn next.length > cap ? next.slice(next.length - cap) : next;\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 * - \"task_cancelled\" – user-initiated cancel (see cancel()); process tree killed\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 / user cancel) before exit handler fires. */\n\tprivate killReasons = new Map<string, \"stalled\" | \"timeout\" | \"cancelled\">();\n\t/** Persistent terminal status map, survives wait_for consumption. */\n\tprivate taskStatus = new Map<string, \"done\" | \"failed\" | \"stalled\" | \"timeout\" | \"cancelled\">();\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(\n\t\ttask_id: string,\n\t): \"running\" | \"queued\" | \"done\" | \"failed\" | \"stalled\" | \"timeout\" | \"cancelled\" | \"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.status === \"cancelled\") return \"cancelled\";\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/**\n\t * Cancel a task on the user's behalf (Esc/abort mid-turn). A queued task is\n\t * removed and settles immediately; a running task's whole process tree is\n\t * killed and settles with status \"cancelled\" when its exit is observed\n\t * (unless it already wrote a valid result.json — completed work is honored).\n\t * Returns false for unknown/settled task ids.\n\t */\n\tcancel(task_id: string): boolean {\n\t\tconst queued = this.queue.findIndex((t) => t.task_id === task_id);\n\t\tif (queued !== -1) {\n\t\t\tthis.queue.splice(queued, 1);\n\t\t\tconst result: SubagentResult = {\n\t\t\t\ttask_id,\n\t\t\t\tok: false,\n\t\t\t\tstdout: \"\",\n\t\t\t\tstderr: \"\",\n\t\t\t\texit_code: null,\n\t\t\t\terror: \"cancelled before start\",\n\t\t\t\tstatus: \"cancelled\",\n\t\t\t};\n\t\t\tthis.emit(\"task_cancelled\", { task_id });\n\t\t\tthis.resolveWaiter(task_id, result);\n\t\t\treturn true;\n\t\t}\n\t\tconst slot = this.slots.get(task_id);\n\t\tif (!slot) return false;\n\t\tthis.killReasons.set(task_id, \"cancelled\");\n\t\tif (slot.pid > 0) {\n\t\t\tkillProcessTree(slot.pid);\n\t\t} else if (!slot.process.killed) {\n\t\t\tslot.process.kill(\"SIGKILL\");\n\t\t}\n\t\treturn true;\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\t// Atomic like result.json: background pollers may read output.json while\n\t\t\t// it is being (re)written.\n\t\t\twriteFileAtomicSync(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\t// Kill the whole process group/tree, not just the direct child: a\n\t\t\t// subagent's own children (bash commands, nested subagents) must not\n\t\t\t// outlive the pool.\n\t\t\tif (slot.pid > 0) {\n\t\t\t\tkillProcessTree(slot.pid);\n\t\t\t} else if (!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\t// POSIX: the child leads its own process group so a kill can reach its\n\t\t\t\t// whole tree (see lifeguard/dispose). A single-PID SIGKILL orphans any\n\t\t\t\t// grandchildren the subagent spawned (its own bash commands, nested\n\t\t\t\t// subagents), which kept burning CPU after their parent was reaped.\n\t\t\t\tdetached: process.platform !== \"win32\",\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\t// Capture (tail-capped) for diagnostics, and treat any output as a\n\t\t\t// heartbeat: a child busily streaming events is alive even when the\n\t\t\t// parent's starved event loop hasn't parsed its {\"ping\":true} line yet.\n\t\t\t// All *parsing* happens in the single JSONL reader below.\n\t\t\tstdout = appendTail(stdout, data.toString());\n\t\t\tthis.lifeguard.recordHeartbeat(task.task_id);\n\t\t});\n\n\t\t// The one parser on the child's stdout: UTF-8-safe, LF-only framing —\n\t\t// multi-byte characters and large events split across pipe chunks are\n\t\t// reassembled before parsing. Each complete line feeds the token budget\n\t\t// (usage telemetry) and the ping/forward/drop classifier; previously the\n\t\t// budget ran its own naive chunk-splitting parser on the same stream, which\n\t\t// corrupted lines split mid-character. The line buffer is capped so a\n\t\t// runaway writer cannot OOM the parent. Detached when the child exits (see\n\t\t// cleanup below); the reader also self-detaches on stream error/close.\n\t\tif (proc.stdout) {\n\t\t\tdetachStdoutReader = attachJsonlLineReader(\n\t\t\t\tproc.stdout,\n\t\t\t\t(line) => {\n\t\t\t\t\tbudget.processLine(line);\n\t\t\t\t\tconst action = classifySubagentLine(line);\n\t\t\t\t\tif (action.kind === \"heartbeat\") {\n\t\t\t\t\t\tthis.lifeguard.recordHeartbeat(task.task_id);\n\t\t\t\t\t} else if (action.kind === \"progress\") {\n\t\t\t\t\t\tthis.emit(\"task_progress\", {\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\tevent: action.event,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{ maxBuffer: MAX_SUBAGENT_EVENT_LINE_CHARS },\n\t\t\t);\n\t\t}\n\t\tproc.stderr?.on(\"data\", (data: Buffer) => {\n\t\t\tstderr = appendTail(stderr, data.toString());\n\t\t});\n\n\t\t// True when this attempt scheduled another run of the same task id (spawn\n\t\t// retry or inherited-model fallback). The retry reuses the task's TokenBudget\n\t\t// so usage accumulates across attempts; the .finally below must then leave\n\t\t// the budget (and its listeners) alone instead of tearing it down under the\n\t\t// retry's feet.\n\t\tlet retryScheduled = false;\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\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 (lifeguard reap or user cancel) before producing a valid\n\t\t\t\t// result, honor the kill; a child that already wrote a verified\n\t\t\t\t// result.json completed its work and settles as a success below.\n\t\t\t\tif (killReason !== undefined && !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\tretryScheduled = true;\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\t// The retry (started synchronously here) looks the budget up from\n\t\t\t\t\t// this.budgets and reuses it; flag it so the .finally below doesn't\n\t\t\t\t\t// strip the budget's listeners or delete the entry the retry now owns.\n\t\t\t\t\tretryScheduled = true;\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\t// Runs on success AND failure: the stdout reader used to be detached only\n\t\t\t\t// on the success path, leaking listeners (and their buffers) whenever a\n\t\t\t\t// child failed or the wait rejected.\n\t\t\t\tdetachStdoutReader?.();\n\t\t\t\tproc.stdout?.removeAllListeners(\"data\");\n\t\t\t\tproc.stderr?.removeAllListeners(\"data\");\n\t\t\t\tproc.stdout?.destroy();\n\t\t\t\tproc.stderr?.destroy();\n\t\t\t\tif (!retryScheduled) {\n\t\t\t\t\tbudget.removeAllListeners();\n\t\t\t\t\tthis.budgets.delete(task.task_id);\n\t\t\t\t}\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.status === \"cancelled\") this.taskStatus.set(task_id, \"cancelled\");\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"]}
@@ -14,6 +14,7 @@ import { SubagentLifeguard } from "./lifeguard.js";
14
14
  import { resolveModelReference } from "./model-categories.js";
15
15
  import { OutputVerifier } from "./output-verifier.js";
16
16
  import { currentSubagentDepth, resolveMaxSubagentDepth, SUBAGENT_DEPTH_ENV, SUBAGENT_SKIP_MCP_ENV, toolAllowlistNeedsMcp, } from "./subagent-depth.js";
17
+ import { SUBAGENT_PROGRESS_EVENTS } from "./subagent-events.js";
17
18
  import { TokenBudget } from "./token-budget.js";
18
19
  /**
19
20
  * Provider/model failure signatures where inheriting the parent model can
@@ -28,16 +29,13 @@ const INHERITED_MODEL_FALLBACK_ERROR = /usage[_\s-]?limit|subscription|quota|rat
28
29
  export const DEFAULT_SUBAGENT_MAX_TURNS = 50;
29
30
  /**
30
31
  * AgentSession event `type`s forwarded from a subagent's json event stream as
31
- * `task_progress` events. Deliberately coarse: the child also emits per-delta
32
- * `message_update` / `tool_execution_update` events (a high-volume firehose) and
33
- * large `message_*` bodies, which are dropped here to keep the parent's event loop
34
- * and the task panel from thrashing under concurrent subagents.
32
+ * `task_progress` events. Deliberately coarse; the child now also filters its
33
+ * stdout to this set plus `message_end` at the source (see
34
+ * SUBAGENT_STDOUT_EVENT_TYPES), so the per-delta firehose no longer crosses the
35
+ * pipe. Re-exported from the shared module so the child emitter and this
36
+ * consumer stay in lockstep.
35
37
  */
36
- export const FORWARDED_SUBAGENT_EVENTS = new Set([
37
- "turn_end",
38
- "tool_execution_start",
39
- "tool_execution_end",
40
- ]);
38
+ export const FORWARDED_SUBAGENT_EVENTS = SUBAGENT_PROGRESS_EVENTS;
41
39
  /**
42
40
  * Cap on the captured stdout/stderr text kept per task (tail-truncated). The
43
41
  * capture exists for diagnostics (failure reasons, output.json), so keeping the