@kolisachint/hoocode-agent 0.4.110 → 0.4.111
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +61 -0
- package/dist/core/format-duration.d.ts +7 -0
- package/dist/core/format-duration.d.ts.map +1 -0
- package/dist/core/format-duration.js +16 -0
- package/dist/core/format-duration.js.map +1 -0
- package/dist/core/keybindings.d.ts +10 -0
- package/dist/core/keybindings.d.ts.map +1 -1
- package/dist/core/keybindings.js +10 -0
- package/dist/core/keybindings.js.map +1 -1
- package/dist/core/lifeguard.d.ts +15 -0
- package/dist/core/lifeguard.d.ts.map +1 -1
- package/dist/core/lifeguard.js +48 -18
- package/dist/core/lifeguard.js.map +1 -1
- package/dist/core/subagent-inbox.d.ts +1 -1
- package/dist/core/subagent-inbox.d.ts.map +1 -1
- package/dist/core/subagent-inbox.js +2 -0
- package/dist/core/subagent-inbox.js.map +1 -1
- package/dist/core/subagent-pool-instance.d.ts.map +1 -1
- package/dist/core/subagent-pool-instance.js +18 -11
- package/dist/core/subagent-pool-instance.js.map +1 -1
- package/dist/core/subagent-pool.d.ts +25 -3
- package/dist/core/subagent-pool.d.ts.map +1 -1
- package/dist/core/subagent-pool.js +120 -25
- package/dist/core/subagent-pool.js.map +1 -1
- package/dist/core/subagent-result.d.ts.map +1 -1
- package/dist/core/subagent-result.js +6 -4
- package/dist/core/subagent-result.js.map +1 -1
- package/dist/core/task-store.d.ts +45 -3
- package/dist/core/task-store.d.ts.map +1 -1
- package/dist/core/task-store.js +51 -5
- package/dist/core/task-store.js.map +1 -1
- package/dist/core/team-view.d.ts.map +1 -1
- package/dist/core/team-view.js +2 -0
- package/dist/core/team-view.js.map +1 -1
- package/dist/core/token-budget.d.ts +13 -1
- package/dist/core/token-budget.d.ts.map +1 -1
- package/dist/core/token-budget.js +18 -1
- package/dist/core/token-budget.js.map +1 -1
- package/dist/core/tools/subagent.d.ts +1 -1
- package/dist/core/tools/subagent.d.ts.map +1 -1
- package/dist/core/tools/subagent.js +184 -53
- package/dist/core/tools/subagent.js.map +1 -1
- package/dist/core/tools/todo.d.ts.map +1 -1
- package/dist/core/tools/todo.js +39 -7
- package/dist/core/tools/todo.js.map +1 -1
- package/dist/modes/interactive/components/keybinding-hints.d.ts +10 -0
- package/dist/modes/interactive/components/keybinding-hints.d.ts.map +1 -1
- package/dist/modes/interactive/components/keybinding-hints.js +27 -1
- package/dist/modes/interactive/components/keybinding-hints.js.map +1 -1
- package/dist/modes/interactive/components/task-panel.d.ts +22 -1
- package/dist/modes/interactive/components/task-panel.d.ts.map +1 -1
- package/dist/modes/interactive/components/task-panel.js +302 -80
- package/dist/modes/interactive/components/task-panel.js.map +1 -1
- package/dist/modes/interactive/components/team-attach-panel.d.ts.map +1 -1
- package/dist/modes/interactive/components/team-attach-panel.js +15 -5
- package/dist/modes/interactive/components/team-attach-panel.js.map +1 -1
- package/dist/modes/interactive/theme/dark.json +8 -1
- package/dist/modes/interactive/theme/light.json +8 -1
- package/dist/modes/interactive/theme/theme-schema.json +28 -1
- package/dist/modes/interactive/theme/theme.d.ts +12 -1
- package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
- package/dist/modes/interactive/theme/theme.js +52 -0
- package/dist/modes/interactive/theme/theme.js.map +1 -1
- package/dist/modes/interactive/voice/voice-panel.d.ts.map +1 -1
- package/dist/modes/interactive/voice/voice-panel.js +5 -2
- package/dist/modes/interactive/voice/voice-panel.js.map +1 -1
- package/dist/modes/rpc/jsonl.d.ts +16 -1
- package/dist/modes/rpc/jsonl.d.ts.map +1 -1
- package/dist/modes/rpc/jsonl.js +53 -8
- package/dist/modes/rpc/jsonl.js.map +1 -1
- package/dist/utils/atomic-file.d.ts +13 -0
- package/dist/utils/atomic-file.d.ts.map +1 -0
- package/dist/utils/atomic-file.js +26 -0
- package/dist/utils/atomic-file.js.map +1 -0
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package.json +1 -1
- package/package.json +4 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lifeguard.js","sourceRoot":"","sources":["../../src/core/lifeguard.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,YAAY,EAAE,SAAS,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACjG,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAE/C,MAAM,WAAW,GAA2B;IAC3C,OAAO,EAAE,CAAC,GAAG,EAAE,GAAG,IAAI;IACtB,IAAI,EAAE,EAAE,GAAG,EAAE,GAAG,IAAI;IACpB,IAAI,EAAE,EAAE,GAAG,EAAE,GAAG,IAAI;IACpB,MAAM,EAAE,CAAC,GAAG,EAAE,GAAG,IAAI;IACrB,GAAG,EAAE,CAAC,GAAG,EAAE,GAAG,IAAI;CAClB,CAAC;AAEF,MAAM,2BAA2B,GAAG,KAAK,CAAC;AAC1C,MAAM,2BAA2B,GAAG,IAAI,CAAC;AACzC,MAAM,wBAAwB,GAAG,IAAI,CAAC;AAEtC;;;;;;;;;;GAUG;AACH,MAAM,0BAA0B,GAAG,GAAG,CAAC;AAEvC;;;GAGG;AACH,MAAM,mBAAmB,GAAG,CAAC,CAAC;AAS9B;;;;GAIG;AACH,MAAM,OAAO,iBAAkB,SAAQ,YAAY;IAC1C,SAAS,GAAG,IAAI,GAAG,EAA4B,CAAC;IAChD,aAAa,GAAG,IAAI,GAAG,EAAkB,CAAC;IAC1C,QAAQ,GAAG,IAAI,GAAG,EAA0B,CAAC;IACrD,4EAA4E;IACpE,SAAS,GAAG,IAAI,GAAG,EAAkB,CAAC;IAC9C,gFAAgF;IACxE,aAAa,GAAG,IAAI,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GAAG,EAAE,KAAK,CAAC,CAAC;YACnC,IAAI,CAAC;gBACJ,MAAM,KAAK,GAAG,QAAQ,CAAC,SAAS,CAAC,CAAC;gBAClC,IAAI,KAAK,CAAC,WAAW,EAAE,EAAE,CAAC;oBACzB,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;gBACtB,CAAC;qBAAM,CAAC;oBACP,UAAU,CAAC,SAAS,CAAC,CAAC;gBACvB,CAAC;YACF,CAAC;YAAC,MAAM,CAAC;gBACR,SAAS;YACV,CAAC;QACF,CAAC;QACD,IAAI,CAAC;YACJ,SAAS,CAAC,GAAG,CAAC,CAAC;QAChB,CAAC;QAAC,MAAM,CAAC;YACR,SAAS;QACV,CAAC;IAAA,CACD;CACD","sourcesContent":["import type { ChildProcess } from \"node:child_process\";\nimport { EventEmitter } from \"node:events\";\nimport { existsSync, readdirSync, readFileSync, rmdirSync, statSync, unlinkSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { getDispatchRoot } from \"../config.js\";\n\nconst TIMEOUTS_MS: Record<string, number> = {\n\texplore: 5 * 60 * 1000,\n\tedit: 10 * 60 * 1000,\n\ttest: 10 * 60 * 1000,\n\treview: 8 * 60 * 1000,\n\tdoc: 5 * 60 * 1000,\n};\n\nconst HEARTBEAT_MISS_THRESHOLD_MS = 60000;\nconst HEARTBEAT_CHECK_INTERVAL_MS = 5000;\nconst PARENT_SHUTDOWN_GRACE_MS = 5000;\n\n/**\n * Concurrency tolerance. Each *additional* concurrently-monitored subagent adds\n * this fraction to the heartbeat-miss and hard-timeout budgets.\n *\n * When several subagents run at once (plus background MCP tools), they saturate\n * the CPU and starve the parent's event loop: its `setInterval` heartbeat check\n * fires late, and it cannot read a child's `{\"ping\":true}` line in time even\n * though the child is healthy and still working. Scaling the budgets by load\n * stops that contention from false-positive SIGKILLing healthy subagents — the\n * failure the demo hit when running many agents + MCP tools in the background.\n */\nconst LOAD_TOLERANCE_PER_PROCESS = 0.5;\n\n/**\n * Hard ceiling on the load tolerance multiplier, so a genuinely stuck subagent\n * is still eventually reaped no matter how busy the pool is.\n */\nconst MAX_LOAD_MULTIPLIER = 4;\n\nexport interface LifeguardProcess {\n\tpid: number;\n\ttask_id: string;\n\tagent_type: string;\n\tprocess: ChildProcess;\n}\n\n/**\n * Monitors running subagent processes for heartbeats, hard timeouts,\n * and parent-exit cleanup. Emits \"stalled\" and \"timeout\" events when\n * processes are terminated.\n */\nexport class SubagentLifeguard extends EventEmitter {\n\tprivate processes = new Map<string, LifeguardProcess>();\n\tprivate lastHeartbeat = new Map<string, number>();\n\tprivate timeouts = new Map<string, NodeJS.Timeout>();\n\t/** When each task started, used to compute the load-scaled hard timeout. */\n\tprivate startedAt = new Map<string, number>();\n\t/** Per-agent base hard timeout (before load scaling), captured at monitor(). */\n\tprivate baseTimeoutMs = new Map<string, number>();\n\tprivate checkInterval: NodeJS.Timeout | null = null;\n\t/** Wall-clock time the heartbeat check last ran, to measure event-loop lag. */\n\tprivate lastCheckAt = Date.now();\n\t/**\n\t * Count of external in-process tasks (e.g. background MCP tools) running in the\n\t * parent alongside the monitored subagents. These don't show up in `processes`\n\t * but still saturate the parent's CPU/event loop, so they're folded into the\n\t * load multiplier. Updated by the pool via setExternalLoad().\n\t */\n\tprivate externalLoad = 0;\n\tprivate disposed = false;\n\tprivate readonly cwd: string;\n\tprivate parentShutdownHandler?: () => void;\n\n\tconstructor(cwd: string) {\n\t\tsuper();\n\t\tthis.cwd = cwd;\n\t\tthis.setupParentExitHandlers();\n\t\tthis.sweepOldAgents();\n\t\tthis.lastCheckAt = Date.now();\n\t\tthis.checkInterval = setInterval(() => this.checkHeartbeats(), HEARTBEAT_CHECK_INTERVAL_MS);\n\t}\n\n\t/**\n\t * Set the count of external in-process tasks (background MCP tools) sharing the\n\t * parent's CPU/event loop. Folded into loadMultiplier() so concurrent MCP work\n\t * widens the heartbeat/timeout budgets just like extra monitored subagents do.\n\t * Negative values are clamped to 0.\n\t */\n\tsetExternalLoad(count: number): void {\n\t\tthis.externalLoad = Math.max(0, Math.floor(count));\n\t}\n\n\t/**\n\t * Tolerance multiplier for the current load. 1 concurrent task → 1x; each extra\n\t * concurrent task adds LOAD_TOLERANCE_PER_PROCESS, capped at MAX_LOAD_MULTIPLIER.\n\t * Concurrency counts both monitored subagents and external load (background MCP\n\t * tools), since both contend for the same parent event loop.\n\t */\n\tprivate loadMultiplier(): number {\n\t\tconst concurrent = this.processes.size + this.externalLoad;\n\t\tconst mult = 1 + Math.max(0, concurrent - 1) * LOAD_TOLERANCE_PER_PROCESS;\n\t\treturn Math.min(mult, MAX_LOAD_MULTIPLIER);\n\t}\n\n\t/**\n\t * Begin monitoring a child process. The process must emit a\n\t * `{\"ping\":true}` JSON line on stdout every 30 seconds.\n\t */\n\tmonitor(task_id: string, agent_type: string, proc: ChildProcess): void {\n\t\tif (this.disposed) return;\n\n\t\tconst pid = proc.pid ?? 0;\n\t\tthis.processes.set(task_id, { pid, task_id, agent_type, process: proc });\n\t\tthis.lastHeartbeat.set(task_id, Date.now());\n\n\t\tconst timeoutMs = TIMEOUTS_MS[agent_type] ?? TIMEOUTS_MS.explore;\n\t\tthis.startedAt.set(task_id, Date.now());\n\t\tthis.baseTimeoutMs.set(task_id, timeoutMs);\n\t\t// Arm the hard timeout scaled by current load. When it fires, handleTimeout\n\t\t// re-checks load and re-arms (up to MAX_LOAD_MULTIPLIER) if the pool is still\n\t\t// busy, so a slow-but-progressing subagent isn't killed for CPU contention.\n\t\tconst timeout = setTimeout(\n\t\t\t() => {\n\t\t\t\tthis.handleTimeout(task_id);\n\t\t\t},\n\t\t\tMath.round(timeoutMs * this.loadMultiplier()),\n\t\t);\n\t\tthis.timeouts.set(task_id, timeout);\n\n\t\tproc.once(\"exit\", () => {\n\t\t\tthis.untrack(task_id);\n\t\t});\n\t}\n\n\t/** Record a heartbeat for a monitored task. */\n\trecordHeartbeat(task_id: string): void {\n\t\tif (this.processes.has(task_id)) {\n\t\t\tthis.lastHeartbeat.set(task_id, Date.now());\n\t\t}\n\t}\n\n\t/** Get the last recorded heartbeat timestamp, or null. */\n\tlastHeartbeatAt(task_id: string): number | null {\n\t\treturn this.lastHeartbeat.get(task_id) ?? null;\n\t}\n\n\t/** True if the task is currently being monitored. */\n\tisMonitoring(task_id: string): boolean {\n\t\treturn this.processes.has(task_id);\n\t}\n\n\t/** Kill all monitored processes and clean up. */\n\tdispose(): void {\n\t\tif (this.disposed) return;\n\t\tthis.disposed = true;\n\n\t\tif (this.checkInterval) {\n\t\t\tclearInterval(this.checkInterval);\n\t\t\tthis.checkInterval = null;\n\t\t}\n\n\t\tfor (const timeout of this.timeouts.values()) {\n\t\t\tclearTimeout(timeout);\n\t\t}\n\t\tthis.timeouts.clear();\n\n\t\tfor (const monitored of this.processes.values()) {\n\t\t\tif (!monitored.process.killed) {\n\t\t\t\tmonitored.process.kill(\"SIGKILL\");\n\t\t\t}\n\t\t}\n\t\tthis.processes.clear();\n\t\tthis.lastHeartbeat.clear();\n\t\tthis.startedAt.clear();\n\t\tthis.baseTimeoutMs.clear();\n\t\tthis.removeAllListeners();\n\n\t\tif (this.parentShutdownHandler) {\n\t\t\tprocess.removeListener(\"SIGINT\", this.parentShutdownHandler);\n\t\t\tprocess.removeListener(\"SIGTERM\", this.parentShutdownHandler);\n\t\t}\n\t}\n\n\tprivate checkHeartbeats(): void {\n\t\tconst now = Date.now();\n\t\t// Event-loop lag: how much later than scheduled this check actually ran.\n\t\t// Heavy CPU load (many concurrent subagents + background MCP tools) starves\n\t\t// the loop, delaying both this check *and* our reading of child heartbeats.\n\t\t// Forgive that gap so the parent's own starvation isn't charged against the\n\t\t// children as a missed heartbeat.\n\t\tconst loopLag = Math.max(0, now - this.lastCheckAt - HEARTBEAT_CHECK_INTERVAL_MS);\n\t\tthis.lastCheckAt = now;\n\n\t\tconst threshold = HEARTBEAT_MISS_THRESHOLD_MS * this.loadMultiplier() + loopLag;\n\t\tfor (const [task_id] of this.processes) {\n\t\t\tconst last = this.lastHeartbeat.get(task_id);\n\t\t\tif (last === undefined) continue;\n\t\t\tif (now - last > threshold) {\n\t\t\t\tthis.handleStalled(task_id);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate handleStalled(task_id: string): void {\n\t\tconst monitored = this.processes.get(task_id);\n\t\tif (!monitored) return;\n\n\t\t// Record why we reaped this child so a recurrence is diagnosable rather than\n\t\t// just \"stalled\": how long since the last heartbeat, and the load factors\n\t\t// (concurrent monitored subagents, threshold) that fed the decision.\n\t\tconst last = this.lastHeartbeat.get(task_id);\n\t\tconst silentMs = last === undefined ? -1 : Date.now() - last;\n\t\tconsole.error(\n\t\t\t`[LIFEGUARD] stalled task_id=${task_id} agent=${monitored.agent_type} ` +\n\t\t\t\t`silent_ms=${silentMs} concurrent=${this.processes.size} ` +\n\t\t\t\t`load_mult=${this.loadMultiplier().toFixed(2)} base_threshold_ms=${HEARTBEAT_MISS_THRESHOLD_MS}`,\n\t\t);\n\n\t\tif (!monitored.process.killed) {\n\t\t\tmonitored.process.kill(\"SIGKILL\");\n\t\t}\n\n\t\tthis.emit(\"stalled\", { task_id, pid: monitored.pid });\n\t\t// Process exit handler will call untrack()\n\t}\n\n\tprivate handleTimeout(task_id: string): void {\n\t\tconst monitored = this.processes.get(task_id);\n\t\tif (!monitored) return;\n\n\t\t// Under load the wall-clock timer can fire while the subagent is still doing\n\t\t// real work — its turns are just slow because the CPU is shared. Re-arm rather\n\t\t// than kill, up to a hard ceiling (base * MAX_LOAD_MULTIPLIER) so a genuinely\n\t\t// stuck agent still terminates.\n\t\tconst started = this.startedAt.get(task_id) ?? Date.now();\n\t\tconst base = this.baseTimeoutMs.get(task_id) ?? TIMEOUTS_MS[monitored.agent_type] ?? TIMEOUTS_MS.explore;\n\t\tconst elapsed = Date.now() - started;\n\t\tconst ceiling = base * MAX_LOAD_MULTIPLIER;\n\t\tif (this.loadMultiplier() > 1 && elapsed < ceiling) {\n\t\t\tconst remaining = ceiling - elapsed;\n\t\t\tconst next = Math.min(\n\t\t\t\tMath.round(base * this.loadMultiplier()),\n\t\t\t\tMath.max(HEARTBEAT_CHECK_INTERVAL_MS, remaining),\n\t\t\t);\n\t\t\tthis.timeouts.set(\n\t\t\t\ttask_id,\n\t\t\t\tsetTimeout(() => this.handleTimeout(task_id), next),\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tif (!monitored.process.killed) {\n\t\t\tmonitored.process.kill(\"SIGKILL\");\n\t\t}\n\n\t\tthis.emit(\"timeout\", { task_id, pid: monitored.pid });\n\t\tthis.timeouts.delete(task_id);\n\t\t// Process exit handler will call untrack()\n\t}\n\n\tprivate untrack(task_id: string): void {\n\t\tconst timeout = this.timeouts.get(task_id);\n\t\tif (timeout) {\n\t\t\tclearTimeout(timeout);\n\t\t\tthis.timeouts.delete(task_id);\n\t\t}\n\t\tthis.processes.delete(task_id);\n\t\tthis.lastHeartbeat.delete(task_id);\n\t\tthis.startedAt.delete(task_id);\n\t\tthis.baseTimeoutMs.delete(task_id);\n\t}\n\n\tprivate setupParentExitHandlers(): void {\n\t\tconst shutdown = () => this.gracefulShutdown();\n\t\tthis.parentShutdownHandler = shutdown;\n\t\tprocess.setMaxListeners(Math.max(process.getMaxListeners(), 20));\n\t\tprocess.once(\"SIGINT\", shutdown);\n\t\tprocess.once(\"SIGTERM\", shutdown);\n\t}\n\n\tprivate gracefulShutdown(): void {\n\t\t// SIGTERM all children\n\t\tfor (const monitored of this.processes.values()) {\n\t\t\tif (!monitored.process.killed) {\n\t\t\t\tmonitored.process.kill(\"SIGTERM\");\n\t\t\t}\n\t\t}\n\n\t\t// SIGKILL after grace period\n\t\tsetTimeout(() => {\n\t\t\tfor (const monitored of this.processes.values()) {\n\t\t\t\tif (!monitored.process.killed) {\n\t\t\t\t\tmonitored.process.kill(\"SIGKILL\");\n\t\t\t\t}\n\t\t\t}\n\t\t}, PARENT_SHUTDOWN_GRACE_MS).unref();\n\t}\n\n\tprivate sweepOldAgents(): void {\n\t\tconst dispatchDir = getDispatchRoot(this.cwd);\n\t\tif (!existsSync(dispatchDir)) return;\n\n\t\tconst now = Date.now();\n\t\tconst cutoff = 24 * 60 * 60 * 1000; // 24 hours\n\n\t\tfor (const entry of readdirSync(dispatchDir)) {\n\t\t\tconst entryPath = join(dispatchDir, entry);\n\t\t\ttry {\n\t\t\t\tconst stats = statSync(entryPath);\n\t\t\t\tif (!stats.isDirectory()) continue;\n\n\t\t\t\tif (now - stats.mtimeMs > cutoff) {\n\t\t\t\t\tconst hasRunningPid = this.hasRunningPid(entryPath);\n\t\t\t\t\tif (!hasRunningPid) {\n\t\t\t\t\t\tthis.rmrf(entryPath);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// Ignore errors for individual entries\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate hasRunningPid(dir: string): boolean {\n\t\tconst pidFile = join(dir, \"pid\");\n\t\tif (!existsSync(pidFile)) return false;\n\n\t\ttry {\n\t\t\tconst pid = Number.parseInt(readFileSync(pidFile, \"utf-8\"), 10);\n\t\t\tif (Number.isNaN(pid)) return false;\n\t\t\tprocess.kill(pid, 0); // Check if process exists\n\t\t\treturn true;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tprivate rmrf(dir: string): void {\n\t\tfor (const entry of readdirSync(dir)) {\n\t\t\tconst entryPath = join(dir, entry);\n\t\t\ttry {\n\t\t\t\tconst stats = statSync(entryPath);\n\t\t\t\tif (stats.isDirectory()) {\n\t\t\t\t\tthis.rmrf(entryPath);\n\t\t\t\t} else {\n\t\t\t\t\tunlinkSync(entryPath);\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// Ignore\n\t\t\t}\n\t\t}\n\t\ttry {\n\t\t\trmdirSync(dir);\n\t\t} catch {\n\t\t\t// Ignore\n\t\t}\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"lifeguard.js","sourceRoot":"","sources":["../../src/core/lifeguard.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,aA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,UAAU,CAAC,OAAO,CAAC;YAAE,OAAO,KAAK,CAAC;QAEvC,IAAI,CAAC;YACJ,MAAM,GAAG,GAAG,MAAM,CAAC,QAAQ,CAAC,YAAY,CAAC,OAAO,EAAE,OAAO,CAAC,EAAE,EAAE,CAAC,CAAC;YAChE,IAAI,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC;gBAAE,OAAO,KAAK,CAAC;YACpC,OAAO,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC,0BAA0B;YAChD,OAAO,IAAI,CAAC;QACb,CAAC;QAAC,MAAM,CAAC;YACR,OAAO,KAAK,CAAC;QACd,CAAC;IAAA,CACD;IAEO,IAAI,CAAC,GAAW,EAAQ;QAC/B,KAAK,MAAM,KAAK,IAAI,WAAW,CAAC,GAAG,CAAC,EAAE,CAAC;YACtC,MAAM,SAAS,GAAG,IAAI,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;YACnC,IAAI,CAAC;gBACJ,MAAM,KAAK,GAAG,QAAQ,CAAC,SAAS,CAAC,CAAC;gBAClC,IAAI,KAAK,CAAC,WAAW,EAAE,EAAE,CAAC;oBACzB,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;gBACtB,CAAC;qBAAM,CAAC;oBACP,UAAU,CAAC,SAAS,CAAC,CAAC;gBACvB,CAAC;YACF,CAAC;YAAC,MAAM,CAAC;gBACR,SAAS;YACV,CAAC;QACF,CAAC;QACD,IAAI,CAAC;YACJ,SAAS,CAAC,GAAG,CAAC,CAAC;QAChB,CAAC;QAAC,MAAM,CAAC;YACR,SAAS;QACV,CAAC;IAAA,CACD;CACD","sourcesContent":["import type { ChildProcess } from \"node:child_process\";\nimport { EventEmitter } from \"node:events\";\nimport { existsSync, readdirSync, readFileSync, rmdirSync, statSync, unlinkSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { getDispatchRoot } from \"../config.js\";\nimport { killProcessTree } from \"../utils/shell.js\";\n\nconst TIMEOUTS_MS: Record<string, number> = {\n\texplore: 5 * 60 * 1000,\n\tedit: 10 * 60 * 1000,\n\ttest: 10 * 60 * 1000,\n\treview: 8 * 60 * 1000,\n\tdoc: 5 * 60 * 1000,\n};\n\nconst HEARTBEAT_MISS_THRESHOLD_MS = 60000;\nconst HEARTBEAT_CHECK_INTERVAL_MS = 5000;\nconst PARENT_SHUTDOWN_GRACE_MS = 5000;\n\n/**\n * Concurrency tolerance. Each *additional* concurrently-monitored subagent adds\n * this fraction to the heartbeat-miss and hard-timeout budgets.\n *\n * When several subagents run at once (plus background MCP tools), they saturate\n * the CPU and starve the parent's event loop: its `setInterval` heartbeat check\n * fires late, and it cannot read a child's `{\"ping\":true}` line in time even\n * though the child is healthy and still working. Scaling the budgets by load\n * stops that contention from false-positive SIGKILLing healthy subagents — the\n * failure the demo hit when running many agents + MCP tools in the background.\n */\nconst LOAD_TOLERANCE_PER_PROCESS = 0.5;\n\n/**\n * Hard ceiling on the load tolerance multiplier, so a genuinely stuck subagent\n * is still eventually reaped no matter how busy the pool is.\n */\nconst MAX_LOAD_MULTIPLIER = 4;\n\nexport interface LifeguardProcess {\n\tpid: number;\n\ttask_id: string;\n\tagent_type: string;\n\tprocess: ChildProcess;\n}\n\n/**\n * Monitors running subagent processes for heartbeats, hard timeouts,\n * and parent-exit cleanup. Emits \"stalled\" and \"timeout\" events when\n * processes are terminated.\n */\nexport class SubagentLifeguard extends EventEmitter {\n\tprivate processes = new Map<string, LifeguardProcess>();\n\tprivate lastHeartbeat = new Map<string, number>();\n\tprivate timeouts = new Map<string, NodeJS.Timeout>();\n\t/** When each task started, used to compute the load-scaled hard timeout. */\n\tprivate startedAt = new Map<string, number>();\n\t/** Per-agent base hard timeout (before load scaling), captured at monitor(). */\n\tprivate baseTimeoutMs = new Map<string, number>();\n\tprivate checkInterval: NodeJS.Timeout | null = null;\n\t/** Wall-clock time the heartbeat check last ran, to measure event-loop lag. */\n\tprivate lastCheckAt = Date.now();\n\t/**\n\t * Count of external in-process tasks (e.g. background MCP tools) running in the\n\t * parent alongside the monitored subagents. These don't show up in `processes`\n\t * but still saturate the parent's CPU/event loop, so they're folded into the\n\t * load multiplier. Updated by the pool via setExternalLoad().\n\t */\n\tprivate externalLoad = 0;\n\t/**\n\t * Tasks already reaped (stalled/timeout kill sent) but whose `exit` has not\n\t * fired yet. The heartbeat check runs every 5s, so without this a stalled task\n\t * would re-emit \"stalled\" (and re-kill) on every tick until the process exits.\n\t */\n\tprivate reaping = new Set<string>();\n\tprivate disposed = false;\n\tprivate readonly cwd: string;\n\tprivate parentShutdownHandler?: () => void;\n\n\tconstructor(cwd: string) {\n\t\tsuper();\n\t\tthis.cwd = cwd;\n\t\tthis.setupParentExitHandlers();\n\t\tthis.sweepOldAgents();\n\t\tthis.lastCheckAt = Date.now();\n\t\tthis.checkInterval = setInterval(() => this.checkHeartbeats(), HEARTBEAT_CHECK_INTERVAL_MS);\n\t}\n\n\t/**\n\t * Set the count of external in-process tasks (background MCP tools) sharing the\n\t * parent's CPU/event loop. Folded into loadMultiplier() so concurrent MCP work\n\t * widens the heartbeat/timeout budgets just like extra monitored subagents do.\n\t * Negative values are clamped to 0.\n\t */\n\tsetExternalLoad(count: number): void {\n\t\tthis.externalLoad = Math.max(0, Math.floor(count));\n\t}\n\n\t/**\n\t * Tolerance multiplier for the current load. 1 concurrent task → 1x; each extra\n\t * concurrent task adds LOAD_TOLERANCE_PER_PROCESS, capped at MAX_LOAD_MULTIPLIER.\n\t * Concurrency counts both monitored subagents and external load (background MCP\n\t * tools), since both contend for the same parent event loop.\n\t */\n\tprivate loadMultiplier(): number {\n\t\tconst concurrent = this.processes.size + this.externalLoad;\n\t\tconst mult = 1 + Math.max(0, concurrent - 1) * LOAD_TOLERANCE_PER_PROCESS;\n\t\treturn Math.min(mult, MAX_LOAD_MULTIPLIER);\n\t}\n\n\t/**\n\t * Begin monitoring a child process. The process must emit a\n\t * `{\"ping\":true}` JSON line on stdout every 30 seconds.\n\t */\n\tmonitor(task_id: string, agent_type: string, proc: ChildProcess): void {\n\t\tif (this.disposed) return;\n\n\t\tconst pid = proc.pid ?? 0;\n\t\tthis.processes.set(task_id, { pid, task_id, agent_type, process: proc });\n\t\tthis.lastHeartbeat.set(task_id, Date.now());\n\n\t\tconst timeoutMs = TIMEOUTS_MS[agent_type] ?? TIMEOUTS_MS.explore;\n\t\tthis.startedAt.set(task_id, Date.now());\n\t\tthis.baseTimeoutMs.set(task_id, timeoutMs);\n\t\t// Arm the hard timeout scaled by current load. When it fires, handleTimeout\n\t\t// re-checks load and re-arms (up to MAX_LOAD_MULTIPLIER) if the pool is still\n\t\t// busy, so a slow-but-progressing subagent isn't killed for CPU contention.\n\t\tconst timeout = setTimeout(\n\t\t\t() => {\n\t\t\t\tthis.handleTimeout(task_id);\n\t\t\t},\n\t\t\tMath.round(timeoutMs * this.loadMultiplier()),\n\t\t);\n\t\tthis.timeouts.set(task_id, timeout);\n\n\t\tproc.once(\"exit\", () => {\n\t\t\tthis.untrack(task_id);\n\t\t});\n\t}\n\n\t/** Record a heartbeat for a monitored task. */\n\trecordHeartbeat(task_id: string): void {\n\t\tif (this.processes.has(task_id)) {\n\t\t\tthis.lastHeartbeat.set(task_id, Date.now());\n\t\t}\n\t}\n\n\t/** Get the last recorded heartbeat timestamp, or null. */\n\tlastHeartbeatAt(task_id: string): number | null {\n\t\treturn this.lastHeartbeat.get(task_id) ?? null;\n\t}\n\n\t/** True if the task is currently being monitored. */\n\tisMonitoring(task_id: string): boolean {\n\t\treturn this.processes.has(task_id);\n\t}\n\n\t/** Kill all monitored processes and clean up. */\n\tdispose(): void {\n\t\tif (this.disposed) return;\n\t\tthis.disposed = true;\n\n\t\tif (this.checkInterval) {\n\t\t\tclearInterval(this.checkInterval);\n\t\t\tthis.checkInterval = null;\n\t\t}\n\n\t\tfor (const timeout of this.timeouts.values()) {\n\t\t\tclearTimeout(timeout);\n\t\t}\n\t\tthis.timeouts.clear();\n\n\t\tfor (const monitored of this.processes.values()) {\n\t\t\tthis.killTree(monitored);\n\t\t}\n\t\tthis.processes.clear();\n\t\tthis.lastHeartbeat.clear();\n\t\tthis.startedAt.clear();\n\t\tthis.baseTimeoutMs.clear();\n\t\tthis.reaping.clear();\n\t\tthis.removeAllListeners();\n\n\t\tif (this.parentShutdownHandler) {\n\t\t\tprocess.removeListener(\"SIGINT\", this.parentShutdownHandler);\n\t\t\tprocess.removeListener(\"SIGTERM\", this.parentShutdownHandler);\n\t\t}\n\t}\n\n\tprivate checkHeartbeats(): void {\n\t\tconst now = Date.now();\n\t\t// Event-loop lag: how much later than scheduled this check actually ran.\n\t\t// Heavy CPU load (many concurrent subagents + background MCP tools) starves\n\t\t// the loop, delaying both this check *and* our reading of child heartbeats.\n\t\t// Forgive that gap so the parent's own starvation isn't charged against the\n\t\t// children as a missed heartbeat.\n\t\tconst loopLag = Math.max(0, now - this.lastCheckAt - HEARTBEAT_CHECK_INTERVAL_MS);\n\t\tthis.lastCheckAt = now;\n\n\t\tconst threshold = HEARTBEAT_MISS_THRESHOLD_MS * this.loadMultiplier() + loopLag;\n\t\tfor (const [task_id] of this.processes) {\n\t\t\tif (this.reaping.has(task_id)) continue;\n\t\t\tconst last = this.lastHeartbeat.get(task_id);\n\t\t\tif (last === undefined) continue;\n\t\t\tif (now - last > threshold) {\n\t\t\t\tthis.handleStalled(task_id);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate handleStalled(task_id: string): void {\n\t\tconst monitored = this.processes.get(task_id);\n\t\tif (!monitored || this.reaping.has(task_id)) return;\n\t\tthis.reaping.add(task_id);\n\n\t\t// Record why we reaped this child so a recurrence is diagnosable rather than\n\t\t// just \"stalled\": how long since the last heartbeat, and the load factors\n\t\t// (concurrent monitored subagents, threshold) that fed the decision.\n\t\tconst last = this.lastHeartbeat.get(task_id);\n\t\tconst silentMs = last === undefined ? -1 : Date.now() - last;\n\t\tconsole.error(\n\t\t\t`[LIFEGUARD] stalled task_id=${task_id} agent=${monitored.agent_type} ` +\n\t\t\t\t`silent_ms=${silentMs} concurrent=${this.processes.size} ` +\n\t\t\t\t`load_mult=${this.loadMultiplier().toFixed(2)} base_threshold_ms=${HEARTBEAT_MISS_THRESHOLD_MS}`,\n\t\t);\n\n\t\tthis.killTree(monitored);\n\n\t\tthis.emit(\"stalled\", { task_id, pid: monitored.pid });\n\t\t// Process exit handler will call untrack()\n\t}\n\n\tprivate handleTimeout(task_id: string): void {\n\t\tconst monitored = this.processes.get(task_id);\n\t\tif (!monitored || this.reaping.has(task_id)) return;\n\n\t\t// Under load the wall-clock timer can fire while the subagent is still doing\n\t\t// real work — its turns are just slow because the CPU is shared. Re-arm rather\n\t\t// than kill, up to a hard ceiling (base * MAX_LOAD_MULTIPLIER) so a genuinely\n\t\t// stuck agent still terminates.\n\t\tconst started = this.startedAt.get(task_id) ?? Date.now();\n\t\tconst base = this.baseTimeoutMs.get(task_id) ?? TIMEOUTS_MS[monitored.agent_type] ?? TIMEOUTS_MS.explore;\n\t\tconst elapsed = Date.now() - started;\n\t\tconst ceiling = base * MAX_LOAD_MULTIPLIER;\n\t\tif (this.loadMultiplier() > 1 && elapsed < ceiling) {\n\t\t\tconst remaining = ceiling - elapsed;\n\t\t\tconst next = Math.min(\n\t\t\t\tMath.round(base * this.loadMultiplier()),\n\t\t\t\tMath.max(HEARTBEAT_CHECK_INTERVAL_MS, remaining),\n\t\t\t);\n\t\t\tthis.timeouts.set(\n\t\t\t\ttask_id,\n\t\t\t\tsetTimeout(() => this.handleTimeout(task_id), next),\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tthis.reaping.add(task_id);\n\t\tthis.killTree(monitored);\n\n\t\tthis.emit(\"timeout\", { task_id, pid: monitored.pid });\n\t\tthis.timeouts.delete(task_id);\n\t\t// Process exit handler will call untrack()\n\t}\n\n\t/**\n\t * Kill a monitored subagent and everything it spawned. The pool spawns\n\t * children detached on POSIX (each leads its own process group), so the\n\t * group/tree kill reaches nested grandchildren (the subagent's bash commands,\n\t * its own subagents) that a single-PID SIGKILL would orphan. A pid of 0 means\n\t * the spawn never produced a process — nothing to kill (and `kill(-0)` would\n\t * signal our own process group).\n\t */\n\tprivate killTree(monitored: LifeguardProcess): void {\n\t\tif (monitored.pid > 0) {\n\t\t\tkillProcessTree(monitored.pid);\n\t\t} else if (!monitored.process.killed) {\n\t\t\tmonitored.process.kill(\"SIGKILL\");\n\t\t}\n\t}\n\n\tprivate untrack(task_id: string): void {\n\t\tconst timeout = this.timeouts.get(task_id);\n\t\tif (timeout) {\n\t\t\tclearTimeout(timeout);\n\t\t\tthis.timeouts.delete(task_id);\n\t\t}\n\t\tthis.processes.delete(task_id);\n\t\tthis.lastHeartbeat.delete(task_id);\n\t\tthis.startedAt.delete(task_id);\n\t\tthis.baseTimeoutMs.delete(task_id);\n\t\tthis.reaping.delete(task_id);\n\t}\n\n\tprivate setupParentExitHandlers(): void {\n\t\tconst shutdown = () => this.gracefulShutdown();\n\t\tthis.parentShutdownHandler = shutdown;\n\t\tprocess.setMaxListeners(Math.max(process.getMaxListeners(), 20));\n\t\tprocess.once(\"SIGINT\", shutdown);\n\t\tprocess.once(\"SIGTERM\", shutdown);\n\t}\n\n\tprivate gracefulShutdown(): void {\n\t\t// SIGTERM each child's process group (POSIX; the pool spawns them detached\n\t\t// as group leaders) so their own descendants get the graceful signal too.\n\t\tfor (const monitored of this.processes.values()) {\n\t\t\ttry {\n\t\t\t\tif (process.platform !== \"win32\" && monitored.pid > 0) {\n\t\t\t\t\tprocess.kill(-monitored.pid, \"SIGTERM\");\n\t\t\t\t} else if (!monitored.process.killed) {\n\t\t\t\t\tmonitored.process.kill(\"SIGTERM\");\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// Already gone.\n\t\t\t}\n\t\t}\n\n\t\t// Kill whole trees after the grace period\n\t\tsetTimeout(() => {\n\t\t\tfor (const monitored of this.processes.values()) {\n\t\t\t\tthis.killTree(monitored);\n\t\t\t}\n\t\t}, PARENT_SHUTDOWN_GRACE_MS).unref();\n\t}\n\n\tprivate sweepOldAgents(): void {\n\t\tconst dispatchDir = getDispatchRoot(this.cwd);\n\t\tif (!existsSync(dispatchDir)) return;\n\n\t\tconst now = Date.now();\n\t\tconst cutoff = 24 * 60 * 60 * 1000; // 24 hours\n\n\t\tfor (const entry of readdirSync(dispatchDir)) {\n\t\t\tconst entryPath = join(dispatchDir, entry);\n\t\t\ttry {\n\t\t\t\tconst stats = statSync(entryPath);\n\t\t\t\tif (!stats.isDirectory()) continue;\n\n\t\t\t\tif (now - stats.mtimeMs > cutoff) {\n\t\t\t\t\tconst hasRunningPid = this.hasRunningPid(entryPath);\n\t\t\t\t\tif (!hasRunningPid) {\n\t\t\t\t\t\tthis.rmrf(entryPath);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// Ignore errors for individual entries\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate hasRunningPid(dir: string): boolean {\n\t\tconst pidFile = join(dir, \"pid\");\n\t\tif (!existsSync(pidFile)) return false;\n\n\t\ttry {\n\t\t\tconst pid = Number.parseInt(readFileSync(pidFile, \"utf-8\"), 10);\n\t\t\tif (Number.isNaN(pid)) return false;\n\t\t\tprocess.kill(pid, 0); // Check if process exists\n\t\t\treturn true;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tprivate rmrf(dir: string): void {\n\t\tfor (const entry of readdirSync(dir)) {\n\t\t\tconst entryPath = join(dir, entry);\n\t\t\ttry {\n\t\t\t\tconst stats = statSync(entryPath);\n\t\t\t\tif (stats.isDirectory()) {\n\t\t\t\t\tthis.rmrf(entryPath);\n\t\t\t\t} else {\n\t\t\t\t\tunlinkSync(entryPath);\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// Ignore\n\t\t\t}\n\t\t}\n\t\ttry {\n\t\t\trmdirSync(dir);\n\t\t} catch {\n\t\t\t// Ignore\n\t\t}\n\t}\n}\n"]}
|
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
* └─▶ timeout
|
|
18
18
|
*/
|
|
19
19
|
import type { SubagentPool, TaskResult } from "./subagent-pool.js";
|
|
20
|
-
export type TaskLifecycle = "running" | "done" | "failed" | "stalled" | "timeout" | "collected";
|
|
20
|
+
export type TaskLifecycle = "running" | "done" | "failed" | "stalled" | "timeout" | "cancelled" | "collected";
|
|
21
21
|
/** A non-terminal task is still doing work; the rest have settled. */
|
|
22
22
|
export declare function isOutstanding(lifecycle: TaskLifecycle): boolean;
|
|
23
23
|
export interface InboxRecord {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"subagent-inbox.d.ts","sourceRoot":"","sources":["../../src/core/subagent-inbox.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAGnE,MAAM,MAAM,aAAa,GAAG,SAAS,GAAG,MAAM,GAAG,QAAQ,GAAG,SAAS,GAAG,SAAS,GAAG,WAAW,CAAC;AAEhG,sEAAsE;AACtE,wBAAgB,aAAa,CAAC,SAAS,EAAE,aAAa,GAAG,OAAO,CAE/D;AAED,MAAM,WAAW,WAAW;IAC3B,MAAM,EAAE,MAAM,CAAC;IACf,4DAA4D;IAC5D,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,aAAa,CAAC;IACzB,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,+EAA+E;IAC/E,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,+EAA+E;IAC/E,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,yEAAyE;IACzE,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,oDAAoD;IACpD,KAAK,CAAC,EAAE,MAAM,CAAC;CACf;AAgCD,cAAM,aAAa;IAClB,OAAO,CAAC,OAAO,CAAkC;IACjD,mEAAmE;IACnE,OAAO,CAAC,KAAK,CAAgB;IAC7B,OAAO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kBb;AAED,2EAA2E;AAC3E,eAAO,MAAM,aAAa,eAAsB,CAAC","sourcesContent":["/**\n * Subagent inbox: the notify-and-pull bookkeeping behind background `Task`\n * dispatch and the `TaskOutput` tool.\n *\n * Background dispatches don't push their full result into the parent's context.\n * Instead the parent gets a compact notification (\"explore#1 finished\") and the\n * body is retained here, keyed by task id, until the model explicitly pulls it\n * with TaskOutput. This keeps a wide swarm of subagents from flooding the\n * context with N full summaries, and gives the model a queryable liveness view\n * (running / done / failed + last activity) so it can tell a working subagent\n * from a rogue one. The same surface works at every delegation depth.\n *\n * Lifecycle per task:\n * running ──▶ done (body retained) ──collect──▶ collected (body dropped)\n * ├─▶ failed\n * ├─▶ stalled\n * └─▶ timeout\n */\n\nimport type { SubagentPool, TaskResult } from \"./subagent-pool.js\";\nimport type { SubagentResultFile } from \"./subagent-result.js\";\n\nexport type TaskLifecycle = \"running\" | \"done\" | \"failed\" | \"stalled\" | \"timeout\" | \"collected\";\n\n/** A non-terminal task is still doing work; the rest have settled. */\nexport function isOutstanding(lifecycle: TaskLifecycle): boolean {\n\treturn lifecycle === \"running\";\n}\n\nexport interface InboxRecord {\n\ttaskId: string;\n\t/** Friendly handle shown to the model, e.g. \"explore#1\". */\n\tlabel: string;\n\tagentType: string;\n\tlifecycle: TaskLifecycle;\n\tstartedAt: number;\n\tendedAt?: number;\n\t/** Tool the subagent is currently running, from the pool's progress stream. */\n\tlastActivity?: string;\n\t/** First line of the result/summary, kept even after the body is collected. */\n\tsummaryLine?: string;\n\t/** Full subagent summary, retained only while `done` and uncollected. */\n\tbody?: string;\n\t/** Failure reason when the task did not succeed. */\n\terror?: string;\n}\n\n/** Cap on settled (terminal) records kept for late pulls; running records are never pruned. */\nconst MAX_SETTLED = 50;\n\n/** First non-empty line of a block of text, length-capped. */\nfunction firstLine(text: string, max = 120): string {\n\tconst line = (\n\t\ttext\n\t\t\t.trim()\n\t\t\t.split(\"\\n\")\n\t\t\t.find((l) => l.trim()) ?? \"\"\n\t).trim();\n\treturn line.length > max ? `${line.slice(0, max - 1)}…` : line;\n}\n\n/** Map a subagent's terminal `status` onto an inbox lifecycle. */\nfunction failLifecycle(status: string | undefined): TaskLifecycle {\n\tif (status === \"stalled\") return \"stalled\";\n\tif (status === \"timeout\") return \"timeout\";\n\treturn \"failed\";\n}\n\n/** Derive the \"currently running X\" activity label from a forwarded progress event. */\nfunction activityFromEvent(event: Record<string, unknown>): string | undefined {\n\tif (event.type === \"tool_execution_start\" && typeof event.toolName === \"string\") {\n\t\treturn event.toolName;\n\t}\n\tif (event.type === \"turn_end\") return \"thinking\";\n\treturn undefined;\n}\n\nclass SubagentInbox {\n\tprivate records = new Map<string, InboxRecord>();\n\t/** Insertion order of task ids, for stable listing and pruning. */\n\tprivate order: string[] = [];\n\tprivate labelCounters = new Map<string, number>();\n\tprivate observedPools = new WeakSet<SubagentPool>();\n\t/** One-shot callbacks fired after any record settles, for the wait helpers. */\n\tprivate settleListeners = new Set<() => void>();\n\n\tprivate notifySettle(): void {\n\t\tfor (const listener of [...this.settleListeners]) listener();\n\t}\n\n\t/**\n\t * Resolve once the given task settles (or immediately if already settled /\n\t * unknown), bounded by `timeoutMs`. Backs TaskOutput's per-task wait.\n\t */\n\twaitFor(handle: string, timeoutMs: number): Promise<InboxRecord | undefined> {\n\t\tconst current = this.get(handle);\n\t\tif (!current || !isOutstanding(current.lifecycle)) return Promise.resolve(current);\n\t\treturn new Promise((resolve) => {\n\t\t\tconst cleanup = () => {\n\t\t\t\tthis.settleListeners.delete(check);\n\t\t\t\tclearTimeout(timer);\n\t\t\t};\n\t\t\tconst check = () => {\n\t\t\t\tconst rec = this.get(handle);\n\t\t\t\tif (!rec || !isOutstanding(rec.lifecycle)) {\n\t\t\t\t\tcleanup();\n\t\t\t\t\tresolve(rec);\n\t\t\t\t}\n\t\t\t};\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tcleanup();\n\t\t\t\tresolve(this.get(handle));\n\t\t\t}, timeoutMs);\n\t\t\ttimer.unref?.();\n\t\t\tthis.settleListeners.add(check);\n\t\t});\n\t}\n\n\t/** Resolve once nothing is outstanding (the swarm barrier), bounded by `timeoutMs`. */\n\twaitForAll(timeoutMs: number): Promise<void> {\n\t\tif (this.outstanding().length === 0) return Promise.resolve();\n\t\treturn new Promise((resolve) => {\n\t\t\tconst cleanup = () => {\n\t\t\t\tthis.settleListeners.delete(check);\n\t\t\t\tclearTimeout(timer);\n\t\t\t};\n\t\t\tconst check = () => {\n\t\t\t\tif (this.outstanding().length === 0) {\n\t\t\t\t\tcleanup();\n\t\t\t\t\tresolve();\n\t\t\t\t}\n\t\t\t};\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tcleanup();\n\t\t\t\tresolve();\n\t\t\t}, timeoutMs);\n\t\t\ttimer.unref?.();\n\t\t\tthis.settleListeners.add(check);\n\t\t});\n\t}\n\n\t/** Allocate the next friendly label for an agent type (`explore#1`, `explore#2`, …). */\n\tnextLabel(agentType: string): string {\n\t\tconst n = (this.labelCounters.get(agentType) ?? 0) + 1;\n\t\tthis.labelCounters.set(agentType, n);\n\t\treturn `${agentType}#${n}`;\n\t}\n\n\t/**\n\t * Track a pool's `task_progress` events so running records carry a live\n\t * `lastActivity`. Idempotent per pool, so callers can wire it on every dispatch.\n\t */\n\tobserve(pool: SubagentPool): void {\n\t\t// Tolerate a non-EventEmitter stand-in (test fakes): without progress events\n\t\t// records simply carry no live activity.\n\t\tif (typeof (pool as { on?: unknown }).on !== \"function\") return;\n\t\tif (this.observedPools.has(pool)) return;\n\t\tthis.observedPools.add(pool);\n\t\tpool.on(\"task_progress\", (data: { task_id: string; event: Record<string, unknown> }) => {\n\t\t\tconst rec = this.records.get(data.task_id);\n\t\t\tif (!rec || rec.lifecycle !== \"running\") return;\n\t\t\tconst activity = activityFromEvent(data.event);\n\t\t\tif (activity) rec.lastActivity = activity;\n\t\t});\n\t}\n\n\t/** Register a freshly dispatched background task as running. */\n\tstart(taskId: string, label: string, agentType: string): InboxRecord {\n\t\tconst rec: InboxRecord = { taskId, label, agentType, lifecycle: \"running\", startedAt: Date.now() };\n\t\tthis.records.set(taskId, rec);\n\t\tthis.order.push(taskId);\n\t\tthis.prune();\n\t\treturn rec;\n\t}\n\n\t/** Settle a task from its dispatch result: retain the body on success, the reason on failure. */\n\tfinish(taskId: string, result: TaskResult): InboxRecord | undefined {\n\t\tconst rec = this.records.get(taskId);\n\t\tif (!rec) return undefined;\n\t\trec.endedAt = Date.now();\n\t\trec.lastActivity = undefined;\n\t\tconst r = result.result;\n\t\tconst data = r?.result_data as SubagentResultFile | undefined;\n\t\tif (r?.ok) {\n\t\t\trec.lifecycle = \"done\";\n\t\t\trec.body = data?.summary?.trim() || \"(subagent returned no output)\";\n\t\t\trec.summaryLine = firstLine(rec.body);\n\t\t} else {\n\t\t\trec.lifecycle = failLifecycle(r?.status);\n\t\t\trec.error = r?.error ?? (r?.status ? `subagent ${r.status}` : \"unknown error\");\n\t\t\trec.summaryLine = rec.error;\n\t\t}\n\t\tthis.notifySettle();\n\t\treturn rec;\n\t}\n\n\t/** Settle a task that never produced a TaskResult (e.g. a thrown dispatch error). */\n\tfail(taskId: string, reason: string, lifecycle: TaskLifecycle = \"failed\"): InboxRecord | undefined {\n\t\tconst rec = this.records.get(taskId);\n\t\tif (!rec) return undefined;\n\t\trec.endedAt = Date.now();\n\t\trec.lastActivity = undefined;\n\t\trec.lifecycle = lifecycle;\n\t\trec.error = reason;\n\t\trec.summaryLine = reason;\n\t\tthis.notifySettle();\n\t\treturn rec;\n\t}\n\n\t/** Look up a record by task id or by friendly label. */\n\tget(handle: string): InboxRecord | undefined {\n\t\tconst byId = this.records.get(handle);\n\t\tif (byId) return byId;\n\t\tfor (const rec of this.records.values()) {\n\t\t\tif (rec.label === handle) return rec;\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Read a done task's body and mark it collected, dropping the body so it is not\n\t * re-fed to the model. Returns the record (with `body` still populated for this\n\t * one read) or undefined for an unknown handle.\n\t */\n\tcollect(handle: string): { record: InboxRecord; body: string } | undefined {\n\t\tconst rec = this.get(handle);\n\t\tif (!rec || rec.lifecycle !== \"done\" || rec.body === undefined) return undefined;\n\t\tconst body = rec.body;\n\t\trec.lifecycle = \"collected\";\n\t\trec.body = undefined;\n\t\treturn { record: rec, body };\n\t}\n\n\t/** All records, oldest first. */\n\tlist(): InboxRecord[] {\n\t\treturn this.order.map((id) => this.records.get(id)).filter((r): r is InboxRecord => r !== undefined);\n\t}\n\n\t/** Records still doing work. */\n\toutstanding(): InboxRecord[] {\n\t\treturn this.list().filter((r) => isOutstanding(r.lifecycle));\n\t}\n\n\t/** Test/teardown helper. */\n\tclear(): void {\n\t\tthis.records.clear();\n\t\tthis.order = [];\n\t\tthis.labelCounters.clear();\n\t}\n\n\t/** Drop the oldest settled records once past the cap; running records are kept. */\n\tprivate prune(): void {\n\t\tlet settled = this.order.filter((id) => {\n\t\t\tconst r = this.records.get(id);\n\t\t\treturn r !== undefined && !isOutstanding(r.lifecycle);\n\t\t}).length;\n\t\tif (settled <= MAX_SETTLED) return;\n\t\tconst kept: string[] = [];\n\t\tfor (const id of this.order) {\n\t\t\tconst r = this.records.get(id);\n\t\t\tif (r && !isOutstanding(r.lifecycle) && settled > MAX_SETTLED) {\n\t\t\t\tthis.records.delete(id);\n\t\t\t\tsettled--;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tkept.push(id);\n\t\t}\n\t\tthis.order = kept;\n\t}\n}\n\n/** Process-wide subagent inbox shared by the Task and TaskOutput tools. */\nexport const subagentInbox = new SubagentInbox();\n"]}
|
|
1
|
+
{"version":3,"file":"subagent-inbox.d.ts","sourceRoot":"","sources":["../../src/core/subagent-inbox.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAGnE,MAAM,MAAM,aAAa,GAAG,SAAS,GAAG,MAAM,GAAG,QAAQ,GAAG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MAAM,GAAG,WAAW,CAMnE;IAED,iGAAiG;IACjG,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,GAAG,WAAW,GAAG,SAAS,CAkBlE;IAED,qFAAqF;IACrF,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,SAAS,GAAE,aAAwB,GAAG,WAAW,GAAG,SAAS,CAUjG;IAED,wDAAwD;IACxD,GAAG,CAAC,MAAM,EAAE,MAAM,GAAG,WAAW,GAAG,SAAS,CAO3C;IAED;;;;OAIG;IACH,OAAO,CAAC,MAAM,EAAE,MAAM,GAAG;QAAE,MAAM,EAAE,WAAW,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,GAAG,SAAS,CAOzE;IAED,iCAAiC;IACjC,IAAI,IAAI,WAAW,EAAE,CAEpB;IAED,gCAAgC;IAChC,WAAW,IAAI,WAAW,EAAE,CAE3B;IAED,4BAA4B;IAC5B,KAAK,IAAI,IAAI,CAIZ;IAED,mFAAmF;IACnF,OAAO,CAAC,KAAK;CAkBb;AAED,2EAA2E;AAC3E,eAAO,MAAM,aAAa,eAAsB,CAAC","sourcesContent":["/**\n * Subagent inbox: the notify-and-pull bookkeeping behind background `Task`\n * dispatch and the `TaskOutput` tool.\n *\n * Background dispatches don't push their full result into the parent's context.\n * Instead the parent gets a compact notification (\"explore#1 finished\") and the\n * body is retained here, keyed by task id, until the model explicitly pulls it\n * with TaskOutput. This keeps a wide swarm of subagents from flooding the\n * context with N full summaries, and gives the model a queryable liveness view\n * (running / done / failed + last activity) so it can tell a working subagent\n * from a rogue one. The same surface works at every delegation depth.\n *\n * Lifecycle per task:\n * running ──▶ done (body retained) ──collect──▶ collected (body dropped)\n * ├─▶ failed\n * ├─▶ stalled\n * └─▶ timeout\n */\n\nimport type { SubagentPool, TaskResult } from \"./subagent-pool.js\";\nimport type { SubagentResultFile } from \"./subagent-result.js\";\n\nexport type TaskLifecycle = \"running\" | \"done\" | \"failed\" | \"stalled\" | \"timeout\" | \"cancelled\" | \"collected\";\n\n/** A non-terminal task is still doing work; the rest have settled. */\nexport function isOutstanding(lifecycle: TaskLifecycle): boolean {\n\treturn lifecycle === \"running\";\n}\n\nexport interface InboxRecord {\n\ttaskId: string;\n\t/** Friendly handle shown to the model, e.g. \"explore#1\". */\n\tlabel: string;\n\tagentType: string;\n\tlifecycle: TaskLifecycle;\n\tstartedAt: number;\n\tendedAt?: number;\n\t/** Tool the subagent is currently running, from the pool's progress stream. */\n\tlastActivity?: string;\n\t/** First line of the result/summary, kept even after the body is collected. */\n\tsummaryLine?: string;\n\t/** Full subagent summary, retained only while `done` and uncollected. */\n\tbody?: string;\n\t/** Failure reason when the task did not succeed. */\n\terror?: string;\n}\n\n/** Cap on settled (terminal) records kept for late pulls; running records are never pruned. */\nconst MAX_SETTLED = 50;\n\n/** First non-empty line of a block of text, length-capped. */\nfunction firstLine(text: string, max = 120): string {\n\tconst line = (\n\t\ttext\n\t\t\t.trim()\n\t\t\t.split(\"\\n\")\n\t\t\t.find((l) => l.trim()) ?? \"\"\n\t).trim();\n\treturn line.length > max ? `${line.slice(0, max - 1)}…` : line;\n}\n\n/** Map a subagent's terminal `status` onto an inbox lifecycle. */\nfunction failLifecycle(status: string | undefined): TaskLifecycle {\n\tif (status === \"stalled\") return \"stalled\";\n\tif (status === \"timeout\") return \"timeout\";\n\tif (status === \"cancelled\") return \"cancelled\";\n\treturn \"failed\";\n}\n\n/** Derive the \"currently running X\" activity label from a forwarded progress event. */\nfunction activityFromEvent(event: Record<string, unknown>): string | undefined {\n\tif (event.type === \"tool_execution_start\" && typeof event.toolName === \"string\") {\n\t\treturn event.toolName;\n\t}\n\tif (event.type === \"turn_end\") return \"thinking\";\n\treturn undefined;\n}\n\nclass SubagentInbox {\n\tprivate records = new Map<string, InboxRecord>();\n\t/** Insertion order of task ids, for stable listing and pruning. */\n\tprivate order: string[] = [];\n\tprivate labelCounters = new Map<string, number>();\n\tprivate observedPools = new WeakSet<SubagentPool>();\n\t/** One-shot callbacks fired after any record settles, for the wait helpers. */\n\tprivate settleListeners = new Set<() => void>();\n\n\tprivate notifySettle(): void {\n\t\tfor (const listener of [...this.settleListeners]) listener();\n\t}\n\n\t/**\n\t * Resolve once the given task settles (or immediately if already settled /\n\t * unknown), bounded by `timeoutMs`. Backs TaskOutput's per-task wait.\n\t */\n\twaitFor(handle: string, timeoutMs: number): Promise<InboxRecord | undefined> {\n\t\tconst current = this.get(handle);\n\t\tif (!current || !isOutstanding(current.lifecycle)) return Promise.resolve(current);\n\t\treturn new Promise((resolve) => {\n\t\t\tconst cleanup = () => {\n\t\t\t\tthis.settleListeners.delete(check);\n\t\t\t\tclearTimeout(timer);\n\t\t\t};\n\t\t\tconst check = () => {\n\t\t\t\tconst rec = this.get(handle);\n\t\t\t\tif (!rec || !isOutstanding(rec.lifecycle)) {\n\t\t\t\t\tcleanup();\n\t\t\t\t\tresolve(rec);\n\t\t\t\t}\n\t\t\t};\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tcleanup();\n\t\t\t\tresolve(this.get(handle));\n\t\t\t}, timeoutMs);\n\t\t\ttimer.unref?.();\n\t\t\tthis.settleListeners.add(check);\n\t\t});\n\t}\n\n\t/** Resolve once nothing is outstanding (the swarm barrier), bounded by `timeoutMs`. */\n\twaitForAll(timeoutMs: number): Promise<void> {\n\t\tif (this.outstanding().length === 0) return Promise.resolve();\n\t\treturn new Promise((resolve) => {\n\t\t\tconst cleanup = () => {\n\t\t\t\tthis.settleListeners.delete(check);\n\t\t\t\tclearTimeout(timer);\n\t\t\t};\n\t\t\tconst check = () => {\n\t\t\t\tif (this.outstanding().length === 0) {\n\t\t\t\t\tcleanup();\n\t\t\t\t\tresolve();\n\t\t\t\t}\n\t\t\t};\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tcleanup();\n\t\t\t\tresolve();\n\t\t\t}, timeoutMs);\n\t\t\ttimer.unref?.();\n\t\t\tthis.settleListeners.add(check);\n\t\t});\n\t}\n\n\t/** Allocate the next friendly label for an agent type (`explore#1`, `explore#2`, …). */\n\tnextLabel(agentType: string): string {\n\t\tconst n = (this.labelCounters.get(agentType) ?? 0) + 1;\n\t\tthis.labelCounters.set(agentType, n);\n\t\treturn `${agentType}#${n}`;\n\t}\n\n\t/**\n\t * Track a pool's `task_progress` events so running records carry a live\n\t * `lastActivity`. Idempotent per pool, so callers can wire it on every dispatch.\n\t */\n\tobserve(pool: SubagentPool): void {\n\t\t// Tolerate a non-EventEmitter stand-in (test fakes): without progress events\n\t\t// records simply carry no live activity.\n\t\tif (typeof (pool as { on?: unknown }).on !== \"function\") return;\n\t\tif (this.observedPools.has(pool)) return;\n\t\tthis.observedPools.add(pool);\n\t\tpool.on(\"task_progress\", (data: { task_id: string; event: Record<string, unknown> }) => {\n\t\t\tconst rec = this.records.get(data.task_id);\n\t\t\tif (!rec || rec.lifecycle !== \"running\") return;\n\t\t\tconst activity = activityFromEvent(data.event);\n\t\t\tif (activity) rec.lastActivity = activity;\n\t\t});\n\t}\n\n\t/** Register a freshly dispatched background task as running. */\n\tstart(taskId: string, label: string, agentType: string): InboxRecord {\n\t\tconst rec: InboxRecord = { taskId, label, agentType, lifecycle: \"running\", startedAt: Date.now() };\n\t\tthis.records.set(taskId, rec);\n\t\tthis.order.push(taskId);\n\t\tthis.prune();\n\t\treturn rec;\n\t}\n\n\t/** Settle a task from its dispatch result: retain the body on success, the reason on failure. */\n\tfinish(taskId: string, result: TaskResult): InboxRecord | undefined {\n\t\tconst rec = this.records.get(taskId);\n\t\tif (!rec) return undefined;\n\t\trec.endedAt = Date.now();\n\t\trec.lastActivity = undefined;\n\t\tconst r = result.result;\n\t\tconst data = r?.result_data as SubagentResultFile | undefined;\n\t\tif (r?.ok) {\n\t\t\trec.lifecycle = \"done\";\n\t\t\trec.body = data?.summary?.trim() || \"(subagent returned no output)\";\n\t\t\trec.summaryLine = firstLine(rec.body);\n\t\t} else {\n\t\t\trec.lifecycle = failLifecycle(r?.status);\n\t\t\trec.error = r?.error ?? (r?.status ? `subagent ${r.status}` : \"unknown error\");\n\t\t\trec.summaryLine = rec.error;\n\t\t}\n\t\tthis.notifySettle();\n\t\treturn rec;\n\t}\n\n\t/** Settle a task that never produced a TaskResult (e.g. a thrown dispatch error). */\n\tfail(taskId: string, reason: string, lifecycle: TaskLifecycle = \"failed\"): InboxRecord | undefined {\n\t\tconst rec = this.records.get(taskId);\n\t\tif (!rec) return undefined;\n\t\trec.endedAt = Date.now();\n\t\trec.lastActivity = undefined;\n\t\trec.lifecycle = lifecycle;\n\t\trec.error = reason;\n\t\trec.summaryLine = reason;\n\t\tthis.notifySettle();\n\t\treturn rec;\n\t}\n\n\t/** Look up a record by task id or by friendly label. */\n\tget(handle: string): InboxRecord | undefined {\n\t\tconst byId = this.records.get(handle);\n\t\tif (byId) return byId;\n\t\tfor (const rec of this.records.values()) {\n\t\t\tif (rec.label === handle) return rec;\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Read a done task's body and mark it collected, dropping the body so it is not\n\t * re-fed to the model. Returns the record (with `body` still populated for this\n\t * one read) or undefined for an unknown handle.\n\t */\n\tcollect(handle: string): { record: InboxRecord; body: string } | undefined {\n\t\tconst rec = this.get(handle);\n\t\tif (!rec || rec.lifecycle !== \"done\" || rec.body === undefined) return undefined;\n\t\tconst body = rec.body;\n\t\trec.lifecycle = \"collected\";\n\t\trec.body = undefined;\n\t\treturn { record: rec, body };\n\t}\n\n\t/** All records, oldest first. */\n\tlist(): InboxRecord[] {\n\t\treturn this.order.map((id) => this.records.get(id)).filter((r): r is InboxRecord => r !== undefined);\n\t}\n\n\t/** Records still doing work. */\n\toutstanding(): InboxRecord[] {\n\t\treturn this.list().filter((r) => isOutstanding(r.lifecycle));\n\t}\n\n\t/** Test/teardown helper. */\n\tclear(): void {\n\t\tthis.records.clear();\n\t\tthis.order = [];\n\t\tthis.labelCounters.clear();\n\t}\n\n\t/** Drop the oldest settled records once past the cap; running records are kept. */\n\tprivate prune(): void {\n\t\tlet settled = this.order.filter((id) => {\n\t\t\tconst r = this.records.get(id);\n\t\t\treturn r !== undefined && !isOutstanding(r.lifecycle);\n\t\t}).length;\n\t\tif (settled <= MAX_SETTLED) return;\n\t\tconst kept: string[] = [];\n\t\tfor (const id of this.order) {\n\t\t\tconst r = this.records.get(id);\n\t\t\tif (r && !isOutstanding(r.lifecycle) && settled > MAX_SETTLED) {\n\t\t\t\tthis.records.delete(id);\n\t\t\t\tsettled--;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tkept.push(id);\n\t\t}\n\t\tthis.order = kept;\n\t}\n}\n\n/** Process-wide subagent inbox shared by the Task and TaskOutput tools. */\nexport const subagentInbox = new SubagentInbox();\n"]}
|
|
@@ -36,6 +36,8 @@ function failLifecycle(status) {
|
|
|
36
36
|
return "stalled";
|
|
37
37
|
if (status === "timeout")
|
|
38
38
|
return "timeout";
|
|
39
|
+
if (status === "cancelled")
|
|
40
|
+
return "cancelled";
|
|
39
41
|
return "failed";
|
|
40
42
|
}
|
|
41
43
|
/** Derive the "currently running X" activity label from a forwarded progress event. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"subagent-inbox.js","sourceRoot":"","sources":["../../src/core/subagent-inbox.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAOH,sEAAsE;AACtE,MAAM,UAAU,aAAa,CAAC,SAAwB,EAAW;IAChE,OAAO,SAAS,KAAK,SAAS,CAAC;AAAA,CAC/B;AAoBD,+FAA+F;AAC/F,MAAM,WAAW,GAAG,EAAE,CAAC;AAEvB,8DAA8D;AAC9D,SAAS,SAAS,CAAC,IAAY,EAAE,GAAG,GAAG,GAAG,EAAU;IACnD,MAAM,IAAI,GAAG,CACZ,IAAI;SACF,IAAI,EAAE;SACN,KAAK,CAAC,IAAI,CAAC;SACX,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,IAAI,EAAE,C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,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC;YACvC,MAAM,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;YAC/B,OAAO,CAAC,KAAK,SAAS,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;QAAA,CACtD,CAAC,CAAC,MAAM,CAAC;QACV,IAAI,OAAO,IAAI,WAAW;YAAE,OAAO;QACnC,MAAM,IAAI,GAAa,EAAE,CAAC;QAC1B,KAAK,MAAM,EAAE,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;YAC7B,MAAM,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;YAC/B,IAAI,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,SAAS,CAAC,IAAI,OAAO,GAAG,WAAW,EAAE,CAAC;gBAC/D,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;gBACxB,OAAO,EAAE,CAAC;gBACV,SAAS;YACV,CAAC;YACD,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QACf,CAAC;QACD,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;IAAA,CAClB;CACD;AAED,2EAA2E;AAC3E,MAAM,CAAC,MAAM,aAAa,GAAG,IAAI,aAAa,EAAE,CAAC","sourcesContent":["/**\n * Subagent inbox: the notify-and-pull bookkeeping behind background `Task`\n * dispatch and the `TaskOutput` tool.\n *\n * Background dispatches don't push their full result into the parent's context.\n * Instead the parent gets a compact notification (\"explore#1 finished\") and the\n * body is retained here, keyed by task id, until the model explicitly pulls it\n * with TaskOutput. This keeps a wide swarm of subagents from flooding the\n * context with N full summaries, and gives the model a queryable liveness view\n * (running / done / failed + last activity) so it can tell a working subagent\n * from a rogue one. The same surface works at every delegation depth.\n *\n * Lifecycle per task:\n * running ──▶ done (body retained) ──collect──▶ collected (body dropped)\n * ├─▶ failed\n * ├─▶ stalled\n * └─▶ timeout\n */\n\nimport type { SubagentPool, TaskResult } from \"./subagent-pool.js\";\nimport type { SubagentResultFile } from \"./subagent-result.js\";\n\nexport type TaskLifecycle = \"running\" | \"done\" | \"failed\" | \"stalled\" | \"timeout\" | \"collected\";\n\n/** A non-terminal task is still doing work; the rest have settled. */\nexport function isOutstanding(lifecycle: TaskLifecycle): boolean {\n\treturn lifecycle === \"running\";\n}\n\nexport interface InboxRecord {\n\ttaskId: string;\n\t/** Friendly handle shown to the model, e.g. \"explore#1\". */\n\tlabel: string;\n\tagentType: string;\n\tlifecycle: TaskLifecycle;\n\tstartedAt: number;\n\tendedAt?: number;\n\t/** Tool the subagent is currently running, from the pool's progress stream. */\n\tlastActivity?: string;\n\t/** First line of the result/summary, kept even after the body is collected. */\n\tsummaryLine?: string;\n\t/** Full subagent summary, retained only while `done` and uncollected. */\n\tbody?: string;\n\t/** Failure reason when the task did not succeed. */\n\terror?: string;\n}\n\n/** Cap on settled (terminal) records kept for late pulls; running records are never pruned. */\nconst MAX_SETTLED = 50;\n\n/** First non-empty line of a block of text, length-capped. */\nfunction firstLine(text: string, max = 120): string {\n\tconst line = (\n\t\ttext\n\t\t\t.trim()\n\t\t\t.split(\"\\n\")\n\t\t\t.find((l) => l.trim()) ?? \"\"\n\t).trim();\n\treturn line.length > max ? `${line.slice(0, max - 1)}…` : line;\n}\n\n/** Map a subagent's terminal `status` onto an inbox lifecycle. */\nfunction failLifecycle(status: string | undefined): TaskLifecycle {\n\tif (status === \"stalled\") return \"stalled\";\n\tif (status === \"timeout\") return \"timeout\";\n\treturn \"failed\";\n}\n\n/** Derive the \"currently running X\" activity label from a forwarded progress event. */\nfunction activityFromEvent(event: Record<string, unknown>): string | undefined {\n\tif (event.type === \"tool_execution_start\" && typeof event.toolName === \"string\") {\n\t\treturn event.toolName;\n\t}\n\tif (event.type === \"turn_end\") return \"thinking\";\n\treturn undefined;\n}\n\nclass SubagentInbox {\n\tprivate records = new Map<string, InboxRecord>();\n\t/** Insertion order of task ids, for stable listing and pruning. */\n\tprivate order: string[] = [];\n\tprivate labelCounters = new Map<string, number>();\n\tprivate observedPools = new WeakSet<SubagentPool>();\n\t/** One-shot callbacks fired after any record settles, for the wait helpers. */\n\tprivate settleListeners = new Set<() => void>();\n\n\tprivate notifySettle(): void {\n\t\tfor (const listener of [...this.settleListeners]) listener();\n\t}\n\n\t/**\n\t * Resolve once the given task settles (or immediately if already settled /\n\t * unknown), bounded by `timeoutMs`. Backs TaskOutput's per-task wait.\n\t */\n\twaitFor(handle: string, timeoutMs: number): Promise<InboxRecord | undefined> {\n\t\tconst current = this.get(handle);\n\t\tif (!current || !isOutstanding(current.lifecycle)) return Promise.resolve(current);\n\t\treturn new Promise((resolve) => {\n\t\t\tconst cleanup = () => {\n\t\t\t\tthis.settleListeners.delete(check);\n\t\t\t\tclearTimeout(timer);\n\t\t\t};\n\t\t\tconst check = () => {\n\t\t\t\tconst rec = this.get(handle);\n\t\t\t\tif (!rec || !isOutstanding(rec.lifecycle)) {\n\t\t\t\t\tcleanup();\n\t\t\t\t\tresolve(rec);\n\t\t\t\t}\n\t\t\t};\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tcleanup();\n\t\t\t\tresolve(this.get(handle));\n\t\t\t}, timeoutMs);\n\t\t\ttimer.unref?.();\n\t\t\tthis.settleListeners.add(check);\n\t\t});\n\t}\n\n\t/** Resolve once nothing is outstanding (the swarm barrier), bounded by `timeoutMs`. */\n\twaitForAll(timeoutMs: number): Promise<void> {\n\t\tif (this.outstanding().length === 0) return Promise.resolve();\n\t\treturn new Promise((resolve) => {\n\t\t\tconst cleanup = () => {\n\t\t\t\tthis.settleListeners.delete(check);\n\t\t\t\tclearTimeout(timer);\n\t\t\t};\n\t\t\tconst check = () => {\n\t\t\t\tif (this.outstanding().length === 0) {\n\t\t\t\t\tcleanup();\n\t\t\t\t\tresolve();\n\t\t\t\t}\n\t\t\t};\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tcleanup();\n\t\t\t\tresolve();\n\t\t\t}, timeoutMs);\n\t\t\ttimer.unref?.();\n\t\t\tthis.settleListeners.add(check);\n\t\t});\n\t}\n\n\t/** Allocate the next friendly label for an agent type (`explore#1`, `explore#2`, …). */\n\tnextLabel(agentType: string): string {\n\t\tconst n = (this.labelCounters.get(agentType) ?? 0) + 1;\n\t\tthis.labelCounters.set(agentType, n);\n\t\treturn `${agentType}#${n}`;\n\t}\n\n\t/**\n\t * Track a pool's `task_progress` events so running records carry a live\n\t * `lastActivity`. Idempotent per pool, so callers can wire it on every dispatch.\n\t */\n\tobserve(pool: SubagentPool): void {\n\t\t// Tolerate a non-EventEmitter stand-in (test fakes): without progress events\n\t\t// records simply carry no live activity.\n\t\tif (typeof (pool as { on?: unknown }).on !== \"function\") return;\n\t\tif (this.observedPools.has(pool)) return;\n\t\tthis.observedPools.add(pool);\n\t\tpool.on(\"task_progress\", (data: { task_id: string; event: Record<string, unknown> }) => {\n\t\t\tconst rec = this.records.get(data.task_id);\n\t\t\tif (!rec || rec.lifecycle !== \"running\") return;\n\t\t\tconst activity = activityFromEvent(data.event);\n\t\t\tif (activity) rec.lastActivity = activity;\n\t\t});\n\t}\n\n\t/** Register a freshly dispatched background task as running. */\n\tstart(taskId: string, label: string, agentType: string): InboxRecord {\n\t\tconst rec: InboxRecord = { taskId, label, agentType, lifecycle: \"running\", startedAt: Date.now() };\n\t\tthis.records.set(taskId, rec);\n\t\tthis.order.push(taskId);\n\t\tthis.prune();\n\t\treturn rec;\n\t}\n\n\t/** Settle a task from its dispatch result: retain the body on success, the reason on failure. */\n\tfinish(taskId: string, result: TaskResult): InboxRecord | undefined {\n\t\tconst rec = this.records.get(taskId);\n\t\tif (!rec) return undefined;\n\t\trec.endedAt = Date.now();\n\t\trec.lastActivity = undefined;\n\t\tconst r = result.result;\n\t\tconst data = r?.result_data as SubagentResultFile | undefined;\n\t\tif (r?.ok) {\n\t\t\trec.lifecycle = \"done\";\n\t\t\trec.body = data?.summary?.trim() || \"(subagent returned no output)\";\n\t\t\trec.summaryLine = firstLine(rec.body);\n\t\t} else {\n\t\t\trec.lifecycle = failLifecycle(r?.status);\n\t\t\trec.error = r?.error ?? (r?.status ? `subagent ${r.status}` : \"unknown error\");\n\t\t\trec.summaryLine = rec.error;\n\t\t}\n\t\tthis.notifySettle();\n\t\treturn rec;\n\t}\n\n\t/** Settle a task that never produced a TaskResult (e.g. a thrown dispatch error). */\n\tfail(taskId: string, reason: string, lifecycle: TaskLifecycle = \"failed\"): InboxRecord | undefined {\n\t\tconst rec = this.records.get(taskId);\n\t\tif (!rec) return undefined;\n\t\trec.endedAt = Date.now();\n\t\trec.lastActivity = undefined;\n\t\trec.lifecycle = lifecycle;\n\t\trec.error = reason;\n\t\trec.summaryLine = reason;\n\t\tthis.notifySettle();\n\t\treturn rec;\n\t}\n\n\t/** Look up a record by task id or by friendly label. */\n\tget(handle: string): InboxRecord | undefined {\n\t\tconst byId = this.records.get(handle);\n\t\tif (byId) return byId;\n\t\tfor (const rec of this.records.values()) {\n\t\t\tif (rec.label === handle) return rec;\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Read a done task's body and mark it collected, dropping the body so it is not\n\t * re-fed to the model. Returns the record (with `body` still populated for this\n\t * one read) or undefined for an unknown handle.\n\t */\n\tcollect(handle: string): { record: InboxRecord; body: string } | undefined {\n\t\tconst rec = this.get(handle);\n\t\tif (!rec || rec.lifecycle !== \"done\" || rec.body === undefined) return undefined;\n\t\tconst body = rec.body;\n\t\trec.lifecycle = \"collected\";\n\t\trec.body = undefined;\n\t\treturn { record: rec, body };\n\t}\n\n\t/** All records, oldest first. */\n\tlist(): InboxRecord[] {\n\t\treturn this.order.map((id) => this.records.get(id)).filter((r): r is InboxRecord => r !== undefined);\n\t}\n\n\t/** Records still doing work. */\n\toutstanding(): InboxRecord[] {\n\t\treturn this.list().filter((r) => isOutstanding(r.lifecycle));\n\t}\n\n\t/** Test/teardown helper. */\n\tclear(): void {\n\t\tthis.records.clear();\n\t\tthis.order = [];\n\t\tthis.labelCounters.clear();\n\t}\n\n\t/** Drop the oldest settled records once past the cap; running records are kept. */\n\tprivate prune(): void {\n\t\tlet settled = this.order.filter((id) => {\n\t\t\tconst r = this.records.get(id);\n\t\t\treturn r !== undefined && !isOutstanding(r.lifecycle);\n\t\t}).length;\n\t\tif (settled <= MAX_SETTLED) return;\n\t\tconst kept: string[] = [];\n\t\tfor (const id of this.order) {\n\t\t\tconst r = this.records.get(id);\n\t\t\tif (r && !isOutstanding(r.lifecycle) && settled > MAX_SETTLED) {\n\t\t\t\tthis.records.delete(id);\n\t\t\t\tsettled--;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tkept.push(id);\n\t\t}\n\t\tthis.order = kept;\n\t}\n}\n\n/** Process-wide subagent inbox shared by the Task and TaskOutput tools. */\nexport const subagentInbox = new SubagentInbox();\n"]}
|
|
1
|
+
{"version":3,"file":"subagent-inbox.js","sourceRoot":"","sources":["../../src/core/subagent-inbox.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAOH,sEAAsE;AACtE,MAAM,UAAU,aAAa,CAAC,SAAwB,EAAW;IAChE,OAAO,SAAS,KAAK,SAAS,CAAC;AAAA,CAC/B;AAoBD,+FAA+F;AAC/F,MAAM,WAAW,GAAG,EAAE,CAAC;AAEvB,8DAA8D;AAC9D,SAAS,SAAS,CAAC,IAAY,EAAE,GAAG,GAAG,GAAG,EAAU;IACnD,MAAM,IAAI,GAAG,CACZ,IAAI;SACF,IAAI,EAAE;SACN,KAAK,CAAC,IAAI,CAAC;SACX,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,IAAI,EAAE,CAC7B,CAAC,IAAI,EAAE,CAAC;IACT,OAAO,IAAI,CAAC,MAAM,GAAG,GAAG,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE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AAM,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;YAC/B,OAAO,CAAC,KAAK,SAAS,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;QAAA,CACtD,CAAC,CAAC,MAAM,CAAC;QACV,IAAI,OAAO,IAAI,WAAW;YAAE,OAAO;QACnC,MAAM,IAAI,GAAa,EAAE,CAAC;QAC1B,KAAK,MAAM,EAAE,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;YAC7B,MAAM,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;YAC/B,IAAI,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,SAAS,CAAC,IAAI,OAAO,GAAG,WAAW,EAAE,CAAC;gBAC/D,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;gBACxB,OAAO,EAAE,CAAC;gBACV,SAAS;YACV,CAAC;YACD,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QACf,CAAC;QACD,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;IAAA,CAClB;CACD;AAED,2EAA2E;AAC3E,MAAM,CAAC,MAAM,aAAa,GAAG,IAAI,aAAa,EAAE,CAAC","sourcesContent":["/**\n * Subagent inbox: the notify-and-pull bookkeeping behind background `Task`\n * dispatch and the `TaskOutput` tool.\n *\n * Background dispatches don't push their full result into the parent's context.\n * Instead the parent gets a compact notification (\"explore#1 finished\") and the\n * body is retained here, keyed by task id, until the model explicitly pulls it\n * with TaskOutput. This keeps a wide swarm of subagents from flooding the\n * context with N full summaries, and gives the model a queryable liveness view\n * (running / done / failed + last activity) so it can tell a working subagent\n * from a rogue one. The same surface works at every delegation depth.\n *\n * Lifecycle per task:\n * running ──▶ done (body retained) ──collect──▶ collected (body dropped)\n * ├─▶ failed\n * ├─▶ stalled\n * └─▶ timeout\n */\n\nimport type { SubagentPool, TaskResult } from \"./subagent-pool.js\";\nimport type { SubagentResultFile } from \"./subagent-result.js\";\n\nexport type TaskLifecycle = \"running\" | \"done\" | \"failed\" | \"stalled\" | \"timeout\" | \"cancelled\" | \"collected\";\n\n/** A non-terminal task is still doing work; the rest have settled. */\nexport function isOutstanding(lifecycle: TaskLifecycle): boolean {\n\treturn lifecycle === \"running\";\n}\n\nexport interface InboxRecord {\n\ttaskId: string;\n\t/** Friendly handle shown to the model, e.g. \"explore#1\". */\n\tlabel: string;\n\tagentType: string;\n\tlifecycle: TaskLifecycle;\n\tstartedAt: number;\n\tendedAt?: number;\n\t/** Tool the subagent is currently running, from the pool's progress stream. */\n\tlastActivity?: string;\n\t/** First line of the result/summary, kept even after the body is collected. */\n\tsummaryLine?: string;\n\t/** Full subagent summary, retained only while `done` and uncollected. */\n\tbody?: string;\n\t/** Failure reason when the task did not succeed. */\n\terror?: string;\n}\n\n/** Cap on settled (terminal) records kept for late pulls; running records are never pruned. */\nconst MAX_SETTLED = 50;\n\n/** First non-empty line of a block of text, length-capped. */\nfunction firstLine(text: string, max = 120): string {\n\tconst line = (\n\t\ttext\n\t\t\t.trim()\n\t\t\t.split(\"\\n\")\n\t\t\t.find((l) => l.trim()) ?? \"\"\n\t).trim();\n\treturn line.length > max ? `${line.slice(0, max - 1)}…` : line;\n}\n\n/** Map a subagent's terminal `status` onto an inbox lifecycle. */\nfunction failLifecycle(status: string | undefined): TaskLifecycle {\n\tif (status === \"stalled\") return \"stalled\";\n\tif (status === \"timeout\") return \"timeout\";\n\tif (status === \"cancelled\") return \"cancelled\";\n\treturn \"failed\";\n}\n\n/** Derive the \"currently running X\" activity label from a forwarded progress event. */\nfunction activityFromEvent(event: Record<string, unknown>): string | undefined {\n\tif (event.type === \"tool_execution_start\" && typeof event.toolName === \"string\") {\n\t\treturn event.toolName;\n\t}\n\tif (event.type === \"turn_end\") return \"thinking\";\n\treturn undefined;\n}\n\nclass SubagentInbox {\n\tprivate records = new Map<string, InboxRecord>();\n\t/** Insertion order of task ids, for stable listing and pruning. */\n\tprivate order: string[] = [];\n\tprivate labelCounters = new Map<string, number>();\n\tprivate observedPools = new WeakSet<SubagentPool>();\n\t/** One-shot callbacks fired after any record settles, for the wait helpers. */\n\tprivate settleListeners = new Set<() => void>();\n\n\tprivate notifySettle(): void {\n\t\tfor (const listener of [...this.settleListeners]) listener();\n\t}\n\n\t/**\n\t * Resolve once the given task settles (or immediately if already settled /\n\t * unknown), bounded by `timeoutMs`. Backs TaskOutput's per-task wait.\n\t */\n\twaitFor(handle: string, timeoutMs: number): Promise<InboxRecord | undefined> {\n\t\tconst current = this.get(handle);\n\t\tif (!current || !isOutstanding(current.lifecycle)) return Promise.resolve(current);\n\t\treturn new Promise((resolve) => {\n\t\t\tconst cleanup = () => {\n\t\t\t\tthis.settleListeners.delete(check);\n\t\t\t\tclearTimeout(timer);\n\t\t\t};\n\t\t\tconst check = () => {\n\t\t\t\tconst rec = this.get(handle);\n\t\t\t\tif (!rec || !isOutstanding(rec.lifecycle)) {\n\t\t\t\t\tcleanup();\n\t\t\t\t\tresolve(rec);\n\t\t\t\t}\n\t\t\t};\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tcleanup();\n\t\t\t\tresolve(this.get(handle));\n\t\t\t}, timeoutMs);\n\t\t\ttimer.unref?.();\n\t\t\tthis.settleListeners.add(check);\n\t\t});\n\t}\n\n\t/** Resolve once nothing is outstanding (the swarm barrier), bounded by `timeoutMs`. */\n\twaitForAll(timeoutMs: number): Promise<void> {\n\t\tif (this.outstanding().length === 0) return Promise.resolve();\n\t\treturn new Promise((resolve) => {\n\t\t\tconst cleanup = () => {\n\t\t\t\tthis.settleListeners.delete(check);\n\t\t\t\tclearTimeout(timer);\n\t\t\t};\n\t\t\tconst check = () => {\n\t\t\t\tif (this.outstanding().length === 0) {\n\t\t\t\t\tcleanup();\n\t\t\t\t\tresolve();\n\t\t\t\t}\n\t\t\t};\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tcleanup();\n\t\t\t\tresolve();\n\t\t\t}, timeoutMs);\n\t\t\ttimer.unref?.();\n\t\t\tthis.settleListeners.add(check);\n\t\t});\n\t}\n\n\t/** Allocate the next friendly label for an agent type (`explore#1`, `explore#2`, …). */\n\tnextLabel(agentType: string): string {\n\t\tconst n = (this.labelCounters.get(agentType) ?? 0) + 1;\n\t\tthis.labelCounters.set(agentType, n);\n\t\treturn `${agentType}#${n}`;\n\t}\n\n\t/**\n\t * Track a pool's `task_progress` events so running records carry a live\n\t * `lastActivity`. Idempotent per pool, so callers can wire it on every dispatch.\n\t */\n\tobserve(pool: SubagentPool): void {\n\t\t// Tolerate a non-EventEmitter stand-in (test fakes): without progress events\n\t\t// records simply carry no live activity.\n\t\tif (typeof (pool as { on?: unknown }).on !== \"function\") return;\n\t\tif (this.observedPools.has(pool)) return;\n\t\tthis.observedPools.add(pool);\n\t\tpool.on(\"task_progress\", (data: { task_id: string; event: Record<string, unknown> }) => {\n\t\t\tconst rec = this.records.get(data.task_id);\n\t\t\tif (!rec || rec.lifecycle !== \"running\") return;\n\t\t\tconst activity = activityFromEvent(data.event);\n\t\t\tif (activity) rec.lastActivity = activity;\n\t\t});\n\t}\n\n\t/** Register a freshly dispatched background task as running. */\n\tstart(taskId: string, label: string, agentType: string): InboxRecord {\n\t\tconst rec: InboxRecord = { taskId, label, agentType, lifecycle: \"running\", startedAt: Date.now() };\n\t\tthis.records.set(taskId, rec);\n\t\tthis.order.push(taskId);\n\t\tthis.prune();\n\t\treturn rec;\n\t}\n\n\t/** Settle a task from its dispatch result: retain the body on success, the reason on failure. */\n\tfinish(taskId: string, result: TaskResult): InboxRecord | undefined {\n\t\tconst rec = this.records.get(taskId);\n\t\tif (!rec) return undefined;\n\t\trec.endedAt = Date.now();\n\t\trec.lastActivity = undefined;\n\t\tconst r = result.result;\n\t\tconst data = r?.result_data as SubagentResultFile | undefined;\n\t\tif (r?.ok) {\n\t\t\trec.lifecycle = \"done\";\n\t\t\trec.body = data?.summary?.trim() || \"(subagent returned no output)\";\n\t\t\trec.summaryLine = firstLine(rec.body);\n\t\t} else {\n\t\t\trec.lifecycle = failLifecycle(r?.status);\n\t\t\trec.error = r?.error ?? (r?.status ? `subagent ${r.status}` : \"unknown error\");\n\t\t\trec.summaryLine = rec.error;\n\t\t}\n\t\tthis.notifySettle();\n\t\treturn rec;\n\t}\n\n\t/** Settle a task that never produced a TaskResult (e.g. a thrown dispatch error). */\n\tfail(taskId: string, reason: string, lifecycle: TaskLifecycle = \"failed\"): InboxRecord | undefined {\n\t\tconst rec = this.records.get(taskId);\n\t\tif (!rec) return undefined;\n\t\trec.endedAt = Date.now();\n\t\trec.lastActivity = undefined;\n\t\trec.lifecycle = lifecycle;\n\t\trec.error = reason;\n\t\trec.summaryLine = reason;\n\t\tthis.notifySettle();\n\t\treturn rec;\n\t}\n\n\t/** Look up a record by task id or by friendly label. */\n\tget(handle: string): InboxRecord | undefined {\n\t\tconst byId = this.records.get(handle);\n\t\tif (byId) return byId;\n\t\tfor (const rec of this.records.values()) {\n\t\t\tif (rec.label === handle) return rec;\n\t\t}\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Read a done task's body and mark it collected, dropping the body so it is not\n\t * re-fed to the model. Returns the record (with `body` still populated for this\n\t * one read) or undefined for an unknown handle.\n\t */\n\tcollect(handle: string): { record: InboxRecord; body: string } | undefined {\n\t\tconst rec = this.get(handle);\n\t\tif (!rec || rec.lifecycle !== \"done\" || rec.body === undefined) return undefined;\n\t\tconst body = rec.body;\n\t\trec.lifecycle = \"collected\";\n\t\trec.body = undefined;\n\t\treturn { record: rec, body };\n\t}\n\n\t/** All records, oldest first. */\n\tlist(): InboxRecord[] {\n\t\treturn this.order.map((id) => this.records.get(id)).filter((r): r is InboxRecord => r !== undefined);\n\t}\n\n\t/** Records still doing work. */\n\toutstanding(): InboxRecord[] {\n\t\treturn this.list().filter((r) => isOutstanding(r.lifecycle));\n\t}\n\n\t/** Test/teardown helper. */\n\tclear(): void {\n\t\tthis.records.clear();\n\t\tthis.order = [];\n\t\tthis.labelCounters.clear();\n\t}\n\n\t/** Drop the oldest settled records once past the cap; running records are kept. */\n\tprivate prune(): void {\n\t\tlet settled = this.order.filter((id) => {\n\t\t\tconst r = this.records.get(id);\n\t\t\treturn r !== undefined && !isOutstanding(r.lifecycle);\n\t\t}).length;\n\t\tif (settled <= MAX_SETTLED) return;\n\t\tconst kept: string[] = [];\n\t\tfor (const id of this.order) {\n\t\t\tconst r = this.records.get(id);\n\t\t\tif (r && !isOutstanding(r.lifecycle) && settled > MAX_SETTLED) {\n\t\t\t\tthis.records.delete(id);\n\t\t\t\tsettled--;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tkept.push(id);\n\t\t}\n\t\tthis.order = kept;\n\t}\n}\n\n/** Process-wide subagent inbox shared by the Task and TaskOutput tools. */\nexport const subagentInbox = new SubagentInbox();\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"subagent-pool-instance.d.ts","sourceRoot":"","sources":["../../src/core/subagent-pool-instance.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAKH,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AASlD,mFAAmF;AACnF,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,GAAG,YAAY,CA+BzD;
|
|
1
|
+
{"version":3,"file":"subagent-pool-instance.d.ts","sourceRoot":"","sources":["../../src/core/subagent-pool-instance.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAKH,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AASlD,mFAAmF;AACnF,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,GAAG,YAAY,CA+BzD;AAgCD;;;;GAIG;AACH,wBAAgB,gBAAgB,IAAI,YAAY,GAAG,SAAS,CAE3D;AAED;;;;;GAKG;AACH,wBAAgB,wBAAwB,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,IAAI,CAG9D;AAED,mFAAmF;AACnF,wBAAgB,mBAAmB,IAAI,IAAI,CAI1C;AAED;;;GAGG;AACH,wBAAgB,yBAAyB,CAAC,QAAQ,EAAE,YAAY,GAAG,SAAS,GAAG,IAAI,CAElF","sourcesContent":["/**\n * Process-wide SubagentPool singleton.\n *\n * The subagent tool and the `/subagent` command both delegate through one pool\n * so concurrency limits, lifeguard monitoring, and token budgets are shared\n * across every delegation in the session. Created lazily on first use and torn\n * down on process exit.\n */\n\nimport { getAgentDir, getSubagentSpawnCommand } from \"../config.js\";\nimport { SettingsManager } from \"./settings-manager.js\";\nimport { poolConcurrencyForDepth } from \"./subagent-depth.js\";\nimport { SubagentPool } from \"./subagent-pool.js\";\nimport { taskStore } from \"./task-store.js\";\n\nlet pool: SubagentPool | undefined;\nlet override: SubagentPool | undefined;\nlet exitHandlerRegistered = false;\n/** Latest non-default skill paths to forward to subagents, kept in sync with the resource loader. */\nlet latestSkillPaths: string[] = [];\n\n/** Get the shared pool for a given working directory, creating it on first use. */\nexport function getSubagentPool(cwd: string): SubagentPool {\n\tif (override) return override;\n\tif (!pool) {\n\t\tconst { executable, prefixArgs } = getSubagentSpawnCommand();\n\t\t// Pools created inside a nested subagent (depth >= 1) run with a reduced\n\t\t// concurrency cap so deep delegation trees stay bounded; the root keeps the\n\t\t// SubagentPool default.\n\t\t// Load settings for model category resolution\n\t\tconst settingsManager = SettingsManager.create(cwd, getAgentDir());\n\t\tconst globalSettings = settingsManager.getGlobalSettings();\n\t\tconst projectSettings = settingsManager.getProjectSettings();\n\t\t// Merge settings (project overrides global)\n\t\tconst settings = { ...globalSettings, ...projectSettings };\n\n\t\tpool = new SubagentPool({\n\t\t\texecutable,\n\t\t\tprefixArgs,\n\t\t\tcwd,\n\t\t\tskillPaths: latestSkillPaths,\n\t\t\tmaxConcurrency: poolConcurrencyForDepth(),\n\t\t\tsettings,\n\t\t});\n\n\t\twireProgressToTaskStore(pool);\n\n\t\tif (!exitHandlerRegistered) {\n\t\t\texitHandlerRegistered = true;\n\t\t\tprocess.once(\"exit\", () => pool?.dispose());\n\t\t}\n\t}\n\treturn pool;\n}\n\n/**\n * Surface live subagent progress on the task panel's agent roster row. The pool\n * forwards only coarse lifecycle events; we map the currently-executing tool onto\n * the run's `activity` and clear it between tools and on completion. Roster rows\n * are keyed per run by the pool task id (see registerSubagentDispatch), so\n * concurrent same-type subagents update their own rows; patching an unknown id\n * is a no-op. This touches only the roster row, never task nodes — so it cannot\n * collide with the end-of-run task-tree merge. Render coalescing is handled by\n * the TUI's `requestRender`, so per-event patches are fine.\n */\nfunction wireProgressToTaskStore(p: SubagentPool): void {\n\tp.on(\"task_progress\", (data: { task_id: string; event: { type?: string; toolName?: string } }) => {\n\t\tconst { task_id, event } = data;\n\t\tif (event.type === \"tool_execution_start\") {\n\t\t\ttaskStore.patchAgent(task_id, { activity: typeof event.toolName === \"string\" ? event.toolName : \"\" });\n\t\t} else if (event.type === \"turn_end\") {\n\t\t\t// Between turns the subagent is reasoning, not idle — mirror the inbox's\n\t\t\t// \"thinking\" so the panel and TaskOutput agree on what the run is doing.\n\t\t\ttaskStore.patchAgent(task_id, { activity: \"thinking\" });\n\t\t} else if (event.type === \"tool_execution_end\") {\n\t\t\ttaskStore.patchAgent(task_id, { activity: \"\" });\n\t\t}\n\t});\n\tfor (const terminal of [\"task_done\", \"task_failed\", \"task_stalled\", \"task_timeout\", \"task_cancelled\"] as const) {\n\t\tp.on(terminal, (data: { task_id?: string }) => {\n\t\t\tif (data.task_id) taskStore.patchAgent(data.task_id, { activity: \"\" });\n\t\t});\n\t}\n}\n\n/**\n * Return the shared pool if one already exists, without creating it. Use this for\n * best-effort signaling (e.g. reporting external load) that must not spin up a pool\n * and its lifeguard just because the signal fired before any subagent was dispatched.\n */\nexport function peekSubagentPool(): SubagentPool | undefined {\n\treturn override ?? pool;\n}\n\n/**\n * Update the skill paths forwarded to every subagent.\n * Call this after the resource loader reloads or extends its skill set.\n * If the pool has already been created, updates it immediately.\n * If not, the paths will be passed in when the pool is first created.\n */\nexport function updateSubagentSkillPaths(paths: string[]): void {\n\tlatestSkillPaths = paths;\n\tpool?.updateSkillPaths(paths);\n}\n\n/** Dispose and clear the shared pool. Intended for test isolation and shutdown. */\nexport function disposeSubagentPool(): void {\n\tpool?.dispose();\n\tpool = undefined;\n\tlatestSkillPaths = [];\n}\n\n/**\n * Inject a pool instance for tests, bypassing real child-process spawning.\n * Pass `undefined` to clear the override.\n */\nexport function setSubagentPoolForTesting(testPool: SubagentPool | undefined): void {\n\toverride = testPool;\n}\n"]}
|
|
@@ -50,25 +50,32 @@ export function getSubagentPool(cwd) {
|
|
|
50
50
|
/**
|
|
51
51
|
* Surface live subagent progress on the task panel's agent roster row. The pool
|
|
52
52
|
* forwards only coarse lifecycle events; we map the currently-executing tool onto
|
|
53
|
-
* the
|
|
54
|
-
*
|
|
55
|
-
*
|
|
56
|
-
*
|
|
53
|
+
* the run's `activity` and clear it between tools and on completion. Roster rows
|
|
54
|
+
* are keyed per run by the pool task id (see registerSubagentDispatch), so
|
|
55
|
+
* concurrent same-type subagents update their own rows; patching an unknown id
|
|
56
|
+
* is a no-op. This touches only the roster row, never task nodes — so it cannot
|
|
57
|
+
* collide with the end-of-run task-tree merge. Render coalescing is handled by
|
|
58
|
+
* the TUI's `requestRender`, so per-event patches are fine.
|
|
57
59
|
*/
|
|
58
60
|
function wireProgressToTaskStore(p) {
|
|
59
61
|
p.on("task_progress", (data) => {
|
|
60
|
-
const {
|
|
62
|
+
const { task_id, event } = data;
|
|
61
63
|
if (event.type === "tool_execution_start") {
|
|
62
|
-
taskStore.patchAgent(
|
|
64
|
+
taskStore.patchAgent(task_id, { activity: typeof event.toolName === "string" ? event.toolName : "" });
|
|
63
65
|
}
|
|
64
|
-
else if (event.type === "
|
|
65
|
-
|
|
66
|
+
else if (event.type === "turn_end") {
|
|
67
|
+
// Between turns the subagent is reasoning, not idle — mirror the inbox's
|
|
68
|
+
// "thinking" so the panel and TaskOutput agree on what the run is doing.
|
|
69
|
+
taskStore.patchAgent(task_id, { activity: "thinking" });
|
|
70
|
+
}
|
|
71
|
+
else if (event.type === "tool_execution_end") {
|
|
72
|
+
taskStore.patchAgent(task_id, { activity: "" });
|
|
66
73
|
}
|
|
67
74
|
});
|
|
68
|
-
for (const terminal of ["task_done", "task_failed", "task_stalled", "task_timeout"]) {
|
|
75
|
+
for (const terminal of ["task_done", "task_failed", "task_stalled", "task_timeout", "task_cancelled"]) {
|
|
69
76
|
p.on(terminal, (data) => {
|
|
70
|
-
if (data.
|
|
71
|
-
taskStore.patchAgent(data.
|
|
77
|
+
if (data.task_id)
|
|
78
|
+
taskStore.patchAgent(data.task_id, { activity: "" });
|
|
72
79
|
});
|
|
73
80
|
}
|
|
74
81
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"subagent-pool-instance.js","sourceRoot":"","sources":["../../src/core/subagent-pool-instance.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAE,WAAW,EAAE,uBAAuB,EAAE,MAAM,cAAc,CAAC;AACpE,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AAC9D,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAE5C,IAAI,IAA8B,CAAC;AACnC,IAAI,QAAkC,CAAC;AACvC,IAAI,qBAAqB,GAAG,KAAK,CAAC;AAClC,qGAAqG;AACrG,IAAI,gBAAgB,GAAa,EAAE,CAAC;AAEpC,mFAAmF;AACnF,MAAM,UAAU,eAAe,CAAC,GAAW,EAAgB;IAC1D,IAAI,QAAQ;QAAE,OAAO,QAAQ,CAAC;IAC9B,IAAI,CAAC,IAAI,EAAE,CAAC;QACX,MAAM,EAAE,UAAU,EAAE,UAAU,EAAE,GAAG,uBAAuB,EAAE,CAAC;QAC7D,yEAAyE;QACzE,4EAA4E;QAC5E,wBAAw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mBAAmB,GAAS;IAC3C,IAAI,EAAE,OAAO,EAAE,CAAC;IAChB,IAAI,GAAG,SAAS,CAAC;IACjB,gBAAgB,GAAG,EAAE,CAAC;AAAA,CACtB;AAED;;;GAGG;AACH,MAAM,UAAU,yBAAyB,CAAC,QAAkC,EAAQ;IACnF,QAAQ,GAAG,QAAQ,CAAC;AAAA,CACpB","sourcesContent":["/**\n * Process-wide SubagentPool singleton.\n *\n * The subagent tool and the `/subagent` command both delegate through one pool\n * so concurrency limits, lifeguard monitoring, and token budgets are shared\n * across every delegation in the session. Created lazily on first use and torn\n * down on process exit.\n */\n\nimport { getAgentDir, getSubagentSpawnCommand } from \"../config.js\";\nimport { SettingsManager } from \"./settings-manager.js\";\nimport { poolConcurrencyForDepth } from \"./subagent-depth.js\";\nimport { SubagentPool } from \"./subagent-pool.js\";\nimport { taskStore } from \"./task-store.js\";\n\nlet pool: SubagentPool | undefined;\nlet override: SubagentPool | undefined;\nlet exitHandlerRegistered = false;\n/** Latest non-default skill paths to forward to subagents, kept in sync with the resource loader. */\nlet latestSkillPaths: string[] = [];\n\n/** Get the shared pool for a given working directory, creating it on first use. */\nexport function getSubagentPool(cwd: string): SubagentPool {\n\tif (override) return override;\n\tif (!pool) {\n\t\tconst { executable, prefixArgs } = getSubagentSpawnCommand();\n\t\t// Pools created inside a nested subagent (depth >= 1) run with a reduced\n\t\t// concurrency cap so deep delegation trees stay bounded; the root keeps the\n\t\t// SubagentPool default.\n\t\t// Load settings for model category resolution\n\t\tconst settingsManager = SettingsManager.create(cwd, getAgentDir());\n\t\tconst globalSettings = settingsManager.getGlobalSettings();\n\t\tconst projectSettings = settingsManager.getProjectSettings();\n\t\t// Merge settings (project overrides global)\n\t\tconst settings = { ...globalSettings, ...projectSettings };\n\n\t\tpool = new SubagentPool({\n\t\t\texecutable,\n\t\t\tprefixArgs,\n\t\t\tcwd,\n\t\t\tskillPaths: latestSkillPaths,\n\t\t\tmaxConcurrency: poolConcurrencyForDepth(),\n\t\t\tsettings,\n\t\t});\n\n\t\twireProgressToTaskStore(pool);\n\n\t\tif (!exitHandlerRegistered) {\n\t\t\texitHandlerRegistered = true;\n\t\t\tprocess.once(\"exit\", () => pool?.dispose());\n\t\t}\n\t}\n\treturn pool;\n}\n\n/**\n * Surface live subagent progress on the task panel's agent roster row. The pool\n * forwards only coarse lifecycle events; we map the currently-executing tool onto\n * the run's `activity` and clear it between tools and on completion. Roster rows\n * are keyed per run by the pool task id (see registerSubagentDispatch), so\n * concurrent same-type subagents update their own rows; patching an unknown id\n * is a no-op. This touches only the roster row, never task nodes — so it cannot\n * collide with the end-of-run task-tree merge. Render coalescing is handled by\n * the TUI's `requestRender`, so per-event patches are fine.\n */\nfunction wireProgressToTaskStore(p: SubagentPool): void {\n\tp.on(\"task_progress\", (data: { task_id: string; event: { type?: string; toolName?: string } }) => {\n\t\tconst { task_id, event } = data;\n\t\tif (event.type === \"tool_execution_start\") {\n\t\t\ttaskStore.patchAgent(task_id, { activity: typeof event.toolName === \"string\" ? event.toolName : \"\" });\n\t\t} else if (event.type === \"turn_end\") {\n\t\t\t// Between turns the subagent is reasoning, not idle — mirror the inbox's\n\t\t\t// \"thinking\" so the panel and TaskOutput agree on what the run is doing.\n\t\t\ttaskStore.patchAgent(task_id, { activity: \"thinking\" });\n\t\t} else if (event.type === \"tool_execution_end\") {\n\t\t\ttaskStore.patchAgent(task_id, { activity: \"\" });\n\t\t}\n\t});\n\tfor (const terminal of [\"task_done\", \"task_failed\", \"task_stalled\", \"task_timeout\", \"task_cancelled\"] as const) {\n\t\tp.on(terminal, (data: { task_id?: string }) => {\n\t\t\tif (data.task_id) taskStore.patchAgent(data.task_id, { activity: \"\" });\n\t\t});\n\t}\n}\n\n/**\n * Return the shared pool if one already exists, without creating it. Use this for\n * best-effort signaling (e.g. reporting external load) that must not spin up a pool\n * and its lifeguard just because the signal fired before any subagent was dispatched.\n */\nexport function peekSubagentPool(): SubagentPool | undefined {\n\treturn override ?? pool;\n}\n\n/**\n * Update the skill paths forwarded to every subagent.\n * Call this after the resource loader reloads or extends its skill set.\n * If the pool has already been created, updates it immediately.\n * If not, the paths will be passed in when the pool is first created.\n */\nexport function updateSubagentSkillPaths(paths: string[]): void {\n\tlatestSkillPaths = paths;\n\tpool?.updateSkillPaths(paths);\n}\n\n/** Dispose and clear the shared pool. Intended for test isolation and shutdown. */\nexport function disposeSubagentPool(): void {\n\tpool?.dispose();\n\tpool = undefined;\n\tlatestSkillPaths = [];\n}\n\n/**\n * Inject a pool instance for tests, bypassing real child-process spawning.\n * Pass `undefined` to clear the override.\n */\nexport function setSubagentPoolForTesting(testPool: SubagentPool | undefined): void {\n\toverride = testPool;\n}\n"]}
|
|
@@ -37,7 +37,7 @@ export interface SubagentResult {
|
|
|
37
37
|
/** True when the task exceeded its token budget and was hard-stopped. */
|
|
38
38
|
budget_exceeded?: boolean;
|
|
39
39
|
/** Terminal status derived from how the task finished. */
|
|
40
|
-
status?: "complete" | "partial" | "failed" | "stalled" | "timeout";
|
|
40
|
+
status?: "complete" | "partial" | "failed" | "stalled" | "timeout" | "cancelled";
|
|
41
41
|
/** Parsed result.json content when available (e.g. on partial completion). */
|
|
42
42
|
result_data?: Record<string, unknown>;
|
|
43
43
|
/** True when this run used the inherited-model fallback (preferred model failed first). */
|
|
@@ -107,6 +107,19 @@ export declare const DEFAULT_SUBAGENT_MAX_TURNS = 50;
|
|
|
107
107
|
* and the task panel from thrashing under concurrent subagents.
|
|
108
108
|
*/
|
|
109
109
|
export declare const FORWARDED_SUBAGENT_EVENTS: ReadonlySet<string>;
|
|
110
|
+
/**
|
|
111
|
+
* Cap on the captured stdout/stderr text kept per task (tail-truncated). The
|
|
112
|
+
* capture exists for diagnostics (failure reasons, output.json), so keeping the
|
|
113
|
+
* most recent tail is enough; without a cap a chatty child could grow the
|
|
114
|
+
* parent's memory without bound across a long swarm.
|
|
115
|
+
*/
|
|
116
|
+
export declare const MAX_CAPTURED_STREAM_CHARS: number;
|
|
117
|
+
/**
|
|
118
|
+
* Cap on a single un-terminated JSONL line buffered from a child's stdout. The
|
|
119
|
+
* forwarded events are small; anything approaching this is a runaway writer,
|
|
120
|
+
* and the reader drops the line rather than buffering toward OOM.
|
|
121
|
+
*/
|
|
122
|
+
export declare const MAX_SUBAGENT_EVENT_LINE_CHARS: number;
|
|
110
123
|
/** The action the pool should take for one JSONL line from a subagent's stdout. */
|
|
111
124
|
export type SubagentStdoutLine = {
|
|
112
125
|
kind: "heartbeat";
|
|
@@ -133,6 +146,7 @@ export declare function classifySubagentLine(line: string): SubagentStdoutLine;
|
|
|
133
146
|
* - "task_stalled" – heartbeat missed past the load-scaled threshold (60s base,
|
|
134
147
|
* widened under concurrency/event-loop lag), process SIGKILLed
|
|
135
148
|
* - "task_timeout" – hard timeout exceeded, process was SIGKILLed
|
|
149
|
+
* - "task_cancelled" – user-initiated cancel (see cancel()); process tree killed
|
|
136
150
|
* - "budget_warning" – token usage crossed 80% threshold (advisory)
|
|
137
151
|
* - "budget_exceeded" – token usage crossed 100% threshold (advisory; never kills)
|
|
138
152
|
* - "task_progress" – coarse lifecycle event (turn_end, tool start/end) parsed
|
|
@@ -157,7 +171,7 @@ export declare class SubagentPool extends EventEmitter {
|
|
|
157
171
|
private disposed;
|
|
158
172
|
/** Lazily-loaded agent registry (frontmatter definitions) for this pool's cwd. */
|
|
159
173
|
private registry?;
|
|
160
|
-
/** Tracks why a task was killed (stalled / timeout) before exit handler fires. */
|
|
174
|
+
/** Tracks why a task was killed (stalled / timeout / user cancel) before exit handler fires. */
|
|
161
175
|
private killReasons;
|
|
162
176
|
/** Persistent terminal status map, survives wait_for consumption. */
|
|
163
177
|
private taskStatus;
|
|
@@ -180,7 +194,15 @@ export declare class SubagentPool extends EventEmitter {
|
|
|
180
194
|
/** Queue a task. It will run when a slot is free. */
|
|
181
195
|
spawn(task: SubagentPoolTask): void;
|
|
182
196
|
/** Current status of a task. */
|
|
183
|
-
get_status(task_id: string): "running" | "queued" | "done" | "failed" | "stalled" | "timeout" | "unknown";
|
|
197
|
+
get_status(task_id: string): "running" | "queued" | "done" | "failed" | "stalled" | "timeout" | "cancelled" | "unknown";
|
|
198
|
+
/**
|
|
199
|
+
* Cancel a task on the user's behalf (Esc/abort mid-turn). A queued task is
|
|
200
|
+
* removed and settles immediately; a running task's whole process tree is
|
|
201
|
+
* killed and settles with status "cancelled" when its exit is observed
|
|
202
|
+
* (unless it already wrote a valid result.json — completed work is honored).
|
|
203
|
+
* Returns false for unknown/settled task ids.
|
|
204
|
+
*/
|
|
205
|
+
cancel(task_id: string): boolean;
|
|
184
206
|
/** Wait for a task to complete and return its result. */
|
|
185
207
|
wait_for(task_id: string): Promise<SubagentResult>;
|
|
186
208
|
/** Number of currently running subagents. */
|