@wrongstack/core 0.41.0 → 0.51.3
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/dist/{agent-bridge-D_XcS2HL.d.ts → agent-bridge-CjbD-i7-.d.ts} +1 -1
- package/dist/{agent-subagent-runner-C66vi4Gq.d.ts → agent-subagent-runner-DfvlBx5N.d.ts} +3 -3
- package/dist/coordination/index.d.ts +8 -8
- package/dist/coordination/index.js +234 -32
- package/dist/coordination/index.js.map +1 -1
- package/dist/defaults/index.d.ts +11 -11
- package/dist/defaults/index.js +151 -59
- package/dist/defaults/index.js.map +1 -1
- package/dist/{events-BrQiweXN.d.ts → events-Bt44ikPN.d.ts} +135 -1
- package/dist/execution/index.d.ts +34 -8
- package/dist/execution/index.js +61 -28
- package/dist/execution/index.js.map +1 -1
- package/dist/extension/index.d.ts +2 -2
- package/dist/{index-DkVgH3wC.d.ts → index-OzA1XjHL.d.ts} +4 -2
- package/dist/{index-6_csX32J.d.ts → index-mAWBdLyJ.d.ts} +1 -1
- package/dist/index.d.ts +96 -20
- package/dist/index.js +532 -132
- package/dist/index.js.map +1 -1
- package/dist/infrastructure/index.d.ts +2 -2
- package/dist/kernel/index.d.ts +3 -3
- package/dist/kernel/index.js +3 -1
- package/dist/kernel/index.js.map +1 -1
- package/dist/models/index.js +5 -2
- package/dist/models/index.js.map +1 -1
- package/dist/{multi-agent-C8Z1i__e.d.ts → multi-agent-Ba9Ni2hC.d.ts} +1 -1
- package/dist/{multi-agent-coordinator-BUsjiRWl.d.ts → multi-agent-coordinator-BuKq0q89.d.ts} +2 -2
- package/dist/{null-fleet-bus-FvgHnZah.d.ts → null-fleet-bus-C0xd73YP.d.ts} +21 -9
- package/dist/observability/index.d.ts +1 -1
- package/dist/{path-resolver-DumKAi0n.d.ts → path-resolver-nkmdiFgi.d.ts} +1 -1
- package/dist/{plan-templates-DYCeRCDN.d.ts → plan-templates-BmDdJ7UL.d.ts} +1 -1
- package/dist/{provider-runner-Dlv8Fvw9.d.ts → provider-runner-BGro2qQB.d.ts} +1 -1
- package/dist/sdd/index.d.ts +4 -4
- package/dist/storage/index.d.ts +2 -2
- package/dist/{tool-executor-BpK-SWtJ.d.ts → tool-executor-p4tP9tGF.d.ts} +1 -1
- package/dist/types/index.d.ts +7 -7
- package/dist/types/index.js +5 -2
- package/dist/types/index.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/atomic-write.ts","../../src/storage/director-state.ts","../../src/coordination/in-memory-transport.ts","../../src/coordination/agent-bridge.ts","../../src/utils/glob-expand.ts","../../src/coordination/collab-debug.ts","../../src/coordination/director-prompts.ts","../../src/coordination/agents/types.ts","../../src/coordination/agents/phase1-discovery.ts","../../src/coordination/agents/phase2-planning.ts","../../src/coordination/agents/phase3-build.ts","../../src/coordination/agents/phase4-verify.ts","../../src/coordination/agents/phase5-review.ts","../../src/coordination/agents/phase6-domain.ts","../../src/coordination/agents/phase7-knowledge.ts","../../src/coordination/agents/phase8-delivery.ts","../../src/coordination/agents/phase9-meta.ts","../../src/coordination/agents/index.ts","../../src/coordination/dispatcher.ts","../../src/coordination/director-tools.ts","../../src/coordination/fleet-bus.ts","../../src/coordination/large-answer-store.ts","../../src/coordination/model-matrix.ts","../../src/types/errors.ts","../../src/types/provider.ts","../../src/coordination/subagent-budget.ts","../../src/coordination/fleet.ts","../../src/coordination/subagent-nicknames.ts","../../src/coordination/multi-agent-coordinator.ts","../../src/coordination/director.ts","../../src/coordination/delegate-tool.ts","../../src/coordination/agent-subagent-runner.ts","../../src/utils/message-invariants.ts","../../src/storage/session-store.ts","../../src/coordination/director-session.ts","../../src/coordination/auto-extend.ts","../../src/coordination/null-fleet-bus.ts","../../src/coordination/fleet-manager.ts"],"names":["path","fs","stat","resolve","fsp","lock","handlers","fsp2","DirectorAlertLevel","randomUUID","fsp3","first","decision","kind","EventEmitter","baseMessage","fsp4","path2","instantiateRosterConfig","partial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A,CAAK,YAAA,CAAa,OAAO,MAAM,CAAA;AAAA,MACjC;AAAA,IACF;AAAA,EACF;AAAA;AAAA,EAGA,OAAA,GAAgB;AACd,IAAA,IAAI,KAAK,aAAA,EAAe;AACtB,MAAA,YAAA,CAAa,KAAK,aAAa,CAAA;AAC/B,MAAA,IAAA,CAAK,aAAA,GAAgB,IAAA;AAAA,IACvB;AACA,IAAA,IAAA,CAAK,MAAM,OAAA,EAAQ;AAAA,EACrB;AACF","file":"index.js","sourcesContent":["import { randomBytes } from 'node:crypto';\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\n\nexport interface AtomicWriteOptions {\n mode?: number;\n encoding?: BufferEncoding;\n}\n\nexport async function atomicWrite(\n targetPath: string,\n content: string | Uint8Array,\n opts: AtomicWriteOptions = {},\n): Promise<void> {\n const dir = path.dirname(targetPath);\n await fs.mkdir(dir, { recursive: true });\n const tmp = path.join(dir, `.${path.basename(targetPath)}.${randomBytes(6).toString('hex')}.tmp`);\n\n // Write content to tmp first; 'wx' ensures exclusive creation (fails if\n // tmp already exists — extremely unlikely with 6-byte random suffix).\n try {\n if (typeof content === 'string') {\n await fs.writeFile(tmp, content, { flag: 'wx', encoding: opts.encoding ?? 'utf8' });\n } else {\n await fs.writeFile(tmp, content, { flag: 'wx' });\n }\n try {\n const fh = await fs.open(tmp, 'r+');\n try {\n await fh.sync();\n } finally {\n await fh.close();\n }\n } catch {\n // fsync best-effort\n }\n // Now safely read mode from target (if it exists) and apply to tmp before rename.\n // Prefer opts.mode for new files; for existing files preserve their mode.\n let mode: number | undefined;\n try {\n const stat = await fs.stat(targetPath);\n mode = stat.mode & 0o777;\n } catch {\n mode = opts.mode;\n }\n if (mode !== undefined) {\n await fs.chmod(tmp, mode);\n }\n await renameWithRetry(tmp, targetPath);\n } catch (err) {\n try {\n await fs.unlink(tmp);\n } catch {\n // ignore cleanup error\n }\n throw err;\n }\n}\n\nexport async function ensureDir(dir: string): Promise<void> {\n await fs.mkdir(dir, { recursive: true });\n}\n\n// On Windows, fs.rename over an existing file can fail with EPERM/EBUSY/EACCES\n// when antivirus, file indexers, editor file watchers, or a concurrent writer\n// briefly hold a handle on the destination. These are transient — retry with a\n// short backoff before giving up. POSIX renames are atomic and won't hit this.\nconst TRANSIENT_RENAME_CODES = new Set(['EPERM', 'EBUSY', 'EACCES', 'ENOTEMPTY']);\n\nasync function renameWithRetry(from: string, to: string): Promise<void> {\n if (process.platform !== 'win32') {\n await fs.rename(from, to);\n return;\n }\n const delays = [10, 25, 60, 120, 250];\n let lastErr: unknown;\n for (let i = 0; i <= delays.length; i++) {\n try {\n await fs.rename(from, to);\n return;\n } catch (err) {\n lastErr = err;\n const code = (err as NodeJS.ErrnoException)?.code;\n if (!code || !TRANSIENT_RENAME_CODES.has(code) || i === delays.length) {\n throw err;\n }\n await new Promise((resolve) => setTimeout(resolve, delays[i]));\n }\n }\n throw lastErr;\n}\n","import * as fsp from 'node:fs/promises';\nimport { atomicWrite } from '../utils/atomic-write.js';\n\n/**\n * Director state checkpoint — written incrementally throughout a fleet\n * run so a crashed director can be inspected (and eventually resumed)\n * instead of leaving only a final `fleet.json` manifest after `shutdown()`.\n *\n * Schema is JSON-friendly and deliberately denormalized. Each mutation\n * triggers an atomic-write of the whole file — small payloads (typically\n * < 10 KB even with dozens of subagents) make this cheap.\n */\nexport interface DirectorSubagentState {\n id: string;\n name?: string;\n role?: string;\n provider?: string;\n model?: string;\n spawnedAt: string;\n}\n\nexport interface DirectorTaskState {\n taskId: string;\n subagentId?: string;\n description?: string;\n status: 'pending' | 'running' | 'completed' | 'failed' | 'stopped' | 'timeout';\n assignedAt?: string;\n completedAt?: string;\n iterations?: number;\n toolCalls?: number;\n durationMs?: number;\n error?: string;\n}\n\nexport interface DirectorStateSnapshot {\n version: 1;\n directorRunId: string;\n updatedAt: string;\n spawnCount: number;\n maxSpawns?: number;\n spawnDepth: number;\n maxSpawnDepth: number;\n directorBudget?: {\n maxCostUsd?: number;\n };\n subagents: DirectorSubagentState[];\n tasks: DirectorTaskState[];\n /** Aggregated usage snapshot. Optional — populated by the Director on save when available. */\n usage?: unknown;\n}\n\nexport async function loadDirectorState(filePath: string): Promise<DirectorStateSnapshot | null> {\n let raw: string;\n try {\n raw = await fsp.readFile(filePath, 'utf8');\n } catch {\n return null;\n }\n try {\n const parsed = JSON.parse(raw) as DirectorStateSnapshot;\n if (parsed?.version !== 1) return null;\n return parsed;\n } catch {\n return null;\n }\n}\n\n/**\n * Lock file entry written when a director starts. Prevents two directors\n * from resuming the same run — the second one sees the lock and refuses\n * rather than corrupting the checkpoint by writing concurrently.\n */\nexport interface DirectorStateLock {\n pid: number;\n hostname: string;\n startedAt: string;\n}\n\n/**\n * Write a lock file to claim this checkpoint. Returns false if the lock\n * is already held by a live process; returns true if the lock was acquired\n * (either the file didn't exist, or the previous holder is dead).\n */\nexport async function acquireDirectorStateLock(\n lockPath: string,\n processId = process.pid,\n): Promise<boolean> {\n let existing: string | undefined;\n try {\n existing = await fsp.readFile(lockPath, 'utf8');\n } catch {\n // No lock file — we're safe to claim\n }\n\n if (existing) {\n try {\n const lock = JSON.parse(existing) as DirectorStateLock;\n // Check if the process is still alive\n try {\n process.kill(lock.pid, 0);\n // Signal success means the process is alive — another director\n // owns this checkpoint. Refuse.\n return false;\n } catch {\n // ESRCH means the process is dead — stale lock. We'll overwrite.\n }\n } catch {\n // Malformed lock — treat as stale.\n }\n }\n\n const lock: DirectorStateLock = {\n pid: processId,\n hostname: require('node:os').hostname(),\n startedAt: new Date().toISOString(),\n };\n await atomicWrite(lockPath, JSON.stringify(lock), { mode: 0o600 });\n return true;\n}\n\n/**\n * Remove the lock file. Call this on graceful Director.shutdown() so the\n * next director run can claim the checkpoint without stale-lock checks.\n */\nexport async function releaseDirectorStateLock(lockPath: string): Promise<void> {\n try {\n await fsp.unlink(lockPath);\n } catch {\n // ignore\n }\n}\n\n/**\n * In-memory accumulator with atomic-write checkpoint. The Director keeps\n * an instance, mutates it on every spawn/assign/complete/fail event, and\n * the instance debounces writes so a burst of activity collapses into a\n * single disk hit.\n *\n * Supports crash recovery: use `loadDirectorState()` to read an existing\n * checkpoint, then call `DirectorStateCheckpoint.resume(snapshot)` to\n * re-attach to a fleet mid-flight. The lock mechanism ensures no two\n * directors can claim the same checkpoint.\n */\nexport class DirectorStateCheckpoint {\n private snapshot: DirectorStateSnapshot;\n private readonly filePath: string;\n private readonly lockPath: string;\n private timer: NodeJS.Timeout | null = null;\n private readonly debounceMs: number;\n private writing = false;\n private rewriteRequested = false;\n\n constructor(\n filePath: string,\n init: {\n directorRunId: string;\n maxSpawns?: number;\n spawnDepth: number;\n maxSpawnDepth: number;\n directorBudget?: {\n maxCostUsd?: number;\n };\n },\n debounceMs = 250,\n ) {\n this.filePath = filePath;\n // Lock file lives alongside the checkpoint — `<path>.lock`\n this.lockPath = `${filePath}.lock`;\n this.debounceMs = debounceMs;\n this.snapshot = {\n version: 1,\n directorRunId: init.directorRunId,\n updatedAt: new Date().toISOString(),\n spawnCount: 0,\n maxSpawns: init.maxSpawns,\n spawnDepth: init.spawnDepth,\n maxSpawnDepth: init.maxSpawnDepth,\n directorBudget: init.directorBudget,\n subagents: [],\n tasks: [],\n };\n }\n\n /**\n * Attempt to acquire the lock for this checkpoint. Call this before\n * resuming a crashed director run. If it returns false, another\n * director process is still running this fleet — do not resume.\n */\n async acquireLock(): Promise<boolean> {\n return acquireDirectorStateLock(this.lockPath);\n }\n\n /**\n * Release the lock on graceful shutdown. Call `flush()` first to ensure\n * the final checkpoint state is on disk before removing the lock.\n * Without this, the next resume will see a stale-lock and refuse.\n */\n async releaseLock(): Promise<void> {\n return releaseDirectorStateLock(this.lockPath);\n }\n\n /**\n * Resume from a snapshot previously loaded via `loadDirectorState()`.\n * Use this when `--resume <runId>` is triggered — the snapshot has\n * the full fleet state (subagents, tasks) from before the crash; the\n * checkpoint continues from there.\n */\n resume(snapshot: DirectorStateSnapshot): void {\n this.snapshot = snapshot;\n }\n\n current(): DirectorStateSnapshot {\n return this.snapshot;\n }\n\n recordSpawn(sub: DirectorSubagentState, spawnCount: number): void {\n this.snapshot = {\n ...this.snapshot,\n spawnCount,\n subagents: [...this.snapshot.subagents.filter((s) => s.id !== sub.id), sub],\n };\n this.bumpUpdatedAt();\n this.schedule();\n }\n\n recordTaskAssigned(task: DirectorTaskState): void {\n const exists = this.snapshot.tasks.some((t) => t.taskId === task.taskId);\n this.snapshot = {\n ...this.snapshot,\n tasks: exists\n ? this.snapshot.tasks.map((t) => (t.taskId === task.taskId ? { ...t, ...task } : t))\n : [...this.snapshot.tasks, task],\n };\n this.bumpUpdatedAt();\n this.schedule();\n }\n\n recordTaskStatus(\n taskId: string,\n patch: Partial<DirectorTaskState> & { status: DirectorTaskState['status'] },\n ): void {\n this.snapshot = {\n ...this.snapshot,\n tasks: this.snapshot.tasks.map((t) =>\n t.taskId === taskId ? { ...t, ...patch } : t,\n ),\n };\n this.bumpUpdatedAt();\n this.schedule();\n }\n\n setUsage(usage: unknown): void {\n this.snapshot = { ...this.snapshot, usage };\n this.bumpUpdatedAt();\n this.schedule();\n }\n\n /** Force a synchronous flush — used by Director.shutdown(). */\n async flush(): Promise<void> {\n if (this.timer) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n await this.persist();\n // If a rewrite was requested while we waited, persist() scheduled\n // a follow-up write. Loop until no more rewrites are requested so\n // shutdown doesn't return before the most recent state lands on disk.\n while (this.rewriteRequested) {\n this.rewriteRequested = false;\n await this.persist();\n }\n }\n\n private bumpUpdatedAt(): void {\n this.snapshot = { ...this.snapshot, updatedAt: new Date().toISOString() };\n }\n\n private schedule(): void {\n if (this.timer) return;\n this.timer = setTimeout(() => {\n this.timer = null;\n void this.persist();\n }, this.debounceMs);\n }\n\n private async persist(): Promise<void> {\n if (this.writing) {\n // A write is already in flight — defer to a follow-up flush so the\n // most recent state still lands. Without this guard, simultaneous\n // burst mutations can drop the latest snapshot if rename races.\n this.rewriteRequested = true;\n return;\n }\n this.writing = true;\n try {\n await atomicWrite(this.filePath, JSON.stringify(this.snapshot, null, 2), {\n mode: 0o600,\n });\n } catch (err) {\n console.warn(\n '[director-state] checkpoint write failed:',\n err instanceof Error ? err.message : String(err),\n );\n } finally {\n this.writing = false;\n if (this.rewriteRequested) {\n this.rewriteRequested = false;\n this.schedule();\n }\n }\n }\n}\n","import type { BridgeMessage, BridgeTransport } from '../types/agent-bridge.js';\n\n/**\n * In-memory pub/sub transport for agent-to-agent messaging.\n * Subscribers register by agentId and receive messages via callback.\n */\nexport class InMemoryBridgeTransport implements BridgeTransport {\n private readonly subs = new Map<string, Set<(msg: BridgeMessage) => void>>();\n\n send(msg: BridgeMessage, to: string): Promise<void> {\n // Broadcast: deliver to every subscriber except the sender.\n if (to === '*') {\n for (const [id, handlers] of this.subs) {\n if (id === msg.from) continue;\n for (const h of handlers) {\n try {\n h(msg);\n } catch {\n /* ignore */\n }\n }\n }\n return Promise.resolve();\n }\n const handlers = this.subs.get(to);\n if (handlers) {\n for (const h of handlers) {\n try {\n h(msg);\n } catch {\n /* ignore */\n }\n }\n }\n return Promise.resolve();\n }\n\n subscribe(agentId: string, handler: (msg: BridgeMessage) => void): () => void {\n if (!this.subs.has(agentId)) this.subs.set(agentId, new Set());\n this.subs.get(agentId)!.add(handler);\n return () => this.subs.get(agentId)?.delete(handler);\n }\n\n close(agentId: string): Promise<void> {\n this.subs.delete(agentId);\n return Promise.resolve();\n }\n}\n","import { randomUUID } from 'node:crypto';\nimport type {\n AgentBridge,\n AgentBridgeConfig,\n BridgeMessage,\n BridgeTransport,\n} from '../types/agent-bridge.js';\nimport { InMemoryBridgeTransport } from './in-memory-transport.js';\n\n// Re-export for backwards compatibility\nexport { InMemoryBridgeTransport };\n\nexport class InMemoryAgentBridge implements AgentBridge {\n readonly agentId: string;\n readonly coordinatorId: string;\n private readonly transport: BridgeTransport;\n private readonly subscriptions: Set<(msg: BridgeMessage) => void> = new Set();\n private readonly pendingRequests = new Map<\n string,\n {\n resolve: (msg: BridgeMessage) => void;\n reject: (e: Error) => void;\n timer: ReturnType<typeof setTimeout>;\n }\n >();\n private stopped = false;\n private timeoutMs: number;\n /** Guards request() so concurrent calls on the same id can't silently overwrite. */\n private readonly inflightGuards = new Set<string>();\n /** Stores the transport unsubscribe function so it can be called on stop(). */\n private _transportUnsubscribe?: () => void;\n\n constructor(config: AgentBridgeConfig, transport: BridgeTransport) {\n this.agentId = config.agentId;\n this.coordinatorId = config.coordinatorId;\n this.transport = transport;\n this.timeoutMs = config.timeoutMs ?? 30_000;\n\n this._transportUnsubscribe = this.transport.subscribe(this.agentId, (msg) => {\n if (msg.type === 'heartbeat') return;\n\n const pending = this.pendingRequests.get(msg.id);\n if (pending) {\n clearTimeout(pending.timer);\n this.pendingRequests.delete(msg.id);\n this.inflightGuards.delete(msg.id);\n pending.resolve(msg);\n return;\n }\n\n for (const h of this.subscriptions) {\n try {\n h(msg);\n } catch {\n /* ignore */\n }\n }\n });\n }\n\n async send(msg: BridgeMessage): Promise<void> {\n msg.timestamp = Date.now();\n await this.transport.send(msg, msg.to ?? this.coordinatorId);\n }\n\n async broadcast(msg: BridgeMessage): Promise<void> {\n msg.timestamp = Date.now();\n msg.to = '*';\n await this.transport.send(msg, '*');\n }\n\n subscribe(handler: (msg: BridgeMessage) => void | Promise<void>): () => void {\n this.subscriptions.add(handler as (msg: BridgeMessage) => void);\n return () => this.subscriptions.delete(handler as (msg: BridgeMessage) => void);\n }\n\n async request<T>(msg: BridgeMessage, timeoutMs?: number): Promise<BridgeMessage<T>> {\n if (this.stopped) throw new Error('Bridge is stopped');\n const timeout = timeoutMs ?? this.timeoutMs;\n const correlationId = msg.id;\n\n // Guard against concurrent calls reusing the same id. Without this check,\n // a second .set() would silently overwrite the first record — the original\n // caller's timer fires, deletes the entry, and resolves its promise, but\n // the second caller now has no entry to resolve when its timer fires.\n // Throwing here surfaces the caller bug rather than letting it hang.\n if (this.inflightGuards.has(correlationId)) {\n throw new Error(\n `Bridge request id \"${correlationId}\" collides with an in-flight request — caller is reusing message ids`,\n );\n }\n this.inflightGuards.add(correlationId);\n\n return new Promise((resolve, reject) => {\n // Declare timer first so we can reference it in the stopped-check below.\n const timer = setTimeout(() => {\n this.inflightGuards.delete(correlationId);\n this.pendingRequests.delete(correlationId);\n reject(new Error(`Request ${correlationId} timed out after ${timeout}ms`));\n }, timeout);\n\n // Double-check stopped after setting up the pending entry, so stop()\n // can't miss a request that was enqueued before it acquired the lock.\n // Reject if stop() was called after the initial check and cleared\n // the guard — this prevents a request from being enqueued after\n // stop() has already released the lock on pendingRequests.\n if (!this.inflightGuards.has(correlationId)) {\n clearTimeout(timer);\n reject(new Error('Bridge stopped'));\n return;\n }\n\n this.pendingRequests.set(correlationId, {\n resolve: resolve as (msg: BridgeMessage) => void,\n reject,\n timer,\n });\n\n msg.timestamp = Date.now();\n this.transport.send(msg, msg.to ?? this.coordinatorId).catch((e) => {\n clearTimeout(timer);\n this.inflightGuards.delete(correlationId);\n this.pendingRequests.delete(correlationId);\n reject(e);\n });\n });\n }\n\n async stop(): Promise<void> {\n this.stopped = true;\n for (const [, p] of this.pendingRequests) {\n clearTimeout(p.timer);\n p.reject(new Error('Bridge stopped'));\n }\n this.pendingRequests.clear();\n this.inflightGuards.clear();\n this.subscriptions.clear();\n // Call the transport unsubscribe to clean up the subscription handler.\n // This prevents memory leaks when bridges are created and destroyed frequently.\n this._transportUnsubscribe?.();\n this._transportUnsubscribe = undefined;\n await this.transport.close(this.agentId);\n }\n}\n\nexport function createMessage<T = unknown>(\n type: BridgeMessage['type'],\n from: string,\n payload: T,\n to?: string,\n): BridgeMessage<T> {\n return {\n id: randomUUID(),\n type,\n from,\n to,\n payload,\n timestamp: Date.now(),\n priority: 'normal',\n };\n}\n","/**\n * Glob pattern → concrete file path expansion.\n *\n * Supports: *, **, ?, [...]\n * Does NOT support brace expansion {a,b}.\n *\n * Returns the input as-is if it contains no glob metacharacters.\n * On Windows, both / and \\ are accepted as path separators.\n */\n\nimport * as fsp from 'node:fs/promises';\nimport { isAbsolute, resolve } from 'node:path';\n\nconst GLOB_CHARS = new Set(['*', '?', '[']);\nconst IS_WINDOWS = process.platform === 'win32';\nconst SEP = IS_WINDOWS ? '\\\\' : '/';\n\nfunction isGlob(p: string): boolean {\n for (const c of p) {\n if (GLOB_CHARS.has(c)) return true;\n }\n return false;\n}\n\nfunction globToRegex(pat: string): RegExp {\n let i = 0, re = '^';\n while (i < pat.length) {\n const c = pat[i]!;\n if (c === '*') {\n if (pat[i + 1] === '*') {\n re += '.*';\n i += 2;\n if (pat[i] === '/') i++;\n } else {\n re += '[^/\\\\\\\\]*';\n i++;\n }\n } else if (c === '?') {\n re += '[^/\\\\\\\\]';\n i++;\n } else if (c === '[') {\n let cls = '[';\n i++;\n if (pat[i] === '!' || pat[i] === '^') {\n cls += '^';\n i++;\n }\n while (i < pat.length && pat[i] !== ']') {\n const ch = pat[i] ?? '';\n if (ch === '\\\\') cls += '\\\\\\\\';\n else if (ch === ']' || ch === '^') cls += `\\\\${ch}`;\n else cls += ch;\n i++;\n }\n cls += ']';\n re += cls;\n i++;\n } else {\n re += c.replace(/[.+^${}()|\\\\]/g, '\\\\$&');\n i++;\n }\n }\n return new RegExp(re + '$');\n}\n\nfunction baseDir(pat: string): string {\n let i = pat.length - 1;\n while (i >= 0 && !GLOB_CHARS.has(pat[i]!) && pat[i] !== SEP && pat[i] !== '/') i--;\n const cut = i >= 0 ? pat.lastIndexOf(SEP, i) : pat.lastIndexOf('/', i);\n return cut < 0 ? '.' : pat.slice(0, cut);\n}\n\n/**\n * Resolve `pattern` to the set of concrete file paths it matches.\n * Literal paths (no glob chars) are returned as-is.\n *\n * @example\n * await expandGlob('src/**\\/*.ts') // → ['src/a.ts', 'src/b/c.ts', ...]\n * await expandGlob('foo.txt') // → ['foo.txt']\n */\nexport async function expandGlob(pattern: string): Promise<string[]> {\n if (!isGlob(pattern)) return [pattern];\n\n const results = new Set<string>();\n const abs = isAbsolute(pattern);\n const base = abs ? baseDir(pattern) : baseDir(pattern);\n const relPat = base === '.' ? pattern : pattern.slice(base.length + 1);\n\n async function walk(dir: string, pat: string): Promise<void> {\n let entries: string[];\n try {\n entries = await fsp.readdir(dir);\n } catch {\n return;\n }\n\n const firstGlob = pat.search(/[*?[\\[]/);\n\n if (firstGlob < 0) {\n const re = globToRegex(pat);\n for (const e of entries) {\n if (re.test(e)) {\n const full = `${dir}${SEP}${e}`;\n results.add(abs ? resolve(full) : full);\n }\n }\n return;\n }\n\n const before = pat.slice(0, firstGlob);\n const rest = pat.slice(firstGlob);\n\n if (before.endsWith('**')) {\n // Match at current dir then recurse into subdirs\n await walk(dir, rest);\n for (const e of entries) {\n const full = `${dir}${SEP}${e}`;\n try {\n const stat = await fsp.stat(full);\n if (stat.isDirectory()) await walk(full, rest);\n } catch {\n /* skip inaccessible */\n }\n }\n } else if (before === '') {\n // Pattern starts with a glob char — match files in current dir only\n const re = globToRegex(rest);\n for (const e of entries) {\n if (re.test(e)) {\n const full = `${dir}${SEP}${e}`;\n results.add(abs ? resolve(full) : full);\n }\n }\n } else {\n // Literal segment(s) before the glob — descend into matching subdir\n const seg = before.replace(/[*?[\\]]/g, '').replace(/\\/$/, '');\n if (entries.includes(seg)) {\n const full = `${dir}${SEP}${seg}`;\n try {\n const stat = await fsp.stat(full);\n if (stat.isDirectory()) await walk(full, rest);\n } catch {\n /* skip */\n }\n }\n }\n }\n\n await walk(base === '.' ? '.' : base, relPat);\n return [...results];\n}\n","/**\n * Collaborative Debugging Session — parallel multi-agent debugging on the same problem.\n *\n * Architecture:\n * - BugHunter, RefactorPlanner, and Critic run in parallel on shared file snapshots.\n * - Findings flow through the FleetBus via structured events: bug.found → refactor.plan → critic.evaluation.\n * - The Director acts as ResultRouter, collecting outputs and routing them to dependents.\n * - A shared scratchpad stores intermediate results so agents can read each other's\n * conclusions without needing each other's full transcripts.\n *\n * Flow:\n * 1. Director.spawnCollab() creates a CollabSession with a SharedFileSnapshot.\n * 2. All three agents are spawned simultaneously and receive the same file snapshot.\n * 3. BugHunter emits bug.found events → Director routes to RefactorPlanner.\n * 4. RefactorPlanner subscribes to bug.found and emits refactor.plan events.\n * 5. Critic subscribes to both bug.found and refactor.plan and emits critic.evaluation.\n * 6. Director collects all results and produces a structured CollabDebugReport.\n *\n * Timeout and cancellation:\n * - CollabSession agents report budget threshold events to the Director via fleet events.\n * - The Director's collabAlert() handler receives warnings for timeout/iteration/tool_call\n * thresholds and can decide to cancel the session or let it continue.\n * - Director.cancelCollabSession() sends director.cancel_collab to all collab agents,\n * causing them to finish early with a 'cancelled' status in the report.\n * - The Director reads /btw notes via getLeaderBtwNotes() and can inject them into\n * collab agents via task context before making cancellation decisions.\n */\n\nimport { EventEmitter } from 'node:events';\nimport * as fsp from 'node:fs/promises';\nimport { randomUUID } from 'node:crypto';\nimport type { SubagentConfig, TaskResult } from '../types/multi-agent.js';\nimport { expandGlob } from '../utils/glob-expand.js';\n\n/**\n * Default maximum number of files a collab_debug session may target.\n * Each of the three agents (BugHunter, RefactorPlanner, Critic) receives\n * the full file snapshot as context — a large target causes token overflow\n * and timeout failures. Keep this low (20-30) for reliable sessions.\n * Used when neither `maxTargetFiles` nor `contextWindow` is provided.\n */\nexport const DEFAULT_MAX_TARGET_FILES = 30;\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * Alert levels the Director can emit when a collab session needs attention.\n * These flow through the FleetBus so the host can display them in the UI.\n */\nexport enum DirectorAlertLevel {\n /** The agent is still making progress but has hit a soft budget limit. */\n WARNING = 'warning',\n /** The agent has hit a hard limit and the session cannot continue. */\n CRITICAL = 'critical',\n /** The Director has decided to cancel the session (user request or policy). */\n CANCELLED = 'cancelled',\n}\n\nexport interface DirectorAlert {\n sessionId: string;\n subagentId: string;\n role: string;\n level: DirectorAlertLevel;\n /** Human-readable message for UI/logs */\n message: string;\n /** Budget kind that triggered this alert, if any */\n budgetKind?: 'timeout' | 'idle_timeout' | 'iterations' | 'tool_calls' | 'tokens' | 'cost';\n /** Elapsed ms at time of alert */\n elapsedMs?: number;\n /** Limit that was hit */\n limit?: number;\n /** /btw notes the director has collected (may be empty) */\n btwNotes?: string[];\n}\n\n/**\n * Immutable snapshot of target files at the start of a collab session.\n * All agents in the session read from this snapshot — they see the same baseline.\n */\nexport interface SharedFileSnapshot {\n id: string;\n createdAt: string;\n files: SharedFileEntry[];\n}\n\nexport interface SharedFileEntry {\n path: string;\n content: string;\n language?: string;\n}\n\n/**\n * Bug finding emitted by BugHunter and consumed by RefactorPlanner + Critic.\n */\nexport interface BugFinding {\n id: string;\n type: string;\n severity: 'critical' | 'high' | 'medium' | 'low';\n location: { file: string; line: number };\n description: string;\n suggestedFix?: string;\n}\n\n/**\n * Refactoring plan emitted by RefactorPlanner, consuming BugFinding(s).\n */\nexport interface RefactorPlan {\n id: string;\n basedOnBugIds: string[];\n phases: RefactorPhase[];\n riskScore: 'low' | 'medium' | 'high';\n estimatedChangeCount: number;\n rollbackStrategy: string;\n}\n\n/** One phase within a refactor plan. */\nexport interface RefactorPhase {\n number: number;\n title: string;\n tasks: string[];\n risk: 'low' | 'medium' | 'high';\n}\n\n/**\n * Critic evaluation of a bug finding or refactor plan.\n */\nexport interface CriticEvaluation {\n id: string;\n subjectType: 'bug_finding' | 'refactor_plan';\n subjectId: string;\n score: number; // 0-10\n verdict: 'approve' | 'needs_revision' | 'reject';\n strengths: string[];\n weaknesses: string[];\n concerns: CriticConcern[];\n}\n\nexport interface CriticConcern {\n description: string;\n location?: { file: string; line: number };\n severity: 'blocking' | 'advisory';\n}\n\n/**\n * Full structured report produced when a CollabSession resolves.\n */\nexport interface CollabDebugReport {\n sessionId: string;\n startedAt: string;\n completedAt: string;\n targetPaths: string[];\n /** How the session ended. 'completed' = all agents finished normally.\n * 'cancelled' = Director called cancelCollabSession().\n * 'timeout' = session-level timeout elapsed before all agents finished.\n * 'critical_alert' = Director escalated a warning to a cancel decision.\n */\n disposition: 'completed' | 'cancelled' | 'timeout' | 'critical_alert';\n bugs: BugFinding[];\n refactorPlans: RefactorPlan[];\n evaluations: CriticEvaluation[];\n /** Alerts that were raised during the session (may be empty). */\n alerts: DirectorAlert[];\n /** Overall verdict from the Critic across all evaluated subjects. */\n overallVerdict: 'approve' | 'needs_revision' | 'reject';\n /** Markdown-formatted summary for the director's context window. */\n summary: string;\n}\n\n/**\n * Per-agent budget configuration for collab sessions.\n * Allows the caller (Director) to control the exact limits instead of\n * using hard-coded defaults that may not match the director's policy.\n */\nexport interface CollabBudgetConfig {\n maxIterations: number;\n maxToolCalls: number;\n timeoutMs: number;\n}\n\n/**\n * Budget overrides for specific roles in a collab session.\n * When a role is not present in the map, the default budget is used.\n */\nexport type CollabBudgetOverrides = Partial<Record<string, CollabBudgetConfig>>;\n\n// ---------------------------------------------------------------------------\n// Event payload types (what gets put on the FleetBus)\n// ---------------------------------------------------------------------------\n\nexport interface BugFoundPayload {\n finding: BugFinding;\n}\n\nexport interface RefactorPlanPayload {\n plan: RefactorPlan;\n}\n\nexport interface CriticEvaluationPayload {\n evaluation: CriticEvaluation;\n}\n\n/**\n * Emitted by a collab agent when it hits a soft budget limit.\n * The Director's fleet handler receives this and calls collabAlert().\n */\nexport interface CollabBudgetWarningPayload {\n sessionId: string;\n role: string;\n kind: 'timeout' | 'idle_timeout' | 'iterations' | 'tool_calls' | 'tokens' | 'cost';\n used: number;\n limit: number;\n timeoutMs?: number;\n elapsedMs: number;\n}\n\n/**\n * Emitted by the Director to cancel all agents in a collab session.\n * CollabSession listens for this and causes its agent pool to finish early.\n */\nexport interface DirectorCancelCollabPayload {\n sessionId: string;\n reason: string;\n cancelledAt: string;\n}\n\n// ---------------------------------------------------------------------------\n// CollabSessionOptions — extends base with budget + alert callbacks\n// ---------------------------------------------------------------------------\n\nexport interface CollabSessionOptions {\n /** Paths to scan — used to build the SharedFileSnapshot. */\n targetPaths: string[];\n /** Files already read and snapshot. When provided, snapshot is skipped. */\n prebuiltSnapshot?: SharedFileSnapshot;\n /** Max time to wait for the session to resolve (ms). Default: 10 min. */\n timeoutMs?: number;\n /**\n * Maximum number of files to include in the snapshot.\n * - If set explicitly: use this value (hard override).\n * - If `contextWindow` is set: calculate dynamically from estimated token budget.\n * - If neither: use `DEFAULT_MAX_TARGET_FILES` (30).\n */\n maxTargetFiles?: number;\n /**\n * Context window size (in tokens) of the model running the subagents.\n * When provided and `maxTargetFiles` is not set, the limit is computed\n * dynamically: `floor((contextWindow * 0.4) / AVG_TOKENS_PER_FILE)`.\n * If not provided, `DEFAULT_MAX_TARGET_FILES` is used as the fallback.\n */\n contextWindow?: number;\n /**\n * Budget overrides per role. When provided, these override the hard-coded\n * defaults so the Director can enforce fleet-wide budget policy.\n * Keys must match role names: 'bug-hunter', 'refactor-planner', 'critic'.\n */\n budgetOverrides?: CollabBudgetOverrides;\n /**\n * Called by the Director when a collab agent hits a soft budget limit.\n * The Director uses this to decide whether to cancel the session or extend.\n * Return 'cancel' to stop the session immediately; 'extend' to continue\n * with the agent's proposed new limits; 'ignore' to let the default\n * auto-extend logic handle it.\n */\n onBudgetWarning?: (alert: DirectorAlert) => 'cancel' | 'extend' | 'ignore';\n}\n\n// ---------------------------------------------------------------------------\n// CollabSession — coordinates the three-agent pipeline\n// ---------------------------------------------------------------------------\n\nexport class CollabSession extends EventEmitter {\n readonly sessionId: string;\n readonly options: CollabSessionOptions;\n readonly snapshot: SharedFileSnapshot;\n\n private readonly director: import('./director.js').Director;\n private readonly fleetBus: import('./fleet-bus.js').FleetBus;\n private readonly subagentIds = new Map<string, string>(); // role → subagentId\n private readonly bugs = new Map<string, BugFinding>();\n private readonly plans = new Map<string, RefactorPlan>();\n private readonly evaluations = new Map<string, CriticEvaluation>();\n private readonly disposers = new Array<() => void>();\n private settled = false;\n private readonly timeoutMs: number;\n private cancelled = false;\n private readonly alerts: DirectorAlert[] = [];\n\n /** Tracks tool call counts per subagent for progress-based timeout decisions. */\n private readonly progressBySubagent = new Map<string, number>();\n /** Last tool call count when a timeout warning was handled. */\n private readonly lastTimeoutProgress = new Map<string, number>();\n /** Session-level timeout timer handle (cleared on cancel or natural completion). */\n private _timeoutTimer?: NodeJS.Timeout;\n\n constructor(\n director: import('./director.js').Director,\n fleetBus: import('./fleet-bus.js').FleetBus,\n options: CollabSessionOptions,\n ) {\n super();\n this.sessionId = randomUUID();\n this.options = options;\n this.director = director;\n this.fleetBus = fleetBus;\n this.timeoutMs = options.timeoutMs ?? 10 * 60 * 1000;\n\n if (options.prebuiltSnapshot) {\n this.snapshot = options.prebuiltSnapshot;\n } else {\n this.snapshot = {\n id: this.sessionId,\n createdAt: new Date().toISOString(),\n files: [],\n };\n }\n }\n\n get id(): string { return this.sessionId; }\n\n getSessionAlerts(): DirectorAlert[] {\n return [...this.alerts];\n }\n\n isCancelled(): boolean {\n return this.cancelled;\n }\n\n /**\n * Snapshot of role → subagentId map. The Director calls coordinator.stop()\n * for each agent when cancelling the session, using this map to enumerate\n * all three collab agents.\n */\n getSubagentIds(): ReadonlyMap<string, string> {\n return new Map(this.subagentIds);\n }\n\n /**\n * Returns the effective file limit for this session.\n * Priority: explicit `maxTargetFiles` > dynamic from `contextWindow` > `DEFAULT_MAX_TARGET_FILES`.\n */\n effectiveFileLimit(): number {\n if (this.options.maxTargetFiles !== undefined) {\n return this.options.maxTargetFiles;\n }\n if (this.options.contextWindow !== undefined) {\n // Reserve 40% of context window for the file snapshot.\n // Heuristic: ~2000 tokens per average source file.\n return Math.max(5, Math.floor((this.options.contextWindow * 0.4) / 2000));\n }\n return DEFAULT_MAX_TARGET_FILES;\n }\n\n async buildSnapshot(): Promise<SharedFileSnapshot> {\n if (this.snapshot.files.length > 0) return this.snapshot;\n const allFiles: string[] = [];\n for (const pattern of this.options.targetPaths) {\n const expanded = await expandGlob(pattern);\n allFiles.push(...expanded);\n }\n const limit = this.effectiveFileLimit();\n if (allFiles.length > limit) {\n const hint = this.options.contextWindow\n ? `contextWindow=${this.options.contextWindow} → calculated limit=${limit}`\n : `default limit=${DEFAULT_MAX_TARGET_FILES}`;\n throw new Error(\n `[collab_debug] Target has ${allFiles.length} files, which exceeds the ` +\n `limit (${hint}). Narrow the target or pass maxTargetFiles / contextWindow ` +\n `to override. For large codebases, run package-by-package or ` +\n `module-by-module sessions instead of targeting the entire repo.`,\n );\n }\n for (const filePath of allFiles) {\n try {\n const content = await fsp.readFile(filePath, 'utf8');\n const ext = filePath.split('.').pop() ?? '';\n const language = ext === 'ts' || ext === 'tsx' ? 'typescript'\n : ext === 'js' || ext === 'jsx' ? 'javascript'\n : ext === 'md' ? 'markdown'\n : ext === 'json' ? 'json'\n : undefined;\n this.snapshot.files.push({ path: filePath, content, language });\n } catch {\n this.snapshot.files.push({ path: filePath, content: '', language: undefined });\n }\n }\n return this.snapshot;\n }\n\n /**\n * Cancel the session. Emits director.cancel_collab on the FleetBus so all\n * collab agents finish early. The session-level timeout timer is also cleared.\n * Safe to call multiple times (idempotent after first call).\n */\n cancel(reason = 'Director cancelled collab session'): void {\n if (this.settled) return;\n this.cancelled = true;\n if (this._timeoutTimer) {\n clearTimeout(this._timeoutTimer);\n this._timeoutTimer = undefined;\n }\n this.fleetBus.emit({\n subagentId: this.director.id,\n ts: Date.now(),\n type: 'director.cancel_collab',\n payload: { sessionId: this.sessionId, reason, cancelledAt: new Date().toISOString() } as DirectorCancelCollabPayload,\n });\n this.fleetBus.emit({\n subagentId: this.director.id,\n ts: Date.now(),\n type: 'collab.cancelled',\n payload: { sessionId: this.sessionId, reason },\n });\n }\n\n async start(): Promise<CollabDebugReport> {\n if (this.settled) throw new Error('session already settled');\n this.settled = true;\n\n await this.buildSnapshot();\n this.wireFleetBus();\n\n const [bugHunterId, refactorPlannerId, criticId] = await Promise.all([\n this.spawnAgent('bug-hunter', this.buildBugHunterTask()),\n this.spawnAgent('refactor-planner', this.buildRefactorPlannerTask()),\n this.spawnAgent('critic', this.buildCriticTask()),\n ]);\n\n this.subagentIds.set('bug-hunter', bugHunterId);\n this.subagentIds.set('refactor-planner', refactorPlannerId);\n this.subagentIds.set('critic', criticId);\n\n const timeout = new Promise<never>((_, reject) => {\n this._timeoutTimer = setTimeout(() => {\n this.cancel('Session-level timeout reached');\n reject(new Error(`CollabSession timed out after ${this.timeoutMs}ms`));\n }, this.timeoutMs);\n });\n\n let results: TaskResult[][] | null = null;\n try {\n results = await Promise.race([\n Promise.all([\n this.director.awaitTasks([bugHunterId]),\n this.director.awaitTasks([refactorPlannerId]),\n this.director.awaitTasks([criticId]),\n ]),\n timeout,\n ]);\n } catch (err) {\n // Promise.race rejected — either the timeout fired or one of the\n // awaitTasks failed. In both cases `results` is unassigned. Clear the\n // timer if the timeout won the race, always clean up, then re-throw.\n // NOTE: we cannot distinguish timeout from awaitTasks failure here\n // without additional state. Both are treated as session failure.\n if (this._timeoutTimer) {\n clearTimeout(this._timeoutTimer);\n this._timeoutTimer = undefined;\n }\n this.cleanup();\n const error = err instanceof Error ? err : new Error(String(err));\n this.emit('session.error', error);\n throw error;\n }\n\n // If we are here, Promise.race resolved (not rejected) — results were assigned.\n // Guard with non-null assertion since TypeScript doesn't know the try/catch\n // guarantees this when we reach this line.\n for (const result of results!.flat()) {\n await this.parseAndEmit(result);\n }\n\n const report = this.assembleReport();\n this.cleanup();\n this.emit('session.done', report);\n return report;\n }\n\n private async parseAndEmit(result: TaskResult): Promise<void> {\n if (result.status !== 'success' || result.result == null) return;\n const text =\n typeof result.result === 'string' ? result.result : JSON.stringify(result.result);\n\n for (const obj of this.extractJsonObjects(text)) {\n const type =\n 'finding' in obj\n ? 'bug.found'\n : 'plan' in obj\n ? 'refactor.plan'\n : 'evaluation' in obj\n ? 'critic.evaluation'\n : null;\n if (!type) continue;\n this.fleetBus.emit({\n subagentId: result.subagentId,\n taskId: result.taskId,\n ts: Date.now(),\n type,\n payload: obj,\n });\n }\n }\n\n private extractJsonObjects(text: string): Array<Record<string, unknown>> {\n const objects: Array<Record<string, unknown>> = [];\n let depth = 0;\n let start = -1;\n let inString = false;\n let escaped = false;\n for (let i = 0; i < text.length; i++) {\n const ch = text[i];\n if (inString) {\n if (escaped) escaped = false;\n else if (ch === '\\\\') escaped = true;\n else if (ch === '\"') inString = false;\n continue;\n }\n if (ch === '\"') {\n inString = true;\n } else if (ch === '{') {\n if (depth === 0) start = i;\n depth++;\n } else if (ch === '}' && depth > 0) {\n depth--;\n if (depth === 0 && start >= 0) {\n const candidate = text.slice(start, i + 1);\n try {\n const parsed = JSON.parse(candidate);\n if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {\n objects.push(parsed as Record<string, unknown>);\n }\n } catch {\n // skip malformed span\n }\n start = -1;\n }\n }\n }\n return objects;\n }\n\n private budgetForRole(role: string): { maxIterations: number; maxToolCalls: number; timeoutMs: number } {\n if (this.options.budgetOverrides?.[role]) {\n return this.options.budgetOverrides[role]!;\n }\n const defaults: Record<string, { maxIterations: number; maxToolCalls: number; timeoutMs: number }> = {\n 'bug-hunter': { maxIterations: 2000, maxToolCalls: 5000, timeoutMs: 10 * 60 * 1000 },\n 'refactor-planner': { maxIterations: 1500, maxToolCalls: 4000, timeoutMs: 8 * 60 * 1000 },\n 'critic': { maxIterations: 1000, maxToolCalls: 3000, timeoutMs: 6 * 60 * 1000 },\n };\n return defaults[role] ?? { maxIterations: 1500, maxToolCalls: 4000, timeoutMs: 8 * 60 * 1000 };\n }\n\n private async spawnAgent(role: string, taskBrief: string): Promise<string> {\n const budget = this.budgetForRole(role);\n const cfg: SubagentConfig = {\n id: `${role}-${this.sessionId}`,\n name: role,\n role,\n tools: ['fleet_emit', 'fleet_status', 'read', 'grep', 'glob', 'bash', 'write'],\n maxIterations: budget.maxIterations,\n maxToolCalls: budget.maxToolCalls,\n timeoutMs: budget.timeoutMs,\n };\n const subagentId = await this.director.spawn(cfg);\n await this.director.assign({ id: randomUUID(), subagentId, description: taskBrief });\n return subagentId;\n }\n\n private buildBugHunterTask(): string {\n const scratchpad = this.director.sharedScratchpadPath ?? '/tmp';\n const fileContents = this.snapshot.files\n .map((f) => `=== ${f.path} ===\\n${f.content}`)\n .join('\\n\\n');\n return (\n `You are BugHunter. Scan the following files for bugs and code smells.\\n\\n` +\n `Target files:\\n${fileContents}\\n\\n` +\n `For each bug found, emit it using the fleet_emit tool immediately:\\n` +\n `{ \"type\": \"bug.found\", \"payload\": { \"finding\": { \"id\": \"<uuid>\", \"type\": \"<pattern>\", ` +\n `\"severity\": \"<critical|high|medium|low>\", ` +\n `\"location\": { \"file\": \"<path>\", \"line\": <n> }, \"description\": \"<explain>\", \"suggestedFix\": \"<optional>\" } } }\\n\\n` +\n `After scanning all files, write your full markdown bug report to:\\n` +\n `${scratchpad}/bug-hunter-report-${this.sessionId}.md\\n\\n` +\n `Important: emit each finding as soon as you find it. Do not batch or wait until the end.`\n );\n }\n\n private buildRefactorPlannerTask(): string {\n const scratchpad = this.director.sharedScratchpadPath ?? '/tmp';\n const bugHunterReportPath = `${scratchpad}/bug-hunter-report-${this.sessionId}.md`;\n const fileContents = this.snapshot.files\n .map((f) => `=== ${f.path} ===\\n${f.content}`)\n .join('\\n\\n');\n return (\n `You are RefactorPlanner. Plan refactorings for the following files.\\n\\n` +\n `Target files:\\n${fileContents}\\n\\n` +\n `Read the BugHunter report at: ${bugHunterReportPath}\\n\\n` +\n `For each bug you can address, emit a refactor plan using fleet_emit:\\n` +\n `{ \"type\": \"refactor.plan\", \"payload\": { \"plan\": { \"id\": \"<uuid>\", \"basedOnBugIds\": [\"<bug-id>\"], ` +\n `\"phases\": [{ \"number\": 1, \"title\": \"<phase>\", \"tasks\": [\"<task>\"], \"risk\": \"<low|medium|high>\" }], ` +\n `\"riskScore\": \"<low|medium|high>\", \"estimatedChangeCount\": <n>, \"rollbackStrategy\": \"<text>\" } } }\\n\\n` +\n `Also write your full markdown plan to:\\n` +\n `${scratchpad}/refactor-plan-${this.sessionId}.md\\n\\n` +\n `Emit each plan immediately. Do not wait until planning is complete.`\n );\n }\n\n private buildCriticTask(): string {\n const scratchpad = this.director.sharedScratchpadPath ?? '/tmp';\n const bugHunterReportPath = `${scratchpad}/bug-hunter-report-${this.sessionId}.md`;\n const refactorPlanPath = `${scratchpad}/refactor-plan-${this.sessionId}.md`;\n const fileContents = this.snapshot.files\n .map((f) => `=== ${f.path} ===\\n${f.content}`)\n .join('\\n\\n');\n return (\n `You are Critic. Evaluate bug findings and refactor plans.\\n\\n` +\n `Target files:\\n${fileContents}\\n\\n` +\n `Read the BugHunter report at: ${bugHunterReportPath}\\n` +\n `Read the RefactorPlanner report at: ${refactorPlanPath}\\n\\n` +\n `For each bug and refactor plan, emit your evaluation using fleet_emit:\\n` +\n `{ \"type\": \"critic.evaluation\", \"payload\": { \"evaluation\": { \"id\": \"<uuid>\", ` +\n `\"subjectType\": \"<bug_finding|refactor_plan>\", \"subjectId\": \"<id>\", ` +\n `\"score\": <0-10>, \"verdict\": \"<approve|needs_revision|reject>\", ` +\n `\"strengths\": [\"<strength>\"], \"weaknesses\": [\"<weakness>\"], ` +\n `\"concerns\": [{ \"description\": \"<concern>\", \"severity\": \"<blocking|advisory>\" }] } } }\\n\\n` +\n `After all evaluations, write your markdown report to:\\n` +\n `${scratchpad}/critic-report-${this.sessionId}.md\\n\\n` +\n `Emit each evaluation immediately. Do not wait until you have read all reports.`\n );\n }\n\n private wireFleetBus(): void {\n // Track tool executions for progress-based timeout decisions\n const dTool = this.fleetBus.filter('tool.executed', (e) => {\n this.progressBySubagent.set(e.subagentId, (this.progressBySubagent.get(e.subagentId) ?? 0) + 1);\n });\n this.disposers.push(dTool);\n\n // budget.threshold_reached → Director's alert handler\n const dBudget = this.fleetBus.filter('budget.threshold_reached', (e) => {\n const payload = e.payload as {\n kind: 'timeout' | 'idle_timeout' | 'iterations' | 'tool_calls' | 'tokens' | 'cost';\n used: number;\n limit: number;\n timeoutMs?: number;\n extend: (extra: Record<string, unknown>) => void;\n deny: () => void;\n };\n const role = this.roleFromSubagentId(e.subagentId);\n if (!role) return;\n\n // Gather /btw notes so the Director can inspect them before deciding\n const btwNotes = this.director.getLeaderBtwNotes();\n\n const alert: DirectorAlert = {\n sessionId: this.sessionId,\n subagentId: e.subagentId,\n role,\n level: DirectorAlertLevel.WARNING,\n message: `${role} hit ${payload.kind} soft limit (${payload.used}/${payload.limit})`,\n budgetKind: payload.kind,\n elapsedMs: payload.timeoutMs,\n limit: payload.limit,\n btwNotes,\n };\n\n this.alerts.push(alert);\n\n this.fleetBus.emit({\n subagentId: e.subagentId,\n ts: Date.now(),\n type: 'collab.warning',\n payload: alert,\n });\n\n const decision = this.options.onBudgetWarning?.(alert) ?? 'ignore';\n\n if (decision === 'cancel') {\n this.cancel(`Director cancelled: ${role} ${payload.kind} threshold`);\n return;\n }\n\n // Progress-based timeout handling: extend if agent is doing work,\n // deny only if genuinely stuck (no tool calls since last grant).\n // Both wall-clock timeout and idle timeout use this heartbeat-aware path.\n if (payload.kind === 'timeout' || payload.kind === 'idle_timeout') {\n const progress = this.progressBySubagent.get(e.subagentId) ?? 0;\n const lastProgress = this.lastTimeoutProgress.get(e.subagentId) ?? -1;\n if (progress <= lastProgress) {\n payload.deny();\n return;\n }\n this.lastTimeoutProgress.set(e.subagentId, progress);\n const newLimit = Math.min(Math.ceil((payload.timeoutMs ?? payload.limit) * 2), 24 * 60 * 60_000);\n setImmediate(() => {\n payload.extend({ timeoutMs: newLimit });\n });\n return;\n }\n\n if (decision === 'extend') {\n setImmediate(() => {\n const base = Math.max(payload.limit, payload.used);\n const extra: Record<string, unknown> = {};\n switch (payload.kind) {\n case 'iterations': extra.maxIterations = Math.min(Math.ceil(base * 1.5), 50_000); break;\n case 'tool_calls': extra.maxToolCalls = Math.min(Math.ceil(base * 1.5), 100_000); break;\n case 'tokens': extra.maxTokens = Math.min(Math.ceil(base * 1.5), 5_000_000); break;\n case 'cost': extra.maxCostUsd = Math.min(base * 1.5, 100); break;\n }\n payload.extend(extra);\n });\n return;\n }\n\n // 'ignore' (or any unrecognized decision): apply a conservative\n // auto-extension for non-timeout kinds so the session keeps making\n // progress rather than hitting a hard limit. The Director sees the\n // collab.warning event and can always call cancelCollabSession() if the\n // pattern looks like a bad infinite loop. Timeout kind is already handled\n // above by the progress-based logic.\n if ((payload.kind as string) !== 'timeout') {\n setImmediate(() => {\n const base = Math.max(payload.limit, payload.used);\n const extra: Record<string, unknown> = {};\n switch (payload.kind) {\n case 'iterations': extra.maxIterations = Math.min(Math.ceil(base * 1.25), 50_000); break;\n case 'tool_calls': extra.maxToolCalls = Math.min(Math.ceil(base * 1.25), 100_000); break;\n case 'tokens': extra.maxTokens = Math.min(Math.ceil(base * 1.25), 5_000_000); break;\n case 'cost': extra.maxCostUsd = Math.min(base * 1.25, 100); break;\n }\n payload.extend(extra);\n });\n }\n });\n this.disposers.push(dBudget);\n\n // Director cancel signal\n const dCancel = this.fleetBus.filter('director.cancel_collab', (e) => {\n const payload = e.payload as DirectorCancelCollabPayload;\n if (payload.sessionId !== this.sessionId) return;\n this.cancelled = true;\n if (this._timeoutTimer) {\n clearTimeout(this._timeoutTimer);\n this._timeoutTimer = undefined;\n }\n this.fleetBus.emit({\n subagentId: this.director.id,\n ts: Date.now(),\n type: 'collab.cancelled',\n payload: { sessionId: this.sessionId, reason: payload.reason },\n });\n });\n this.disposers.push(dCancel);\n\n // bug.found → RefactorPlanner + Critic\n const d1 = this.fleetBus.filter('bug.found', (e) => {\n const payload = e.payload as BugFoundPayload;\n if (payload?.finding) {\n this.bugs.set(payload.finding.id, payload.finding);\n this.emit('bug.found', payload);\n }\n });\n this.disposers.push(d1);\n\n // refactor.plan → Critic\n const d2 = this.fleetBus.filter('refactor.plan', (e) => {\n const payload = e.payload as RefactorPlanPayload;\n if (payload?.plan) {\n this.plans.set(payload.plan.id, payload.plan);\n this.emit('refactor.plan', payload);\n }\n });\n this.disposers.push(d2);\n\n // critic.evaluation\n const d3 = this.fleetBus.filter('critic.evaluation', (e) => {\n const payload = e.payload as CriticEvaluationPayload;\n if (payload?.evaluation) {\n this.evaluations.set(payload.evaluation.id, payload.evaluation);\n this.emit('critic.evaluation', payload);\n }\n });\n this.disposers.push(d3);\n }\n\n private roleFromSubagentId(subagentId: string): string | null {\n // Fast path: check tracked subagentIds map first (normal case during session).\n for (const [role, id] of this.subagentIds) {\n if (id === subagentId) return role;\n }\n // Fallback: derive from id prefix pattern used in spawnAgent.\n // Handles budget events that fire before subagentIds entry is populated\n // (edge case at session start — race between first tool call and map insert).\n const match = subagentId.match(/^(bug-hunter|refactor-planner|critic)/);\n return match?.[1] ?? null;\n }\n\n private assembleReport(): CollabDebugReport {\n const bugList = Array.from(this.bugs.values());\n const planList = Array.from(this.plans.values());\n const evalList = Array.from(this.evaluations.values());\n\n let disposition: CollabDebugReport['disposition'] = 'completed';\n if (this.cancelled) disposition = 'cancelled';\n\n const verdictOrder: Record<CollabDebugReport['overallVerdict'], number> = {\n approve: 0, needs_revision: 1, reject: 2,\n };\n const overallVerdict = evalList.reduce<CollabDebugReport['overallVerdict']>(\n (worst, eval_) => {\n const w = verdictOrder[worst];\n const c = verdictOrder[eval_.verdict];\n return c > w ? eval_.verdict : worst;\n },\n 'approve',\n );\n\n const summary = this.buildMarkdownSummary(bugList, planList, evalList, overallVerdict, disposition);\n\n return {\n sessionId: this.sessionId,\n startedAt: this.snapshot.createdAt,\n completedAt: new Date().toISOString(),\n targetPaths: this.options.targetPaths,\n disposition,\n bugs: bugList,\n refactorPlans: planList,\n evaluations: evalList,\n alerts: [...this.alerts],\n overallVerdict,\n summary,\n };\n }\n\n private buildMarkdownSummary(\n bugs: BugFinding[],\n plans: RefactorPlan[],\n evals: CriticEvaluation[],\n overallVerdict: CollabDebugReport['overallVerdict'],\n disposition: CollabDebugReport['disposition'],\n ): string {\n const lines: string[] = [\n `## Collaborative Debugging Report — ${this.sessionId}`,\n '',\n `**Target:** ${this.options.targetPaths.join(', ')}`,\n `**Disposition:** ${disposition.toUpperCase()}`,\n `**Overall Verdict:** **${overallVerdict.toUpperCase()}**`,\n '',\n ];\n\n if (this.alerts.length > 0) {\n lines.push('### Alerts', '');\n for (const alert of this.alerts) {\n lines.push(`- **[${alert.level.toUpperCase()}]** ${alert.role}: ${alert.message}`);\n }\n lines.push('');\n }\n\n if (bugs.length > 0) {\n lines.push('### Bugs Found', '');\n for (const b of bugs) {\n lines.push(`- **[${b.severity.toUpperCase()}]** \\`${b.location.file}:${b.location.line}\\` — ${b.description}`);\n }\n lines.push('');\n }\n\n if (plans.length > 0) {\n lines.push('### Refactor Plans', '');\n for (const p of plans) {\n lines.push(`- **Phase plan** (risk: ${p.riskScore}, ~${p.estimatedChangeCount} changes)`);\n for (const phase of p.phases) {\n lines.push(` - Phase ${phase.number}: ${phase.title} [${phase.risk}]`);\n }\n }\n lines.push('');\n }\n\n if (evals.length > 0) {\n lines.push('### Critic Evaluations', '');\n for (const e of evals) {\n lines.push(`- [${e.subjectType}] score=${e.score}/10 — **${e.verdict.toUpperCase()}**`);\n for (const c of e.concerns) {\n if (c.severity === 'blocking') lines.push(` - ${c.description}`);\n }\n }\n lines.push('');\n }\n\n return lines.join('\\n');\n }\n\n private cleanup(): void {\n for (const dispose of this.disposers) dispose();\n this.disposers.length = 0;\n }\n}","/**\n * System-prompt composition helpers for the Director ecosystem.\n *\n * Two callers need composed prompts:\n *\n * 1. The **leader** (the director's own Agent) — needs a preamble that\n * explains the fleet protocol: when to spawn, when to await, how to\n * roll up, and the eight orchestration tools it owns.\n *\n * 2. Each **subagent** — needs a baseline that explains it has a parent\n * it can call via the bridge, a role-specific block, the task brief,\n * and finally any per-spawn `systemPromptOverride` from `SubagentConfig`.\n *\n * Both composers are pure functions: feed them parts, they return a string.\n * No I/O, no side effects, no implicit defaults beyond the ones exported\n * here. Callers (CLI multi-agent factory, Director itself) decide which\n * parts to fill in — that keeps the composition seam visible and testable.\n */\n\n/**\n * Default fleet-protocol preamble injected at the **front** of the\n * director-agent's system prompt. Kept deliberately short — long preambles\n * crowd out the user's leader prompt and the LLM stops attending. The tool\n * descriptions live on the tool definitions themselves; this preamble only\n * teaches *when* to reach for them.\n */\nexport const DEFAULT_DIRECTOR_PREAMBLE = `\\\nYou are the Director of a multi-agent fleet. You orchestrate worker\nsubagents by spawning them, assigning tasks, awaiting completions, and\nrolling up their outputs into your next decision.\n\nCore fleet tools available to you:\n - spawn_subagent — create a worker with a chosen provider / model / role\n - assign_task — hand a piece of work to a specific subagent\n - await_tasks — block until named task ids complete (parallel-safe)\n - ask_subagent — synchronously query a running subagent via the bridge\n - roll_up — aggregate finished tasks into a markdown/json summary\n - terminate_subagent — abort a stuck worker (use sparingly)\n - fleet_status — snapshot of all subagents and pending tasks\n - fleet_usage — token + cost breakdown per subagent and total\n\nWorking rules:\n 1. Decompose first. Before spawning, decide which sub-tasks are\n independent and can run in parallel. Sequential work doesn't need a\n subagent — do it yourself.\n 2. Match worker to job. Cheap/fast model for triage, capable model for\n synthesis. Different providers per sibling is allowed and encouraged.\n 3. Always pair an assign with an await. Don't fire-and-forget; you owe\n the user a single coherent answer at the end.\n 4. Roll up before deciding. After await_tasks resolves, call roll_up so\n the results are folded back into your context in a compact form.\n 5. Budget is real. Check fleet_usage periodically. If a subagent is\n thrashing, terminate it rather than letting cost climb silently.\n 6. Never claim a subagent's work as your own without verifying it. If a\n result looks wrong, ask_subagent for clarification before passing it\n to the user.\n 7. Wind down when satisfied. When the results are good enough, call\n work_complete — no new subagents will spawn and queued tasks complete\n as aborted. Running subagents finish naturally. Call terminate_subagent\n only for ones you need to stop immediately.\\\n`;\n\n/**\n * Default baseline prepended to every subagent's system prompt. Tells the\n * subagent its place in the hierarchy and the bridge contract — without\n * this, a subagent has no way to know it *can* ask the parent for\n * clarification, and it will hallucinate answers when context is missing.\n *\n * Bridge contract: subagents may `send` progress and `request` answers, but\n * MAY NOT exfiltrate the parent's full system prompt or tools list. The\n * baseline reinforces this in plain text — the actual enforcement is at\n * the bridge transport layer.\n */\nexport const DEFAULT_SUBAGENT_BASELINE = `\\\nYou are a subagent operating under a Director. You were spawned to handle\na specific slice of a larger plan — do that slice well and report back.\n\nBridge contract:\n - You have a parent (the Director). You may call \\`request\\` on the\n parent bridge to ask a clarifying question. Use this sparingly; the\n parent is also working.\n - You MAY NOT request the parent's system prompt, tool list, or other\n subagents' context. Those are not yours to read.\n - Your final task output is what the Director sees. Be concise,\n structured, and self-contained — assume the Director will paste your\n output into its own context.\\\n`;\n\n/** Parts the leader-prompt composer accepts. All optional. */\nexport interface DirectorPromptParts {\n /** The user's existing leader system prompt — typically what was passed\n * via `MultiAgentConfig.leaderSystemPrompt`. */\n basePrompt?: string;\n /** Override the built-in fleet preamble. Pass empty string to suppress. */\n directorPreamble?: string;\n /** Optional roster summary block — a short list of pre-configured roles\n * the director can spawn (e.g. \"researcher, coder, reviewer\"). Helps\n * small models discover the available shapes without scanning tools. */\n rosterSummary?: string;\n}\n\n/**\n * Compose the leader/director's system prompt. Order:\n * 1. Director preamble (fleet protocol)\n * 2. Roster summary (optional, when provided)\n * 3. User base prompt (the per-project leader prompt)\n *\n * Sections are separated by a blank line. Empty parts are skipped so the\n * output never contains stray blank-line runs.\n */\nexport function composeDirectorPrompt(parts: DirectorPromptParts = {}): string {\n const sections: string[] = [];\n const preamble = parts.directorPreamble ?? DEFAULT_DIRECTOR_PREAMBLE;\n if (preamble && preamble.trim().length > 0) sections.push(preamble.trim());\n if (parts.rosterSummary && parts.rosterSummary.trim().length > 0) {\n sections.push(`Available roles you can spawn:\\n${parts.rosterSummary.trim()}`);\n }\n if (parts.basePrompt && parts.basePrompt.trim().length > 0) {\n sections.push(parts.basePrompt.trim());\n }\n return sections.join('\\n\\n');\n}\n\n/** Parts the subagent-prompt composer accepts. Layered from generic to\n * specific; later layers override earlier ones when they conflict. */\nexport interface SubagentPromptParts {\n /** Base persona/identity for *every* subagent. Defaults to the bridge\n * contract baseline. Pass empty string to suppress. */\n baseline?: string;\n /** Role-specific block, e.g. \"You are a code reviewer. Focus on…\". */\n role?: string;\n /** Task brief — usually the same string the runner passes as user input,\n * but exposed here in case the factory wants it duplicated in the\n * system prompt for reinforcement. */\n task?: string;\n /**\n * Absolute path to a shared scratchpad directory the whole fleet can\n * read/write. When set, the composer adds a \"Shared notes\" block that\n * tells the subagent where to drop findings and where to look for\n * sibling output. This is the cheap fleet-coordination channel —\n * agents don't need each other's transcripts, just each other's\n * conclusions. Falls between `task` and `override` so the override\n * can still narrow or replace it.\n */\n sharedScratchpad?: string;\n /** Final per-spawn override from `SubagentConfig.systemPromptOverride`.\n * Added last so it wins on conflict — that's by design: the spawn site\n * knows the most about what this specific subagent should do. */\n override?: string;\n}\n\n/**\n * Compose a subagent's system prompt. Order:\n * 1. Baseline (bridge contract)\n * 2. Role\n * 3. Task brief\n * 4. Per-spawn override\n *\n * Same blank-line-separated joining as the director composer.\n *\n * Layering rationale: the baseline never needs to change between\n * subagents; the role is the \"what kind of worker is this\"; the task is\n * the \"what should you do *now*\"; the override is the spawn-site escape\n * hatch (\"…and respond only in JSON\"). Putting override last means it\n * never gets squashed by something earlier in the chain.\n */\nexport function composeSubagentPrompt(parts: SubagentPromptParts = {}): string {\n const sections: string[] = [];\n const baseline = parts.baseline ?? DEFAULT_SUBAGENT_BASELINE;\n if (baseline && baseline.trim().length > 0) sections.push(baseline.trim());\n if (parts.role && parts.role.trim().length > 0) {\n sections.push(`Role:\\n${parts.role.trim()}`);\n }\n if (parts.task && parts.task.trim().length > 0) {\n sections.push(`Task:\\n${parts.task.trim()}`);\n }\n if (parts.sharedScratchpad && parts.sharedScratchpad.trim().length > 0) {\n sections.push(\n `Shared notes:\\n` +\n `A scratchpad shared with the rest of the fleet is mounted at \\`${parts.sharedScratchpad.trim()}\\`.\\n` +\n `- Write your final findings as markdown files there (e.g. \\`findings.md\\`, \\`security.md\\`).\\n` +\n `- Before starting, list the directory and read any sibling files relevant to your task — ` +\n `they may already contain context you can build on.\\n` +\n `- Use stable filenames (one file per concern); overwrite instead of appending so the ` +\n `Director sees the latest state.`,\n );\n }\n if (parts.override && parts.override.trim().length > 0) {\n sections.push(parts.override.trim());\n }\n return sections.join('\\n\\n');\n}\n\n/**\n * Render a short bullet list summarising a roster — useful for stuffing\n * into `composeDirectorPrompt({ rosterSummary })` so the director model\n * can see available roles without scanning tool descriptions.\n *\n * Each entry: `- <role-id>: <name>[ (provider/model)] — <prompt-headline>`\n * The prompt headline is the first non-empty line of `config.prompt`,\n * truncated to 80 chars. Skipped entirely when the role has no prompt.\n */\nexport function rosterSummaryFromConfigs(\n roster: Record<\n string,\n { name: string; provider?: string; model?: string; prompt?: string; role?: string }\n >,\n): string {\n const lines: string[] = [];\n for (const [roleId, cfg] of Object.entries(roster)) {\n const tag = cfg.provider && cfg.model ? ` (${cfg.provider}/${cfg.model})` : '';\n const headline = cfg.prompt\n ? (cfg.prompt.split('\\n').find((l) => l.trim().length > 0) ?? '').trim().slice(0, 80)\n : '';\n const tail = headline ? ` — ${headline}` : '';\n lines.push(`- ${roleId}: ${cfg.name}${tag}${tail}`);\n }\n return lines.join('\\n');\n}\n","/**\n * Catalog types for the WrongStack agent fleet.\n *\n * An `AgentDefinition` bundles the runtime `SubagentConfig` (id/name/role/\n * prompt/tools) with two things the bare config lacks:\n * - a per-role `budget` tier (consumed by FLEET_ROSTER_BUDGETS), and\n * - dispatcher `capability` metadata (keywords + summary + phase) used by\n * the smart dispatcher to route a free-form task to the best agent.\n *\n * Phase files (`phase1-discovery.ts` … `phase9-meta.ts`) each export an\n * `AgentDefinition[]`; `index.ts` aggregates them into `AGENT_CATALOG`.\n * `fleet.ts` derives `FLEET_ROSTER` + `FLEET_ROSTER_BUDGETS` from the catalog.\n */\nimport type { SubagentConfig } from '../../types/multi-agent.js';\n\n/** Lifecycle phase grouping. Drives statusline labels + dispatcher tie-breaks. */\nexport type AgentPhase =\n | 'discovery'\n | 'planning'\n | 'build'\n | 'verify'\n | 'review'\n | 'domain'\n | 'knowledge'\n | 'delivery'\n | 'meta';\n\n/** Per-role budget tier. Same shape as fleet.ts `FleetRosterBudget`. */\nexport interface AgentBudgetTier {\n timeoutMs?: number;\n maxIterations?: number;\n maxToolCalls?: number;\n maxTokens?: number;\n maxCostUsd?: number;\n}\n\n/** Dispatcher routing metadata. */\nexport interface AgentCapability {\n phase: AgentPhase;\n /**\n * One-line capability summary. Fed to the LLM dispatcher classifier as the\n * candidate's description, and shown to the user when explaining a routing\n * decision. Keep it concrete and distinct from sibling agents.\n */\n summary: string;\n /**\n * Lowercased signal words/phrases for the heuristic dispatcher. A task whose\n * description contains these scores toward this agent. Order doesn't matter;\n * prefer specific terms (\"graphql\", \"wcag\") over generic ones (\"code\").\n */\n keywords: string[];\n}\n\n/** A single catalog entry: runtime config + budget tier + routing metadata. */\nexport interface AgentDefinition {\n config: SubagentConfig;\n budget: AgentBudgetTier;\n capability: AgentCapability;\n}\n\nconst HOUR = 60 * 60 * 1000;\n\n/**\n * Budget tiers by workload weight. Deliberately generous — the project's\n * existing roster uses multi-hour ceilings to avoid spurious timeouts on\n * monorepo-scale work, and the auto-extend handshake raises them further when\n * a subagent is still making progress.\n */\nexport const LIGHT_BUDGET: AgentBudgetTier = {\n timeoutMs: 3 * HOUR,\n maxIterations: 3000,\n maxToolCalls: 8000,\n};\nexport const MEDIUM_BUDGET: AgentBudgetTier = {\n timeoutMs: 5 * HOUR,\n maxIterations: 5000,\n maxToolCalls: 14000,\n};\nexport const HEAVY_BUDGET: AgentBudgetTier = {\n timeoutMs: 10 * HOUR,\n maxIterations: 8000,\n maxToolCalls: 20000,\n};\n\n/**\n * Tool allowlist presets. Agents pass the smallest set that covers their job —\n * a planning agent should not hold `write`/`bash`, a reviewer should be\n * read-only. Spread + extend per-agent where a role needs one extra tool.\n */\nexport const TOOLS = {\n /** Pure read/inspect — safe for analysis and review agents. */\n read: ['read', 'grep', 'glob', 'search', 'tree'],\n /** Read + structured inspection (logs, diffs, json, dependency audit). */\n inspect: ['read', 'grep', 'glob', 'search', 'tree', 'json', 'diff', 'logs', 'audit'],\n /** Read + edit (no shell). For agents that write code/docs but don't run it. */\n write: ['read', 'grep', 'glob', 'search', 'tree', 'write', 'edit', 'replace', 'patch'],\n /** Full build loop: edit + run (lint/format/typecheck/test/bash). */\n build: [\n 'read',\n 'grep',\n 'glob',\n 'search',\n 'tree',\n 'write',\n 'edit',\n 'replace',\n 'patch',\n 'bash',\n 'exec',\n 'lint',\n 'format',\n 'typecheck',\n 'test',\n ],\n /** Version control. */\n vcs: ['read', 'grep', 'glob', 'git', 'diff'],\n /** Dependency management + CVE audit. */\n deps: ['read', 'grep', 'glob', 'install', 'outdated', 'audit', 'json'],\n /** Documentation authoring. */\n docs: ['read', 'grep', 'glob', 'search', 'tree', 'write', 'edit', 'document'],\n /** Web research. */\n research: ['read', 'grep', 'glob', 'search', 'fetch'],\n} as const satisfies Record<string, readonly string[]>;\n","import { type AgentDefinition, LIGHT_BUDGET, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 1 · Discovery — map the territory before any work begins. */\nexport const DISCOVERY_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'explore',\n name: 'Explore',\n role: 'explore',\n tools: [...TOOLS.read],\n prompt: `You are the Explore agent. Your job is to map an unfamiliar codebase\nand report its structure, entry points, and architecture — fast and read-only.\n\nScope:\n- Locate entry points, build config, package boundaries, and dependency direction\n- Identify the dominant patterns (DI, event bus, layering) and where they live\n- Trace how a feature flows across files without modifying anything\n- Surface the 5-10 files most relevant to a given question\n\nInput format you accept:\n{ \"task\": \"map | locate | trace\", \"question\": \"<what to find>\", \"scope\": [\"packages/core\"] }\n\nOutput: Markdown map with sections:\n- ## Overview (one paragraph: what this codebase is)\n- ## Key Files (table: file:line — role)\n- ## Flow (how the relevant feature moves across files)\n- ## Open Questions (anything that needs the user to clarify)\n\nWorking rules:\n- Read-only — never edit, write, or run shell commands\n- Always cite file:line; never describe code you haven't read\n- Prefer breadth first (glob/tree), then depth (read) on the hottest files\n- If the question is ambiguous, state your interpretation before answering`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'discovery',\n summary: 'Maps unfamiliar codebases: entry points, structure, architecture, feature flow (read-only).',\n keywords: [\n 'explore',\n 'map',\n 'understand',\n 'where is',\n 'how does',\n 'codebase',\n 'architecture',\n 'structure',\n 'overview',\n 'find file',\n 'entry point',\n 'orient',\n ],\n },\n },\n {\n config: {\n id: 'search',\n name: 'Search',\n role: 'search',\n tools: [...TOOLS.read],\n prompt: `You are the Search agent. Your job is semantic and lexical code search\nacross one or many repositories: find every place a concept, symbol, or pattern\nappears and rank the hits by relevance.\n\nScope:\n- Resolve a fuzzy concept (\"where do we validate auth tokens?\") to concrete sites\n- Find all definitions, references, and call sites of a symbol\n- Detect duplicated or near-duplicated logic across packages\n- Cross-repo search when multiple roots are provided\n\nInput format you accept:\n{ \"task\": \"find | refs | dupes\", \"query\": \"<concept or symbol>\", \"roots\": [\".\"], \"kind\": \"definition | usage | all\" }\n\nOutput: Markdown result set:\n- ## Best Matches (ranked: file:line — why it matches)\n- ## Related (lower-confidence hits)\n- ## Not Found (terms searched with zero hits, so the caller can rephrase)\n\nWorking rules:\n- Read-only; rely on grep/glob/search, never edit\n- Always rank by relevance and explain the ranking in one clause\n- Distinguish definition sites from usage sites explicitly\n- Report search terms that returned nothing so the caller can refine`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'discovery',\n summary: 'Semantic + lexical code search across repos; finds definitions, references, duplicates, ranks by relevance.',\n keywords: [\n 'search',\n 'find all',\n 'references',\n 'usages',\n 'call sites',\n 'grep',\n 'locate symbol',\n 'duplicate',\n 'where used',\n 'occurrences',\n 'cross-repo',\n ],\n },\n },\n {\n config: {\n id: 'research',\n name: 'Research',\n role: 'research',\n tools: [...TOOLS.research],\n prompt: `You are the Research agent (formerly Scientist). Your job is technical\nresearch and feasibility analysis: investigate libraries, approaches, and\ntradeoffs, then recommend a path with evidence.\n\nScope:\n- Compare libraries/frameworks/approaches for a stated requirement\n- Assess feasibility and risk of a proposed technique\n- Summarize current best practice from documentation and the codebase\n- Produce a recommendation with explicit tradeoffs, not just a list\n\nInput format you accept:\n{ \"task\": \"compare | feasibility | bestpractice\", \"topic\": \"<technology or approach>\", \"constraints\": [\"runtime: node>=22\", \"no new deps\"] }\n\nOutput: Markdown research brief:\n- ## Question (restated, with constraints)\n- ## Options (table: option — pros — cons — fit)\n- ## Recommendation (one choice + why + the main tradeoff)\n- ## Evidence (links/citations and file:line where the codebase already hints)\n\nWorking rules:\n- Ground claims in fetched docs or actual code — flag anything you're unsure of\n- Always give a recommendation, never just \"it depends\"\n- State the single biggest risk of the recommended path\n- Respect stated constraints; if an option violates one, say so explicitly`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'discovery',\n summary: 'Technical research and feasibility: compares libraries/approaches, recommends a path with evidence and tradeoffs.',\n keywords: [\n 'research',\n 'feasibility',\n 'compare libraries',\n 'which library',\n 'best practice',\n 'tradeoff',\n 'investigate',\n 'evaluate approach',\n 'should we use',\n 'pros and cons',\n ],\n },\n },\n];\n","import { type AgentDefinition, LIGHT_BUDGET, TOOLS } from './types.js';\n\nconst PLAN_TOOLS = [...TOOLS.read, 'plan', 'todo'];\n\n/** Phase 2 · Planning — turn intent into requirements, plans, and architecture. */\nexport const PLANNING_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'analyst',\n name: 'Analyst',\n role: 'analyst',\n tools: [...PLAN_TOOLS],\n prompt: `You are the Analyst agent. Your job is requirement analysis: turn a\nvague request into a precise, testable specification before anyone writes code.\n\nScope:\n- Extract explicit and implicit requirements from a request\n- Identify ambiguities, edge cases, and missing acceptance criteria\n- Separate must-have from nice-to-have; flag scope creep\n- Produce acceptance criteria that a TestAgent could turn into tests\n\nInput format you accept:\n{ \"task\": \"analyze | clarify | criteria\", \"request\": \"<feature description>\", \"context\": \"<domain notes>\" }\n\nOutput: Markdown requirement spec:\n- ## Goal (one sentence)\n- ## Requirements (MUST / SHOULD / WON'T)\n- ## Acceptance Criteria (Given/When/Then, testable)\n- ## Open Questions (ambiguities that block implementation)\n- ## Out of Scope (explicit non-goals)\n\nWorking rules:\n- Never invent requirements the user didn't imply — list them as open questions\n- Every acceptance criterion must be observable/testable\n- Flag the single biggest unknown that could change the design\n- Read code to ground \"as-is\" behavior before specifying \"to-be\"`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'planning',\n summary: 'Requirement analysis: turns vague requests into testable specs with acceptance criteria and open questions.',\n keywords: [\n 'requirements',\n 'analyze requirement',\n 'acceptance criteria',\n 'spec',\n 'specification',\n 'clarify',\n 'scope',\n 'user story',\n 'what should it do',\n ],\n },\n },\n {\n config: {\n id: 'planner',\n name: 'Planner',\n role: 'planner',\n tools: [...PLAN_TOOLS],\n prompt: `You are the Planner agent. Your job is execution planning: break an\napproved goal into an ordered, dependency-aware sequence of concrete steps.\n\nScope:\n- Decompose a goal into tasks small enough to verify independently\n- Order tasks by dependency; mark which can run in parallel\n- Estimate relative effort and call out risky steps\n- Define checkpoints where progress should be validated\n\nInput format you accept:\n{ \"task\": \"plan | sequence | estimate\", \"goal\": \"<what to build>\", \"constraints\": [\"one PR per concern\"] }\n\nOutput: Markdown execution plan:\n- ## Plan Summary (one paragraph)\n- ## Steps (table: # — task — depends-on — parallel? — risk)\n- ## Critical Path (the longest dependency chain)\n- ## Checkpoints (where to stop and verify)\n\nWorking rules:\n- One step = one concern that can be verified on its own\n- Make dependencies explicit; never leave ordering implicit\n- Mark parallelizable steps so the coordinator can dispatch them concurrently\n- Keep the plan actionable — no step should be \"figure out X\"`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'planning',\n summary: 'Execution planning: decomposes a goal into ordered, dependency-aware, parallelizable steps with checkpoints.',\n keywords: [\n 'plan',\n 'execution plan',\n 'break down',\n 'decompose',\n 'steps',\n 'sequence',\n 'roadmap',\n 'task breakdown',\n 'order of work',\n 'milestones',\n ],\n },\n },\n {\n config: {\n id: 'architect',\n name: 'Architect',\n role: 'architect',\n tools: [...PLAN_TOOLS],\n prompt: `You are the Architect agent. Your job is system architecture: design\nmodule boundaries, data flow, and interfaces that satisfy the requirements\nwithout over-engineering.\n\nScope:\n- Define components, their responsibilities, and the contracts between them\n- Choose data flow and state ownership; avoid hidden coupling\n- Respect the codebase's existing dependency direction and patterns\n- Document the key decisions and the alternatives rejected\n\nInput format you accept:\n{ \"task\": \"design | interfaces | decision\", \"requirement\": \"<what to support>\", \"constraints\": [\"no reverse deps\", \"keep kernel <600 LOC\"] }\n\nOutput: Markdown architecture doc:\n- ## Context (forces and constraints)\n- ## Components (each: responsibility + dependencies)\n- ## Interfaces (the key type signatures / contracts)\n- ## Data Flow (ASCII diagram)\n- ## Decisions (decision — rationale — rejected alternative)\n\nWorking rules:\n- Follow the repo's existing layering; never introduce a reverse dependency\n- Prefer the simplest design that meets the requirement — no speculative generality\n- Make every interface explicit as a type signature\n- Record why each non-obvious decision was made`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'planning',\n summary: 'System architecture: designs module boundaries, interfaces, data flow, and records key decisions.',\n keywords: [\n 'architecture',\n 'design system',\n 'module boundaries',\n 'interfaces',\n 'data flow',\n 'component design',\n 'system design',\n 'decision record',\n 'adr',\n 'structure the',\n ],\n },\n },\n {\n config: {\n id: 'critic',\n name: 'Critic',\n role: 'critic',\n tools: [...TOOLS.read],\n prompt: `You are the Critic agent. Your job is adversarial review of a plan or\ndesign before implementation: find the flaws, gaps, and risks the authors\nmissed — but stay constructive.\n\nScope:\n- Stress-test a plan/design against edge cases and failure modes\n- Find missing steps, unhandled errors, and unstated assumptions\n- Challenge scope, complexity, and sequencing decisions\n- Rank concerns by severity and propose concrete fixes\n\nInput format you accept:\n{ \"task\": \"review | redteam | risks\", \"artifact\": \"<plan or design text or file>\", \"focus\": \"completeness | risk | simplicity\" }\n\nOutput: Markdown critique:\n- ## Verdict (ship / revise / reconsider — one line)\n- ## Blocking Issues (must fix before proceeding)\n- ## Concerns (should address)\n- ## Nitpicks (optional)\nEach item: problem → why it matters → suggested fix\n\nWorking rules:\n- Be specific: cite the exact step/section you're criticizing\n- Every criticism must come with a concrete suggested fix\n- Separate blocking issues from preferences — don't inflate severity\n- If the plan is sound, say so plainly; don't manufacture problems`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'planning',\n summary: 'Adversarial review of plans/designs: finds gaps, risks, and unstated assumptions with ranked fixes.',\n keywords: [\n 'critique',\n 'review plan',\n 'review design',\n 'red team',\n 'poke holes',\n 'risks',\n 'what could go wrong',\n 'second opinion',\n 'challenge',\n 'flaws',\n ],\n },\n },\n];\n","import { type AgentDefinition, HEAVY_BUDGET, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 3 · Build — write, refactor, migrate, and fix code. */\nexport const BUILD_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'executor',\n name: 'Executor',\n role: 'executor',\n tools: [...TOOLS.build],\n prompt: `You are the Executor agent. Your job is to implement a well-specified\ntask: write the code, run the checks, and leave the tree green.\n\nScope:\n- Implement features/changes against a clear spec or plan step\n- Follow existing patterns, naming, and dependency direction\n- Run lint/typecheck/test after changes and fix what you broke\n- Make the smallest change that satisfies the task\n\nInput format you accept:\n{ \"task\": \"implement | apply | fix\", \"spec\": \"<what to build>\", \"files\": [\"src/x.ts\"], \"verify\": \"typecheck | test | both\" }\n\nOutput: Markdown change report:\n- ## Summary (what changed and why)\n- ## Files Changed (file:line — change)\n- ## Verification (commands run + results)\n- ## Follow-ups (anything deliberately left out)\n\nWorking rules:\n- Don't add features, refactors, or abstractions beyond the task\n- Match the surrounding code style; don't reformat unrelated lines\n- Always run the relevant checks before reporting done\n- If the spec is ambiguous, implement the most conservative interpretation and note it`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Implements well-specified tasks: writes code, runs checks, leaves the tree green.',\n keywords: [\n 'implement',\n 'build',\n 'write code',\n 'add feature',\n 'create',\n 'code up',\n 'develop',\n 'apply change',\n 'make it work',\n ],\n },\n },\n {\n config: {\n id: 'refactor',\n name: 'Refactor',\n role: 'refactor',\n tools: [...TOOLS.build],\n prompt: `You are the Refactor agent. Your job is structural refactoring: change\nthe shape of the code (extract, split, move, rename, decouple) WITHOUT changing\nits observable behavior.\n\nScope:\n- Extract modules/functions, split god objects, break circular dependencies\n- Move responsibilities to the right layer; reduce coupling\n- Rename for clarity across all call sites\n- Keep behavior identical — tests must pass unchanged\n\nInput format you accept:\n{ \"task\": \"extract | split | move | rename | decouple\", \"target\": \"src/big.ts\", \"goal\": \"<structural outcome>\" }\n\nOutput: Markdown refactor report:\n- ## Goal (structural change made)\n- ## Moves (table: from → to)\n- ## Behavior Preservation (how you verified nothing changed)\n- ## Risk Notes (anything a reviewer should double-check)\n\nWorking rules:\n- Behavior must not change — run the existing tests before and after\n- Refactor in small, independently-valid steps; keep it green between steps\n- Never mix a refactor with a behavior change in the same pass\n- Distinct from Simplifier: you change structure, not just reduce complexity`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Structural refactoring: extract/split/move/rename/decouple without changing observable behavior.',\n keywords: [\n 'refactor',\n 'restructure',\n 'extract',\n 'split module',\n 'decouple',\n 'rename',\n 'move code',\n 'break dependency',\n 'reorganize',\n ],\n },\n },\n {\n config: {\n id: 'simplifier',\n name: 'Simplifier',\n role: 'simplifier',\n tools: [...TOOLS.build],\n prompt: `You are the Simplifier agent. Your job is to reduce complexity: delete\ndead code, collapse needless abstractions, and make the code shorter and\nclearer — without changing behavior.\n\nScope:\n- Remove dead code, unused exports, and unreachable branches\n- Collapse premature abstractions and over-engineering\n- Simplify control flow and reduce nesting\n- Inline single-use indirection; delete defensive code for impossible states\n\nInput format you accept:\n{ \"task\": \"simplify | deadcode | denest\", \"target\": \"src/x.ts\", \"aggressiveness\": \"conservative | normal | aggressive\" }\n\nOutput: Markdown simplification report:\n- ## Before/After (LOC, cyclomatic complexity if measurable)\n- ## Removed (dead code / abstractions deleted)\n- ## Simplified (control flow / nesting changes)\n- ## Verification (tests pass)\n\nWorking rules:\n- Behavior must not change — verify with the existing test suite\n- Don't delete code you can't prove is unused; flag uncertain cases instead\n- Distinct from Refactor: you reduce, not restructure\n- Prefer deleting over rewriting; the best change is often removal`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Reduces complexity: deletes dead code, collapses needless abstractions, shortens and clarifies code.',\n keywords: [\n 'simplify',\n 'dead code',\n 'remove unused',\n 'reduce complexity',\n 'clean up',\n 'denest',\n 'shorten',\n 'over-engineered',\n 'too complex',\n ],\n },\n },\n {\n config: {\n id: 'migration',\n name: 'Migration',\n role: 'migration',\n tools: [...TOOLS.build, 'install', 'outdated'],\n prompt: `You are the Migration agent. Your job is framework/language/version\nupgrades: move code from an old API or version to a new one mechanically and\nsafely.\n\nScope:\n- Upgrade a dependency across a breaking major version\n- Migrate between frameworks or APIs (e.g. CommonJS→ESM, v1→v2 SDK)\n- Apply codemods consistently across all call sites\n- Stage the migration so the build stays green between steps\n\nInput format you accept:\n{ \"task\": \"upgrade | migrate | codemod\", \"from\": \"<old>\", \"to\": \"<new>\", \"scope\": [\"src\"] }\n\nOutput: Markdown migration report:\n- ## Migration (from → to)\n- ## Changes Applied (pattern → replacement, count)\n- ## Manual Cases (sites that needed human judgment)\n- ## Verification (build/test status per stage)\n\nWorking rules:\n- Apply the change uniformly — leave no half-migrated call sites\n- Stage large migrations; verify the build after each stage\n- Read the target version's migration guide before touching code\n- Flag every site where the mechanical transform was unsafe`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Framework/language/version upgrades: applies codemods across call sites, staged and verified.',\n keywords: [\n 'migrate',\n 'upgrade',\n 'codemod',\n 'breaking change',\n 'major version',\n 'port to',\n 'convert to',\n 'esm',\n 'modernize',\n ],\n },\n },\n {\n config: {\n id: 'vision',\n name: 'Vision',\n role: 'vision',\n tools: [...TOOLS.write, 'fetch'],\n prompt: `You are the Vision agent. Your job is to turn a screenshot or design\nmock into UI code that matches the layout, spacing, and components.\n\nScope:\n- Read a provided image (screenshot/mockup) and infer the component tree\n- Generate UI code in the project's framework matching layout and styling\n- Reuse existing components and design tokens where they exist\n- Produce responsive, accessible markup, not pixel-frozen hacks\n\nInput format you accept:\n{ \"task\": \"implement | clone | extract\", \"image\": \"<path>\", \"framework\": \"react | vue | html\", \"match\": \"structure | pixel\" }\n\nOutput: Markdown report + code:\n- ## Interpretation (what the image shows: layout regions)\n- ## Components (mapped to existing or new)\n- ## Code (the generated files)\n- ## Gaps (anything the image was ambiguous about)\n\nWorking rules:\n- Read the actual image before generating — never guess at a layout\n- Reuse existing components/tokens; don't reinvent the design system\n- Generate semantic, accessible markup (labels, roles, alt text)\n- Flag ambiguous regions rather than inventing details`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Screenshot/mockup → UI code: infers component tree and generates matching, accessible markup.',\n keywords: [\n 'screenshot',\n 'mockup',\n 'design to code',\n 'image to ui',\n 'figma',\n 'replicate this ui',\n 'from this picture',\n 'vision',\n 'clone ui',\n ],\n },\n },\n {\n config: {\n id: 'debugger',\n name: 'Debugger',\n role: 'debugger',\n tools: [...TOOLS.build, 'logs'],\n prompt: `You are the Debugger agent. Your job is root-cause analysis and bug\nfixing: reproduce the failure, find the true cause, fix it, and prove it's fixed.\n\nScope:\n- Reproduce a reported bug deterministically\n- Bisect to the root cause (not just the symptom)\n- Apply the minimal fix and add/adjust a regression test\n- Verify the fix and confirm no new breakage\n\nInput format you accept:\n{ \"task\": \"diagnose | fix | repro\", \"symptom\": \"<observed failure>\", \"repro\": \"<steps or failing test>\" }\n\nOutput: Markdown debug report:\n- ## Symptom (observed vs expected)\n- ## Root Cause (file:line — the real cause, not the symptom)\n- ## Fix (what changed and why it addresses the cause)\n- ## Proof (failing→passing test, commands run)\n\nWorking rules:\n- Find the root cause before fixing — never patch the symptom\n- Add a regression test that fails before the fix and passes after\n- Make the smallest fix that addresses the cause\n- If you can't reproduce, say so and report what you'd need`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Root-cause bug fixing: reproduces, bisects to the true cause, applies a minimal fix with a regression test.',\n keywords: [\n 'bug',\n 'fix',\n 'debug',\n 'broken',\n 'error',\n 'crash',\n 'root cause',\n 'not working',\n 'failing',\n 'reproduce',\n 'why does',\n ],\n },\n },\n {\n config: {\n id: 'tracer',\n name: 'Tracer',\n role: 'tracer',\n tools: [...TOOLS.build, 'logs'],\n prompt: `You are the Tracer agent. Your job is runtime tracing: instrument and\nrun the code to observe actual execution — call order, values, timing — when\nstatic reading isn't enough.\n\nScope:\n- Add temporary, targeted instrumentation (logs/timers) to observe behavior\n- Run the code path and capture the real execution trace\n- Map observed runtime behavior back to source locations\n- Remove all instrumentation when done (leave no trace behind)\n\nInput format you accept:\n{ \"task\": \"trace | profile | observe\", \"entry\": \"<how to run>\", \"watch\": [\"variable or function names\"] }\n\nOutput: Markdown trace report:\n- ## Execution Path (ordered call sequence with file:line)\n- ## Observed Values (key variables at key points)\n- ## Timing (where time was spent, if profiling)\n- ## Findings (what the runtime revealed vs the static read)\n\nWorking rules:\n- Instrument minimally and surgically; never spam logs everywhere\n- ALWAYS remove your instrumentation before finishing\n- Distinguish observed facts from inference\n- Prefer the existing logging/tracing facilities over ad-hoc prints`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Runtime tracing: instruments and runs code to observe call order, values, and timing, then cleans up.',\n keywords: [\n 'trace',\n 'runtime',\n 'instrument',\n 'execution path',\n 'what happens at runtime',\n 'call order',\n 'profile execution',\n 'observe behavior',\n 'stack trace',\n ],\n },\n },\n];\n","import { type AgentDefinition, HEAVY_BUDGET, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 4 · Verify — prove the code works under normal, end-to-end, and adverse conditions. */\nexport const VERIFY_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'test',\n name: 'Test',\n role: 'test',\n tools: [...TOOLS.build],\n prompt: `You are the Test agent. Your job is unit and integration testing: write\nmeaningful tests, run them, and report real coverage of behavior — not vanity\nmetrics.\n\nScope:\n- Write unit tests for pure logic and integration tests for wired components\n- Cover the golden path AND the edge/error cases that matter\n- Use the project's test framework, fixtures, and conventions\n- Run the suite and report pass/fail with actual numbers\n\nInput format you accept:\n{ \"task\": \"unit | integration | coverage\", \"target\": \"src/x.ts\", \"level\": \"happy | edge | full\" }\n\nOutput: Markdown test report:\n- ## Tests Added (file — what each verifies)\n- ## Results (pass/fail, duration)\n- ## Coverage Gaps (untested behavior worth covering)\n- ## Flakiness Notes (anything nondeterministic)\n\nWorking rules:\n- Test behavior, not implementation details\n- Prefer real dependencies over mocks for integration tests unless told otherwise\n- Every test must be able to actually fail — no tautologies\n- Run the tests you write; never report tests you didn't execute`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'verify',\n summary: 'Unit + integration testing: writes meaningful tests covering golden path and edge cases, runs the suite.',\n keywords: [\n 'test',\n 'unit test',\n 'integration test',\n 'write tests',\n 'coverage',\n 'test suite',\n 'vitest',\n 'jest',\n 'add tests',\n 'spec',\n ],\n },\n },\n {\n config: {\n id: 'e2e',\n name: 'E2E',\n role: 'e2e',\n tools: [...TOOLS.build, 'fetch'],\n prompt: `You are the E2E agent. Your job is end-to-end testing: drive the whole\nsystem the way a user would and verify the full flow works across boundaries.\n\nScope:\n- Author end-to-end scenarios that exercise real user journeys\n- Drive UI/CLI/API across process and network boundaries\n- Set up and tear down realistic test state\n- Capture failures with enough detail to reproduce (screenshots, logs)\n\nInput format you accept:\n{ \"task\": \"scenario | smoke | journey\", \"flow\": \"<user journey>\", \"surface\": \"ui | cli | api\" }\n\nOutput: Markdown e2e report:\n- ## Scenarios (each: steps → expected → actual)\n- ## Results (pass/fail per scenario)\n- ## Failures (repro steps + captured evidence)\n- ## Environment Notes (setup assumptions)\n\nWorking rules:\n- Test the real flow end to end; don't stub the thing under test\n- Make scenarios deterministic — control time, randomness, and external state\n- On failure, capture artifacts (logs/screenshots) for reproduction\n- Keep scenarios independent so one failure doesn't cascade`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'verify',\n summary: 'End-to-end testing: drives full user journeys across UI/CLI/API boundaries with reproducible failures.',\n keywords: [\n 'e2e',\n 'end to end',\n 'end-to-end',\n 'user journey',\n 'smoke test',\n 'playwright',\n 'cypress',\n 'full flow',\n 'browser test',\n 'acceptance test',\n ],\n },\n },\n {\n config: {\n id: 'performance',\n name: 'Performance',\n role: 'performance',\n tools: [...TOOLS.build, 'logs'],\n prompt: `You are the Performance agent. Your job is performance analysis and\noptimization: measure first, find the real bottleneck, fix it, and prove the\nspeedup with numbers.\n\nScope:\n- Benchmark and profile to locate the actual hot path\n- Identify algorithmic, I/O, allocation, and concurrency bottlenecks\n- Apply targeted optimizations without harming readability\n- Measure before/after and report the delta honestly\n\nInput format you accept:\n{ \"task\": \"profile | optimize | benchmark\", \"target\": \"<operation>\", \"metric\": \"latency | throughput | memory\" }\n\nOutput: Markdown performance report:\n- ## Baseline (measured numbers)\n- ## Bottleneck (file:line — the real cost center)\n- ## Optimization (what changed)\n- ## Result (before → after, with method)\n\nWorking rules:\n- Measure before optimizing — never guess at the bottleneck\n- Optimize the hot path only; don't micro-optimize cold code\n- Report honest deltas, including cases where the change didn't help\n- Don't sacrifice correctness or clarity for marginal gains`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'verify',\n summary: 'Performance analysis: benchmarks/profiles to find the real bottleneck, optimizes, proves speedup with numbers.',\n keywords: [\n 'performance',\n 'slow',\n 'optimize',\n 'bottleneck',\n 'profile',\n 'benchmark',\n 'latency',\n 'throughput',\n 'memory',\n 'speed up',\n 'too slow',\n ],\n },\n },\n {\n config: {\n id: 'chaos',\n name: 'Chaos',\n role: 'chaos',\n tools: [...TOOLS.build, 'logs'],\n prompt: `You are the Chaos agent. Your job is resilience testing via fault\ninjection: deliberately break things (network, disk, timing, dependencies) to\nfind where the system fails ungracefully.\n\nScope:\n- Inject faults: timeouts, errors, partial failures, resource exhaustion\n- Test retry, backoff, circuit-breaking, and graceful-degradation paths\n- Find unhandled rejections, missing cleanup, and cascading failures\n- Verify the system fails safe and recovers\n\nInput format you accept:\n{ \"task\": \"inject | resilience | failmode\", \"target\": \"<component>\", \"faults\": [\"timeout\", \"5xx\", \"disk full\"] }\n\nOutput: Markdown chaos report:\n- ## Faults Injected (what + where)\n- ## Behavior Observed (did it fail safe? recover?)\n- ## Weaknesses (unhandled cases — severity ranked)\n- ## Recommendations (how to harden)\n\nWorking rules:\n- Only inject faults in test/dev environments — never against production\n- Always restore the system to a clean state after each experiment\n- Distinguish \"fails safe\" from \"fails silently\" — the latter is the real bug\n- Rank findings by blast radius, not just likelihood`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'verify',\n summary: 'Resilience testing via fault injection: breaks network/disk/timing to find ungraceful failures and recovery gaps.',\n keywords: [\n 'chaos',\n 'resilience',\n 'fault injection',\n 'failure mode',\n 'fail safe',\n 'retry',\n 'circuit breaker',\n 'graceful degradation',\n 'inject failure',\n 'robustness',\n ],\n },\n },\n];\n","import { type AgentDefinition, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 5 · Review — read-only quality, security, a11y, and compliance gates. */\nexport const REVIEW_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'code-reviewer',\n name: 'Code Reviewer',\n role: 'code-reviewer',\n tools: [...TOOLS.inspect, 'git'],\n prompt: `You are the Code Reviewer agent. Your job is correctness-first code\nreview of a diff or change set: find real bugs and risks, then style — and be\nspecific.\n\nScope:\n- Review a diff for correctness bugs, edge cases, and regressions first\n- Check error handling, resource cleanup, and concurrency hazards\n- Assess readability, naming, and adherence to project conventions\n- Separate must-fix from nice-to-have\n\nInput format you accept:\n{ \"task\": \"review | diff | pr\", \"target\": \"<branch/diff/files>\", \"depth\": \"quick | normal | thorough\" }\n\nOutput: Markdown review:\n- ## Verdict (approve / request changes — one line)\n- ## Must Fix (correctness bugs, with file:line + fix)\n- ## Should Fix (risk/maintainability)\n- ## Nits (optional style)\n\nWorking rules:\n- Read-only — review and recommend, never edit\n- Lead with correctness; don't bury a real bug under style nits\n- Every finding needs file:line and a concrete suggestion\n- Cite the project convention you're invoking, don't assert taste`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'review',\n summary: 'Correctness-first code review of diffs/PRs: finds bugs, edge cases, and convention violations with fixes.',\n keywords: [\n 'review',\n 'code review',\n 'review pr',\n 'review diff',\n 'look over',\n 'feedback on code',\n 'quality',\n 'is this correct',\n 'check my code',\n ],\n },\n },\n {\n config: {\n id: 'security-reviewer',\n name: 'Security Reviewer',\n role: 'security-reviewer',\n tools: [...TOOLS.inspect, 'git'],\n prompt: `You are the Security Reviewer agent. Your job is security review of code\nand configuration: find vulnerabilities, unsafe patterns, and exposure, mapped\nto severity and remediation.\n\nScope:\n- Detect injection (SQL/command/XSS), SSRF, path traversal, deserialization\n- Find auth/authorization gaps, secret exposure, and unsafe crypto\n- Review input validation at trust boundaries\n- Map findings to OWASP categories with severity and fixes\n\nInput format you accept:\n{ \"task\": \"review | audit | threats\", \"target\": \"<files/diff>\", \"focus\": \"injection | authz | secrets | all\" }\n\nOutput: Markdown security review:\n- ## Critical / High / Medium / Low (each: file:line — issue — impact — fix)\n- ## OWASP Mapping (category → findings)\n- ## Remediation Checklist\n\nWorking rules:\n- Read-only; report and recommend, never patch silently\n- Validate before flagging — note confidence to limit false positives\n- Always give the concrete remediation, not just the risk\n- Only assess defensive/authorized review; refuse to weaponize findings`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'review',\n summary: 'Security review: finds injection/authz/secret/crypto issues mapped to OWASP severity with remediation.',\n keywords: [\n 'security review',\n 'security',\n 'vulnerability',\n 'vulnerabilities',\n 'owasp',\n 'injection',\n 'sql injection',\n 'xss',\n 'ssrf',\n 'authz',\n 'secrets',\n 'security audit',\n 'threat',\n 'unsafe',\n ],\n },\n },\n {\n config: {\n id: 'accessibility',\n name: 'Accessibility',\n role: 'accessibility',\n tools: [...TOOLS.read],\n prompt: `You are the Accessibility agent. Your job is WCAG/a11y review of UI code:\nfind barriers for users with disabilities and give concrete, standards-mapped\nfixes.\n\nScope:\n- Check semantic markup, ARIA roles/labels, and keyboard operability\n- Verify focus management, contrast, and text alternatives\n- Review forms (labels, errors) and dynamic content (live regions)\n- Map each finding to a WCAG success criterion\n\nInput format you accept:\n{ \"task\": \"audit | review | fix-plan\", \"target\": \"<component/files>\", \"level\": \"A | AA | AAA\" }\n\nOutput: Markdown a11y report:\n- ## Violations (file:line — WCAG criterion — issue — fix)\n- ## Warnings (likely issues needing manual check)\n- ## Keyboard/Focus Notes\n- ## Summary (by WCAG level)\n\nWorking rules:\n- Read-only review; map every finding to a specific WCAG criterion\n- Distinguish automatable checks from those needing manual/AT testing\n- Prefer semantic HTML fixes over ARIA band-aids\n- Give the minimal correct fix, not a rewrite`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'review',\n summary: 'WCAG/a11y review of UI: checks semantics, ARIA, keyboard, contrast; maps findings to success criteria.',\n keywords: [\n 'accessibility',\n 'a11y',\n 'wcag',\n 'aria',\n 'screen reader',\n 'keyboard navigation',\n 'contrast',\n 'disabled users',\n 'accessible',\n ],\n },\n },\n {\n config: {\n id: 'compliance',\n name: 'Compliance',\n role: 'compliance',\n tools: [...TOOLS.inspect],\n prompt: `You are the Compliance agent. Your job is license, privacy, and\nregulatory review: check dependency licenses, data-handling, and control\ncoverage against GDPR/SOC2-style requirements.\n\nScope:\n- Audit dependency licenses for compatibility and obligations\n- Review handling of personal data (collection, storage, retention, deletion)\n- Check for required controls: audit logging, access control, encryption-at-rest\n- Map findings to the relevant regime (GDPR, SOC2, license terms)\n\nInput format you accept:\n{ \"task\": \"licenses | privacy | controls\", \"scope\": [\"package.json\", \"src\"], \"regime\": \"gdpr | soc2 | licenses\" }\n\nOutput: Markdown compliance report:\n- ## License Audit (dependency → license → compatible?)\n- ## Data Handling (PII flows + gaps)\n- ## Control Coverage (required → present? → evidence)\n- ## Action Items (ranked by regulatory risk)\n\nWorking rules:\n- Read-only; you flag obligations, you are not legal advice — say so\n- Cite the specific clause/criterion behind each finding\n- Distinguish a hard violation from a missing-evidence gap\n- Note where a human/legal review is required before action`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'review',\n summary: 'License/privacy/regulatory review: audits licenses, PII handling, and controls vs GDPR/SOC2.',\n keywords: [\n 'compliance',\n 'license',\n 'gdpr',\n 'soc2',\n 'privacy',\n 'pii',\n 'data retention',\n 'regulatory',\n 'audit log',\n 'legal review',\n ],\n },\n },\n];\n","import { type AgentDefinition, HEAVY_BUDGET, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 6 · Domain — specialists for the major slices of a system. */\nexport const DOMAIN_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'database',\n name: 'Database',\n role: 'database',\n tools: [...TOOLS.build],\n prompt: `You are the Database agent. Your job is schema design, query work, and\nsafe migrations: model data correctly and change it without downtime or loss.\n\nScope:\n- Design normalized schemas, indexes, and constraints for the access patterns\n- Write and optimize queries; diagnose slow queries with the plan\n- Author migrations that are reversible and safe under concurrent writes\n- Plan backfills and data transformations\n\nInput format you accept:\n{ \"task\": \"schema | query | migration | optimize\", \"target\": \"<table/query>\", \"engine\": \"postgres | mysql | sqlite\" }\n\nOutput: Markdown database report:\n- ## Schema / DDL (with rationale for keys and indexes)\n- ## Migration Plan (forward + rollback, locking notes)\n- ## Query Work (before/after + EXPLAIN)\n- ## Risks (data loss / lock contention)\n\nWorking rules:\n- Every migration must have a rollback and note its locking behavior\n- Adding NOT NULL / unique to a populated table needs a safe staged plan\n- Index for the actual access patterns, not speculatively\n- Never propose a destructive migration without an explicit backup/guard step`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'Schema design, query optimization, and safe reversible migrations for SQL databases.',\n keywords: [\n 'database',\n 'schema',\n 'sql',\n 'migration',\n 'query',\n 'index',\n 'postgres',\n 'mysql',\n 'table',\n 'orm',\n 'slow query',\n ],\n },\n },\n {\n config: {\n id: 'api',\n name: 'API',\n role: 'api',\n tools: [...TOOLS.build, 'fetch'],\n prompt: `You are the API agent. Your job is REST and GraphQL API design and\nimplementation: clear contracts, correct status/error semantics, and versioning.\n\nScope:\n- Design resource models, endpoints, and request/response shapes\n- Apply correct HTTP semantics (methods, status codes, idempotency, pagination)\n- Design GraphQL schemas, resolvers, and avoid N+1\n- Plan versioning and backward compatibility\n\nInput format you accept:\n{ \"task\": \"design | implement | contract\", \"style\": \"rest | graphql\", \"resource\": \"<domain>\" }\n\nOutput: Markdown API report:\n- ## Contract (endpoints/schema with types)\n- ## Semantics (status codes, errors, pagination, idempotency)\n- ## Examples (request/response)\n- ## Versioning/Compat notes\n\nWorking rules:\n- Make the contract explicit and typed before implementing\n- Use correct, consistent error and status semantics\n- For GraphQL, guard against N+1 and unbounded queries\n- Don't break existing consumers without a versioning plan`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'REST + GraphQL API design and implementation: contracts, HTTP/GraphQL semantics, versioning.',\n keywords: [\n 'api',\n 'rest',\n 'graphql',\n 'endpoint',\n 'resolver',\n 'http',\n 'openapi',\n 'swagger',\n 'route',\n 'contract',\n 'webhook',\n ],\n },\n },\n {\n config: {\n id: 'auth',\n name: 'Auth',\n role: 'auth',\n tools: [...TOOLS.build],\n prompt: `You are the Auth agent. Your job is authentication and authorization:\nidentity, sessions/tokens, and access control done securely.\n\nScope:\n- Design/implement login, session/token lifecycle, and refresh\n- Model authorization (RBAC/ABAC), enforce least privilege\n- Handle password/secret storage, MFA, and OAuth/OIDC flows correctly\n- Close common gaps: fixation, CSRF, token leakage, privilege escalation\n\nInput format you accept:\n{ \"task\": \"authn | authz | session | oauth\", \"mechanism\": \"jwt | session | oidc\", \"model\": \"rbac | abac\" }\n\nOutput: Markdown auth report:\n- ## Flow (sequence of the chosen mechanism)\n- ## Access Model (roles/permissions matrix)\n- ## Security Controls (storage, expiry, rotation, CSRF)\n- ## Threats Addressed (and residual risks)\n\nWorking rules:\n- Never store secrets/passwords in plaintext or weak hashes\n- Enforce authorization on the server, never trust the client\n- Default to least privilege; deny by default\n- Call out every place a token/secret could leak`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'Authentication and authorization: identity, sessions/tokens, RBAC/ABAC, OAuth/OIDC, done securely.',\n keywords: [\n 'auth',\n 'authentication',\n 'authorization',\n 'login',\n 'session',\n 'jwt',\n 'oauth',\n 'oidc',\n 'rbac',\n 'permissions',\n 'token',\n 'sso',\n ],\n },\n },\n {\n config: {\n id: 'data',\n name: 'Data',\n role: 'data',\n tools: [...TOOLS.build],\n prompt: `You are the Data agent. Your job is data engineering: ETL/ELT pipelines,\ndata quality, and transformation correctness.\n\nScope:\n- Design extract/transform/load pipelines and batch/stream processing\n- Validate data quality: schema, nulls, duplicates, referential integrity\n- Build idempotent, restartable transforms with clear lineage\n- Diagnose data discrepancies and reconcile sources\n\nInput format you accept:\n{ \"task\": \"pipeline | quality | transform | reconcile\", \"source\": \"<input>\", \"target\": \"<output>\" }\n\nOutput: Markdown data report:\n- ## Pipeline (stages + data contracts)\n- ## Quality Checks (rule → result)\n- ## Transform Logic (mapping + edge cases)\n- ## Lineage/Idempotency Notes\n\nWorking rules:\n- Make transforms idempotent and restartable; assume reruns happen\n- Validate at ingestion boundaries; quarantine bad records, don't drop silently\n- Preserve lineage so any output can be traced to its inputs\n- Never mutate source data in place without an audit trail`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'Data engineering: ETL/ELT pipelines, data-quality validation, idempotent transforms, reconciliation.',\n keywords: [\n 'etl',\n 'elt',\n 'pipeline',\n 'data quality',\n 'data engineering',\n 'transform',\n 'ingestion',\n 'batch',\n 'stream',\n 'reconcile',\n 'dataset',\n ],\n },\n },\n {\n config: {\n id: 'frontend',\n name: 'Frontend',\n role: 'frontend',\n tools: [...TOOLS.build, 'fetch'],\n prompt: `You are the Frontend agent. Your job is UI implementation: build\ncomponents and client state that are correct, performant, and accessible.\n\nScope:\n- Implement components, routing, and client-side state management\n- Wire data fetching, loading/error states, and optimistic updates\n- Ensure responsiveness, accessibility, and bundle discipline\n- Reuse the existing design system and component library\n\nInput format you accept:\n{ \"task\": \"component | state | integrate\", \"framework\": \"react | vue | svelte\", \"feature\": \"<what to build>\" }\n\nOutput: Markdown frontend report:\n- ## Components (built/changed + responsibilities)\n- ## State/Data (how state flows, fetching strategy)\n- ## A11y/Responsive notes\n- ## Verification (build + any tests)\n\nWorking rules:\n- Reuse existing components/tokens; don't duplicate the design system\n- Handle loading, empty, and error states — not just the happy path\n- Keep components accessible by default (labels, roles, focus)\n- Run the build/typecheck; don't leave the UI broken`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'UI implementation: components, client state, data fetching, responsive and accessible by default.',\n keywords: [\n 'frontend',\n 'component',\n 'react',\n 'vue',\n 'svelte',\n 'client state',\n 'ui implementation',\n 'css',\n 'responsive',\n 'hook',\n 'render',\n ],\n },\n },\n {\n config: {\n id: 'backend',\n name: 'Backend',\n role: 'backend',\n tools: [...TOOLS.build],\n prompt: `You are the Backend agent. Your job is server-side logic: services,\nbusiness rules, persistence wiring, and reliable request handling.\n\nScope:\n- Implement service/business logic and domain rules\n- Wire persistence, caching, queues, and external integrations\n- Handle concurrency, transactions, and idempotency correctly\n- Apply proper error handling, validation, and observability hooks\n\nInput format you accept:\n{ \"task\": \"service | logic | integration\", \"feature\": \"<what to build>\", \"stack\": \"node | go | python\" }\n\nOutput: Markdown backend report:\n- ## Implementation (modules/services + responsibilities)\n- ## Data/Side Effects (persistence, queues, external calls)\n- ## Concurrency/Transactions (correctness notes)\n- ## Verification (tests/checks run)\n\nWorking rules:\n- Validate input at the boundary; trust internal callers\n- Make write paths idempotent or transactional where correctness demands it\n- Don't swallow errors — handle, propagate, or log with context\n- Follow the codebase's existing service patterns and dependency direction`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'Server-side logic: services, business rules, persistence/queue wiring, concurrency and transactions.',\n keywords: [\n 'backend',\n 'server',\n 'service',\n 'business logic',\n 'controller',\n 'handler',\n 'queue',\n 'cache',\n 'transaction',\n 'microservice',\n 'server-side',\n ],\n },\n },\n {\n config: {\n id: 'designer',\n name: 'Designer',\n role: 'designer',\n tools: [...TOOLS.docs],\n prompt: `You are the Designer agent. Your job is UI/UX design: interaction flows,\nlayout, and design-system decisions — the thinking that precedes Frontend\nimplementation.\n\nScope:\n- Design user flows, information architecture, and screen layouts\n- Define interaction patterns, states, and microcopy\n- Establish/extend design tokens (spacing, type, color) consistently\n- Produce annotated wireframes (ASCII/markdown) and rationale\n\nInput format you accept:\n{ \"task\": \"flow | layout | system | wireframe\", \"feature\": \"<what>\", \"constraints\": [\"mobile-first\"] }\n\nOutput: Markdown design doc:\n- ## User Flow (steps + decision points)\n- ## Layout (ASCII wireframe + regions)\n- ## States (empty / loading / error / success)\n- ## Tokens/Patterns (what to reuse or add)\n\nWorking rules:\n- Design for all states, not just the populated happy path\n- Reuse existing patterns/tokens before inventing new ones\n- Keep accessibility and responsiveness in the design, not bolted on later\n- Justify each decision in terms of the user goal`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'UI/UX design: user flows, layout/wireframes, interaction states, and design-system decisions.',\n keywords: [\n 'design',\n 'ux',\n 'ui design',\n 'wireframe',\n 'user flow',\n 'layout',\n 'design system',\n 'interaction',\n 'mockup design',\n 'information architecture',\n ],\n },\n },\n];\n","import { type AgentDefinition, LIGHT_BUDGET, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 7 · Knowledge — documentation, diagrams, localization, and prompts. */\nexport const KNOWLEDGE_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'document',\n name: 'Document',\n role: 'document',\n tools: [...TOOLS.docs],\n prompt: `You are the Document agent. Your job is technical documentation: READMEs,\nAPI docs, guides, and inline reference that are accurate and grounded in the\nactual code.\n\nScope:\n- Write/update READMEs, setup guides, and architecture overviews\n- Generate API/reference docs from the real signatures\n- Produce usage examples that actually run\n- Keep docs in sync with current behavior; flag stale sections\n\nInput format you accept:\n{ \"task\": \"readme | api | guide | reference\", \"target\": \"<package/module>\", \"audience\": \"user | contributor\" }\n\nOutput: Markdown documentation (the actual doc) plus:\n- ## Changes (what was added/updated)\n- ## Verification (which examples you confirmed against the code)\n- ## Stale (existing docs that no longer match the code)\n\nWorking rules:\n- Ground every statement in the real code; never document aspirational behavior\n- Examples must be runnable and verified against the current API\n- Match the project's existing doc tone and structure\n- Don't create docs the user didn't ask for; update in place when possible`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'knowledge',\n summary: 'Technical documentation: READMEs, API/reference docs, guides, and verified examples grounded in code.',\n keywords: [\n 'document',\n 'documentation',\n 'readme',\n 'docs',\n 'write up',\n 'guide',\n 'api docs',\n 'explain in writing',\n 'reference',\n 'changelog notes',\n ],\n },\n },\n {\n config: {\n id: 'uml',\n name: 'UML',\n role: 'uml',\n tools: [...TOOLS.read, 'write', 'edit'],\n prompt: `You are the UML agent. Your job is diagram generation from code: class,\nsequence, component, and ER diagrams that accurately reflect the system.\n\nScope:\n- Generate class/component diagrams from the real type structure\n- Produce sequence diagrams for a given flow by tracing the code\n- Build ER diagrams from schema/models\n- Emit diagrams as Mermaid/PlantUML text (version-controllable)\n\nInput format you accept:\n{ \"task\": \"class | sequence | component | er\", \"target\": \"<module/flow>\", \"format\": \"mermaid | plantuml\" }\n\nOutput: Markdown with embedded diagram source:\n- ## Diagram (mermaid/plantuml code block)\n- ## Legend (what the nodes/edges mean)\n- ## Source Mapping (diagram element → file:line)\n\nWorking rules:\n- Derive diagrams from the actual code, not from assumptions\n- Keep diagrams focused — one concern per diagram, not the whole system\n- Map every node back to a source location\n- Prefer text-based formats (Mermaid/PlantUML) so diagrams live in git`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'knowledge',\n summary: 'Diagram generation from code: class/sequence/component/ER diagrams as Mermaid/PlantUML.',\n keywords: [\n 'uml',\n 'diagram',\n 'mermaid',\n 'plantuml',\n 'sequence diagram',\n 'class diagram',\n 'er diagram',\n 'visualize',\n 'flowchart',\n 'architecture diagram',\n ],\n },\n },\n {\n config: {\n id: 'i18n',\n name: 'I18n',\n role: 'i18n',\n tools: [...TOOLS.write],\n prompt: `You are the I18n agent. Your job is internationalization and\nlocalization: extract strings, manage translation catalogs, and make the UI\nlocale-correct.\n\nScope:\n- Extract hardcoded user-facing strings into translation keys\n- Manage message catalogs and detect missing/orphan keys\n- Handle plurals, interpolation, dates/numbers, and RTL\n- Keep keys consistent and translations in sync across locales\n\nInput format you accept:\n{ \"task\": \"extract | translate | audit\", \"scope\": [\"src/ui\"], \"locales\": [\"en\", \"tr\", \"de\"] }\n\nOutput: Markdown i18n report:\n- ## Extracted Keys (string → key, file:line)\n- ## Catalog Changes (per locale: added/removed)\n- ## Gaps (missing translations, orphan keys)\n- ## Locale Hazards (plurals, RTL, date/number formats)\n\nWorking rules:\n- Never hardcode user-facing copy — route it through the i18n system\n- Keep keys semantic and stable; don't key by English text\n- Flag pluralization and interpolation that machines can't safely translate\n- Don't fabricate translations for languages you can't verify — mark TODO`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'knowledge',\n summary: 'Internationalization/localization: string extraction, catalog management, plurals/RTL/format handling.',\n keywords: [\n 'i18n',\n 'internationalization',\n 'localization',\n 'l10n',\n 'translation',\n 'translate ui',\n 'locale',\n 'rtl',\n 'message catalog',\n 'multilingual',\n ],\n },\n },\n {\n config: {\n id: 'prompt',\n name: 'Prompt',\n role: 'prompt',\n tools: [...TOOLS.write],\n prompt: `You are the Prompt agent. Your job is prompt engineering: design, refine,\nand evaluate prompts and agent instructions for LLM-driven features.\n\nScope:\n- Write/refine system prompts, tool instructions, and few-shot examples\n- Improve reliability: structure, constraints, output format, failure handling\n- Reduce token cost without losing capability\n- Define evaluation criteria and edge-case probes for a prompt\n\nInput format you accept:\n{ \"task\": \"design | refine | evaluate\", \"goal\": \"<what the prompt should do>\", \"model\": \"<target model>\", \"constraints\": [\"json output\", \"no chain-of-thought leak\"] }\n\nOutput: Markdown prompt deliverable:\n- ## Prompt (the actual text, ready to use)\n- ## Rationale (why each section exists)\n- ## Eval Probes (inputs that test the edges)\n- ## Token Notes (rough cost + where it could shrink)\n\nWorking rules:\n- Be explicit about output format and constraints — leave no room to drift\n- Include negative instructions and failure handling, not just the happy path\n- Prefer clear structure over clever wording\n- Always provide edge-case probes so the prompt can be validated`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'knowledge',\n summary: 'Prompt engineering: designs/refines/evaluates LLM system prompts and agent instructions.',\n keywords: [\n 'prompt',\n 'prompt engineering',\n 'system prompt',\n 'llm instructions',\n 'few-shot',\n 'refine prompt',\n 'agent instructions',\n 'prompt template',\n ],\n },\n },\n];\n","import { type AgentDefinition, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 8 · Delivery & Ops — ship it, run it, keep it healthy. */\nexport const DELIVERY_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'git',\n name: 'Git',\n role: 'git',\n tools: [...TOOLS.vcs, 'bash'],\n prompt: `You are the Git agent. Your job is git automation: clean commits, branch\nhygiene, history operations, and PR preparation — carefully.\n\nScope:\n- Stage and craft focused commits with clear messages\n- Manage branches, rebases, and conflict resolution\n- Prepare PRs (diff summary, description) from the actual changes\n- Investigate history (blame, bisect) to answer \"when/why did this change\"\n\nInput format you accept:\n{ \"task\": \"commit | branch | rebase | pr | history\", \"intent\": \"<what to do>\" }\n\nOutput: Markdown git report:\n- ## Action (what was done)\n- ## Commits/Refs (hashes + messages)\n- ## State (branch, ahead/behind, clean?)\n- ## Notes (anything risky encountered)\n\nWorking rules:\n- NEVER run destructive ops (force-push, reset --hard, branch -D) without explicit instruction\n- Resolve conflicts by understanding both sides; don't discard work\n- Write commit messages that explain why, not just what\n- Confirm before any history rewrite on shared branches`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'delivery',\n summary: 'Git automation: focused commits, branch/rebase/conflict handling, PR prep, history investigation.',\n keywords: [\n 'git',\n 'commit',\n 'branch',\n 'rebase',\n 'merge',\n 'pull request',\n 'pr',\n 'conflict',\n 'blame',\n 'bisect',\n 'cherry-pick',\n 'stash',\n ],\n },\n },\n {\n config: {\n id: 'release',\n name: 'Release',\n role: 'release',\n tools: [...TOOLS.vcs, 'bash', 'json'],\n prompt: `You are the Release agent. Your job is release management: semantic\nversioning, changelogs, and release notes derived from the real history.\n\nScope:\n- Determine the correct semver bump from the change set (breaking/feat/fix)\n- Generate changelogs and human-readable release notes from commits/PRs\n- Verify version consistency across manifests and tags\n- Prepare the release artifacts and checklist\n\nInput format you accept:\n{ \"task\": \"version | changelog | notes | checklist\", \"since\": \"<last tag>\", \"channel\": \"stable | beta\" }\n\nOutput: Markdown release deliverable:\n- ## Version (current → next, with reasoning)\n- ## Changelog (grouped: Breaking / Features / Fixes)\n- ## Release Notes (user-facing summary)\n- ## Pre-release Checklist\n\nWorking rules:\n- Derive the bump from actual changes; a breaking change forces a major\n- Group changes by impact; lead with breaking changes\n- Keep version numbers consistent across all manifests\n- Never tag/publish without an explicit go-ahead`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'delivery',\n summary: 'Release management: semver bumps, changelogs, and release notes derived from real history.',\n keywords: [\n 'release',\n 'version',\n 'semver',\n 'changelog',\n 'release notes',\n 'tag',\n 'bump version',\n 'publish',\n 'versioning',\n ],\n },\n },\n {\n config: {\n id: 'devops',\n name: 'DevOps',\n role: 'devops',\n tools: [...TOOLS.build],\n prompt: `You are the DevOps agent. Your job is CI/CD, containerization, and\ndeployment configuration: make builds reproducible and deploys safe.\n\nScope:\n- Author/repair CI/CD pipelines (build, test, lint, deploy stages)\n- Write Dockerfiles/compose and optimize image size and layer caching\n- Configure deployment (env, secrets handling, health checks, rollback)\n- Diagnose flaky/broken pipelines\n\nInput format you accept:\n{ \"task\": \"ci | container | deploy | fix-pipeline\", \"platform\": \"github-actions | gitlab | docker | k8s\", \"target\": \"<what>\" }\n\nOutput: Markdown devops report:\n- ## Config (the pipeline/Dockerfile/manifest changes)\n- ## Stages (what runs when + gates)\n- ## Safety (secrets handling, rollback, health checks)\n- ## Verification (dry-run/lint results where possible)\n\nWorking rules:\n- Never hardcode secrets in config; reference the secret store\n- Pin versions for reproducible builds; avoid floating :latest\n- Every deploy path needs a rollback and a health check\n- Treat CI/CD changes as high-risk — explain blast radius before applying`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'delivery',\n summary: 'CI/CD, containerization, and deployment config: reproducible builds and safe deploys with rollback.',\n keywords: [\n 'devops',\n 'ci',\n 'cd',\n 'ci/cd',\n 'pipeline',\n 'docker',\n 'dockerfile',\n 'kubernetes',\n 'k8s',\n 'deploy',\n 'github actions',\n 'container',\n ],\n },\n },\n {\n config: {\n id: 'observability',\n name: 'Observability',\n role: 'observability',\n tools: [...TOOLS.build, 'logs'],\n prompt: `You are the Observability agent. Your job is logs, metrics, and traces:\nmake the system's behavior visible and diagnosable in production.\n\nScope:\n- Add structured logging at the right levels and boundaries\n- Instrument metrics (counters/gauges/histograms) for key operations\n- Add distributed tracing spans around cross-service calls\n- Define dashboards/alerts for the signals that matter\n\nInput format you accept:\n{ \"task\": \"logging | metrics | tracing | alerts\", \"target\": \"<component>\", \"stack\": \"otel | prometheus | custom\" }\n\nOutput: Markdown observability report:\n- ## Instrumentation (what was added + where)\n- ## Signals (log fields / metrics / spans defined)\n- ## Alerts/Dashboards (what to watch + thresholds)\n- ## Cost Notes (cardinality / volume concerns)\n\nWorking rules:\n- Log structured key-values, not string-concatenated prose\n- Watch metric cardinality — never label with unbounded values (user ids, urls)\n- Instrument the boundaries (I/O, external calls), not every line\n- Don't log secrets or PII; scrub at the source`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'delivery',\n summary: 'Observability: structured logging, metrics, distributed tracing, and alerts/dashboards.',\n keywords: [\n 'observability',\n 'logging',\n 'metrics',\n 'tracing',\n 'telemetry',\n 'opentelemetry',\n 'otel',\n 'prometheus',\n 'monitoring',\n 'alert',\n 'dashboard',\n 'instrument',\n ],\n },\n },\n {\n config: {\n id: 'dependency',\n name: 'Dependency',\n role: 'dependency',\n tools: [...TOOLS.deps, 'bash'],\n prompt: `You are the Dependency agent. Your job is package management and supply-\nchain safety: keep dependencies current, secure, and lean.\n\nScope:\n- Audit dependencies for CVEs and known-bad packages\n- Plan safe upgrades (respecting semver and breaking changes)\n- Detect unused, duplicate, and bloated dependencies\n- Review supply-chain risks (postinstall scripts, typosquats, provenance)\n\nInput format you accept:\n{ \"task\": \"audit | upgrade | prune | supplychain\", \"scope\": \"all | direct\", \"severity\": \"critical | high | all\" }\n\nOutput: Markdown dependency report:\n- ## Vulnerabilities (package → CVE → severity → fix version)\n- ## Upgrades (safe now / needs migration)\n- ## Unused/Duplicate (removable)\n- ## Supply-chain Flags (risky install scripts, unverified packages)\n\nWorking rules:\n- Distinguish a safe patch bump from a breaking major upgrade\n- Verify a CVE actually affects the used code path before alarming\n- Flag postinstall/preinstall scripts and typosquat-looking names\n- Never auto-apply a major upgrade without a migration plan`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'delivery',\n summary: 'Package management + supply-chain safety: CVE audit, safe upgrades, pruning, install-script review.',\n keywords: [\n 'dependency',\n 'dependencies',\n 'package',\n 'npm',\n 'pnpm',\n 'cve',\n 'vulnerability scan',\n 'upgrade deps',\n 'audit',\n 'supply chain',\n 'outdated',\n 'lockfile',\n ],\n },\n },\n];\n","import { type AgentDefinition, LIGHT_BUDGET, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 9 · Meta — agents that improve the agent system itself. */\nexport const META_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'skill-manage',\n name: 'Skill Manager',\n role: 'skill-manage',\n tools: [...TOOLS.write],\n prompt: `You are the Skill Manager agent. Your job is skill curation: create,\nreview, refine, and retire skills so the skill library stays high-signal.\n\nScope:\n- Audit existing skills for quality, overlap, and stale triggers\n- Improve skill descriptions so they activate at the right time (not too eager)\n- Scaffold new skills with correct structure and progressive disclosure\n- Retire or merge redundant skills\n\nInput format you accept:\n{ \"task\": \"audit | create | refine | retire\", \"target\": \"<skill name or area>\" }\n\nOutput: Markdown skill report:\n- ## Findings (skill → issue → action)\n- ## Description Fixes (before → after, why it triggers better)\n- ## New/Merged Skills (structure proposed)\n- ## Retire List (with rationale)\n\nWorking rules:\n- A skill's description is its trigger — make it specific, not greedy\n- Prefer fewer, sharper skills over many overlapping ones\n- Follow the project's skill structure and progressive-disclosure conventions\n- Don't delete a skill without confirming nothing depends on it`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'meta',\n summary: 'Skill curation: audits, refines descriptions/triggers, scaffolds, and retires skills.',\n keywords: [\n 'skill',\n 'skills',\n 'curate skill',\n 'skill description',\n 'create skill',\n 'skill library',\n 'skill trigger',\n 'manage skills',\n ],\n },\n },\n {\n config: {\n id: 'self-improving',\n name: 'Self-Improving',\n role: 'self-improving',\n tools: [...TOOLS.inspect],\n prompt: `You are the Self-Improving agent. Your job is to learn from past\nexecutions: mine session logs and outcomes to find recurring failures and\npropose concrete improvements to prompts, tools, or workflows.\n\nScope:\n- Analyze session/agent execution logs for failure and inefficiency patterns\n- Correlate outcomes with prompts, tool usage, and budgets\n- Propose specific changes (prompt edits, budget tweaks, new guardrails)\n- Track whether prior recommendations actually helped\n\nInput format you accept:\n{ \"task\": \"analyze | propose | evaluate\", \"logs\": \"<session path/dir>\", \"focus\": \"failures | efficiency | cost\" }\n\nOutput: Markdown improvement report:\n- ## Patterns (recurring failure/inefficiency + frequency)\n- ## Root Causes (why, with evidence from logs)\n- ## Proposed Changes (concrete edits, ranked by expected impact)\n- ## Validation Plan (how to confirm the change helped)\n\nWorking rules:\n- Ground every recommendation in observed log evidence, not intuition\n- Quantify the problem (how often, how costly) before proposing a fix\n- Propose the smallest change that addresses the root cause\n- Mark recommendations that need A/B validation before adoption`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'meta',\n summary: 'Learns from execution logs: mines recurring failures/inefficiencies and proposes evidence-based improvements.',\n keywords: [\n 'self-improving',\n 'learn from',\n 'session logs',\n 'execution analysis',\n 'recurring failure',\n 'improve agents',\n 'post-mortem',\n 'retrospective',\n 'meta-analysis',\n ],\n },\n },\n {\n config: {\n id: 'context',\n name: 'Context',\n role: 'context',\n tools: [...TOOLS.inspect, 'remember', 'forget'],\n prompt: `You are the Context agent. Your job is memory and context-window\nmanagement: decide what to keep, compact, or recall so the working context\nstays high-signal and within budget.\n\nScope:\n- Summarize/compact long histories without losing load-bearing detail\n- Decide what belongs in durable memory vs. ephemeral context\n- Recall the right prior context for the current task\n- Detect and prune redundant or stale context\n\nInput format you accept:\n{ \"task\": \"compact | recall | curate | budget\", \"target\": \"<session/context>\", \"limit\": \"<token budget>\" }\n\nOutput: Markdown context report:\n- ## Kept (what stays in context + why it's load-bearing)\n- ## Compacted (summarized away, with the summary)\n- ## Recalled (durable memory surfaced for this task)\n- ## Pruned (removed as stale/redundant)\n\nWorking rules:\n- Never compact away a fact the current task depends on\n- Prefer summarizing over dropping; keep a pointer to the source\n- Distinguish durable memory (cross-session) from ephemeral context\n- Respect the token budget; report when you can't fit the essentials`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'meta',\n summary: 'Memory + context-window management: compaction, recall, and curation within a token budget.',\n keywords: [\n 'context',\n 'context window',\n 'memory',\n 'compact',\n 'summarize history',\n 'recall',\n 'token budget',\n 'prune context',\n 'remember',\n 'dfmt',\n ],\n },\n },\n {\n config: {\n id: 'cost',\n name: 'Cost',\n role: 'cost',\n tools: [...TOOLS.inspect],\n prompt: `You are the Cost agent. Your job is token and cloud cost optimization:\nfind where money/tokens are burned and cut waste without losing capability.\n\nScope:\n- Analyze token spend by model, prompt, and tool usage\n- Identify expensive patterns: oversized prompts, redundant calls, wrong model tier\n- Recommend model routing (cheap model for cheap tasks, premium where it pays)\n- Estimate savings of each recommendation\n\nInput format you accept:\n{ \"task\": \"analyze | optimize | route | estimate\", \"scope\": \"<session/feature>\", \"lever\": \"tokens | model | calls\" }\n\nOutput: Markdown cost report:\n- ## Spend Breakdown (by model / prompt / tool)\n- ## Waste (the costly patterns, with $ impact)\n- ## Recommendations (ranked by savings, with risk)\n- ## Estimated Savings (per recommendation)\n\nWorking rules:\n- Quantify in tokens AND dollars; don't hand-wave \"it's expensive\"\n- Recommend the cheapest model that still meets the quality bar\n- Prefer caching and prompt trimming before downgrading models\n- Flag any optimization that risks correctness or capability`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'meta',\n summary: 'Token/cloud cost optimization: finds spend waste, recommends model routing and trimming with $ estimates.',\n keywords: [\n 'cost',\n 'token cost',\n 'optimize cost',\n 'spend',\n 'cheaper',\n 'model routing',\n 'budget',\n 'expensive',\n 'reduce tokens',\n 'pricing',\n 'cloud cost',\n ],\n },\n },\n];\n","/**\n * Agent catalog aggregator.\n *\n * Collects every phase's `AgentDefinition[]` into:\n * - `ALL_AGENT_DEFINITIONS` — flat list, catalog order (phase 1 → 9)\n * - `AGENT_CATALOG` — keyed by role for O(1) lookup\n * - `AGENTS_BY_PHASE` — grouped for statusline / dispatcher tie-breaks\n *\n * `fleet.ts` derives `FLEET_ROSTER` + `FLEET_ROSTER_BUDGETS` from this, and the\n * dispatcher routes free-form tasks against `capability` metadata here.\n */\nimport type { AgentDefinition, AgentPhase } from './types.js';\nimport { DISCOVERY_AGENTS } from './phase1-discovery.js';\nimport { PLANNING_AGENTS } from './phase2-planning.js';\nimport { BUILD_AGENTS } from './phase3-build.js';\nimport { VERIFY_AGENTS } from './phase4-verify.js';\nimport { REVIEW_AGENTS } from './phase5-review.js';\nimport { DOMAIN_AGENTS } from './phase6-domain.js';\nimport { KNOWLEDGE_AGENTS } from './phase7-knowledge.js';\nimport { DELIVERY_AGENTS } from './phase8-delivery.js';\nimport { META_AGENTS } from './phase9-meta.js';\n\nexport * from './types.js';\nexport {\n DISCOVERY_AGENTS,\n PLANNING_AGENTS,\n BUILD_AGENTS,\n VERIFY_AGENTS,\n REVIEW_AGENTS,\n DOMAIN_AGENTS,\n KNOWLEDGE_AGENTS,\n DELIVERY_AGENTS,\n META_AGENTS,\n};\n\n/** Every catalog agent, in phase order. */\nexport const ALL_AGENT_DEFINITIONS: AgentDefinition[] = [\n ...DISCOVERY_AGENTS,\n ...PLANNING_AGENTS,\n ...BUILD_AGENTS,\n ...VERIFY_AGENTS,\n ...REVIEW_AGENTS,\n ...DOMAIN_AGENTS,\n ...KNOWLEDGE_AGENTS,\n ...DELIVERY_AGENTS,\n ...META_AGENTS,\n];\n\n/** Phase → its agents, for grouped display and dispatcher fallbacks. */\nexport const AGENTS_BY_PHASE: Record<AgentPhase, AgentDefinition[]> = {\n discovery: DISCOVERY_AGENTS,\n planning: PLANNING_AGENTS,\n build: BUILD_AGENTS,\n verify: VERIFY_AGENTS,\n review: REVIEW_AGENTS,\n domain: DOMAIN_AGENTS,\n knowledge: KNOWLEDGE_AGENTS,\n delivery: DELIVERY_AGENTS,\n meta: META_AGENTS,\n};\n\n/**\n * Role → definition. Built once at module load. Throws on a duplicate role so\n * a copy-paste collision fails loudly at startup instead of silently shadowing.\n */\nexport const AGENT_CATALOG: Record<string, AgentDefinition> = (() => {\n const map: Record<string, AgentDefinition> = {};\n for (const def of ALL_AGENT_DEFINITIONS) {\n const role = def.config.role;\n if (!role) {\n throw new Error(`Agent \"${def.config.name}\" is missing a role`);\n }\n if (map[role]) {\n throw new Error(`Duplicate agent role in catalog: \"${role}\"`);\n }\n map[role] = def;\n }\n return map;\n})();\n\n/** Role lookup helper. Returns undefined for unknown roles. */\nexport function getAgentDefinition(role: string): AgentDefinition | undefined {\n return AGENT_CATALOG[role];\n}\n","/**\n * Smart agent dispatcher.\n *\n * Routes a free-form task description to the best agent in the catalog using a\n * two-stage strategy:\n *\n * 1. Heuristic — keyword/phrase scoring against each agent's `capability`\n * metadata. Deterministic, instant, no provider call. Multi-word phrases\n * score higher than single words (they're more specific signals).\n *\n * 2. LLM fallback — when the heuristic is ambiguous (confidence below the\n * threshold, or no keyword hit at all) an injected `classifier` resolves\n * the tie. The classifier is provider-agnostic: callers wire it to any\n * `complete(prompt) => text` function via `makeLLMClassifier`, so core\n * stays free of provider dependencies and the path is unit-testable.\n *\n * If neither stage yields a confident pick, the dispatcher falls back to the\n * `executor` generalist rather than failing.\n */\nimport {\n AGENT_CATALOG,\n ALL_AGENT_DEFINITIONS,\n type AgentDefinition,\n} from './agents/index.js';\n\n/** Default agent used when nothing else matches — the generalist builder. */\nexport const DEFAULT_DISPATCH_ROLE = 'executor';\n\nexport interface DispatchCandidate {\n role: string;\n name: string;\n score: number;\n /** Capability keywords that matched the task text. */\n matched: string[];\n}\n\nexport type DispatchMethod = 'heuristic' | 'llm' | 'fallback';\n\nexport interface DispatchResult {\n role: string;\n definition: AgentDefinition;\n /** 0..1 — heuristic margin, or 1 when an LLM made a definite choice. */\n confidence: number;\n method: DispatchMethod;\n /** Human-readable explanation of why this agent was chosen. */\n reason: string;\n /** Runner-up candidates (top heuristic scorers), best-first. */\n alternatives: DispatchCandidate[];\n}\n\n/**\n * Provider-agnostic classifier seam. Given the task and the candidate agents\n * (role + summary), return the chosen role (and optional reason), or null to\n * decline. Wire via `makeLLMClassifier`.\n */\nexport type DispatchClassifier = (\n task: string,\n candidates: { role: string; name: string; summary: string }[],\n) => Promise<{ role: string; reason?: string } | null>;\n\nexport interface DispatchOptions {\n /** Optional LLM fallback for ambiguous tasks. */\n classifier?: DispatchClassifier;\n /** Heuristic confidence below this triggers the classifier. Default 0.4. */\n confidenceThreshold?: number;\n /** How many top candidates to offer the classifier. Default 6. */\n maxCandidates?: number;\n /** Override the catalog (testing). Defaults to the full `AGENT_CATALOG`. */\n catalog?: Record<string, AgentDefinition>;\n}\n\nfunction normalize(text: string): string {\n return ` ${text.toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim()} `;\n}\n\n/**\n * Score every agent against the task. A keyword hit adds 1 point; a multi-word\n * keyword phrase adds points equal to its word count (more specific = stronger\n * signal). Returns candidates sorted best-first, zero-score agents dropped.\n */\nexport function scoreAgents(\n task: string,\n catalog: Record<string, AgentDefinition> = AGENT_CATALOG,\n): DispatchCandidate[] {\n const hay = normalize(task);\n const out: DispatchCandidate[] = [];\n for (const def of Object.values(catalog)) {\n if (!def?.config?.role) continue;\n let score = 0;\n const matched: string[] = [];\n for (const kw of def.capability.keywords) {\n const needle = normalize(kw);\n if (hay.includes(needle.trimEnd() + ' ') || hay.includes(' ' + needle.trimStart())) {\n const words = kw.trim().split(/\\s+/).length;\n score += words;\n matched.push(kw);\n }\n }\n if (score > 0) {\n out.push({ role: def.config.role, name: def.config.name, score, matched });\n }\n }\n out.sort((a, b) => b.score - a.score);\n return out;\n}\n\n/**\n * Heuristic confidence from the score distribution: the margin between the top\n * candidate and the runner-up, scaled by the top score's strength. A clear\n * winner (high top, low second) approaches 1; a near-tie approaches 0.\n */\nfunction heuristicConfidence(candidates: DispatchCandidate[]): number {\n if (candidates.length === 0) return 0;\n const top = candidates[0]!.score;\n const second = candidates[1]?.score ?? 0;\n // Strength factor: a single weak match (score 1) shouldn't read as confident.\n const strength = Math.min(1, top / 3);\n const margin = (top - second + 1) / (top + 1);\n return Math.min(1, strength * margin);\n}\n\n/**\n * Route a task to the best agent. Async because the LLM fallback may run; the\n * pure-heuristic path resolves without awaiting anything.\n */\nexport async function dispatchAgent(\n task: string,\n opts: DispatchOptions = {},\n): Promise<DispatchResult> {\n const catalog = opts.catalog ?? AGENT_CATALOG;\n const threshold = opts.confidenceThreshold ?? 0.4;\n const maxCandidates = opts.maxCandidates ?? 6;\n\n const candidates = scoreAgents(task, catalog);\n const confidence = heuristicConfidence(candidates);\n const top = candidates[0];\n\n // Confident heuristic pick — done, no provider call.\n if (top && confidence >= threshold) {\n return {\n role: top.role,\n definition: catalog[top.role]!,\n confidence,\n method: 'heuristic',\n reason: `Matched keywords: ${top.matched.slice(0, 4).join(', ')}`,\n alternatives: candidates.slice(1, maxCandidates),\n };\n }\n\n // Ambiguous or no signal — ask the classifier if one is wired.\n if (opts.classifier) {\n // Offer the classifier the top heuristic candidates; if there were none,\n // offer the whole catalog so it can still choose.\n const pool = (candidates.length > 0\n ? candidates.slice(0, maxCandidates).map((c) => catalog[c.role]!)\n : ALL_AGENT_DEFINITIONS\n ).map((d) => ({\n role: d.config.role as string,\n name: d.config.name,\n summary: d.capability.summary,\n }));\n try {\n const choice = await opts.classifier(task, pool);\n if (choice && catalog[choice.role]) {\n return {\n role: choice.role,\n definition: catalog[choice.role]!,\n confidence: 1,\n method: 'llm',\n reason: choice.reason ?? 'Selected by LLM classifier',\n alternatives: candidates.slice(0, maxCandidates).filter((c) => c.role !== choice.role),\n };\n }\n } catch {\n // Classifier failure must not break dispatch — fall through to fallback.\n }\n }\n\n // Best heuristic guess if we have one, else the generalist.\n if (top) {\n return {\n role: top.role,\n definition: catalog[top.role]!,\n confidence,\n method: 'heuristic',\n reason: `Weak match (${top.matched.slice(0, 3).join(', ') || 'low signal'})`,\n alternatives: candidates.slice(1, maxCandidates),\n };\n }\n const fallbackRole = catalog[DEFAULT_DISPATCH_ROLE]\n ? DEFAULT_DISPATCH_ROLE\n : Object.keys(catalog)[0]!;\n return {\n role: fallbackRole,\n definition: catalog[fallbackRole]!,\n confidence: 0,\n method: 'fallback',\n reason: 'No keyword signal; defaulting to the generalist Executor',\n alternatives: [],\n };\n}\n\n/**\n * Build a `DispatchClassifier` from a minimal `complete(prompt) => text`\n * function. The caller supplies the provider call; this owns the prompt and\n * the parsing. Keeps `dispatcher` free of any provider import.\n */\nexport function makeLLMClassifier(\n complete: (prompt: string) => Promise<string>,\n): DispatchClassifier {\n return async (task, candidates) => {\n const list = candidates.map((c, i) => `${i + 1}. ${c.role} — ${c.summary}`).join('\\n');\n const prompt = `You are an agent router. Pick the single best agent for the task.\n\nTask:\n${task}\n\nAgents:\n${list}\n\nReply with ONLY a compact JSON object: {\"role\":\"<one role id from the list>\",\"reason\":\"<short why>\"}.\nDo not add prose, markdown, or code fences.`;\n const raw = (await complete(prompt)).trim();\n // Tolerate accidental code fences / surrounding text — extract first {...}.\n const match = raw.match(/\\{[\\s\\S]*\\}/);\n if (!match) return null;\n try {\n const parsed = JSON.parse(match[0]) as { role?: unknown; reason?: unknown };\n if (typeof parsed.role !== 'string') return null;\n const role = parsed.role.trim();\n const valid = candidates.some((c) => c.role === role);\n if (!valid) return null;\n return { role, reason: typeof parsed.reason === 'string' ? parsed.reason : undefined };\n } catch {\n return null;\n }\n };\n}\n","import { randomUUID } from 'node:crypto';\nimport type { SubagentConfig, TaskSpec } from '../types/multi-agent.js';\nimport type { JSONSchema, Tool } from '../types/tool.js';\nimport { type Director, FleetSpawnBudgetError, FleetCostCapError } from './director.js';\nimport { dispatchAgent } from './dispatcher.js';\nimport type { AgentDefinition } from './agents/index.js';\nimport type { CollabSessionOptions } from './collab-debug.js';\n\n// ---------------------------------------------------------------------------\n// Director-facing tool factories.\n//\n// Each tool's input schema is intentionally minimal — the director model\n// reads the descriptions and gets clean structured shapes. We avoid deep\n// nested schemas because they confuse smaller models.\n\nexport function makeSpawnTool(director: Director, roster?: Record<string, SubagentConfig>): Tool {\n const inputSchema: JSONSchema = {\n type: 'object',\n properties: {\n role: { type: 'string', description: 'Roster role id. When set, the spawn uses the matching config from the roster and ignores other fields.' },\n description: { type: 'string', description: 'Free-form task description. When `role` is not set, the director uses the smart dispatcher to route this to the best-matching catalog agent. Use this when you don\\'t know the exact role name.' },\n name: { type: 'string', description: 'Display name for the subagent. Used as a fallback when description-based dispatch does not resolve a role.' },\n provider: { type: 'string', description: 'Provider id (e.g. \"anthropic\", \"openai\"). Defaults to the leader provider when omitted.' },\n model: { type: 'string', description: 'Model id within the provider. Defaults to the leader model when omitted.' },\n systemPromptOverride: { type: 'string', description: 'Extra prompt text appended after the role-base prompt.' },\n maxIterations: { type: 'number', minimum: 1 },\n maxToolCalls: { type: 'number', minimum: 1 },\n maxCostUsd: { type: 'number', minimum: 0 },\n timeoutMs: { type: 'number', minimum: 1, description: 'Hard wall-clock cap in milliseconds. Defaults to none (idle timeout is the default reaper).' },\n idleTimeoutMs: { type: 'number', minimum: 1, description: 'Idle timeout in ms: reap the subagent after this long with no activity. Resets on every iteration/tool call. Default is role/coordinator-specific.' },\n maxTokens: { type: 'number', minimum: 1, description: 'Maximum total tokens (input + output) the subagent may use.' },\n },\n required: [],\n };\n return {\n name: 'spawn_subagent',\n description: 'Create a new subagent under this director. Returns the subagent id.',\n usageHint: 'Pass `role` (matches the roster), `description` (smart dispatch to best agent), or `name` + `provider`/`model`. Returns `{ subagentId }`.',\n permission: 'auto',\n mutating: false,\n inputSchema,\n async execute(input: unknown) {\n const i = (input ?? {}) as Record<string, unknown>;\n const role = typeof i.role === 'string' ? i.role : undefined;\n const description = typeof i.description === 'string' ? i.description : undefined;\n\n // Resolve base config from roster, explicit role, or dispatch-by-description\n let cfg: SubagentConfig | undefined;\n\n if (role && roster) {\n const base = roster[role];\n if (!base) return { error: `unknown role \"${role}\". roster has: ${Object.keys(roster).join(', ')}` };\n cfg = instantiateRosterConfig(role, base);\n } else if (description && !role) {\n // Smart dispatch: route description to best catalog agent using dispatcher\n const dispatchResult = await dispatchAgent(description, {\n classifier: director.dispatchClassifier,\n catalog: roster as unknown as Record<string, AgentDefinition> | undefined,\n });\n const dispatchRole = dispatchResult.role;\n // If we have a matching roster entry for the dispatched role, use it\n if (roster?.[dispatchRole]) {\n cfg = instantiateRosterConfig(dispatchRole, roster[dispatchRole]!);\n } else {\n // Dispatch found a catalog agent but there's no roster entry — use the\n // catalog definition's config as a base template (role name + defaults).\n // We must not mutate the original definition, so spread it.\n const def = dispatchResult.definition;\n cfg = {\n name: def.config.name ?? dispatchRole,\n role: dispatchRole,\n provider: def.config.provider,\n model: def.config.model,\n };\n }\n }\n\n // Fall back to name-only config when neither role nor description dispatch resolved\n cfg ??= { name: (i.name as string) ?? 'subagent' };\n\n if (typeof i.name === 'string') cfg.name = i.name;\n if (typeof i.provider === 'string') cfg.provider = i.provider;\n if (typeof i.model === 'string') cfg.model = i.model;\n if (typeof i.systemPromptOverride === 'string') cfg.systemPromptOverride = i.systemPromptOverride;\n if (typeof i.maxIterations === 'number') cfg.maxIterations = i.maxIterations;\n if (typeof i.maxToolCalls === 'number') cfg.maxToolCalls = i.maxToolCalls;\n if (typeof i.maxCostUsd === 'number') cfg.maxCostUsd = i.maxCostUsd;\n if (typeof i.timeoutMs === 'number') cfg.timeoutMs = i.timeoutMs;\n if (typeof i.idleTimeoutMs === 'number') cfg.idleTimeoutMs = i.idleTimeoutMs;\n if (typeof i.maxTokens === 'number') cfg.maxTokens = i.maxTokens;\n try {\n const subagentId = await director.spawn(cfg);\n return { subagentId, provider: cfg.provider, model: cfg.model, name: cfg.name, role: cfg.role };\n } catch (err) {\n if (err instanceof FleetSpawnBudgetError) {\n return { error: err.message, kind: err.kind, limit: err.limit, observed: err.observed };\n }\n if (err instanceof FleetCostCapError) {\n return { error: err.message, kind: err.kind, limit: err.limit, observed: err.observed };\n }\n return { error: err instanceof Error ? err.message : String(err) };\n }\n },\n };\n}\n\nfunction instantiateRosterConfig(role: string, base: SubagentConfig): SubagentConfig {\n return {\n ...base,\n // Roster entries are templates. A director may spawn several\n // workers with the same role, so never reuse the template id.\n id: `${role}-${randomUUID().slice(0, 8)}`,\n };\n}\n\nexport function makeAssignTool(director: Director): Tool {\n const inputSchema: JSONSchema = {\n type: 'object',\n properties: {\n subagentId: { type: 'string', minLength: 1, description: 'Target subagent id. Required.' },\n description: { type: 'string', minLength: 1, description: 'The task in natural language — what you want this subagent to do.' },\n maxToolCalls: { type: 'number', minimum: 1, description: 'Optional per-task tool-call budget override.' },\n timeoutMs: { type: 'number', minimum: 1, description: 'Optional per-task timeout in ms.' },\n },\n required: ['subagentId', 'description'],\n };\n return {\n name: 'assign_task',\n description: 'Hand a task to a previously spawned subagent. Returns the task id.',\n permission: 'auto',\n mutating: false,\n inputSchema,\n async execute(input: unknown) {\n const i = input as { subagentId: string; description: string; maxToolCalls?: number; timeoutMs?: number };\n const task: TaskSpec = { id: randomUUID(), description: i.description, subagentId: i.subagentId, maxToolCalls: i.maxToolCalls, timeoutMs: i.timeoutMs };\n const taskId = await director.assign(task);\n return { taskId, subagentId: i.subagentId };\n },\n };\n}\n\nexport function makeAwaitTasksTool(director: Director): Tool {\n return {\n name: 'await_tasks',\n description: 'Block until every named task completes. Returns the array of TaskResult.',\n permission: 'auto',\n mutating: false,\n inputSchema: { type: 'object', properties: { taskIds: { type: 'array', items: { type: 'string' }, description: 'One or more task ids returned by `assign_task`.' } }, required: ['taskIds'] },\n async execute(input: unknown) {\n const i = input as { taskIds: string[] };\n const results = await director.awaitTasks(i.taskIds);\n return { results };\n },\n };\n}\n\nexport function makeAskTool(director: Director): Tool {\n return {\n name: 'ask_subagent',\n description: 'Synchronously ask a subagent a question. Blocks until the subagent replies via the bridge.',\n permission: 'auto',\n mutating: false,\n inputSchema: {\n type: 'object',\n properties: {\n subagentId: { type: 'string', minLength: 1, description: 'Subagent to ask. Must be a previously spawned id.' },\n question: { type: 'string', minLength: 1, description: 'The question or instruction.' },\n timeoutMs: { type: 'number', minimum: 1, description: 'Optional timeout in ms (default 30s).' },\n },\n required: ['subagentId', 'question'],\n },\n async execute(input: unknown) {\n const i = input as { subagentId: string; question: string; timeoutMs?: number };\n try {\n const answer = await director.ask(i.subagentId, { question: i.question }, i.timeoutMs);\n // Store large answers out-of-band; return only a summary string in ctx.\n const stored = director.largeAnswerStore.storeAnswer(answer);\n if (stored.inline) {\n return { ok: true, answer: stored.summary };\n }\n return {\n ok: true,\n answer: stored.summary,\n _answerKey: stored.key,\n _hint: 'Response was large and stored. Use ask_result with the key to retrieve it.',\n };\n } catch (err) {\n return { ok: false, error: err instanceof Error ? err.message : String(err) };\n }\n },\n };\n}\n\n/**\n * Retrieve a previously stored `ask_subagent` answer by its store key.\n * The key was returned as `_answerKey` in the ask_subagent response.\n * Use this only for large responses that were stored out-of-context.\n */\nexport function makeAskResultTool(director: Director): Tool {\n return {\n name: 'ask_result',\n description: 'Retrieve a large `ask_subagent` response that was stored out-of-context (>2K chars). Returns the full stored value.',\n permission: 'auto',\n mutating: false,\n inputSchema: {\n type: 'object',\n properties: {\n key: {\n type: 'string',\n minLength: 1,\n description: 'The `_answerKey` returned by `ask_subagent` for a large response.',\n },\n },\n required: ['key'],\n },\n async execute(input: unknown) {\n const i = input as { key: string };\n const value = director.largeAnswerStore.retrieveAnswer(i.key);\n if (value === undefined) {\n return { ok: false, error: `No stored answer found for key \"${i.key}\" — it may have been cleared or the key is invalid.` };\n }\n return { ok: true, value };\n },\n };\n}\n\nexport function makeRollUpTool(director: Director): Tool {\n return {\n name: 'roll_up',\n description: \"Aggregate completed task results into a single formatted summary.\",\n permission: 'auto',\n mutating: false,\n inputSchema: {\n type: 'object',\n properties: {\n taskIds: { type: 'array', items: { type: 'string' }, description: 'Completed task ids to aggregate.' },\n style: { type: 'string', enum: ['markdown', 'json'], description: 'Output flavor — markdown (default) or json.' },\n },\n required: ['taskIds'],\n },\n async execute(input: unknown) {\n const i = input as { taskIds: string[]; style?: 'markdown' | 'json' };\n const summary = director.rollUp(i.taskIds, i.style ?? 'markdown');\n return { summary, count: i.taskIds.length };\n },\n };\n}\n\nexport function makeTerminateTool(director: Director): Tool {\n return {\n name: 'terminate_subagent',\n description: 'Forcibly abort a subagent. The subagent finishes its current iteration then exits with status \"stopped\".',\n permission: 'auto',\n mutating: true,\n inputSchema: { type: 'object', properties: { subagentId: { type: 'string', description: 'Subagent to abort.' } }, required: ['subagentId'] },\n async execute(input: unknown) {\n const i = input as { subagentId: string };\n await director.terminate(i.subagentId);\n return { ok: true };\n },\n };\n}\n\nexport function makeTerminateAllTool(director: Director): Tool {\n return {\n name: 'terminate_all',\n description:\n 'Forcibly stop every subagent in the fleet and drain the pending task queue. ' +\n 'In-flight tasks are terminated mid-execution; pending tasks receive ' +\n '\"aborted_by_parent\" completion immediately. ' +\n 'Use this when the fleet is wedged, looping, or you need a clean slate. ' +\n 'Compare: work_complete stops spawning but lets running agents finish naturally.',\n permission: 'auto',\n mutating: true,\n inputSchema: { type: 'object', properties: {}, required: [] },\n async execute() {\n await director.terminateAll();\n return { ok: true, message: `Fleet shutdown complete — all subagents stopped, pending tasks drained.` };\n },\n };\n}\n\nexport function makeFleetStatusTool(director: Director): Tool {\n return {\n name: 'fleet_status',\n description: \"Snapshot of the fleet — every subagent's current status, coordinator counts (total/running/idle/stopped), pending task descriptions, and usage rollup.\",\n permission: 'auto',\n mutating: false,\n inputSchema: { type: 'object', properties: {}, required: [] },\n async execute() {\n const base = director.status();\n const fm = director.fleetManager;\n const stats = fm?.getFleetStats();\n const fleetStatus = fm?.getFleetStatus();\n return {\n subagents: base.subagents,\n coordinatorStats: stats\n ? { total: stats.total, running: stats.running, idle: stats.idle, stopped: stats.stopped }\n : undefined,\n pending: fleetStatus?.pending ?? [],\n usage: fm?.snapshot(),\n };\n },\n };\n}\n\nexport function makeFleetUsageTool(director: Director): Tool {\n return {\n name: 'fleet_usage',\n description: 'Token + cost breakdown across the fleet, per-subagent and totals.',\n permission: 'auto',\n mutating: false,\n inputSchema: { type: 'object', properties: {}, required: [] },\n async execute() { return director.snapshot(); },\n };\n}\n\n/**\n * Read a subagent's JSONL transcript and return the last assistant text,\n * stop reason, and tool-use count. The director can call this on a\n * running or timed-out subagent to see what it actually produced without\n * having to wait for natural completion.\n */\nexport function makeFleetSessionTool(director: Director): Tool {\n return {\n name: 'fleet_session',\n description:\n 'Read a subagent\\'s JSONL transcript and extract its last assistant text, stop reason, and tool-use count. Use this to see what a running or timed-out subagent actually produced.',\n permission: 'auto',\n mutating: false,\n inputSchema: {\n type: 'object',\n properties: {\n subagentId: { type: 'string', description: 'Subagent id to read the transcript of.' },\n tail: { type: 'number', description: 'Number of trailing JSONL lines to return. Omit for the full transcript.' },\n },\n required: ['subagentId'],\n },\n async execute(input: unknown) {\n const i = input as { subagentId: string; tail?: number };\n const result = await director.readSession(i.subagentId, i.tail);\n if (!result) {\n return {\n error: `fleet_session: transcript unavailable for \"${i.subagentId}\". Is sessionsRoot configured?`,\n };\n }\n return result;\n },\n };\n}\n\n/**\n * Health snapshot per subagent — budget pressure (how close to limits),\n * last activity timestamp, and current status. Lets the director make\n * smarter routing decisions without having to call fleet_usage + fleet_status separately.\n */\nexport function makeFleetHealthTool(director: Director): Tool {\n return {\n name: 'fleet_health',\n description:\n 'Per-subagent health report: budget pressure (pct of limits consumed), last activity timestamp, and current status. Use to decide whether to assign more work to a subagent or spawn a fresh one.',\n permission: 'auto',\n mutating: false,\n inputSchema: { type: 'object', properties: {}, required: [] },\n async execute() {\n const status = director.status();\n const snapshot = director.snapshot();\n const subagents = status.subagents ?? [];\n const perSubagent = snapshot.perSubagent ?? {};\n return {\n subagents: subagents.map((s) => {\n const usage = perSubagent[s.id];\n return {\n id: s.id,\n status: s.status,\n lastEventAt: usage?.lastEventAt,\n budgetPressure: {\n iterations: usage?.iterations,\n toolCalls: usage?.toolCalls,\n costUsd: usage?.cost,\n },\n };\n }),\n };\n },\n };\n}\n\n/**\n * Collaborative debugging session: BugHunter, RefactorPlanner, and Critic\n * run in parallel on the same target files, with findings flowing through\n * the FleetBus (bug.found → refactor.plan → critic.evaluation).\n *\n * Returns a structured CollabDebugReport containing all bug findings,\n * refactor plans, critic evaluations, and an overall verdict.\n */\nexport function makeCollabDebugTool(director: Director): Tool {\n return {\n name: 'collab_debug',\n description:\n 'Start a collaborative debugging session: BugHunter, RefactorPlanner, and Critic ' +\n 'run in parallel on the same target files. BugHunter finds bugs and emits bug.found events. ' +\n 'RefactorPlanner listens for bug.found and emits refactor.plan events. ' +\n 'Critic evaluates both and emits critic.evaluation events. ' +\n 'Returns a structured report with overall verdict (approve / needs_revision / reject).',\n permission: 'auto',\n mutating: false,\n inputSchema: {\n type: 'object',\n properties: {\n targetPaths: {\n type: 'array',\n items: { type: 'string' },\n description: 'File paths / glob patterns to scan for bugs.',\n },\n timeoutMs: {\n type: 'number',\n minimum: 1,\n description: 'Timeout in ms. Default: 600000 (10 minutes).',\n },\n maxTargetFiles: {\n type: 'number',\n minimum: 1,\n description:\n 'Maximum number of files to include in the snapshot. ' +\n 'If not set, the limit is computed dynamically from contextWindow ' +\n 'or falls back to the default (30).',\n },\n contextWindow: {\n type: 'number',\n minimum: 1,\n description:\n 'Context window size (tokens) of the model. When provided and ' +\n 'maxTargetFiles is not set, the file limit is computed dynamically ' +\n 'as floor((contextWindow * 0.4) / 2000).',\n },\n },\n required: ['targetPaths'],\n },\n async execute(input: unknown) {\n const i = input as { targetPaths?: string[]; timeoutMs?: number; maxTargetFiles?: number; contextWindow?: number };\n if (!i.targetPaths?.length) {\n return { error: 'collab_debug: targetPaths is required and must be non-empty.' };\n }\n const options: CollabSessionOptions = {\n targetPaths: i.targetPaths,\n timeoutMs: i.timeoutMs,\n maxTargetFiles: i.maxTargetFiles,\n contextWindow: i.contextWindow,\n };\n try {\n const report = await director.spawnCollab(options);\n return {\n sessionId: report.sessionId,\n overallVerdict: report.overallVerdict,\n bugCount: report.bugs.length,\n planCount: report.refactorPlans.length,\n evaluationCount: report.evaluations.length,\n summary: report.summary,\n bugs: report.bugs,\n refactorPlans: report.refactorPlans,\n evaluations: report.evaluations,\n };\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n return { error: 'collab_debug failed: ' + msg };\n }\n },\n };\n}\n\n/**\n * Tool for subagents to emit structured events on the FleetBus.\n * Any agent can emit any event type; the Director routes it to all listeners.\n * Common event types in collaborative sessions:\n * bug.found — BugHunter emits per-finding\n * refactor.plan — RefactorPlanner emits per-plan\n * critic.evaluation — Critic emits per-evaluation\n *\n * The payload structure is event-type-specific. Use null for empty payloads.\n */\nexport function makeFleetEmitTool(director: Director): Tool {\n return {\n name: 'fleet_emit',\n description:\n 'Emit a structured event on the FleetBus. Any subagent can emit any event type; the Director routes it to all listeners. Use it to stream findings, progress updates, or final results to other agents in real time.',\n permission: 'auto',\n mutating: false,\n inputSchema: {\n type: 'object',\n properties: {\n type: {\n type: 'string',\n description: 'Event type string (e.g. bug.found, refactor.plan, critic.evaluation, progress, result).',\n },\n payload: {\n type: 'object',\n description: 'Event payload. Structure depends on event type. Use null if no payload.',\n },\n },\n required: ['type'],\n },\n async execute(input: unknown) {\n const i = input as { type: string; payload?: Record<string, unknown> | null };\n director.fleet.emit({\n subagentId: director.id,\n ts: Date.now(),\n type: i.type,\n payload: i.payload ?? {},\n });\n return { ok: true, event: i.type };\n },\n };\n}\n\n/**\n * Signal that the director's work is satisfied and the fleet should wind down.\n *\n * Once called:\n * - `spawn_subagent` throws — no new subagents can be created\n * - `assign_task` synthesizes an immediate `aborted_by_parent` completion\n * for any queued task (callers awaiting those tasks unblock immediately)\n * - Running subagents are NOT killed — they finish naturally; no new\n * tasks are dispatched to them\n *\n * Use this when you are satisfied with the results and want the fleet to\n * stop spawning without forcibly stopping in-flight work. Call\n * `terminate_subagent` separately for any subagent you need to stop immediately.\n */\nexport function makeWorkCompleteTool(director: Director): Tool {\n return {\n name: 'work_complete',\n description:\n \"Signal that the director is satisfied with the results and the fleet should wind down. \" +\n \"After calling this, spawn_subagent will refuse with a budget error and assign_task \" +\n \"will instantly complete any queued tasks as aborted. Running subagents finish naturally. \" +\n \"Call terminate_subagent separately to stop specific subagents immediately.\",\n permission: 'auto',\n mutating: false,\n inputSchema: { type: 'object', properties: {}, required: [] },\n async execute() {\n director.workComplete();\n return { ok: true, message: 'Fleet wind-down signaled. No new spawns or task dispatches.' };\n },\n };\n}\n","import type { EventBus } from '../kernel/events.js';\r\n\r\n/**\r\n * Single fleet-wide event with subagent attribution. Whatever a child\r\n * agent emits on its own EventBus gets re-published here, prefixed with\r\n * `subagentId` so a single subscriber can multiplex across the fleet.\r\n *\r\n * The director uses `FleetBus.filter('tool.executed', …)` to see every\r\n * tool call across the fleet; the TUI uses\r\n * `FleetBus.subscribe(id, handler)` to render a per-subagent panel.\r\n */\r\nexport interface FleetEvent {\r\n subagentId: string;\r\n taskId?: string;\r\n ts: number;\r\n type: string;\r\n payload: unknown;\r\n}\r\n\r\nexport type FleetHandler = (event: FleetEvent) => void;\r\n\r\n/**\r\n * Fan-in for per-subagent EventBuses. Each subagent's bus is plugged in\r\n * via `attach()`; the FleetBus re-emits every event with subagent\r\n * attribution. Detachment is automatic via the returned disposer — call\r\n * it when a subagent terminates so we don't leak listeners.\r\n *\r\n * The bus exposes two subscription modes: by `subagentId` (everything\r\n * from one child) and by `type` (one event-type across the fleet). They\r\n * compose — if you need a per-subagent + per-type slice, subscribe by\r\n * type and filter on `event.subagentId` in your handler.\r\n */\r\nexport class FleetBus {\r\n private readonly byId = new Map<string, Set<FleetHandler>>();\r\n private readonly byType = new Map<string, Set<FleetHandler>>();\r\n private readonly any = new Set<FleetHandler>();\r\n\r\n /**\r\n * Hook a subagent's EventBus into the fleet. Uses `onAny()` (an alias for\r\n * `onPattern('*')`) to forward all events with subagent attribution, so\r\n * new kernel event types are automatically forwarded without any manual\r\n * registration. `subagent.*` events are excluded because they originate\r\n * from MultiAgentHost on the parent bus, not the subagent's own bus.\r\n *\r\n * Returns a disposer that detaches every subscription; call on\r\n * subagent teardown so the listeners don't outlive the run.\r\n */\r\n attach(subagentId: string, bus: EventBus, taskId?: string): () => void {\r\n // Subscribe to every event on the subagent's EventBus and re-emit with\r\n // attribution via the onAny() alias for onPattern('*'). The payload is\r\n // typed as `unknown` in the FleetEvent — use the type guard in the\r\n // handler to narrow it.\r\n //\r\n // Skip subagent lifecycle events (subagent.*) — those are emitted by\r\n // MultiAgentHost on the parent EventBus, not on the subagent's own bus.\r\n // Forwarding them would create duplicate fleet events for the same logical\r\n // occurrence. Use the parent EventBus path (events.on('subagent.*')) for\r\n // lifecycle events instead.\r\n const off = bus.onAny((type, payload) => {\r\n if (type.startsWith('subagent.')) return;\r\n this.emit({ subagentId, taskId, ts: Date.now(), type, payload });\r\n });\r\n\r\n return () => {\r\n off();\r\n };\r\n }\r\n\r\n /** Subscribe to every event from one subagent. */\r\n subscribe(subagentId: string, handler: FleetHandler): () => void {\r\n let set = this.byId.get(subagentId);\r\n if (!set) {\r\n set = new Set();\r\n this.byId.set(subagentId, set);\r\n }\r\n set.add(handler);\r\n return () => {\r\n set!.delete(handler);\r\n };\r\n }\r\n\r\n /** Subscribe to one event type across all subagents. */\r\n filter(type: string, handler: FleetHandler): () => void {\r\n let set = this.byType.get(type);\r\n if (!set) {\r\n set = new Set();\r\n this.byType.set(type, set);\r\n }\r\n set.add(handler);\r\n return () => {\r\n set!.delete(handler);\r\n };\r\n }\r\n\r\n /** Subscribe to literally everything. The fleet roll-up uses this. */\r\n onAny(handler: FleetHandler): () => void {\r\n this.any.add(handler);\r\n return () => {\r\n this.any.delete(handler);\r\n };\r\n }\r\n\r\n emit(event: FleetEvent): void {\r\n // Each fan-out is best-effort — a misbehaving handler must not\r\n // bring down the bus or other handlers. Errors are swallowed\r\n // (matching the rest of the project's listener-error policy).\r\n const byId = this.byId.get(event.subagentId);\r\n if (byId)\r\n for (const h of byId) {\r\n try {\r\n h(event);\r\n } catch {\r\n /* ignore */\r\n }\r\n }\r\n const byType = this.byType.get(event.type);\r\n if (byType)\r\n for (const h of byType) {\r\n try {\r\n h(event);\r\n } catch {\r\n /* ignore */\r\n }\r\n }\r\n for (const h of this.any) {\r\n try {\r\n h(event);\r\n } catch {\r\n /* ignore */\r\n }\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Roll-up of token usage + cost across an entire director run. The\r\n * director's `fleet_status` tool returns this so the model can reason\r\n * about budget in its next turn (\"the researcher already burned $0.40,\r\n * lean on summaries for the next task\").\r\n */\r\nexport interface FleetUsage {\r\n total: {\r\n input: number;\r\n output: number;\r\n cacheRead: number;\r\n cacheWrite: number;\r\n cost: number;\r\n };\r\n perSubagent: Record<string, SubagentUsageSnapshot>;\r\n}\r\n\r\nexport interface SubagentUsageSnapshot {\r\n subagentId: string;\r\n provider?: string;\r\n model?: string;\r\n input: number;\r\n output: number;\r\n cacheRead: number;\r\n cacheWrite: number;\r\n cost: number;\r\n toolCalls: number;\r\n iterations: number;\r\n startedAt: number;\r\n lastEventAt: number;\r\n}\r\n\r\n/**\r\n * Aggregates provider.response + tool.executed events from the FleetBus\r\n * into a live `FleetUsage` snapshot. Costs are computed by the caller\r\n * via a `priceLookup(subagentId)` so we don't bake provider-pricing\r\n * coupling into core; the CLI/tests supply a function that resolves\r\n * each subagent's per-token rates from the models registry.\r\n */\r\nexport class FleetUsageAggregator {\r\n private readonly perSubagent = new Map<string, SubagentUsageSnapshot>();\r\n private readonly total = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };\r\n private readonly unsub = new Array<() => void>();\r\n\r\n constructor(\r\n bus: FleetBus,\r\n private readonly priceLookup?: (\r\n subagentId: string,\r\n provider?: string,\r\n model?: string,\r\n ) => { input?: number; output?: number; cacheRead?: number; cacheWrite?: number } | undefined,\r\n private readonly metaLookup?: (\r\n subagentId: string,\r\n ) => { provider?: string; model?: string } | undefined,\r\n ) {\r\n this.unsub.push(bus.filter('provider.response', (e) => this.onProviderResponse(e)));\r\n this.unsub.push(bus.filter('tool.executed', (e) => this.onToolExecuted(e)));\r\n this.unsub.push(bus.filter('iteration.started', (e) => this.onIterationStarted(e)));\r\n }\r\n\r\n /**\r\n * Remove a terminated subagent's data from the aggregator and subtract its\r\n * contribution from the running totals. Call this when a subagent is removed\r\n * from the fleet so the aggregator doesn't accumulate unbounded data for\r\n * entities that will never emit events again.\r\n */\r\n removeSubagent(subagentId: string): void {\r\n const snap = this.perSubagent.get(subagentId);\r\n if (!snap) return;\r\n this.perSubagent.delete(subagentId);\r\n this.total.input -= snap.input;\r\n this.total.output -= snap.output;\r\n this.total.cacheRead -= snap.cacheRead;\r\n this.total.cacheWrite -= snap.cacheWrite;\r\n this.total.cost -= snap.cost;\r\n }\r\n\r\n /** Disposes all fleet-bus subscriptions. Call when the aggregator is no longer needed. */\r\n dispose(): void {\r\n for (const off of this.unsub) off();\r\n this.unsub.length = 0;\r\n }\r\n\r\n /** Live snapshot — safe to call from a tool's execute() body. */\r\n snapshot(): FleetUsage {\r\n return {\r\n total: { ...this.total },\r\n perSubagent: Object.fromEntries(\r\n Array.from(this.perSubagent.entries()).map(([k, v]) => [k, { ...v }]),\r\n ),\r\n };\r\n }\r\n\r\n private ensure(subagentId: string): SubagentUsageSnapshot {\r\n let snap = this.perSubagent.get(subagentId);\r\n if (!snap) {\r\n const meta = this.metaLookup?.(subagentId);\r\n snap = {\r\n subagentId,\r\n provider: meta?.provider,\r\n model: meta?.model,\r\n input: 0,\r\n output: 0,\r\n cacheRead: 0,\r\n cacheWrite: 0,\r\n cost: 0,\r\n toolCalls: 0,\r\n iterations: 0,\r\n startedAt: Date.now(),\r\n lastEventAt: Date.now(),\r\n };\r\n this.perSubagent.set(subagentId, snap);\r\n }\r\n return snap;\r\n }\r\n\r\n private onProviderResponse(e: FleetEvent): void {\r\n const snap = this.ensure(e.subagentId);\r\n const p = e.payload as {\r\n usage?: { input?: number; output?: number; cacheRead?: number; cacheWrite?: number };\r\n };\r\n const usage = p?.usage;\r\n if (!usage) return;\r\n snap.input += usage.input ?? 0;\r\n snap.output += usage.output ?? 0;\r\n snap.cacheRead += usage.cacheRead ?? 0;\r\n snap.cacheWrite += usage.cacheWrite ?? 0;\r\n this.total.input += usage.input ?? 0;\r\n this.total.output += usage.output ?? 0;\r\n this.total.cacheRead += usage.cacheRead ?? 0;\r\n this.total.cacheWrite += usage.cacheWrite ?? 0;\r\n const price = this.priceLookup?.(e.subagentId, snap.provider, snap.model);\r\n if (price) {\r\n const delta =\r\n ((usage.input ?? 0) / 1_000_000) * (price.input ?? 0) +\r\n ((usage.output ?? 0) / 1_000_000) * (price.output ?? 0) +\r\n ((usage.cacheRead ?? 0) / 1_000_000) * (price.cacheRead ?? 0) +\r\n ((usage.cacheWrite ?? 0) / 1_000_000) * (price.cacheWrite ?? 0);\r\n snap.cost += delta;\r\n this.total.cost += delta;\r\n }\r\n snap.lastEventAt = e.ts;\r\n }\r\n\r\n private onToolExecuted(e: FleetEvent): void {\r\n const snap = this.ensure(e.subagentId);\r\n snap.toolCalls += 1;\r\n snap.lastEventAt = e.ts;\r\n }\r\n\r\n private onIterationStarted(e: FleetEvent): void {\r\n const snap = this.ensure(e.subagentId);\r\n snap.iterations += 1;\r\n snap.lastEventAt = e.ts;\r\n }\r\n}\r\n","/**\n * LargeAnswerStore — prevents `ask_subagent` results from bloating the\n * director's context window.\n *\n * Problem: `ask_subagent` returns full subagent responses as tool_result\n * content. A single response can be 10-50K+ tokens. When the director\n * calls `ask` multiple times, these accumulate in ctx.messages and can\n * push context pressure past 100%, causing provider overflow errors or\n * silent quality degradation.\n *\n * Solution: responses above `sizeThreshold` chars are stored here\n * (in-memory Map keyed by stable id). The tool result returns only a\n * compact summary + the store key. Callers retrieve the full result\n * via `retrieveAnswer(key)` when they need it.\n *\n * The store is scoped to a single Director.run() lifecycle.\n * It is NOT persisted — if the process crashes the results are lost,\n * which is acceptable since the subagent already finished and the\n * summary is in context.\n */\n\nexport interface AnswerEntry {\n key: string;\n value: unknown;\n size: number;\n storedAt: number;\n}\n\nexport class LargeAnswerStore {\n /**\n * Responses above this size (in characters) are stored out-of-context.\n * Below this, the full answer is returned inline (no overhead).\n * Default: 2000 chars ≈ 400-600 tokens.\n */\n readonly sizeThreshold: number;\n\n private readonly store = new Map<string, AnswerEntry>();\n\n constructor(sizeThreshold = 2000) {\n this.sizeThreshold = sizeThreshold;\n }\n\n /**\n * Store a value, returning a summary + key for inline use.\n * If the value is below sizeThreshold, returns it as-is (no store entry).\n */\n storeAnswer(value: unknown): { key?: string; summary: string; inline: boolean } {\n if (value === undefined || value === null) {\n return { summary: String(value), inline: true };\n }\n\n const serialized = typeof value === 'string' ? value : JSON.stringify(value);\n const size = serialized.length;\n\n if (size <= this.sizeThreshold) {\n return { summary: serialized.slice(0, 500), inline: true };\n }\n\n // Stable key derived from content hash — same value always gets same key\n // within this store's lifetime.\n const key = `a-${hashStr(serialized)}`;\n\n this.store.set(key, {\n key,\n value,\n size,\n storedAt: Date.now(),\n });\n\n return {\n key,\n summary: `[stored: ${size} chars — use roll_up or ask_result tool to retrieve, key=${key}]`,\n inline: false,\n };\n }\n\n /**\n * Retrieve a previously stored answer by its key.\n * Returns undefined if the key is unknown or the store was cleared.\n */\n retrieveAnswer(key: string): unknown | undefined {\n return this.store.get(key)?.value;\n }\n\n /**\n * Check if a key exists in the store.\n */\n hasAnswer(key: string): boolean {\n return this.store.has(key);\n }\n\n /** Number of stored entries. */\n get size(): number {\n return this.store.size;\n }\n\n /** Total characters stored. */\n get totalChars(): number {\n let total = 0;\n for (const e of this.store.values()) total += e.size;\n return total;\n }\n\n /** Clear all stored entries. Call at the end of a director run. */\n clear(): void {\n this.store.clear();\n }\n}\n\n/** Fast string hash for stable key derivation. Not cryptographic. */\nfunction hashStr(s: string): string {\n let h = 5381;\n for (let i = 0; i < s.length; i++) {\n h = (h * 33) ^ s.charCodeAt(i);\n }\n return (h >>> 0).toString(36);\n}\n","/**\n * Per-task model matrix resolution.\n *\n * The matrix (Config.modelMatrix) maps a catalog **role**, a **phase** name, or\n * the `*` default to a {@link ModelMatrixEntry} (model + optional provider).\n * At subagent spawn time we resolve the most specific match so different task\n * types can run on different models — e.g. `security-scanner` on one model,\n * `documentation` on another — while the leader keeps its own model.\n *\n * Resolution precedence (most → least specific):\n * 1. exact role (matrix[\"security-scanner\"])\n * 2. the role's phase (matrix[\"review\"])\n * 3. the `*` default (matrix[\"*\"])\n * 4. undefined (caller falls back to the leader model)\n *\n * Set via the `/setmodel` slash command; this module is the single source of\n * truth both that command and the spawn path use to validate + resolve keys.\n */\nimport type { ModelMatrixEntry } from '../types/config.js';\nimport { AGENTS_BY_PHASE, AGENT_CATALOG } from './agents/index.js';\n\n/** All valid phase keys, in catalog order. */\nexport const MATRIX_PHASE_KEYS: readonly string[] = Object.keys(AGENTS_BY_PHASE);\n\n/** Role → phase lookup, built once from the catalog. */\nconst ROLE_TO_PHASE: Record<string, string> = (() => {\n const map: Record<string, string> = {};\n for (const [phase, defs] of Object.entries(AGENTS_BY_PHASE)) {\n for (const def of defs) {\n const role = def.config.role;\n if (role) map[role] = phase;\n }\n }\n return map;\n})();\n\n/** The phase a catalog role belongs to, or undefined for unknown roles. */\nexport function phaseForRole(role: string | undefined): string | undefined {\n return role ? ROLE_TO_PHASE[role] : undefined;\n}\n\n/**\n * Resolve the matrix entry for a subagent role. Returns the most specific\n * match (role → phase → `*`), or undefined when nothing matches.\n */\nexport function resolveModelMatrix(\n matrix: Record<string, ModelMatrixEntry> | undefined,\n role: string | undefined,\n): ModelMatrixEntry | undefined {\n if (!matrix) return undefined;\n if (role && matrix[role]) return matrix[role];\n const phase = phaseForRole(role);\n if (phase && matrix[phase]) return matrix[phase];\n if (matrix['*']) return matrix['*'];\n return undefined;\n}\n\nexport type MatrixKeyKind = 'role' | 'phase' | 'default' | 'unknown';\n\n/** Classify a matrix key so `/setmodel` can reject typos before persisting. */\nexport function matrixKeyKind(key: string): MatrixKeyKind {\n if (key === '*') return 'default';\n if (key in AGENT_CATALOG) return 'role';\n if (MATRIX_PHASE_KEYS.includes(key)) return 'phase';\n return 'unknown';\n}\n\n/** True when `key` is a usable matrix key (role, phase, or `*`). */\nexport function isValidMatrixKey(key: string): boolean {\n return matrixKeyKind(key) !== 'unknown';\n}\n","/**\n * WrongStack error hierarchy.\n *\n * Every error thrown by the framework is a `WrongStackError` with a\n * machine-readable `code`, a `subsystem` tag, and a `severity` level.\n * This lets consumers (CLI, TUI, plugins, tests) branch on structured\n * data instead of parsing error messages.\n */\n\n// ── Error codes ──────────────────────────────────────────────────────\n\n/**\n * Machine-readable error codes as frozen constants.\n *\n * Use `ERROR_CODES.X` instead of raw string literals for:\n * - IDE autocomplete and compile-time validation\n * - Safe refactoring (rename updates all usages)\n * - Plugin extensibility (extend the object to add custom codes)\n *\n * The `ErrorCode` type is derived from this object, so adding a new\n * code here automatically updates the type without extra changes.\n */\nexport const ERROR_CODES = {\n // Provider\n PROVIDER_RATE_LIMITED: 'PROVIDER_RATE_LIMITED',\n PROVIDER_AUTH_FAILED: 'PROVIDER_AUTH_FAILED',\n PROVIDER_OVERLOADED: 'PROVIDER_OVERLOADED',\n PROVIDER_INVALID_REQUEST: 'PROVIDER_INVALID_REQUEST',\n PROVIDER_SERVER_ERROR: 'PROVIDER_SERVER_ERROR',\n PROVIDER_NETWORK_ERROR: 'PROVIDER_NETWORK_ERROR',\n PROVIDER_CONTEXT_OVERFLOW: 'PROVIDER_CONTEXT_OVERFLOW',\n // Tool\n TOOL_NOT_FOUND: 'TOOL_NOT_FOUND',\n TOOL_PERMISSION_DENIED: 'TOOL_PERMISSION_DENIED',\n TOOL_EXECUTION_FAILED: 'TOOL_EXECUTION_FAILED',\n TOOL_TIMEOUT: 'TOOL_TIMEOUT',\n TOOL_INPUT_INVALID: 'TOOL_INPUT_INVALID',\n // Config\n CONFIG_INVALID: 'CONFIG_INVALID',\n CONFIG_NOT_FOUND: 'CONFIG_NOT_FOUND',\n CONFIG_PARSE_FAILED: 'CONFIG_PARSE_FAILED',\n CONFIG_MIGRATION_NEEDED: 'CONFIG_MIGRATION_NEEDED',\n // Plugin\n PLUGIN_LOAD_FAILED: 'PLUGIN_LOAD_FAILED',\n PLUGIN_API_MISMATCH: 'PLUGIN_API_MISMATCH',\n PLUGIN_MISSING_DEPENDENCY: 'PLUGIN_MISSING_DEPENDENCY',\n // Agent\n AGENT_ITERATION_LIMIT: 'AGENT_ITERATION_LIMIT',\n AGENT_CONTEXT_OVERFLOW: 'AGENT_CONTEXT_OVERFLOW',\n AGENT_ABORTED: 'AGENT_ABORTED',\n AGENT_RUN_FAILED: 'AGENT_RUN_FAILED',\n // Session\n SESSION_NOT_FOUND: 'SESSION_NOT_FOUND',\n SESSION_CORRUPTED: 'SESSION_CORRUPTED',\n SESSION_WRITE_FAILED: 'SESSION_WRITE_FAILED',\n // Container / Registry\n CONTAINER_TOKEN_ALREADY_BOUND: 'CONTAINER_TOKEN_ALREADY_BOUND',\n CONTAINER_TOKEN_NOT_BOUND: 'CONTAINER_TOKEN_NOT_BOUND',\n CONTAINER_CIRCULAR_DEPENDENCY: 'CONTAINER_CIRCULAR_DEPENDENCY',\n REGISTRY_DUPLICATE: 'REGISTRY_DUPLICATE',\n REGISTRY_NOT_FOUND: 'REGISTRY_NOT_FOUND',\n REGISTRY_INVALID: 'REGISTRY_INVALID',\n // File system\n FS_READ_FAILED: 'FS_READ_FAILED',\n FS_WRITE_FAILED: 'FS_WRITE_FAILED',\n FS_MKDIR_FAILED: 'FS_MKDIR_FAILED',\n FS_DELETE_FAILED: 'FS_DELETE_FAILED',\n FS_ATOMIC_WRITE_FAILED: 'FS_ATOMIC_WRITE_FAILED',\n // General\n UNKNOWN: 'UNKNOWN',\n} as const;\n\n/**\n * Union type derived from `ERROR_CODES`. Using `typeof ERROR_CODES[keyof typeof ERROR_CODES]`\n * instead of a string literal union means TypeScript auto-updates the type whenever\n * a new code is added to `ERROR_CODES` — no need to keep two lists in sync.\n */\nexport type ErrorCode = (typeof ERROR_CODES)[keyof typeof ERROR_CODES];\n\nexport type ErrorSubsystem =\n | 'provider'\n | 'tool'\n | 'config'\n | 'plugin'\n | 'agent'\n | 'session'\n | 'container'\n | 'fs'\n | 'general';\nexport type ErrorSeverity = 'fatal' | 'error' | 'warning';\n\n// ── Base error class ─────────────────────────────────────────────────\n\nexport class WrongStackError extends Error {\n readonly code: ErrorCode;\n readonly subsystem: ErrorSubsystem;\n readonly severity: ErrorSeverity;\n readonly recoverable: boolean;\n readonly context?: Record<string, unknown>;\n\n constructor(opts: {\n message: string;\n code: ErrorCode;\n subsystem: ErrorSubsystem;\n severity?: ErrorSeverity;\n recoverable?: boolean;\n context?: Record<string, unknown>;\n cause?: unknown;\n }) {\n super(opts.message, { cause: opts.cause });\n this.name = 'WrongStackError';\n this.code = opts.code;\n this.subsystem = opts.subsystem;\n this.severity = opts.severity ?? 'error';\n this.recoverable = opts.recoverable ?? false;\n this.context = opts.context;\n }\n\n /**\n * Render a one-line user-facing description.\n * Subclasses should override for domain-specific formatting.\n */\n describe(): string {\n const ctx = this.context ? ` ${formatContext(this.context)}` : '';\n return `${this.code}: ${this.message}${ctx}`;\n }\n}\n\nfunction formatContext(ctx: Record<string, unknown>): string {\n const parts = Object.entries(ctx)\n .filter(([, v]) => v !== undefined)\n .slice(0, 3)\n .map(([k, v]) => `${k}=${String(v)}`);\n return parts.length > 0 ? `[${parts.join(' ')}]` : '';\n}\n\n// ── Specific error classes ───────────────────────────────────────────\n\n/**\n * Tool execution errors — thrown by ToolExecutor and individual tools.\n */\nexport class ToolError extends WrongStackError {\n readonly toolName: string;\n\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n | 'TOOL_NOT_FOUND'\n | 'TOOL_PERMISSION_DENIED'\n | 'TOOL_EXECUTION_FAILED'\n | 'TOOL_TIMEOUT'\n | 'TOOL_INPUT_INVALID'\n >;\n toolName: string;\n recoverable?: boolean;\n context?: Record<string, unknown>;\n cause?: unknown;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'tool',\n recoverable: opts.recoverable,\n context: { tool: opts.toolName, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'ToolError';\n this.toolName = opts.toolName;\n }\n}\n\n/**\n * Config loading / validation errors.\n */\nexport class ConfigError extends WrongStackError {\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'CONFIG_INVALID' | 'CONFIG_NOT_FOUND' | 'CONFIG_PARSE_FAILED' | 'CONFIG_MIGRATION_NEEDED'\n >;\n context?: Record<string, unknown>;\n cause?: unknown;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'config',\n severity: 'fatal',\n recoverable: false,\n context: opts.context,\n cause: opts.cause,\n });\n this.name = 'ConfigError';\n }\n}\n\n/**\n * Plugin loading / lifecycle errors.\n */\nexport class PluginError extends WrongStackError {\n readonly pluginName: string;\n\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'PLUGIN_LOAD_FAILED' | 'PLUGIN_API_MISMATCH' | 'PLUGIN_MISSING_DEPENDENCY'\n >;\n pluginName: string;\n context?: Record<string, unknown>;\n cause?: unknown;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'plugin',\n severity: 'error',\n recoverable: opts.code === ERROR_CODES.PLUGIN_MISSING_DEPENDENCY,\n context: { plugin: opts.pluginName, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'PluginError';\n this.pluginName = opts.pluginName;\n }\n}\n\n/**\n * Agent runtime errors — thrown by Agent.run when a non-WrongStackError\n * escapes the inner loop, so callers always see a structured error.\n */\nexport class AgentError extends WrongStackError {\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'AGENT_ITERATION_LIMIT' | 'AGENT_CONTEXT_OVERFLOW' | 'AGENT_ABORTED' | 'AGENT_RUN_FAILED'\n >;\n recoverable?: boolean;\n context?: Record<string, unknown>;\n cause?: unknown;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'agent',\n severity: opts.code === ERROR_CODES.AGENT_ABORTED ? 'warning' : 'error',\n recoverable: opts.recoverable ?? opts.code === ERROR_CODES.AGENT_ITERATION_LIMIT,\n context: opts.context,\n cause: opts.cause,\n });\n this.name = 'AgentError';\n }\n}\n\n/**\n * Wrap an arbitrary thrown value into a `WrongStackError` so the caller\n * always gets a structured error. Pass-throughs WrongStackError instances\n * unchanged; raw `Error`s and primitives get an `AGENT_RUN_FAILED` wrapper\n * with the original preserved as `cause`.\n */\nexport function toWrongStackError(\n err: unknown,\n code: Extract<ErrorCode, 'AGENT_RUN_FAILED' | 'AGENT_ABORTED' | 'UNKNOWN'> = ERROR_CODES.AGENT_RUN_FAILED,\n): WrongStackError {\n if (err instanceof WrongStackError) return err;\n const message = err instanceof Error ? err.message : String(err);\n return new AgentError({\n message,\n code: code === 'UNKNOWN' ? ERROR_CODES.AGENT_RUN_FAILED : code,\n cause: err,\n });\n}\n\n/**\n * Session storage errors.\n */\nexport class SessionError extends WrongStackError {\n readonly sessionId?: string;\n\n constructor(opts: {\n message: string;\n code: Extract<ErrorCode, 'SESSION_NOT_FOUND' | 'SESSION_CORRUPTED' | 'SESSION_WRITE_FAILED'>;\n sessionId?: string;\n context?: Record<string, unknown>;\n cause?: unknown;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'session',\n severity: opts.code === ERROR_CODES.SESSION_WRITE_FAILED ? 'error' : 'warning',\n recoverable: opts.code !== ERROR_CODES.SESSION_CORRUPTED,\n context: { sessionId: opts.sessionId, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'SessionError';\n this.sessionId = opts.sessionId;\n }\n}\n\n/**\n * File system operation errors.\n */\nexport class FsError extends WrongStackError {\n readonly path?: string;\n\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'FS_READ_FAILED' | 'FS_WRITE_FAILED' | 'FS_MKDIR_FAILED' | 'FS_DELETE_FAILED' | 'FS_ATOMIC_WRITE_FAILED'\n >;\n path?: string;\n context?: Record<string, unknown>;\n cause?: unknown;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'fs',\n severity: 'error',\n recoverable: opts.code !== ERROR_CODES.FS_READ_FAILED,\n context: { path: opts.path, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'FsError';\n this.path = opts.path;\n }\n}\n\n// ── Type guards ──────────────────────────────────────────────────────\n\nexport function isWrongStackError(err: unknown): err is WrongStackError {\n return err instanceof WrongStackError;\n}\n\nexport function isToolError(err: unknown): err is ToolError {\n return err instanceof ToolError;\n}\n\nexport function isConfigError(err: unknown): err is ConfigError {\n return err instanceof ConfigError;\n}\n\nexport function isPluginError(err: unknown): err is PluginError {\n return err instanceof PluginError;\n}\n\nexport function isSessionError(err: unknown): err is SessionError {\n return err instanceof SessionError;\n}\n\nexport function isAgentError(err: unknown): err is AgentError {\n return err instanceof AgentError;\n}\n\nexport function isFsError(err: unknown): err is FsError {\n return err instanceof FsError;\n}\n","import type { ContentBlock, TextBlock } from './blocks.js';\nimport type { ErrorCode } from './errors.js';\nimport { WrongStackError, ERROR_CODES } from './errors.js';\nimport type { Message } from './messages.js';\nimport type { Tool } from './tool.js';\n\n/**\n * Token usage for a single provider call, normalized across providers.\n *\n * Disjoint semantics: the four fields never overlap. `input` is the count\n * of FRESH input tokens (billed at the full input rate); `cacheRead` and\n * `cacheWrite` are separate cached subsets each priced at their own rate.\n * The total context the model loaded for this turn is\n * `input + (cacheRead ?? 0) + (cacheWrite ?? 0)`.\n *\n * Provider quirks normalized at the adapter layer:\n * - Anthropic: returns `input_tokens` already disjoint from cache fields.\n * - OpenAI / OpenAI-compatible: `prompt_tokens` is the TOTAL including\n * cached portion; the adapter subtracts `cached_tokens` to stay disjoint.\n * - Google: `promptTokenCount` likewise includes cache; adapter subtracts\n * `cachedContentTokenCount`.\n *\n * Cost math and the context-fullness chip both depend on the disjoint\n * invariant — a TOTAL `input` plus a separate `cacheRead` count would bill\n * cached tokens twice and skew cache-hit-ratio reporting.\n */\nexport interface Usage {\n input: number;\n output: number;\n cacheRead?: number;\n cacheWrite?: number;\n}\n\nexport interface Capabilities {\n tools: boolean;\n parallelTools: boolean;\n vision: boolean;\n streaming: boolean;\n promptCache: boolean;\n systemPrompt: boolean;\n jsonMode: boolean;\n maxContext: number;\n cacheControl: 'native' | 'auto' | 'none';\n}\n\nexport interface Request {\n model: string;\n system?: TextBlock[];\n messages: Message[];\n tools?: Tool[];\n maxTokens: number;\n temperature?: number;\n topP?: number;\n stopSequences?: string[];\n toolChoice?: 'auto' | 'required' | 'none' | { type: 'tool'; name: string };\n}\n\nexport type StopReason = 'end_turn' | 'tool_use' | 'max_tokens' | 'stop_sequence' | 'refusal';\n\nexport interface Response {\n content: ContentBlock[];\n stopReason: StopReason;\n usage: Usage;\n model: string;\n}\n\nexport type StreamEvent =\n | { type: 'message_start'; model: string }\n | {\n type: 'content_block_start';\n kind: 'text' | 'tool_use' | 'thinking';\n id?: string;\n name?: string;\n }\n | { type: 'content_block_stop'; index: number }\n | { type: 'text_delta'; text: string }\n | { type: 'tool_use_start'; id: string; name: string }\n | { type: 'tool_use_input_delta'; id: string; partial: string }\n | { type: 'tool_use_stop'; id: string; input: unknown; providerMeta?: Record<string, unknown> }\n | { type: 'thinking_start'; providerMeta?: Record<string, unknown> }\n | { type: 'thinking_delta'; text: string }\n | { type: 'thinking_signature'; signature: string }\n | { type: 'thinking_stop' }\n | { type: 'message_stop'; stopReason: StopReason; usage: Usage };\n\nexport interface Provider {\n readonly id: string;\n readonly capabilities: Capabilities;\n /** Canonical streaming entry point. `complete()` defaults to a wrapper that\n * aggregates this stream — providers may override for non-streaming wires. */\n stream(req: Request, opts: { signal: AbortSignal }): AsyncIterable<StreamEvent>;\n complete(req: Request, opts: { signal: AbortSignal }): Promise<Response>;\n}\n\n/**\n * Structured body parsed from a provider's HTTP error response. Populated\n * best-effort: providers return JSON shaped differently (Anthropic uses\n * `{error: {type, message}}`, OpenAI uses `{error: {message, code}}`,\n * Google uses `{error: {status, message}}`), so the fields here are the\n * intersection that's usable for rendering and routing.\n */\nexport interface ProviderErrorBody {\n /** Provider-specific kind, e.g. \"overloaded_error\", \"rate_limit_error\", \"invalid_request_error\". */\n type?: string;\n /** Human-readable explanation from the provider. */\n message?: string;\n /** Provider request id, when present in the body or headers. */\n requestId?: string;\n /** Parsed Retry-After header (or equivalent body hint) in milliseconds. */\n retryAfterMs?: number;\n /** The raw response body (truncated to ~2 KB), kept for debugging. */\n raw?: string;\n /** True when `raw` was truncated; check `rawLength` for the original size. */\n truncated?: boolean;\n /** Original length of the response body in bytes, when `truncated` is true. */\n rawLength?: number;\n}\n\nexport class ProviderError extends WrongStackError {\n public readonly status: number;\n public readonly retryable: boolean;\n public readonly providerId: string;\n public readonly body?: ProviderErrorBody;\n\n constructor(\n message: string,\n status: number,\n retryable: boolean,\n providerId: string,\n opts: { body?: ProviderErrorBody; cause?: unknown } = {},\n ) {\n super({\n message,\n code: providerStatusToCode(status, opts.body?.type),\n subsystem: 'provider',\n severity: status >= 500 ? 'error' : 'warning',\n recoverable: retryable,\n context: { providerId, status },\n cause: opts.cause,\n });\n this.name = 'ProviderError';\n this.status = status;\n this.retryable = retryable;\n this.providerId = providerId;\n this.body = opts.body;\n }\n\n /**\n * Render a one-line, user-facing description. Designed for the CLI/TUI\n * status line and the agent's retry warning. Avoids dumping raw JSON\n * (which is what users see today when a 529 lands and the log message\n * includes the full `{\"type\":\"error\",...}` body).\n *\n * Examples:\n * \"minimax-coding-plan overloaded (529): High traffic detected. Upgrade for highspeed model. [req 06534785201de9c0…]\"\n * \"openai rate limited (429): Retry after 12s\"\n * \"anthropic invalid request (400): messages.0.role must be one of 'user'|'assistant'\"\n * \"groq HTTP 500 (server error)\"\n */\n override describe(): string {\n const kind = describeStatus(this.status, this.body?.type);\n const head = `${this.providerId} ${kind}`;\n const detail = this.body?.message?.trim();\n const reqId = this.body?.requestId\n ? ` [req ${this.body.requestId.slice(0, 16)}${this.body.requestId.length > 16 ? '…' : ''}]`\n : '';\n if (detail && detail.length > 0) {\n return `${head}: ${truncate(detail, 240)}${reqId}`;\n }\n return `${head}${reqId}`;\n }\n}\n\nfunction describeStatus(status: number, type?: string): string {\n if (status === 0) return 'network error';\n if (type === 'overloaded_error' || status === 529) return `overloaded (${status})`;\n if (type === 'rate_limit_error' || status === 429) return `rate limited (${status})`;\n if (type === 'authentication_error' || status === 401) return `auth failed (${status})`;\n if (type === 'permission_error' || status === 403) return `forbidden (${status})`;\n if (type === 'not_found_error' || status === 404) return `not found (${status})`;\n if (type === 'invalid_request_error' || status === 400) return `invalid request (${status})`;\n if (status === 408) return `timeout (${status})`;\n if (status >= 500 && status < 600) return `HTTP ${status} (server error)`;\n if (type) return `${type} (${status})`;\n return `HTTP ${status}`;\n}\n\nfunction truncate(s: string, n: number): string {\n return s.length <= n ? s : `${s.slice(0, n - 1)}…`;\n}\n\nfunction providerStatusToCode(status: number, type?: string): ErrorCode {\n if (status === 0) return ERROR_CODES.PROVIDER_NETWORK_ERROR;\n if (type === 'rate_limit_error' || status === 429) return ERROR_CODES.PROVIDER_RATE_LIMITED;\n if (type === 'authentication_error' || status === 401) return ERROR_CODES.PROVIDER_AUTH_FAILED;\n if (type === 'overloaded_error' || status === 529) return ERROR_CODES.PROVIDER_OVERLOADED;\n if (type === 'invalid_request_error' || status === 400) return ERROR_CODES.PROVIDER_INVALID_REQUEST;\n if (status === 408) return ERROR_CODES.PROVIDER_NETWORK_ERROR;\n if (status >= 500) return ERROR_CODES.PROVIDER_SERVER_ERROR;\n return ERROR_CODES.PROVIDER_INVALID_REQUEST;\n}\n","import type { Usage } from '../types/provider.js';\nimport type { EventBus } from '../kernel/events.js';\n\nexport type BudgetKind = 'tool_calls' | 'iterations' | 'tokens' | 'timeout' | 'idle_timeout' | 'cost';\n\nexport class BudgetExceededError extends Error {\n readonly kind: BudgetKind;\n readonly limit: number;\n readonly observed: number;\n\n constructor(kind: BudgetKind, limit: number, observed: number) {\n super(`Budget exceeded: ${kind} (limit=${limit}, observed=${observed})`);\n this.name = 'BudgetExceededError';\n this.kind = kind;\n this.limit = limit;\n this.observed = observed;\n }\n}\n\nexport interface BudgetLimits {\n maxIterations?: number;\n maxToolCalls?: number;\n maxTokens?: number;\n /** Estimated USD cost ceiling. */\n maxCostUsd?: number;\n /**\n * Hard wall-clock timeout measured from `start()`. Off by default — set it\n * explicitly only when a task must finish within an absolute window. For\n * the everyday \"don't kill an agent that's still working\" guard, prefer\n * `idleTimeoutMs`, which resets on activity.\n */\n timeoutMs?: number;\n /**\n * Idle timeout: the maximum gap (ms) between activity signals (iterations,\n * tool calls, token usage, streamed progress) before the subagent is\n * considered hung and reaped. Unlike `timeoutMs`, an actively-working\n * agent continuously resets this clock via `markActivity()`, so it never\n * trips on a long-but-productive run — only on a genuine stall.\n */\n idleTimeoutMs?: number;\n}\n\n/**\n * Controls how the budget behaves when `onThreshold` is set and a limit is hit.\n *\n * `'auto'` — emit `budget.threshold_reached` on the EventBus and wait for a\n * coordinator response (extend/stop). If no listener responds within\n * `DECISION_TIMEOUT_MS` the decision defaults to `'stop'`.\n * `'sync'` — do not emit any event; treat the threshold as a hard stop and\n * throw `BudgetExceededError` synchronously. Useful for fire-and-forget\n * subagents that have an `onThreshold` handler for logging/metrics but are\n * not wired into a coordinator.\n *\n * @default 'auto'\n */\nexport type BudgetNegotiationMode = 'auto' | 'sync';\n\nexport interface BudgetUsage {\n iterations: number;\n toolCalls: number;\n tokens: { input: number; output: number; total: number };\n costUsd: number;\n elapsedMs: number;\n}\n\n/**\n * Thrown by `SubagentBudget.record*` when a soft limit is hit and\n * an `onThreshold` handler is configured that wants to ask the\n * coordinator (via `budget.threshold_reached` event). The runner\n * catches this and awaits the embedded `decision` promise to get\n * the coordinator's extend/stop decision.\n *\n * Distinct from `BudgetExceededError` which is a hard stop.\n */\nexport class BudgetThresholdSignal extends Error {\n readonly kind: BudgetKind;\n readonly limit: number;\n readonly used: number;\n /** Resolves to 'extend' (with optional new limits) or 'stop' */\n readonly decision: Promise<BudgetThresholdDecision>;\n\n constructor(\n kind: BudgetKind,\n limit: number,\n used: number,\n decision: Promise<BudgetThresholdDecision>,\n ) {\n super(`Budget soft limit: ${kind} (limit=${limit}, used=${used})`);\n this.name = 'BudgetThresholdSignal';\n this.kind = kind;\n this.limit = limit;\n this.used = used;\n this.decision = decision;\n }\n}\n\nexport type BudgetThresholdDecision =\n | 'stop'\n | { extend: Partial<BudgetLimits> };\n\n/**\n * Callback invoked when a budget limit is about to be exceeded.\n * Return 'throw' for hard stop (default — throws BudgetExceededError).\n * Return 'continue' to allow one more unit and re-check next time.\n * Return a Promise to ask the coordinator via `budget.threshold_reached`\n * event (uses the same grant/deny pattern as `iteration.limit_reached`).\n */\nexport type BudgetThresholdHandler = (info: {\n kind: BudgetKind;\n used: number;\n limit: number;\n requestDecision: () => Promise<BudgetThresholdDecision>;\n}) => 'throw' | 'continue' | Promise<BudgetThresholdDecision>;\n\n/**\n * Per-subagent budget enforcement. Each subagent gets its own instance so a\n * runaway agent can't drain the cost ceiling of its siblings. All record/check\n * methods are O(1) and safe to call from hot paths.\n *\n * Behavior without `onThreshold`: hard stops synchronously on every limit hit.\n *\n * Behavior with `onThreshold` and `_mode === 'auto'`: emits `budget.threshold_reached`\n * on the EventBus and throws `BudgetThresholdSignal`. The coordinator's verdict\n * (extend/stop) resolves the embedded promise. If no listener responds within\n * `DECISION_TIMEOUT_MS` the decision defaults to `'stop'`.\n *\n * Behavior with `onThreshold` and `_mode === 'sync'`: throws `BudgetExceededError`\n * synchronously regardless of EventBus state or listener presence. This is useful\n * for fire-and-forget subagents that have an `onThreshold` handler for logging/metrics\n * but are not wired into a coordinator — the `'sync'` mode makes the hard-stop\n * behavior explicit and means tests can use `expect().toThrow()` even without\n * a fully-wired EventBus.\n */\nexport class SubagentBudget {\n readonly limits: Readonly<BudgetLimits>;\n private iterations = 0;\n private toolCalls = 0;\n private tokenInput = 0;\n private tokenOutput = 0;\n private costUsd = 0;\n private startTime: number | null = null;\n /**\n * Timestamp of the most recent activity (iteration / tool call / token\n * usage / streamed progress). Drives the idle timeout — reset by\n * `markActivity()`. Initialised to `start()` time so a never-active agent\n * still eventually trips its idle window.\n */\n private lastActivityTime: number | null = null;\n private _onThreshold: BudgetThresholdHandler | undefined;\n /**\n * Hard cap on how long `_negotiateExtension` waits for the coordinator to\n * respond before defaulting to 'stop'. Without this fallback an absent\n * or hung listener (Director not built / event filter detached mid-run)\n * leaves the budget over-limit and never enforces anything.\n */\n private static readonly DECISION_TIMEOUT_MS = 60_000;\n /**\n * Injected by the runner when wiring the budget to its EventBus.\n * Used to emit `budget.threshold_reached` events in `'auto'` mode.\n */\n _events?: EventBus;\n\n /**\n * Negotiation mode — controls whether a threshold hit tries to emit\n * `budget.threshold_reached` and wait for a coordinator decision, or\n * falls straight through to a synchronous hard stop.\n *\n * `'auto'` (default) — emit on the EventBus and wait; times out to 'stop'.\n * `'sync'` — throw `BudgetExceededError` immediately regardless of listeners.\n */\n private _mode: BudgetNegotiationMode;\n\n /**\n * Optional callback for soft-limit handling. When set, the budget will\n * invoke it rather than throw immediately. The handler decides whether to\n * throw synchronously, continue, or ask the coordinator for an extension.\n */\n get onThreshold(): BudgetThresholdHandler | undefined {\n return this._onThreshold;\n }\n set onThreshold(fn: BudgetThresholdHandler | undefined) {\n this._onThreshold = fn;\n }\n\n /** Returns the current negotiation mode. */\n get mode(): BudgetNegotiationMode {\n return this._mode;\n }\n\n constructor(limits: BudgetLimits = {}, mode: BudgetNegotiationMode = 'auto') {\n this._mode = mode;\n // NOT frozen: `negotiateExtension` patches these limits in place when the\n // coordinator grants an auto-extension. Freezing made every granted\n // extension throw `TypeError: Cannot assign to read only property` in\n // strict mode, which the runner caught as a hard stop — so extensions\n // silently became kills. The `readonly limits: Readonly<BudgetLimits>`\n // typing still blocks external mutation at compile time.\n this.limits = { ...limits };\n }\n\n start(): void {\n this.startTime = Date.now();\n this.lastActivityTime = this.startTime;\n }\n\n /**\n * Reset the idle clock. Called on any sign of forward progress —\n * iterations, tool calls, token usage, and streamed tool/text progress —\n * so a long-but-productive subagent never trips its `idleTimeoutMs`.\n */\n markActivity(): void {\n this.lastActivityTime = Date.now();\n }\n\n /**\n * Milliseconds since the last activity signal. Returns 0 before `start()`\n * (nothing to measure yet). Used by the coordinator watchdog to decide\n * whether to re-arm (still active) or reap (genuinely idle).\n */\n idleMs(): number {\n const since = this.lastActivityTime ?? this.startTime;\n return since === null ? 0 : Date.now() - since;\n }\n\n /** Returns true if we're within 10% of any limit — useful for pre-flight checks. */\n isNearLimit(): boolean {\n const { maxIterations, maxToolCalls, maxTokens, maxCostUsd } = this.limits;\n if (maxIterations && this.iterations >= maxIterations * 0.9) return true;\n if (maxToolCalls && this.toolCalls >= maxToolCalls * 0.9) return true;\n if (maxTokens && this.tokenInput + this.tokenOutput >= maxTokens * 0.9) return true;\n if (maxCostUsd && this.costUsd >= maxCostUsd * 0.9) return true;\n return false;\n }\n\n /**\n * Synchronous budget check. Always throws synchronously so callers (especially\n * test event handlers using `expect().toThrow()`) get an unhandled rejection\n * when the budget is exceeded without a handler.\n *\n * Decision table:\n * - no `onThreshold` handler → throw `BudgetExceededError` (hard stop, always)\n * - `mode === 'sync'` → throw `BudgetExceededError` (hard stop, always)\n * - `mode === 'auto'` + no listener → throw `BudgetExceededError` (hard stop; no one to ask)\n * - `mode === 'auto'` + listener → throw `BudgetThresholdSignal` with async decision promise\n */\n /**\n * Collects all exceeded budget kinds into a single NOOP-free negotiation.\n * Called by recordIteration / recordToolCall / recordUsage — each may call\n * this for its own kind. The first call starts the negotiation and stores\n * the Promise in _pendingNegotiation. Subsequent calls for DIFFERENT\n * kinds (while a negotiation is in flight) are NOOPs — they don't start\n * new conversations with the coordinator. This prevents an EventBus flood\n * when multiple budget kinds are exceeded simultaneously in one iteration.\n *\n * Returns the kinds that were found to be exceeded (for logging/debugging).\n */\n private checkLimits(elapsedMs?: number): { kind: BudgetKind; used: number; limit: number }[] {\n const exceeded: { kind: BudgetKind; used: number; limit: number }[] = [];\n\n if (this.limits.maxIterations !== undefined && this.iterations > this.limits.maxIterations) {\n exceeded.push({ kind: 'iterations', used: this.iterations, limit: this.limits.maxIterations });\n }\n if (this.limits.maxToolCalls !== undefined && this.toolCalls > this.limits.maxToolCalls) {\n exceeded.push({ kind: 'tool_calls', used: this.toolCalls, limit: this.limits.maxToolCalls });\n }\n const totalTokens = this.tokenInput + this.tokenOutput;\n if (this.limits.maxTokens !== undefined && totalTokens > this.limits.maxTokens) {\n exceeded.push({ kind: 'tokens', used: totalTokens, limit: this.limits.maxTokens });\n }\n if (this.limits.maxCostUsd !== undefined && this.costUsd > this.limits.maxCostUsd) {\n exceeded.push({ kind: 'cost', used: this.costUsd, limit: this.limits.maxCostUsd });\n }\n // Timeout: called from checkTimeout() with elapsedMs (wall-clock) and the\n // current idle gap. Either crossing its limit trips its own kind so the\n // coordinator and auto-extend policy can distinguish them.\n // Wall-clock (`timeoutMs`) is an explicit hard cap; idle (`idleTimeoutMs`)\n // is the default guard that resets on activity. Both can be exceeded in\n // the same call — we push both entries so all violated limits are reported.\n if (elapsedMs !== undefined) {\n const idle = this.idleMs();\n if (this.limits.idleTimeoutMs !== undefined && idle > this.limits.idleTimeoutMs) {\n exceeded.push({ kind: 'idle_timeout', used: idle, limit: this.limits.idleTimeoutMs });\n }\n if (this.limits.timeoutMs !== undefined && elapsedMs > this.limits.timeoutMs) {\n exceeded.push({ kind: 'timeout', used: elapsedMs, limit: this.limits.timeoutMs });\n }\n }\n\n if (exceeded.length === 0) return [];\n\n if (!this._onThreshold) {\n // Hard stop — throw on the first exceeded kind.\n const first = exceeded[0]!;\n throw new BudgetExceededError(first.kind, first.limit, first.used);\n }\n if (this._mode === 'sync') {\n // Hard stop in sync mode.\n const first = exceeded[0]!;\n throw new BudgetExceededError(first.kind, first.limit, first.used);\n }\n const bus = this._events;\n if (!bus || !bus.hasListenerFor('budget.threshold_reached')) {\n const first = exceeded[0]!;\n throw new BudgetExceededError(first.kind, first.limit, first.used);\n }\n\n // Start a negotiation for each exceeded kind that doesn't already have one.\n // The first exceeded kind throws BudgetThresholdSignal so the caller sees\n // the soft-limit event. Subsequent exceeded kinds (in the same call) start\n // their own negotiations silently — they won't throw again.\n for (const entry of exceeded) {\n if (this._pendingNegotiations.has(entry.kind)) continue; // already negotiating this kind\n const decision = this._negotiateExtension(entry.kind, exceeded);\n this._pendingNegotiations.set(entry.kind, decision);\n }\n\n const first = exceeded[0]!;\n const decision = this._pendingNegotiations.get(first.kind)!;\n throw new BudgetThresholdSignal(first.kind, first.limit, first.used, decision);\n }\n\n /**\n * Per-kind in-flight negotiation Promises. Each budget kind can have its\n * own concurrent negotiation — e.g. iterations and timeout can both\n * be exceeded simultaneously without blocking each other. The same kind\n * cannot start two concurrent negotiations (dedup guard).\n * Cleared in `_negotiateExtension`'s `finally` block.\n */\n private _pendingNegotiations = new Map<BudgetKind, Promise<BudgetThresholdDecision>>();\n\n /**\n * Drive the threshold handler to a decision. Resolves with `'stop'`\n * (signal the runner to abort) or `{ extend: ... }` (limits already\n * patched in-place; the runner should not abort). Clears the\n * per-kind slot in `_pendingNegotiations` in `finally`.\n *\n * The 'continue' return from a sync handler is treated as\n * `{ extend: {} }` — keep going without patching; next overrun fires\n * a fresh signal.\n */\n private async _negotiateExtension(\n kind: BudgetKind,\n exceeded: { kind: BudgetKind; used: number; limit: number }[],\n ): Promise<BudgetThresholdDecision> {\n try {\n // Use the first exceeded kind for the handler call.\n const first = exceeded[0]!;\n const result = this._onThreshold!({\n kind: first.kind,\n used: first.used,\n limit: first.limit,\n requestDecision: (): Promise<BudgetThresholdDecision> => {\n const bus = this._events;\n if (!bus || !bus.hasListenerFor('budget.threshold_reached')) {\n return Promise.resolve('stop');\n }\n return new Promise<BudgetThresholdDecision>((resolve) => {\n let resolved = false;\n const respond = (d: BudgetThresholdDecision) => {\n if (resolved) return;\n resolved = true;\n resolve(d);\n };\n const fallback = setTimeout(\n () => respond('stop'),\n SubagentBudget.DECISION_TIMEOUT_MS,\n );\n // Emit one event per exceeded kind so the FleetBus routes them.\n for (const { kind, used, limit } of exceeded) {\n bus.emit('budget.threshold_reached', {\n kind: kind as 'iterations' | 'tool_calls' | 'tokens' | 'cost' | 'timeout' | 'idle_timeout',\n used,\n limit,\n timeoutMs: SubagentBudget.DECISION_TIMEOUT_MS,\n extend: (extra: Partial<BudgetLimits>) => {\n clearTimeout(fallback);\n respond({ extend: extra });\n },\n deny: () => {\n clearTimeout(fallback);\n respond('stop');\n },\n });\n }\n });\n },\n });\n\n if (result === 'throw') return 'stop';\n if (result === 'continue') return { extend: {} };\n\n const decision = await result;\n if (decision === 'stop') return 'stop';\n\n // 'extend' — patch in-place limits BEFORE resolving so the runner's\n // continue path sees the new ceiling.\n const ext = decision.extend;\n if (ext.maxIterations !== undefined) {\n (this.limits as Record<string, unknown>).maxIterations = ext.maxIterations;\n }\n if (ext.maxToolCalls !== undefined) {\n (this.limits as Record<string, unknown>).maxToolCalls = ext.maxToolCalls;\n }\n if (ext.maxTokens !== undefined) {\n (this.limits as Record<string, unknown>).maxTokens = ext.maxTokens;\n }\n if (ext.maxCostUsd !== undefined) {\n (this.limits as Record<string, unknown>).maxCostUsd = ext.maxCostUsd;\n }\n if (ext.timeoutMs !== undefined) {\n (this.limits as Record<string, unknown>).timeoutMs = ext.timeoutMs;\n }\n if (ext.idleTimeoutMs !== undefined) {\n (this.limits as Record<string, unknown>).idleTimeoutMs = ext.idleTimeoutMs;\n }\n return decision;\n } finally {\n this._pendingNegotiations.delete(kind);\n }\n }\n\n recordIteration(): void {\n this.iterations++;\n this.markActivity();\n void this.checkLimits();\n }\n\n recordToolCall(): void {\n this.toolCalls++;\n this.markActivity();\n void this.checkLimits();\n }\n\n recordUsage(usage: Usage, costUsd = 0): void {\n this.tokenInput += usage.input;\n this.tokenOutput += usage.output;\n this.costUsd += costUsd;\n this.markActivity();\n void this.checkLimits();\n }\n\n /**\n * Wall-clock budget check. Unlike other limits, timeout is always a hard stop\n * — wall-clock time cannot be \"extended\" by the coordinator, so it throws\n * synchronously rather than entering the negotiation flow.\n *\n * Decision table:\n * - no `onThreshold` handler → throw `BudgetExceededError`\n * - `mode === 'sync'` → throw `BudgetExceededError`\n * - `mode === 'auto'` + no listener → throw `BudgetExceededError`\n * - `mode === 'auto'` + listener → throw `BudgetExceededError` (timeout is not extendable)\n */\n checkTimeout(): void {\n if (this.startTime === null) return;\n const { timeoutMs, idleTimeoutMs } = this.limits;\n if (timeoutMs === undefined && idleTimeoutMs === undefined) return;\n const elapsed = Date.now() - this.startTime;\n const wallTripped = timeoutMs !== undefined && elapsed > timeoutMs;\n const idleTripped = idleTimeoutMs !== undefined && this.idleMs() > idleTimeoutMs;\n if (!wallTripped && !idleTripped) return;\n void this.checkLimits(elapsed);\n }\n\n /** Returns true if a wall-clock or idle timeout has occurred without throwing. */\n isTimedOut(): boolean {\n if (this.startTime === null) return false;\n const { timeoutMs, idleTimeoutMs } = this.limits;\n if (timeoutMs !== undefined && Date.now() - this.startTime > timeoutMs) return true;\n if (idleTimeoutMs !== undefined && this.idleMs() > idleTimeoutMs) return true;\n return false;\n }\n\n usage(): BudgetUsage {\n return {\n iterations: this.iterations,\n toolCalls: this.toolCalls,\n tokens: {\n input: this.tokenInput,\n output: this.tokenOutput,\n total: this.tokenInput + this.tokenOutput,\n },\n costUsd: this.costUsd,\n elapsedMs: this.startTime === null ? 0 : Date.now() - this.startTime,\n };\n }\n}\n","/**\r\n * Pre-built subagent role configurations for the WrongStack fleet.\r\n * These can be passed to `MultiAgentHost.spawn()` or used as templates\r\n * for the director's roster.\r\n */\r\nimport type { SubagentConfig } from '../types/multi-agent.js';\r\nimport { ALL_AGENT_DEFINITIONS } from './agents/index.js';\r\n\r\n/**\r\n * Audit Log Agent — analyzes session logs, event streams, and traces.\r\n * Use for: post-mortems, trend analysis, operational insights.\r\n */\r\nexport const AUDIT_LOG_AGENT: SubagentConfig = {\r\n id: 'audit-log',\r\n name: 'Audit Log',\r\n role: 'audit-log',\r\n prompt: `You are the Audit Log agent. Your job is to analyze structured JSONL\r\nsession logs and produce actionable markdown reports.\r\n\r\nScope:\r\n- Parse session logs (iteration counts, tool calls, errors, usage)\r\n- Detect repeated failure patterns across multiple runs\r\n- Identify tool usage anomalies (over-use, failures, unexpected chains)\r\n- Track token consumption trends\r\n- Generate structured audit reports with severity ratings\r\n\r\nInput format you accept:\r\n{ \"task\": \"analyze | report | trends\", \"sessionPath\": \"<path>\", \"focus\": \"errors | tools | usage | all\" }\r\n\r\nOutput: Markdown audit report with sections:\r\n- ## Summary (totals, error rate)\r\n- ## Top Errors (count + context)\r\n- ## Tool Usage (table with calls, failures, avg duration)\r\n- ## Anomalies (pattern → severity)\r\n\r\nWorking rules:\r\n- Never fabricate numbers — read the actual logs first\r\n- Always include file:line references for errors\r\n- If sessionPath is missing, ask the director to provide it\r\n- Report confidence level: high (>90% accuracy), medium, low`,\r\n\r\n // No hardcoded budgets — the orchestrator (delegate tool or\r\n // spawn_subagent) decides per-task how much room a subagent gets.\r\n // A monorepo audit needs hours; a single-file lint check needs\r\n // seconds. Pinning a number here forces the orchestrator to fight\r\n // the role's default instead of just asking for what it needs.\r\n};\r\n\r\n/**\r\n * Bug Hunter Agent — systematic bug and code smell detection.\r\n * Use for: pre-refactoring health checks, code review, regression prevention.\r\n */\r\nexport const BUG_HUNTER_AGENT: SubagentConfig = {\r\n id: 'bug-hunter',\r\n name: 'Bug Hunter',\r\n role: 'bug-hunter',\r\n prompt: `You are the Bug Hunter agent. Your job is to systematically scan\r\nsource code for bugs, anti-patterns, and code smells using pattern matching\r\nand heuristics. Output a prioritized hit list with file:line references.\r\n\r\nScope:\r\n- Detect common bug patterns (uncaught errors, resource leaks, race conditions)\r\n- Identify anti-patterns (callback hell, God objects, circular deps)\r\n- Find TypeScript-specific issues (unsafe any, missing null checks, branded types)\r\n- Flag security-sensitive constructs (eval, innerHTML, hardcoded secrets)\r\n- Rank findings: critical > high > medium > low\r\n\r\nInput format you accept:\r\n{ \"task\": \"scan | hunt | check\", \"paths\": [\"src/**/*.ts\"], \"focus\": \"bugs | patterns | security | all\", \"severityThreshold\": \"medium\" }\r\n\r\nOutput: Markdown bug hunt report:\r\n- ## Critical (must fix first)\r\n- ## High (should fix)\r\n- ## Medium\r\n- ## Low (consider)\r\nEach entry: **[TYPE]** \\`file:line\\` — description + suggested fix\r\n\r\nBug pattern reference you know:\r\n| Pattern | Regex hint | Severity |\r\n|---------|------------|----------|\r\n| Uncaught promise | /\\.then\\\\(.*\\\\)/ without catch | high |\r\n| Event leak | on\\\\( without off/removeListener | high |\r\n| Hardcoded secret | [a-zA-Z0-9/_-]{20,} in config files | critical |\r\n| unsafe any | : any\\\\b or <any> | medium |\r\n| innerHTML | innerHTML\\\\s*= | high |\r\n\r\nWorking rules:\r\n- Never scan node_modules — it's noise\r\n- Always include file:line for every finding\r\n- If >30% of findings are false positives, note the confidence level\r\n- Ask director for clarification if paths are ambiguous`,\r\n\r\n // Budgets are set by the orchestrator per task — see fleet.ts header.\r\n};\r\n\r\n/**\r\n * Refactor Planner Agent — structured refactoring planning.\r\n * Use for: large rewrites, technical debt reduction, architecture improvements.\r\n */\r\nexport const REFACTOR_PLANNER_AGENT: SubagentConfig = {\r\n id: 'refactor-planner',\r\n name: 'Refactor Planner',\r\n role: 'refactor-planner',\r\n prompt: `You are the Refactor Planner agent. Your job is to analyze code\r\nstructure and produce a concrete, phased refactoring plan with risk\r\nassessment, dependency ordering, and rollback strategy.\r\n\r\nScope:\r\n- Map module-level dependencies (import graph)\r\n- Identify coupling hotspots (high fan-in/out modules)\r\n- Assess refactoring risk by complexity and test coverage\r\n- Generate phased plans with checkpoint milestones\r\n- Produce diff-friendly task lists (one task = one concern)\r\n\r\nInput format you accept:\r\n{ \"task\": \"plan | assess | roadmap\", \"target\": \"src/core\", \"constraint\": \"no-breaking-changes | minimal-downtime | full-rewrite\", \"focus\": \"architecture | performance | maintainability\" }\r\n\r\nOutput: Markdown refactor plan:\r\n- ## Phase 1: Low Risk / High Payoff (do first)\r\n Table: | # | Task | Module | Risk | Est. Time |\r\n- ## Phase 2: Medium Risk\r\n- ## Phase 3: High Risk (requires full regression)\r\n- ## Dependency Graph (abbreviated ASCII)\r\n- ## Rollback Strategy\r\n- ## Exit Criteria (checkbox list)\r\n\r\nRisk scoring criteria:\r\n| Factor | Low | Medium | High |\r\n|--------|-----|--------|------|\r\n| Cyclomatic complexity | <10 | 10-20 | >20 |\r\n| Test coverage | >80% | 50-80% | <50% |\r\n| Fan-out (imports) | <5 | 5-15 | >15 |\r\n\r\nWorking rules:\r\n- Always include rollback strategy — every refactor can fail\r\n- Merge tasks that take <1h into a single phase\r\n- Respect team constraints (reviewer availability, parallelization)\r\n- Never plan without analyzing the actual code first`,\r\n\r\n // Budgets are set by the orchestrator per task — see fleet.ts header.\r\n};\r\n\r\n/**\r\n * Security Scanner Agent — vulnerability and secret detection.\r\n * Use for: CI checks, pre-release audits, dependency vulnerability scanning.\r\n */\r\nexport const SECURITY_SCANNER_AGENT: SubagentConfig = {\r\n id: 'security-scanner',\r\n name: 'Security Scanner',\r\n role: 'security-scanner',\r\n prompt: `You are the Security Scanner agent. Your job is to scan code,\r\nconfigs, and dependencies for security issues from hardcoded secrets to\r\nsupply chain risks.\r\n\r\nScope:\r\n- Detect hardcoded secrets: API keys, tokens, passwords, private keys\r\n- Find injection vectors: eval, innerHTML, SQL concat, shell injection\r\n- Identify insecure patterns: weak crypto, hardcoded IVs, disabled TLS\r\n- Scan dependencies for known CVEs (via npm/pnpm audit)\r\n- Flag supply chain risks: postinstall hooks, unverified scripts, .npmrc\r\n\r\nInput format you accept:\r\n{ \"task\": \"scan | audit | secrets | dependencies\", \"paths\": [\"src\", \"config\"], \"depth\": \"quick | normal | deep\" }\r\n\r\nOutput: Markdown security report:\r\n- ## CRITICAL: Secrets Found (with code snippets)\r\n- ## HIGH: Injection Vectors\r\n- ## MEDIUM: Insecure Patterns\r\n- ## Dependency Issues (CVE list)\r\n- ## Summary table (severity → count)\r\n- ## Remediation Checklist (with checkboxes)\r\n\r\nSecret patterns you detect:\r\n| Pattern | Example | Severity |\r\n|---------|---------|----------|\r\n| AWS Access Key | AKIAIOSFODNN7EXAMPLE | critical |\r\n| AWS Secret Key | [a-zA-Z0-9/+=]{40} base64 | critical |\r\n| GitHub Token | ghp_[a-zA-Z0-9]{36} | critical |\r\n| Private Key PEM | -----BEGIN.*PRIVATE KEY----- | critical |\r\n| JWT | eyJ[a-zA-Z0-9_-]+ | high |\r\n\r\nInjection patterns:\r\n| Construct | Safe alternative |\r\n|-----------|-----------------|\r\n| eval(str) | new Function() or parse |\r\n| innerHTML = x | textContent or sanitize |\r\n| exec(\\`cmd \\${x}\\`) | execFile with args array |\r\n\r\nWorking rules:\r\n- Never scan node_modules — use npm audit instead\r\n- Always provide remediation steps, not just findings\r\n- Verify regex-based secrets before flagging (false positive risk)\r\n- When in doubt, flag as medium rather than ignoring potential issues`,\r\n\r\n // Budgets are set by the orchestrator per task — see fleet.ts header.\r\n};\r\n\r\n/**\r\n * Critic Agent — evaluates code quality, architecture decisions, and\r\n * refactoring plans against project conventions and engineering standards.\r\n * Use for: real-time evaluation of bug reports, refactor plans, and\r\n * architectural proposals during collaborative debugging sessions.\r\n */\r\nexport const CRITIC_AGENT: SubagentConfig = {\r\n id: 'critic',\r\n name: 'Critic',\r\n role: 'critic',\r\n prompt: `You are the Critic agent. Your job is to evaluate code quality,\r\narchitectural decisions, and proposed changes against project conventions,\r\nengineering standards, and known quality gates. You do not write code —\r\nyou judge it.\r\n\r\nScope:\r\n- Evaluate bug severity and fix quality from Bug Hunter reports\r\n- Score refactoring plans from Refactor Planner (risk, completeness, trade-offs)\r\n- Flag gaps in test coverage, error handling, and edge case coverage\r\n- Assess whether a proposed change aligns with existing project patterns\r\n- Detect over-engineering or under-engineering relative to the problem scope\r\n\r\nInput format you accept:\r\n{ \"task\": \"evaluate | score | review\", \"subject\": \"bug_report | refactor_plan | diff\", \"focus\": \"correctness | maintainability | risk | all\" }\r\n\r\nOutput: Markdown critic report:\r\n- ## Overall Score (0-10 with rationale)\r\n- ## Strengths (what's solid)\r\n- ## Weaknesses (what needs work)\r\n- ## Specific Concerns (with file:line when applicable)\r\n- ## Verdict: **Approve / Needs Revision / Reject**\r\n\r\nWorking rules:\r\n- Be specific — \"looks fine\" is not a review. Cite concrete evidence.\r\n- When scoring, explain the delta from a perfect score.\r\n- If you have no basis to evaluate a concern, say so rather than speculating.\r\n- Prioritise correctness over style; correctness issues block approval.\r\n- Score thresholds: ≥7 = Approve, 4-6 = Needs Revision, <4 = Reject`,\r\n\r\n // Budgets are set by the orchestrator per task — see fleet.ts header.\r\n};\r\n\r\n/**\r\n * All agents in a map for easy lookup by role. The four legacy pre-built\r\n * agents plus the phase 1-9 catalog (`ALL_AGENT_DEFINITIONS`). Catalog roles\r\n * are guaranteed collision-free by the catalog builder; none overlap the\r\n * legacy four.\r\n */\r\nexport const FLEET_ROSTER: Record<string, SubagentConfig> = {\r\n 'audit-log': AUDIT_LOG_AGENT,\r\n 'bug-hunter': BUG_HUNTER_AGENT,\r\n 'refactor-planner': REFACTOR_PLANNER_AGENT,\r\n 'security-scanner': SECURITY_SCANNER_AGENT,\r\n 'critic': CRITIC_AGENT,\r\n ...Object.fromEntries(\r\n ALL_AGENT_DEFINITIONS.map((d) => [d.config.role as string, d.config] as const),\r\n ),\r\n};\r\n\r\n// ---------------------------------------------------------------------------\r\n// Default per-role budgets.\r\n//\r\n// MASSIVELY RAISED from earlier values. User requested x5–x10 multiplier\r\n// to prevent any timeout or budget exhaustion on long-running tasks\r\n// like monorepo audits, deep refactors, and security scans.\r\n//\r\n// x10 values (realistic upper bound for a single subagent task):\r\n// audit-log: 7.5 hours, 5000 iterations, 15000 tool calls\r\n// bug-hunter: 10 hours, 8000 iterations, 20000 tool calls\r\n// refactor-planner: 7.5 hours, 6000 iterations, 18000 tool calls\r\n// security-scanner: 10 hours, 8000 iterations, 20000 tool calls\r\n//\r\n// These can be overridden per-call via delegate tool parameters.\r\n// ---------------------------------------------------------------------------\r\nexport interface FleetRosterBudget {\r\n timeoutMs?: number;\r\n /** Idle reap window (ms). Resets on activity — see `applyRosterBudget`. */\r\n idleTimeoutMs?: number;\r\n maxIterations?: number;\r\n maxToolCalls?: number;\r\n maxTokens?: number;\r\n maxCostUsd?: number;\r\n}\r\n\r\n/**\r\n * Default idle window for delegated subagents: reap only after this long with\r\n * NO activity (no iteration / tool call / streamed progress). An actively-\r\n * working agent resets this clock continuously, so it runs until its task\r\n * naturally ends — no more wall-clock kills of productive runs. Power users\r\n * can still impose a hard `timeoutMs` per delegate.\r\n */\r\nexport const DEFAULT_IDLE_TIMEOUT_MS = 15 * 60 * 1000;\r\n\r\nexport const FLEET_ROSTER_BUDGETS: Record<string, FleetRosterBudget> = {\r\n 'audit-log': { timeoutMs: 7.5 * 60 * 60 * 1000, maxIterations: 5000, maxToolCalls: 15000 },\r\n 'bug-hunter': { timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000 },\r\n 'refactor-planner': { timeoutMs: 7.5 * 60 * 60 * 1000, maxIterations: 6000, maxToolCalls: 18000 },\r\n 'security-scanner': { timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000 },\r\n 'critic': { timeoutMs: 5 * 60 * 60 * 1000, maxIterations: 4000, maxToolCalls: 12000 },\r\n ...Object.fromEntries(\r\n ALL_AGENT_DEFINITIONS.map((d) => [d.config.role as string, d.budget] as const),\r\n ),\r\n};\r\n\r\n/**\r\n * Apply roster budget to a config (only when the config has no explicit\r\n * budget fields set). This is called by the coordinator before dispatch.\r\n */\r\n// Generic default budget applied when no role matches and no explicit budget\r\n// fields are set. Used for `name` / free-form delegates. There is no default\r\n// wall-clock timeout — a delegated agent runs until its task naturally ends\r\n// (`end_turn`) or it stalls past the idle window. Iteration / tool-call ceilings\r\n// remain as a runaway backstop.\r\nconst GENERIC_SUBAGENT_BUDGET: FleetRosterBudget = {\r\n idleTimeoutMs: DEFAULT_IDLE_TIMEOUT_MS,\r\n maxIterations: 5000,\r\n maxToolCalls: 15000,\r\n};\r\n\r\nexport function applyRosterBudget(cfg: SubagentConfig): SubagentConfig {\r\n // First try role-specific budget; fall back to generic for name-only delegates.\r\n const roleBudget = cfg.role ? FLEET_ROSTER_BUDGETS[cfg.role] : undefined;\r\n const defaultBudget = roleBudget ?? (cfg.name ? GENERIC_SUBAGENT_BUDGET : undefined);\r\n if (!defaultBudget) return cfg;\r\n return {\r\n ...cfg,\r\n // Wall-clock cap is opt-in only: forward an explicit `cfg.timeoutMs`, but\r\n // do NOT impose the roster's historical multi-hour wall-clock default — it\r\n // killed agents that were still actively working. Reaping is idle-based.\r\n timeoutMs: cfg.timeoutMs,\r\n // Idle window is the default reaper. Resets on activity, so a long-but-\r\n // productive run is never killed; only a genuine stall is reaped.\r\n idleTimeoutMs: cfg.idleTimeoutMs ?? defaultBudget.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS,\r\n maxIterations: cfg.maxIterations ?? defaultBudget.maxIterations,\r\n maxToolCalls: cfg.maxToolCalls ?? defaultBudget.maxToolCalls,\r\n maxTokens: cfg.maxTokens ?? defaultBudget.maxTokens,\r\n maxCostUsd: cfg.maxCostUsd ?? defaultBudget.maxCostUsd,\r\n };\r\n}\r\n\r\n/** Quick-access list for spawning all at once. */\r\nexport const ALL_FLEET_AGENTS = Object.values(FLEET_ROSTER);\r\n\r\n// ---------------------------------------------------------------------------\r\n// ACP external agents — WrongStack spawns these as subagents via ACP protocol.\r\n// Each agent runs its own loop; WrongStack sends tasks as ACP messages and\r\n// receives results. These don't go through makeAgentSubagentRunner — they\r\n// are handled by makeACPSubagentRunner in the CLI multi-agent layer.\r\n// ---------------------------------------------------------------------------\r\n\r\n/**\r\n * Cline — ACP-compatible coding agent by @asonix.\r\n * Spawned as: `npx @agentify/cline`\r\n */\r\nexport const CLINE_AGENT: SubagentConfig = {\r\n id: 'cline',\r\n name: 'Cline',\r\n role: 'cline',\r\n prompt: `You are Cline, a coding agent. You help write, edit, and navigate code.\r\nYou operate by receiving tasks via ACP and returning results.\r\nWhen asked to code, make focused changes and explain them briefly.`,\r\n provider: 'acp',\r\n};\r\n\r\n/**\r\n * Gemini CLI — Google's ACP-compatible command-line agent.\r\n * Spawned as: `gemini` (when gemini CLI is installed and in PATH)\r\n */\r\nexport const GEMINI_CLI_AGENT: SubagentConfig = {\r\n id: 'gemini-cli',\r\n name: 'Gemini CLI',\r\n role: 'gemini-cli',\r\n prompt: `You are Gemini CLI, a coding agent powered by Google's Gemini model.\r\nYou help with code generation, editing, debugging, and best practices.\r\nYou operate by receiving tasks via ACP and returning results.`,\r\n provider: 'acp',\r\n};\r\n\r\n/**\r\n * GitHub Copilot (public preview) — ACP-compatible Copilot CLI agent.\r\n * Spawned as: `gh copilot` (when gh CLI with copilot extension is installed)\r\n */\r\nexport const COPILOT_AGENT: SubagentConfig = {\r\n id: 'copilot',\r\n name: 'GitHub Copilot',\r\n role: 'copilot',\r\n prompt: `You are GitHub Copilot, an AI coding assistant.\r\nYou help write, explain, refactor, and review code.\r\nYou operate by receiving tasks via ACP and returning results.`,\r\n provider: 'acp',\r\n};\r\n\r\n/**\r\n * OpenHands — AI coding agent by all-in.ai, ACP-compatible.\r\n * Spawned as: `openhands` (when installed)\r\n */\r\nexport const OPENHANDS_AGENT: SubagentConfig = {\r\n id: 'openhands',\r\n name: 'OpenHands',\r\n role: 'openhands',\r\n prompt: `You are OpenHands, an AI coding agent that can use tools to interact\r\nwith files, terminals, browsers, and other resources.\r\nYou operate by receiving tasks via ACP and returning results.`,\r\n provider: 'acp',\r\n};\r\n\r\n/**\r\n * Goose — IDE agent by ExoRL, ACP-compatible.\r\n * Spawned as: `goose` (when goose CLI is installed)\r\n */\r\nexport const GOOSE_AGENT: SubagentConfig = {\r\n id: 'goose',\r\n name: 'Goose',\r\n role: 'goose',\r\n prompt: `You are Goose, an AI agent that helps with coding tasks.\r\nYou operate by receiving tasks via ACP and returning results.\r\nFocus on writing high-quality, well-tested code.`,\r\n provider: 'acp',\r\n};\r\n\r\n/** All ACP external agents. */\r\nexport const ACP_AGENTS: SubagentConfig[] = [\r\n CLINE_AGENT,\r\n GEMINI_CLI_AGENT,\r\n COPILOT_AGENT,\r\n OPENHANDS_AGENT,\r\n GOOSE_AGENT,\r\n];\r\n\r\n// ACP agents share the same generous budgets as the built-in fleet agents.\r\n// External ACP agents may need more time than typical in-process subagents\r\n// since they run their own loops and may do tool-call round-trips.\r\nFLEET_ROSTER_BUDGETS['cline'] = {timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000};\r\nFLEET_ROSTER_BUDGETS['gemini-cli'] = {timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000};\r\nFLEET_ROSTER_BUDGETS['copilot'] = {timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000};\r\nFLEET_ROSTER_BUDGETS['openhands'] = {timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000};\r\nFLEET_ROSTER_BUDGETS['goose'] = {timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000};\r\n\r\n/** Extended roster including ACP agents. */\r\nexport const FLEET_ROSTER_WITHACP: Record<string, SubagentConfig> = {\r\n ...FLEET_ROSTER,\r\n ...Object.fromEntries(ACP_AGENTS.map((a) => [a.role as string, a])),\r\n};\r\n","/**\n * Subagent nickname pool — famous scientists, mathematicians, and computing pioneers.\n * Names are grouped by domain affinity so the nickname hints at the agent's role.\n */\n\nconst NICKNAME_POOL = {\n // Physics & fundamental sciences\n 'einstein': { name: 'Einstein', domain: 'physics' },\n 'newton': { name: 'Newton', domain: 'physics' },\n 'feynman': { name: 'Feynman', domain: 'physics' },\n 'dirac': { name: 'Dirac', domain: 'physics' },\n 'bohr': { name: 'Bohr', domain: 'physics' },\n 'planck': { name: 'Planck', domain: 'physics' },\n 'curie': { name: 'Curie', domain: 'physics' },\n 'fermi': { name: 'Fermi', domain: 'physics' },\n 'heisenberg': { name: 'Heisenberg', domain: 'physics' },\n 'schrodinger': { name: 'Schrödinger', domain: 'physics' },\n\n // Mathematics\n 'euclid': { name: 'Euclid', domain: 'math' },\n 'gauss': { name: 'Gauss', domain: 'math' },\n 'turing': { name: 'Turing', domain: 'math' },\n 'poincare': { name: 'Poincaré', domain: 'math' },\n 'riemann': { name: 'Riemann', domain: 'math' },\n 'hilbert': { name: 'Hilbert', domain: 'math' },\n 'pythagoras': { name: 'Pythagoras', domain: 'math' },\n\n // Computing & information theory\n 'von-neumann': { name: 'Von Neumann', domain: 'computing' },\n 'shannon': { name: 'Shannon', domain: 'computing' },\n 'hopper': { name: 'Hopper', domain: 'computing' },\n 'backus': { name: 'Backus', domain: 'computing' },\n 'knuth': { name: 'Knuth', domain: 'computing' },\n 'torvalds': { name: 'Torvalds', domain: 'computing' },\n 'stallman': { name: 'Stallman', domain: 'computing' },\n 'berners-lee': { name: 'Berners-Lee', domain: 'computing' },\n 'babbage': { name: 'Babbage', domain: 'computing' },\n 'lovelace': { name: 'Lovelace', domain: 'computing' },\n 'klein': { name: 'Klein', domain: 'computing' },\n\n // Electronics & electrical engineering\n 'edison': { name: 'Edison', domain: 'ee' },\n 'tesla': { name: 'Tesla', domain: 'ee' },\n 'faraday': { name: 'Faraday', domain: 'ee' },\n 'maxwell': { name: 'Maxwell', domain: 'ee' },\n 'ohm': { name: 'Ohm', domain: 'ee' },\n 'bell': { name: 'Bell', domain: 'ee' },\n 'marconi': { name: 'Marconi', domain: 'ee' },\n 'lamarr': { name: 'Lamarr', domain: 'ee' },\n\n // General science / multi-disciplinary\n 'darwin': { name: 'Darwin', domain: 'biology' },\n 'mendel': { name: 'Mendel', domain: 'biology' },\n 'pasteur': { name: 'Pasteur', domain: 'biology' },\n 'hawking': { name: 'Hawking', domain: 'cosmology' },\n 'sagan': { name: 'Sagan', domain: 'cosmology' },\n\n // Exploration & navigation\n 'columbus': { name: 'Columbus', domain: 'exploration' },\n 'polo': { name: 'Polo', domain: 'exploration' },\n 'magellan': { name: 'Magellan', domain: 'exploration' },\n\n // Chemistry / materials\n 'lavoisier': { name: 'Lavoisier', domain: 'chemistry' },\n 'mendeleev': { name: 'Mendeleev', domain: 'chemistry' },\n} as const;\n\n/** Flat ordered list of all available nicknames — used for round-robin. */\nconst ALL_NICKNAMES = Object.values(NICKNAME_POOL);\n\n/** Domain → preferred nickname keys (fallback chain). */\nconst DOMAIN_PREFERENCES: Record<string, string[]> = {\n 'security': ['shannon', 'turing', 'lamarr', 'stallman'],\n 'bug-hunter': ['darwin', 'curie', 'feynman', 'fermi'],\n 'refactor': ['gauss', 'hilbert', 'euclid', 'planck'],\n 'audit-log': ['sagan', 'hawking', 'poincare', 'newton'],\n 'planner': ['hilbert', 'gauss', 'turing', 'euclid'],\n 'researcher': ['sagan', 'hawking', 'darwin', 'pasteur'],\n 'explorer': ['marconi', 'bell', 'columbus', 'polo'],\n 'testing': ['pasteur', 'curie', 'fermi', 'bohr'],\n 'frontend': ['lovelace', 'hopper', 'babbage', 'backus'],\n 'backend': ['torvalds', 'stallman', 'von-neumann', 'backus'],\n 'database': ['turing', 'shannon', 'backus', 'knuth'],\n 'devops': ['tesla', 'edison', 'faraday', 'bell'],\n 'security-scanner': ['shannon', 'turing', 'lamarr', 'stallman'],\n 'refactor-planner': ['gauss', 'hilbert', 'planck', 'newton'],\n 'architect': ['von-neumann', 'turing', 'gauss', 'hilbert'],\n 'critic': ['einstein', 'feynman', 'dirac', 'bohr'],\n 'e2e': ['hopper', 'bell', 'marconi', 'tesla'],\n 'performance': ['knuth', 'gauss', 'planck', 'feynman'],\n 'chaos': ['tesla', 'edison', 'curie', 'fermi'],\n 'cost': ['ohm', 'bell', 'marconi', 'tesla'],\n // default fallback\n 'default': ['einstein', 'newton', 'curie', 'tesla', 'edison', 'turing', 'shannon', 'hopper', 'knuth', 'stallman'],\n};\n\ntype NicknameKey = keyof typeof NICKNAME_POOL;\n\n/**\n * Assign a unique nickname to a subagent based on its role.\n * Returns `Name (Role)` formatted string, e.g. `Einstein (Bug Hunter)`.\n *\n * @param role - The subagent's role id (e.g. 'bug-hunter', 'security-scanner')\n * @param used - Set of nickname keys already assigned in this fleet\n * (so no two subagents share the same base name)\n */\nexport function assignNickname(role: string, used: ReadonlySet<string>): string {\n // 1. Build preference list: role-specific → default fallback\n const preferences = [\n ...(DOMAIN_PREFERENCES[role] ?? []),\n ...(DOMAIN_PREFERENCES['default'] ?? []),\n ];\n\n // 2. Find the first unassigned nickname from preferences. Skip keys that are\n // not in the pool — preference lists can drift out of sync with the pool\n // (typos, removed names), and an unknown key must not crash assignment.\n for (const key of preferences) {\n const entry = NICKNAME_POOL[key as NicknameKey];\n if (entry && !used.has(key)) {\n return `${entry.name} (${formatRole(role)})`;\n }\n }\n\n // 3. Exhausted preferences — pick the first unused name round-robin style\n for (const entry of ALL_NICKNAMES) {\n const key = Object.entries(NICKNAME_POOL).find(([, v]) => v.name === entry.name)?.[0];\n if (key && !used.has(key)) {\n return `${entry.name} (${formatRole(role)})`;\n }\n }\n\n // 4. Pool exhausted — append counter to last resort\n const counter = used.size + 1;\n return `Scientist #${counter} (${formatRole(role)})`;\n}\n\n/** Format role id into human-readable title-case. */\nfunction formatRole(role: string): string {\n return role\n .split(/[-_]/)\n .map((w) => w.charAt(0).toUpperCase() + w.slice(1))\n .join(' ');\n}\n\n/**\n * Returns all available nickname keys. Useful for testing or reset logic.\n */\nexport function getAllNicknameKeys(): string[] {\n return Object.keys(NICKNAME_POOL);\n}","import { randomUUID } from 'node:crypto';\r\nimport { EventEmitter } from 'node:events';\r\nimport type { AgentBridge, BridgeMessage } from '../types/agent-bridge.js';\r\nimport type {\r\n CoordinatorStatus,\r\n MultiAgentConfig,\r\n MultiAgentCoordinator,\r\n SpawnResult,\r\n SubagentConfig,\r\n SubagentContext,\r\n SubagentError,\r\n SubagentErrorKind,\r\n SubagentRunContext,\r\n SubagentRunner,\r\n TaskResult,\r\n TaskSpec,\r\n} from '../types/multi-agent.js';\r\nimport { ProviderError } from '../types/provider.js';\r\nimport { BudgetExceededError, SubagentBudget } from './subagent-budget.js';\r\nimport { applyRosterBudget } from './fleet.js';\r\nimport { assignNickname } from './subagent-nicknames.js';\r\n\r\ntype SubagentStatus = 'running' | 'idle' | 'stopped' | 'error';\r\n\r\ninterface SubagentEntry {\r\n config: SubagentConfig;\r\n context: SubagentContext;\r\n status: SubagentStatus;\r\n currentTask?: string;\r\n abortController: AbortController;\r\n /** Lazily created on first dispatch — budget is per-task, not per-subagent. */\r\n activeBudget?: SubagentBudget;\r\n}\r\n\r\nexport interface MultiAgentCoordinatorOptions {\r\n /**\r\n * Callback that executes a task on behalf of a subagent. Required for\r\n * `assign()` to actually run anything — without it, tasks queue forever.\r\n * The coordinator provides per-subagent isolation (own budget, own signal,\r\n * own bridge) and enforces timeout + concurrency.\r\n */\r\n runner?: SubagentRunner;\r\n}\r\n\r\nexport class DefaultMultiAgentCoordinator extends EventEmitter implements MultiAgentCoordinator {\r\n readonly coordinatorId: string;\r\n readonly config: MultiAgentConfig;\r\n private runner?: SubagentRunner;\r\n private fleetBus?: import('./fleet-bus.js').FleetBus;\r\n\r\n private readonly subagents = new Map<string, SubagentEntry>();\r\n\r\n /**\r\n * Base nickname keys already handed out this run (e.g. `einstein`, `tesla`).\r\n * Prevents two workers sharing a name. Direct `coordinator.spawn()` callers\r\n * (parallel/eternal engine, SDD parallel run) don't go through\r\n * `Director.spawn()` where nicknames are normally assigned, so the\r\n * coordinator upgrades placeholder names (\"Executor\", \"slot-ab12cd\", role\r\n * names) to memorable ones here — that's what surfaces in the fleet monitor.\r\n */\r\n private readonly usedNicknames = new Set<string>();\r\n /** Maps subagentId → nickname key (e.g. 'einstein'). Used to free the slot on remove(). */\r\n private readonly subagentNicknames = new Map<string, string>();\r\n\r\n private pendingTasks: TaskSpec[] = [];\r\n private completedResults: TaskResult[] = [];\r\n /** Prevents completedResults from growing unbounded in long-running coordinators. */\r\n private static readonly MAX_COMPLETED_RESULTS = 10_000;\r\n private totalIterations = 0;\r\n private inFlight = 0;\r\n /**\r\n * Subagents currently being stopped. Set on entry to `stop()`, cleared\r\n * once `recordCompletion` lands the terminal TaskResult. Used by\r\n * `runDispatched` and `findIdleSubagent` to refuse mid-flight dispatch\r\n * to a subagent the caller has already asked to terminate — closes the\r\n * assign+terminate race where a fresh task could land on a worker that\r\n * was about to be killed.\r\n */\r\n private readonly terminating = new Set<string>();\r\n\r\n constructor(config: MultiAgentConfig, options: MultiAgentCoordinatorOptions = {}) {\r\n super();\r\n this.coordinatorId = config.coordinatorId;\r\n this.config = config;\r\n this.runner = options.runner;\r\n }\r\n\r\n /**\r\n * Replace the runner after construction. Used when the runner depends\r\n * on infrastructure (e.g. FleetBus) that isn't available until after\r\n * the coordinator's owning Director is built.\r\n */\r\n setRunner(runner: SubagentRunner): void {\r\n this.runner = runner;\r\n }\r\n\r\n /**\r\n * Wire a FleetBus for director-mode event emission. Call after the\r\n * FleetManager is constructed so the coordinator can emit lifecycle\r\n * events the TUI and monitoring tools subscribe to.\r\n */\r\n setFleetBus(fleet: import('./fleet-bus.js').FleetBus): void {\r\n this.fleetBus = fleet;\r\n }\r\n\r\n /**\r\n * Change the in-flight dispatch ceiling at runtime. Lowering does NOT\r\n * preempt running tasks — already-dispatched subagents finish their\r\n * current task; only future dispatches respect the new cap. Raising\r\n * immediately tries to fill the freed slots from the pending queue.\r\n */\r\n setMaxConcurrent(n: number): void {\r\n if (!Number.isFinite(n) || n < 1) {\r\n throw new Error(`maxConcurrent must be a finite integer >= 1, got ${n}`);\r\n }\r\n this.config.maxConcurrent = Math.floor(n);\r\n this.tryDispatchNext();\r\n }\r\n\r\n /**\r\n * Upgrade a placeholder/role-derived name to a memorable scientist nickname\r\n * (e.g. \"Einstein (Executor)\"). A name is treated as a placeholder when it is\r\n * empty, equals the role (case-insensitive), is a generic default\r\n * (\"subagent\"/\"adhoc\"/\"generic\"), or is an auto-generated `slot-…` id.\r\n * Explicit, human-chosen names — including nicknames already assigned by\r\n * `Director.spawn()` — are left untouched, so this never double-assigns.\r\n */\r\n private withNickname(subagent: SubagentConfig, subagentId: string): SubagentConfig {\r\n const role = subagent.role ?? 'subagent';\r\n const name = subagent.name?.trim() ?? '';\r\n const isPlaceholder =\r\n name === '' ||\r\n name.toLowerCase() === role.toLowerCase() ||\r\n name === 'subagent' ||\r\n name === 'adhoc' ||\r\n name === 'generic' ||\r\n /^slot-/.test(name);\r\n if (!isPlaceholder) return subagent;\r\n const nickname = assignNickname(role, this.usedNicknames);\r\n const baseKey = nickname.split(' ')[0]!.toLowerCase().replace(/[^a-z0-9-]/g, '-');\r\n this.usedNicknames.add(baseKey);\r\n this.subagentNicknames.set(subagentId, baseKey);\r\n return { ...subagent, name: nickname };\r\n }\r\n\r\n async spawn(subagent: SubagentConfig): Promise<SpawnResult> {\r\n const id = subagent.id || randomUUID();\r\n subagent = this.withNickname(subagent, id);\r\n // Duplicate-id guard. Previously a second spawn({id}) with the\r\n // same id silently overwrote the existing entry — orphaning the\r\n // first subagent's AbortController, Context, and any in-flight\r\n // task referencing it. Two spawns with the same id are almost\r\n // always a bug at the caller; refuse and let them surface it.\r\n if (this.subagents.has(id)) {\r\n throw new Error(`Subagent id \"${id}\" already exists — refusing to overwrite`);\r\n }\r\n const context: SubagentContext = {\r\n subagentId: id,\r\n tasks: [],\r\n // Wired later by the caller via setSubagentBridge() once the\r\n // bidirectional bridge is created. Readers must null-check / use\r\n // hasParentBridge() — the type now reflects this.\r\n parentBridge: null,\r\n doneCondition: this.config.doneCondition,\r\n maxConcurrent: this.config.maxConcurrent ?? 16,\r\n };\r\n\r\n this.subagents.set(id, {\r\n config: { ...subagent, id },\r\n context,\r\n status: 'idle',\r\n abortController: new AbortController(),\r\n });\r\n\r\n this.emit('subagent.started', { subagent: { ...subagent, id } });\r\n\r\n this.fleetBus?.emit({\r\n subagentId: id,\r\n ts: Date.now(),\r\n type: 'subagent.assigned',\r\n payload: {\r\n subagentId: id,\r\n name: subagent.name,\r\n provider: subagent.provider,\r\n model: subagent.model,\r\n },\r\n });\r\n\r\n this.emitCoordinatorStats();\r\n\r\n return { subagentId: id, agentId: id };\r\n }\r\n\r\n async assign(task: TaskSpec): Promise<void> {\r\n this.pendingTasks.push(task);\r\n this.tryDispatchNext();\r\n }\r\n\r\n async delegate(to: string, msg: BridgeMessage): Promise<void> {\r\n const subagent = this.subagents.get(to);\r\n if (!subagent) throw new Error(`Subagent \"${to}\" not found`);\r\n if (!subagent.context.parentBridge) {\r\n throw new Error(`Subagent \"${to}\" has no parentBridge — call setSubagentBridge() first`);\r\n }\r\n await subagent.context.parentBridge.send(msg);\r\n }\r\n\r\n /**\r\n * Wire up the communication bridge for a subagent. Call after spawn() once\r\n * the caller has created the bidirectional connection.\r\n */\r\n setSubagentBridge(subagentId: string, bridge: AgentBridge): void {\r\n const subagent = this.subagents.get(subagentId);\r\n if (!subagent) throw new Error(`Subagent \"${subagentId}\" not found`);\r\n subagent.context.parentBridge = bridge;\r\n }\r\n\r\n async stop(subagentId: string): Promise<void> {\r\n const subagent = this.subagents.get(subagentId);\r\n if (!subagent) return;\r\n\r\n // Mark terminating BEFORE the abort so a synchronous tryDispatchNext\r\n // observation in another callback path sees the intent and skips\r\n // this subagent. Cleared by recordCompletion once the runner's\r\n // catch block lands the terminal TaskResult.\r\n this.terminating.add(subagentId);\r\n\r\n // Abort any in-flight run, then sever the bridge so further messages fail\r\n // fast instead of silently queueing on a dead subagent.\r\n subagent.abortController.abort();\r\n subagent.status = 'stopped';\r\n subagent.currentTask = undefined;\r\n subagent.context.parentBridge = null;\r\n\r\n this.emit('subagent.stopped', { subagentId, reason: 'stopped by coordinator' });\r\n\r\n this.fleetBus?.emit({\r\n subagentId,\r\n ts: Date.now(),\r\n type: 'subagent.stopped',\r\n payload: { subagentId, reason: 'stopped by coordinator' },\r\n });\r\n\r\n this.emitCoordinatorStats();\r\n }\r\n\r\n async stopAll(): Promise<void> {\r\n // Clear the queue FIRST so no new tasks land on subagents while\r\n // we're tearing them down. Each dropped task gets a synthetic\r\n // `aborted_by_parent` completion so any caller awaiting it (e.g.\r\n // delegate tool's awaitTasks) resolves instead of hanging.\r\n //\r\n // Pending tasks never reached `inFlight`, so we cannot route them\r\n // through `recordCompletion` — its underflow guard would short-\r\n // circuit on the second pending task and emit a warning instead\r\n // of the completion event. The shared helper inline-emits.\r\n this.drainPendingAsAborted('Coordinator stopAll() drained the pending queue');\r\n // allSettled so one failure doesn't leave other subagents un-stopped.\r\n await Promise.allSettled([...this.subagents.keys()].map((id) => this.stop(id)));\r\n }\r\n\r\n /**\r\n * Get current coordinator stats for monitoring/debugging.\r\n */\r\n getStats(): {\r\n total: number;\r\n running: number;\r\n idle: number;\r\n stopped: number;\r\n inFlight: number;\r\n pending: number;\r\n completed: number;\r\n } {\r\n let running = 0;\r\n let idle = 0;\r\n let stopped = 0;\r\n for (const [, entry] of this.subagents) {\r\n if (entry.status === 'running') running++;\r\n else if (entry.status === 'idle') idle++;\r\n else stopped++;\r\n }\r\n return {\r\n total: this.subagents.size,\r\n running,\r\n idle,\r\n stopped,\r\n inFlight: this.inFlight,\r\n pending: this.pendingTasks.length,\r\n completed: this.completedResults.length,\r\n };\r\n }\r\n\r\n /** Emit a reactive coordinator.stats event on FleetBus so the TUI can subscribe. */\r\n private emitCoordinatorStats(): void {\r\n const stats = this.getStats();\r\n const subagentStatuses = Array.from(this.subagents.entries()).map(([id, s]) => ({\r\n subagentId: id,\r\n taskId: s.currentTask ?? '',\r\n status: s.status,\r\n assigned: s.context.parentBridge !== null,\r\n }));\r\n this.fleetBus?.emit({\r\n subagentId: this.coordinatorId,\r\n ts: Date.now(),\r\n type: 'coordinator.stats',\r\n payload: { ...stats, subagentStatuses },\r\n });\r\n }\r\n\r\n getStatus(): CoordinatorStatus {\r\n return {\r\n coordinatorId: this.coordinatorId,\r\n subagents: Array.from(this.subagents.entries()).map(([id, s]) => ({\r\n id,\r\n name: s.config.name,\r\n status: s.status,\r\n currentTask: s.currentTask,\r\n })),\r\n pendingTasks: this.pendingTasks.length,\r\n completedTasks: this.completedResults.length,\r\n totalIterations: this.totalIterations,\r\n done: this.isDone(),\r\n };\r\n }\r\n\r\n /** Expose snapshot of completed results — useful for callers awaiting all done. */\r\n results(): readonly TaskResult[] {\r\n return this.completedResults;\r\n }\r\n\r\n /**\r\n * Wait for one or more tasks to complete and return their results.\r\n * If a task is already done when called, returns immediately.\r\n * Resolves to an array in the same order as `taskIds`.\r\n */\r\n async awaitTasks(taskIds: string[]): Promise<TaskResult[]> {\r\n return Promise.all(\r\n taskIds.map((id) => {\r\n const cached = this.completedResults.find((r) => r.taskId === id);\r\n if (cached) return cached;\r\n // Fallback: poll until the task completes (up to timeoutMs).\r\n // The coordinator fires 'task.completed' on every result, so\r\n // we use a promise-based waiter tied to that event.\r\n return new Promise<TaskResult>((resolve, reject) => {\r\n const timeout = setTimeout(() => {\r\n this.off('task.completed', handler);\r\n reject(new Error(`awaitTasks timed out waiting for task \"${id}\"`));\r\n }, this.config.timeoutMs ?? 300_000);\r\n const handler = ({ result }: { task: TaskSpec; result: TaskResult }) => {\r\n if (result.taskId === id) {\r\n clearTimeout(timeout);\r\n this.off('task.completed', handler);\r\n resolve(result);\r\n }\r\n };\r\n this.on('task.completed', handler);\r\n });\r\n }),\r\n );\r\n }\r\n\r\n /**\r\n * Manual completion — for callers that drive subagents without a runner\r\n * (e.g. external orchestrators). When a runner is configured the coordinator\r\n * calls this itself.\r\n */\r\n completeTask(result: TaskResult): void {\r\n this.recordCompletion(result);\r\n }\r\n\r\n // --- internal dispatching ---------------------------------------------\r\n\r\n private tryDispatchNext(): void {\r\n while (this.canDispatch()) {\r\n const dispatchable = this.takeNextDispatchableTask();\r\n if (!dispatchable) {\r\n // No idle worker right now. If every spawned subagent is\r\n // stopped or mid-termination, the pending queue is dead —\r\n // a pending task can never start, so synthetic-complete it\r\n // as `aborted_by_parent`. Without this, an `assign()` after\r\n // `stop()` would hang forever waiting for `task.completed`.\r\n // We DO NOT drain when subagents are busy (status='running'):\r\n // those will free up and accept the work normally.\r\n if (this.pendingTasks.length > 0 && !this.hasLiveSubagent()) {\r\n this.drainPendingAsAborted(\r\n 'No live subagent available — all stopped or mid-termination',\r\n );\r\n }\r\n return;\r\n }\r\n const { subagentId, task } = dispatchable;\r\n // Attach a catch so a synchronous throw inside runDispatched (rare —\r\n // e.g. provider misconfiguration before the first await) becomes a\r\n // visible failed task instead of an unhandled rejection that leaves\r\n // `inFlight` permanently elevated.\r\n this.runDispatched(subagentId, task).catch((err) => {\r\n this.recordCompletion({\r\n subagentId,\r\n taskId: task.id,\r\n status: 'failed',\r\n error: classifySubagentError(err),\r\n iterations: 0,\r\n toolCalls: 0,\r\n durationMs: 0,\r\n });\r\n });\r\n }\r\n }\r\n\r\n private canDispatch(): boolean {\r\n const max = this.config.maxConcurrent ?? 16;\r\n return this.inFlight < max && this.pendingTasks.length > 0;\r\n }\r\n\r\n private takeNextDispatchableTask(): { subagentId: string; task: TaskSpec } | null {\r\n for (let i = 0; i < this.pendingTasks.length; i++) {\r\n const task = this.pendingTasks[i]!;\r\n const subagentId = task.subagentId\r\n ? this.isIdleSubagent(task.subagentId)\r\n ? task.subagentId\r\n : null\r\n : this.findIdleSubagent();\r\n if (!subagentId) continue;\r\n this.pendingTasks.splice(i, 1);\r\n return { subagentId, task };\r\n }\r\n return null;\r\n }\r\n\r\n private findIdleSubagent(): string | null {\r\n for (const [id, s] of this.subagents) {\r\n // Skip subagents that are mid-termination — `stop()` set the\r\n // `terminating` flag and aborted the controller, but the\r\n // status mutation happens synchronously after; checking both\r\n // is belt-and-suspenders against any race where status is\r\n // transiently still 'idle' while termination is in flight.\r\n if (s.status === 'idle' && !this.terminating.has(id)) return id;\r\n }\r\n return null;\r\n }\r\n\r\n private isIdleSubagent(id: string): boolean {\r\n const subagent = this.subagents.get(id);\r\n return !!subagent && subagent.status === 'idle' && !this.terminating.has(id);\r\n }\r\n\r\n /**\r\n * Returns true iff at least one spawned subagent could still\r\n * process a task. A \"live\" subagent is one that is not stopped\r\n * AND not mid-termination — `running` workers count because they\r\n * will eventually finish and become idle.\r\n *\r\n * When no subagent has ever been spawned, returns `true` so a\r\n * pre-spawn `assign()` simply queues (legacy behaviour). The\r\n * dead-end detection only fires after `stop()` has retired every\r\n * spawned worker.\r\n *\r\n * Used by `tryDispatchNext` to detect a dead-end pending queue.\r\n */\r\n private hasLiveSubagent(): boolean {\r\n if (this.subagents.size === 0) return true;\r\n for (const [id, s] of this.subagents) {\r\n if (s.status !== 'stopped' && !this.terminating.has(id)) return true;\r\n }\r\n return false;\r\n }\r\n\r\n /**\r\n * Drain every pending task with a synthetic `aborted_by_parent`\r\n * completion event. Same shape as the `stopAll()` drain — we go\r\n * around `recordCompletion` because pending tasks were never\r\n * counted in `inFlight` and routing them through would trip the\r\n * underflow guard on every task after the first.\r\n */\r\n private drainPendingAsAborted(message: string): void {\r\n const dropped = this.pendingTasks.splice(0, this.pendingTasks.length);\r\n for (const t of dropped) {\r\n const synthetic: TaskResult = {\r\n subagentId: t.subagentId ?? 'unassigned',\r\n taskId: t.id,\r\n status: 'stopped',\r\n error: {\r\n kind: 'aborted_by_parent',\r\n message,\r\n retryable: false,\r\n },\r\n iterations: 0,\r\n toolCalls: 0,\r\n durationMs: 0,\r\n };\r\n this.completedResults.push(synthetic);\r\n this.emit('task.completed', { task: t, result: synthetic });\r\n }\r\n }\r\n\r\n private async runDispatched(subagentId: string, task: TaskSpec): Promise<void> {\r\n const subagent = this.subagents.get(subagentId);\r\n if (!subagent) return;\r\n // Final race guard: if `stop(subagentId)` ran between dispatch\r\n // and us arriving here, refuse to start the task and surface it\r\n // as `aborted_by_parent` so any caller awaiting the task id\r\n // unblocks. Without this, the task would be marked 'running',\r\n // collide with the just-completed 'stopped' state, and leak\r\n // inFlight by 1 because no recordCompletion path covers it.\r\n if (this.terminating.has(subagentId) || subagent.status === 'stopped') {\r\n this.recordCompletion({\r\n subagentId,\r\n taskId: task.id,\r\n status: 'stopped',\r\n error: {\r\n kind: 'aborted_by_parent',\r\n message: 'Subagent was terminated before task could start',\r\n retryable: false,\r\n },\r\n iterations: 0,\r\n toolCalls: 0,\r\n durationMs: 0,\r\n });\r\n return;\r\n }\r\n\r\n subagent.status = 'running';\r\n subagent.currentTask = task.id;\r\n task.subagentId = subagentId;\r\n subagent.context.tasks.push(task);\r\n\r\n this.fleetBus?.emit({\r\n subagentId,\r\n taskId: task.id,\r\n ts: Date.now(),\r\n type: 'subagent.running',\r\n payload: { subagentId, taskId: task.id },\r\n });\r\n\r\n this.emit('task.assigned', { task, subagentId });\r\n this.emitCoordinatorStats();\r\n\r\n // Budget combines coordinator defaults with per-subagent and per-task overrides.\r\n // Precedence: task > subagent (raw, no roster fills) > coordinator default > roster default.\r\n // We intentionally call applyRosterBudget LATE — only as a final fallback after\r\n // the coordinator's defaultBudget has had a chance to apply. This prevents\r\n // GENERIC_SUBAGENT_BUDGET (5000 iter) from shadowing the coordinator's explicit default.\r\n const rawMaxIterations = subagent.config.maxIterations;\r\n const rawMaxToolCalls = subagent.config.maxToolCalls;\r\n const rawMaxTokens = subagent.config.maxTokens;\r\n const rawMaxCostUsd = subagent.config.maxCostUsd;\r\n const rawTimeoutMs = subagent.config.timeoutMs;\r\n const rawIdleTimeoutMs = subagent.config.idleTimeoutMs;\r\n const configWithRosterDefaults = applyRosterBudget(subagent.config);\r\n const budget = new SubagentBudget({\r\n maxIterations:\r\n rawMaxIterations ?? this.config.defaultBudget?.maxIterations ?? configWithRosterDefaults.maxIterations,\r\n maxToolCalls:\r\n rawMaxToolCalls ??\r\n this.config.defaultBudget?.maxToolCalls ??\r\n configWithRosterDefaults.maxToolCalls,\r\n maxTokens:\r\n rawMaxTokens ?? this.config.defaultBudget?.maxTokens ?? configWithRosterDefaults.maxTokens,\r\n maxCostUsd:\r\n rawMaxCostUsd ?? this.config.defaultBudget?.maxCostUsd ?? configWithRosterDefaults.maxCostUsd,\r\n // Wall-clock cap is opt-in (explicit config / defaultBudget only); the\r\n // roster no longer supplies one. Idle is the default reaper.\r\n timeoutMs:\r\n rawTimeoutMs ?? this.config.defaultBudget?.timeoutMs ?? configWithRosterDefaults.timeoutMs,\r\n idleTimeoutMs:\r\n rawIdleTimeoutMs ??\r\n this.config.defaultBudget?.idleTimeoutMs ??\r\n configWithRosterDefaults.idleTimeoutMs,\r\n });\r\n subagent.activeBudget = budget;\r\n\r\n if (!this.runner) {\r\n // No runner wired — caller drives execution via completeTask(). Status\r\n // reverts when the caller reports. We intentionally don't bump\r\n // `inFlight` here: `completeTask` → `recordCompletion` would then\r\n // decrement an inFlight that runDispatched never incremented, masking\r\n // the \"no runner\" state. With this guard, `isDone()`'s all_tasks_done\r\n // check still settles correctly once the caller reports.\r\n return;\r\n }\r\n\r\n // Only count inFlight when we actually own the execution lifecycle.\r\n this.inFlight++;\r\n\r\n const startTime = Date.now();\r\n const runCtx: SubagentRunContext = {\r\n subagentId,\r\n config: subagent.config,\r\n budget,\r\n signal: subagent.abortController.signal,\r\n bridge: subagent.context.parentBridge || null,\r\n };\r\n\r\n let result: TaskResult;\r\n\r\n budget.start();\r\n try {\r\n const outcome = await this.executeWithTimeout(this.runner, task, runCtx, budget);\r\n result = {\r\n subagentId,\r\n taskId: task.id,\r\n status: 'success',\r\n result: outcome.result,\r\n iterations: outcome.iterations,\r\n toolCalls: outcome.toolCalls,\r\n durationMs: Date.now() - startTime,\r\n };\r\n } catch (err) {\r\n // Order matters: a timeout calls abort() to signal cooperative runners,\r\n // which also flips `signal.aborted=true`. Inspect the error first so we\r\n // surface 'timeout' rather than masking it as 'stopped'.\r\n const status: TaskResult['status'] =\r\n err instanceof BudgetExceededError && (err.kind === 'timeout' || err.kind === 'idle_timeout')\r\n ? 'timeout'\r\n : subagent.abortController.signal.aborted\r\n ? 'stopped'\r\n : 'failed';\r\n const usage = budget.usage();\r\n result = {\r\n subagentId,\r\n taskId: task.id,\r\n status,\r\n error: classifySubagentError(err, {\r\n parentAborted: subagent.abortController.signal.aborted,\r\n }),\r\n iterations: usage.iterations,\r\n toolCalls: usage.toolCalls,\r\n durationMs: Date.now() - startTime,\r\n };\r\n }\r\n\r\n this.recordCompletion(result);\r\n }\r\n\r\n private async executeWithTimeout(\r\n runner: SubagentRunner,\r\n task: TaskSpec,\r\n ctx: SubagentRunContext,\r\n budget: SubagentBudget,\r\n ) {\r\n const initialTimeoutMs = budget.limits.timeoutMs;\r\n const idleLimitMs = budget.limits.idleTimeoutMs;\r\n if (initialTimeoutMs === undefined && idleLimitMs === undefined) {\r\n return runner(task, ctx);\r\n }\r\n\r\n // Re-armable watchdog. The default guard is IDLE-based: while the agent\r\n // keeps producing activity (iterations / tool calls / streamed progress),\r\n // `budget.idleMs()` stays below the window and we simply re-arm — an\r\n // actively-working subagent is never killed by the clock. Only a genuine\r\n // stall (no activity for `idleTimeoutMs`) reaps it. An explicit wall-clock\r\n // `timeoutMs` (rare, opt-in) keeps the original soft-warning behaviour: it\r\n // negotiates an extension via the Director's auto-extend listener and\r\n // re-arms rather than hard-killing a task solely for running long.\r\n const start = Date.now();\r\n let timer: ReturnType<typeof setTimeout> | null = null;\r\n\r\n const timeoutPromise = new Promise<never>((_, reject) => {\r\n const armFor = (ms: number) => {\r\n if (timer) clearTimeout(timer);\r\n timer = setTimeout(onTick, Math.max(0, ms));\r\n };\r\n // Re-arm for whichever deadline is sooner — the idle window (counted\r\n // from last activity) or the explicit wall-clock cap. Either being\r\n // unset drops out of the min, so single-limit configs behave exactly\r\n // as that limit alone.\r\n const scheduleNext = () => {\r\n const wallRemaining =\r\n initialTimeoutMs === undefined\r\n ? Number.POSITIVE_INFINITY\r\n : (budget.limits.timeoutMs ?? initialTimeoutMs) - (Date.now() - start);\r\n const idleRemaining =\r\n idleLimitMs === undefined\r\n ? Number.POSITIVE_INFINITY\r\n : (budget.limits.idleTimeoutMs ?? idleLimitMs) - budget.idleMs();\r\n // Floor at a small positive so a near-zero remainder can't busy-loop.\r\n armFor(Math.max(25, Math.min(wallRemaining, idleRemaining)));\r\n };\r\n\r\n const onTick = async () => {\r\n const elapsed = Date.now() - start;\r\n const wallLimit =\r\n initialTimeoutMs === undefined ? undefined : budget.limits.timeoutMs ?? initialTimeoutMs;\r\n const idleLimit =\r\n idleLimitMs === undefined ? undefined : budget.limits.idleTimeoutMs ?? idleLimitMs;\r\n const wallExceeded = wallLimit !== undefined && elapsed >= wallLimit;\r\n const idleExceeded = idleLimit !== undefined && budget.idleMs() >= idleLimit;\r\n\r\n // Idle stall with no wall-clock cap also due: a genuinely hung agent\r\n // (no activity for the whole window). Reap it directly — idle is not\r\n // negotiable; the point of the default is to free a stuck slot.\r\n if (idleExceeded && !wallExceeded) {\r\n this.subagents.get(ctx.subagentId)?.abortController.abort();\r\n reject(new BudgetExceededError('timeout', idleLimit!, budget.idleMs()));\r\n return;\r\n }\r\n // Neither deadline actually tripped — we woke early because activity\r\n // pushed the idle deadline out. Re-arm for the new soonest deadline.\r\n if (!wallExceeded) {\r\n scheduleNext();\r\n return;\r\n }\r\n\r\n // Wall-clock cap hit. This is opt-in and keeps the original\r\n // soft-warning behaviour: negotiate an extension rather than\r\n // hard-killing a task solely for running long.\r\n const limit = wallLimit!;\r\n // Without an onThreshold handler the original behaviour stands:\r\n // abort the signal and hard-reject. This preserves the contract\r\n // for direct SubagentBudget consumers that don't wire negotiation.\r\n if (!budget.onThreshold) {\r\n this.subagents.get(ctx.subagentId)?.abortController.abort();\r\n reject(new BudgetExceededError('timeout', limit, elapsed));\r\n return;\r\n }\r\n // With a handler, ask for an extension. The budget's\r\n // requestDecision returns 'stop' on no response (decision\r\n // fallback timer inside SubagentBudget), so this never hangs.\r\n try {\r\n const result = budget.onThreshold({\r\n kind: 'timeout',\r\n used: elapsed,\r\n limit,\r\n requestDecision: () =>\r\n new Promise((resolveDecision) => {\r\n budget._events?.emit('budget.threshold_reached', {\r\n kind: 'timeout',\r\n used: elapsed,\r\n limit,\r\n timeoutMs: 60_000,\r\n extend: (extra) => resolveDecision({ extend: extra }),\r\n deny: () => resolveDecision('stop'),\r\n });\r\n }),\r\n });\r\n const decision = typeof result === 'string' ? result : await result;\r\n if (decision === 'continue' || decision === 'throw' || decision === 'stop') {\r\n // Timeout denied / no-op — re-arm for another full wall window so\r\n // we ask again later. This makes wall-clock timeout a pure warning\r\n // event: the subagent keeps running until it naturally finishes or\r\n // the user stops it. No task is hard-killed solely for running long.\r\n armFor(Math.max(1_000, limit));\r\n return;\r\n }\r\n // 'extend' — patch budget and re-arm for the new remainder.\r\n if (decision.extend.timeoutMs !== undefined) {\r\n (budget.limits as Record<string, unknown>).timeoutMs = decision.extend.timeoutMs;\r\n scheduleNext();\r\n return;\r\n }\r\n // No timeoutMs in extend — fall through to reject.\r\n this.subagents.get(ctx.subagentId)?.abortController.abort();\r\n reject(new BudgetExceededError('timeout', limit, elapsed));\r\n } catch (err) {\r\n this.subagents.get(ctx.subagentId)?.abortController.abort();\r\n reject(\r\n err instanceof BudgetExceededError\r\n ? err\r\n : new BudgetExceededError('timeout', limit, elapsed),\r\n );\r\n }\r\n };\r\n // First arm: whichever of the idle window / wall-clock cap is sooner.\r\n scheduleNext();\r\n });\r\n\r\n try {\r\n return await Promise.race([runner(task, ctx), timeoutPromise]);\r\n } finally {\r\n if (timer) clearTimeout(timer);\r\n }\r\n }\r\n\r\n private recordCompletion(result: TaskResult): void {\r\n this.completedResults.push(result);\r\n // Trim oldest entries when the cap is exceeded — keep the most recent\r\n // results so /fleet and roll_up still have data to work with.\r\n if (this.completedResults.length > DefaultMultiAgentCoordinator.MAX_COMPLETED_RESULTS) {\r\n this.completedResults.splice(\r\n 0,\r\n this.completedResults.length - DefaultMultiAgentCoordinator.MAX_COMPLETED_RESULTS,\r\n );\r\n }\r\n this.totalIterations += result.iterations;\r\n if (this.inFlight > 0) {\r\n this.inFlight--;\r\n } else if (this.runner) {\r\n // Runner-driven path completed without an outstanding inFlight slot —\r\n // shouldn't happen unless completeTask was called externally.\r\n this.emit('warning', {\r\n type: 'inFlight_underflow',\r\n taskId: result.taskId,\r\n subagentId: result.subagentId,\r\n });\r\n return;\r\n }\r\n\r\n const subagent = this.subagents.get(result.subagentId);\r\n if (subagent && subagent.status !== 'stopped') {\r\n const failed = result.status === 'failed' || result.status === 'timeout';\r\n // Synchronously reset the worker to idle after either a clean\r\n // finish or a transient failure. The previous code parked the\r\n // subagent in 'error' and used a `queueMicrotask` to flip it\r\n // back to 'idle' — that opened a window where `assign()` +\r\n // `tryDispatchNext` could race the microtask, leaving the\r\n // worker stuck in 'running' state while actually idle. By\r\n // resetting now, no async gap can leak the state machine.\r\n subagent.status = 'idle';\r\n void failed; // kept for future telemetry hooks\r\n subagent.currentTask = undefined;\r\n // If the run aborted (timeout or explicit stop), the subagent's\r\n // signal is now permanently aborted — recycling the controller lets\r\n // the next dispatched task start with a fresh cancellation scope.\r\n if (subagent.abortController.signal.aborted) {\r\n subagent.abortController = new AbortController();\r\n }\r\n\r\n this.fleetBus?.emit({\r\n subagentId: result.subagentId,\r\n ts: Date.now(),\r\n type: 'subagent.idle',\r\n payload: { subagentId: result.subagentId },\r\n });\r\n }\r\n // Clear the terminating flag now that the worker has a terminal\r\n // TaskResult on record. Subsequent stop() calls re-add it; new\r\n // assign() calls can flow normally.\r\n this.terminating.delete(result.subagentId);\r\n\r\n this.emit('task.completed', {\r\n task: subagent?.context.tasks.find((t) => t.id === result.taskId) ?? { id: result.taskId },\r\n result,\r\n });\r\n\r\n this.fleetBus?.emit({\r\n subagentId: result.subagentId,\r\n taskId: result.taskId,\r\n ts: Date.now(),\r\n type: 'subagent.completed',\r\n payload: {\r\n subagentId: result.subagentId,\r\n taskId: result.taskId,\r\n status: result.status,\r\n iterations: result.iterations,\r\n toolCalls: result.toolCalls,\r\n durationMs: result.durationMs,\r\n },\r\n });\r\n\r\n this.tryDispatchNext();\r\n\r\n // Emit after tryDispatchNext so the stats reflect the post-dispatch\r\n // state (either a new running subagent, or idle if the queue is drained).\r\n this.emitCoordinatorStats();\r\n\r\n if (this.isDone()) {\r\n this.emit('done', {\r\n results: this.completedResults,\r\n totalIterations: this.totalIterations,\r\n });\r\n }\r\n }\r\n\r\n /**\r\n * Stop a subagent and remove it from the coordinator. Releases all\r\n * associated resources (AbortController, context, budget state).\r\n * The subagent entry is deleted so the id can be reused in a future spawn.\r\n */\r\n async remove(subagentId: string): Promise<void> {\r\n const subagent = this.subagents.get(subagentId);\r\n if (!subagent) return;\r\n\r\n // Gracefully stop first — same logic as stop() but don't block on it.\r\n if (subagent.status === 'running' || subagent.status === 'idle') {\r\n this.terminating.add(subagentId);\r\n subagent.abortController.abort();\r\n subagent.status = 'stopped';\r\n }\r\n\r\n // Release all resources associated with this subagent.\r\n this.subagents.delete(subagentId);\r\n this.terminating.delete(subagentId);\r\n // Free the nickname slot so the same name can be reused by a future spawn.\r\n const nicknameKey = this.subagentNicknames.get(subagentId);\r\n if (nicknameKey) {\r\n this.usedNicknames.delete(nicknameKey);\r\n this.subagentNicknames.delete(subagentId);\r\n }\r\n\r\n // Clean up any pending tasks assigned to this subagent — emit synthetic\r\n // 'stopped' completions so callers awaiting them via awaitTasks() unblock\r\n // instead of hanging forever. Without this, a task queued for a removed\r\n // subagent would leave its waiter permanently unresolved.\r\n const orphaned = this.pendingTasks.filter((t) => t.subagentId === subagentId);\r\n this.pendingTasks = this.pendingTasks.filter((t) => t.subagentId !== subagentId);\r\n for (const t of orphaned) {\r\n const synthetic: TaskResult = {\r\n subagentId,\r\n taskId: t.id,\r\n status: 'stopped',\r\n error: {\r\n kind: 'aborted_by_parent',\r\n message: `Subagent \"${subagentId}\" was removed while task \"${t.id}\" was pending`,\r\n retryable: false,\r\n },\r\n iterations: 0,\r\n toolCalls: 0,\r\n durationMs: 0,\r\n };\r\n this.recordCompletion(synthetic);\r\n }\r\n\r\n this.fleetBus?.emit({\r\n subagentId,\r\n ts: Date.now(),\r\n type: 'subagent.removed',\r\n payload: { subagentId },\r\n });\r\n\r\n this.emitCoordinatorStats();\r\n }\r\n\r\n private isDone(): boolean {\r\n if (this.config.doneCondition.type === 'all_tasks_done') {\r\n return this.pendingTasks.length === 0 && this.inFlight === 0;\r\n }\r\n if (\r\n this.config.doneCondition.maxIterations !== undefined &&\r\n this.totalIterations >= this.config.doneCondition.maxIterations\r\n ) {\r\n return true;\r\n }\r\n return false;\r\n }\r\n}\r\n\r\n/**\r\n * Map any raw exception thrown out of a subagent's runner into a\r\n * structured `SubagentError`. This is the single point where the\r\n * coordinator decides \"what kind of failure was that\" — so callers\r\n * (delegate tool output, /agents UI, retry policies) branch on\r\n * `kind` instead of substring-matching `error.message`.\r\n *\r\n * The classification order matters:\r\n * 1. Provider errors first (their `status` + `retryable` are\r\n * already structured, just translate to our enum).\r\n * 2. Budget errors next (BudgetExceededError carries a discrete\r\n * `kind` we can lift directly).\r\n * 3. Parent-abort if the subagent's signal was aborted and we\r\n * didn't recognize the error otherwise — distinguishes user\r\n * Ctrl+C from a tool throwing.\r\n * 4. Substring sniffing for stable error markers (\"agent\r\n * aborted\" from agent-subagent-runner, \"Bridge transport\"\r\n * from agent-bridge).\r\n * 5. Fallback to `unknown` so callers know we couldn't classify.\r\n *\r\n * The `cause` field is always populated when `err` is an Error so\r\n * diagnostics survive even when `kind === 'unknown'` — no info is\r\n * dropped, the classifier just refused to commit.\r\n *\r\n * Exported because tests and CLI surfaces want to assert on the\r\n * classification without instantiating a coordinator.\r\n */\r\nexport function classifySubagentError(\r\n err: unknown,\r\n hints: { parentAborted?: boolean } = {},\r\n): SubagentError {\r\n const cause = err instanceof Error\r\n ? { name: err.name, message: err.message, stack: err.stack }\r\n : undefined;\r\n\r\n if (err instanceof ProviderError) {\r\n const baseMessage = err.describe();\r\n return providerErrorToSubagentError(err, baseMessage, cause);\r\n }\r\n\r\n const baseMessage = err instanceof Error ? err.message : String(err);\r\n\r\n if (err instanceof BudgetExceededError) {\r\n const map: Record<BudgetExceededError['kind'], SubagentErrorKind> = {\r\n iterations: 'budget_iterations',\r\n tool_calls: 'budget_tool_calls',\r\n tokens: 'budget_tokens',\r\n cost: 'budget_cost',\r\n timeout: 'budget_timeout',\r\n idle_timeout: 'budget_timeout',\r\n };\r\n return {\r\n kind: map[err.kind],\r\n message: baseMessage,\r\n // Budgets are user-configured ceilings, not transient failures —\r\n // retrying with the same budget will hit the same ceiling. The\r\n // orchestrator must raise the budget or narrow the task first.\r\n retryable: false,\r\n cause,\r\n };\r\n }\r\n\r\n // Distinguish parent-aborted from real failures BEFORE substring\r\n // sniffing — if the parent signal is aborted, the most common\r\n // exception is \"agent aborted\" thrown by agent-subagent-runner.\r\n if (hints.parentAborted) {\r\n return {\r\n kind: 'aborted_by_parent',\r\n message: baseMessage,\r\n retryable: false,\r\n cause,\r\n };\r\n }\r\n\r\n // Stable markers — these strings live in our own code and are\r\n // checked here intentionally so callers can react without\r\n // exception-type imports.\r\n const lower = baseMessage.toLowerCase();\r\n if (/agent aborted$/i.test(baseMessage)) {\r\n return {\r\n kind: 'aborted_by_parent',\r\n message: baseMessage,\r\n retryable: false,\r\n cause,\r\n };\r\n }\r\n if (/agent exhausted iteration limit$/i.test(baseMessage)) {\r\n return { kind: 'budget_iterations', message: baseMessage, retryable: false, cause };\r\n }\r\n if (/empty response$/i.test(baseMessage)) {\r\n return { kind: 'empty_response', message: baseMessage, retryable: false, cause };\r\n }\r\n // The runner throws `Error('tool failed: <name>')` when an executed tool\r\n // returned `ok:false` and the agent ultimately ended without recovering\r\n // (or aborted). Surface as `tool_failed` so callers don't conflate a\r\n // failed tool with a thrown tool — both are useful but mean different\r\n // things at the LLM layer.\r\n if (/^tool failed: /i.test(baseMessage)) {\r\n return { kind: 'tool_failed', message: baseMessage, retryable: false, cause };\r\n }\r\n if (lower.includes('bridge transport') || /bridge.*(closed|disconnect)/i.test(baseMessage)) {\r\n return { kind: 'bridge_failed', message: baseMessage, retryable: false, cause };\r\n }\r\n if (/context length|max.*tokens?.*exceeded|prompt is too long/i.test(baseMessage)) {\r\n return { kind: 'context_overflow', message: baseMessage, retryable: false, cause };\r\n }\r\n\r\n // Final fallback — preserve cause so diagnostics aren't lost.\r\n return {\r\n kind: 'unknown',\r\n message: baseMessage,\r\n retryable: false,\r\n cause,\r\n };\r\n}\r\n\r\nfunction providerErrorToSubagentError(\r\n err: ProviderError,\r\n message: string,\r\n cause: SubagentError['cause'],\r\n): SubagentError {\r\n const status = err.status;\r\n // Read suggested retry-after from the provider body when present so\r\n // the orchestrator doesn't have to invent a backoff. Most providers\r\n // include retry-after as a header / body field which our provider\r\n // layer normalises into `body.message` — we cannot trust a numeric\r\n // field exists, so we leave backoffMs unset when unknown.\r\n if (status === 429 || err.body?.type === 'rate_limit_error') {\r\n return {\r\n kind: 'provider_rate_limit',\r\n message,\r\n retryable: true,\r\n // Conservative default: 5s. Provider-specific code can override\r\n // by emitting an error whose body carries an explicit hint.\r\n backoffMs: 5_000,\r\n cause,\r\n };\r\n }\r\n if (status === 401 || status === 403 || err.body?.type === 'authentication_error') {\r\n return { kind: 'provider_auth', message, retryable: false, cause };\r\n }\r\n if (status === 408 || status === 0) {\r\n return { kind: 'provider_timeout', message, retryable: true, cause };\r\n }\r\n if (status >= 500 && status < 600) {\r\n return {\r\n kind: 'provider_5xx',\r\n message,\r\n retryable: true,\r\n backoffMs: 3_000,\r\n cause,\r\n };\r\n }\r\n // Other provider errors (400 invalid request, 404 not found, etc.)\r\n // are not retryable as-is and don't have a dedicated kind — surface\r\n // as 'unknown' so the orchestrator treats them as terminal.\r\n return { kind: 'unknown', message, retryable: err.retryable, cause };\r\n}\r\n","import { randomUUID } from 'node:crypto';\nimport * as fsp from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { DirectorStateCheckpoint, type DirectorStateSnapshot } from '../storage/director-state.js';\nimport type { BridgeMessage } from '../types/agent-bridge.js';\nimport type { ModelMatrixEntry } from '../types/config.js';\nimport type {\n CoordinatorStatus,\n MultiAgentConfig,\n SubagentConfig,\n SubagentRunner,\n TaskResult,\n TaskSpec,\n} from '../types/multi-agent.js';\nimport type { SessionWriter } from '../types/session.js';\nimport type { Tool } from '../types/tool.js';\nimport { atomicWrite } from '../utils/atomic-write.js';\nimport { InMemoryAgentBridge } from './agent-bridge.js';\nimport {\n type CollabDebugReport,\n CollabSession,\n type CollabSessionOptions,\n} from './collab-debug.js';\nimport {\n DEFAULT_DIRECTOR_PREAMBLE,\n DEFAULT_SUBAGENT_BASELINE,\n composeDirectorPrompt,\n composeSubagentPrompt,\n rosterSummaryFromConfigs,\n} from './director-prompts.js';\nimport {\n makeAskResultTool,\n makeAskTool,\n makeAssignTool,\n makeAwaitTasksTool,\n makeCollabDebugTool,\n makeFleetEmitTool,\n makeFleetHealthTool,\n makeFleetSessionTool,\n makeFleetStatusTool,\n makeFleetUsageTool,\n makeRollUpTool,\n makeSpawnTool,\n makeTerminateAllTool,\n makeTerminateTool,\n makeWorkCompleteTool,\n} from './director-tools.js';\nimport { FleetBus, type FleetUsage, FleetUsageAggregator } from './fleet-bus.js';\nimport type { FleetManager } from './fleet-manager.js';\nimport type { ICoordinator } from './icoordinator.js';\nimport { InMemoryBridgeTransport } from './in-memory-transport.js';\nimport { LargeAnswerStore } from './large-answer-store.js';\nimport { resolveModelMatrix } from './model-matrix.js';\nimport { DefaultMultiAgentCoordinator } from './multi-agent-coordinator.js';\nimport { assignNickname } from './subagent-nicknames.js';\n\n/**\n * Director — high-level orchestrator that owns a `MultiAgentCoordinator`,\n * a `FleetBus`, and a `FleetUsageAggregator`. Exposes a small imperative\n * API (`spawn`, `assign`, `awaitTasks`, `terminate`, `status`, `usage`)\n * that's easy to test, and a `tools()` factory that wraps the same API\n * as agent-callable `Tool`s so an LLM can drive the orchestration.\n *\n * This class is intentionally *not* an `Agent`. It's a coordinator +\n * observability surface. To make it LLM-driven, construct an Agent\n * with `director.tools()` registered. That keeps the construction\n * symmetric with how other agents are built and avoids smuggling a\n * heavy LLM dependency into core just for the director path.\n */\nexport interface DirectorOptions {\n config: MultiAgentConfig;\n runner?: SubagentRunner;\n /**\n * When set, the director writes a `fleet.json` manifest to this path\n * recording every spawned subagent (id, provider, model, role, task\n * ids). Used by `wstack replay <runId>` to rehydrate a fleet. Pass an\n * absolute file path — the directory must already exist (the\n * director-session factory creates it when used together).\n */\n manifestPath?: string;\n /**\n * Optional roster used by `leaderSystemPrompt()` to render a roles\n * summary into the leader's preamble. Same shape as the roster passed\n * to `tools()` — typically the same value.\n */\n roster?: Record<string, SubagentConfig>;\n /**\n * Override the built-in fleet preamble (see `DEFAULT_DIRECTOR_PREAMBLE`).\n * Pass an empty string to suppress the preamble entirely.\n */\n directorPreamble?: string;\n /**\n * Override the built-in subagent baseline (see\n * `DEFAULT_SUBAGENT_BASELINE`). Pass an empty string to suppress.\n */\n subagentBaseline?: string;\n /**\n * Absolute path to a directory the fleet can use as a shared scratchpad\n * (read + write by every subagent). When set, the director creates it on\n * construction and `subagentSystemPrompt()` automatically injects a\n * \"Shared notes\" block telling subagents where to drop their findings.\n * This is the cheap fleet-coordination channel — agents don't need each\n * other's transcripts, just each other's conclusions.\n *\n * Convention: under a fleet run rooted at `<sessionsRoot>/<runId>/`,\n * pass `<sessionsRoot>/<runId>/shared/` here.\n */\n sharedScratchpadPath?: string;\n /**\n * Maximum number of spawns this director can perform across its\n * lifetime. Default: unlimited. Acts as a hard fleet-wide cost cap —\n * a runaway leader that keeps spawning workers gets cut off cleanly\n * instead of burning provider tokens until the user kills the\n * process. The N+1-th spawn call rejects with a `FleetSpawnBudgetError`.\n */\n maxSpawns?: number;\n /**\n * Maximum nesting depth for spawns. The director constructed by the\n * user is at depth `spawnDepth` (default 0); any subagent that itself\n * acts as a director would construct its own `Director` with\n * `spawnDepth: parent.spawnDepth + 1`. When `spawnDepth >= maxSpawnDepth`,\n * `spawn()` rejects. Default: 2 (root director can spawn workers; a\n * worker that becomes a sub-director cannot itself spawn further).\n * This stops infinite recursive director chains from a hostile or\n * confused prompt.\n */\n maxSpawnDepth?: number;\n /**\n * Current spawn-chain depth for this director instance. Defaults to 0.\n * A nested director should pass `parent.spawnDepth + 1`. Together with\n * `maxSpawnDepth` this bounds the chain.\n */\n spawnDepth?: number;\n /**\n * Absolute path to a director-state checkpoint file. When set, the\n * director writes an incremental snapshot of pending/running/completed\n * tasks + spawned subagents on every state mutation. Distinct from\n * `manifestPath`: the manifest is a final record written on shutdown,\n * the checkpoint is a live mirror useful for crash recovery and the\n * `wstack resume` \"you had N tasks in flight\" banner.\n */\n stateCheckpointPath?: string;\n /**\n * Session writer the director should forward task lifecycle events to\n * (`agent_spawned`, `task_created`, `task_completed`, `task_failed`).\n * When omitted these events stay in-memory only — useful for tests but\n * lossy in production. Production callers (the CLI) pass the same\n * writer the host Agent uses so all events land in a single JSONL.\n */\n sessionWriter?: SessionWriter;\n /**\n * Debounce window for periodic manifest writes triggered by spawn/\n * assign/complete events. Default: 2000ms. Pass 0 to disable periodic\n * writes (the manifest will then only be written on `shutdown()`).\n */\n manifestDebounceMs?: number;\n /**\n * Fleet-wide cost ceiling. When set, `spawn()` refuses any new subagent\n * that would push the fleet's total cost above this limit. The cap\n * is checked BEFORE the spawn is recorded — a refused spawn must not\n * leak partial state into the manifest or fleet bus. Let in-flight\n * tasks complete; refuse new spawns only. When omitted or Infinity,\n * no cost cap applies.\n *\n * Distinct from SubagentBudget.maxCostUsd (per-subagent spend) — this\n * field caps the *entire fleet* total.\n */\n directorBudget?: {\n /**\n * Maximum total USD the fleet may spend across all subagents.\n * Default: Infinity (no cap).\n */\n maxCostUsd?: number;\n };\n /**\n * Maximum auto-extensions per subagent per budget kind before the\n * director denies further extensions. A subagent hitting the same\n * soft limit repeatedly (e.g. 3× budget.threshold_reached for\n * tool_calls) is likely looping on a prompt/config issue, not\n * making legitimate progress. Default: 2. Set to Infinity to\n * disable the cap (use with caution — a misconfigured subagent\n * could burn unlimited budget).\n */\n maxBudgetExtensions?: number;\n /**\n * Debounce window for state-checkpoint writes. Default: 250ms.\n * Bursts of spawn/assign/complete events collapse into one disk\n * hit. Higher values reduce write amplification on fast machines;\n * lower values improve crash-recovery fidelity (less state lost\n * on sudden process exit).\n */\n checkpointDebounceMs?: number;\n /**\n * Sessions root directory for per-subagent JSONL transcripts.\n * When set, the director can read subagent transcripts directly for\n * `fleet_session` tool — no bridge round-trip needed. Path convention:\n * `<sessionsRoot>/<directorRunId>/<subagentId>.jsonl`.\n */\n sessionsRoot?: string;\n /**\n * Director run id — namespaced under `sessionsRoot` to locate per-subagent\n * JSONLs. Defaults to the director's own `id` when omitted.\n */\n directorRunId?: string;\n /**\n * Pre-built fleet manager. When provided the Director delegates all\n * fleet-level policy (spawn budgets, manifest assembly, checkpointing)\n * to this instance and takes ownership of the coordinator + bridge\n * layer only. This enables unit-testing fleet policy in isolation\n * and swapping implementations without changing the Director surface.\n *\n * When omitted the Director creates its own fleet infrastructure\n * (same behavior as before this field was added).\n */\n fleetManager?: FleetManager;\n /**\n * Optional LLM classifier for the smart dispatcher. When set, the\n * `spawn_subagent` tool can accept a free-form `description` field\n * and the director will automatically route to the best-matching\n * catalog agent using `dispatchAgent()`. When omitted, routing is\n * pure heuristic (no provider call) — sufficient for most tasks.\n *\n * Build from a `complete(prompt) => string` function using\n * `makeLLMClassifier(complete)` from the dispatcher module.\n */\n dispatchClassifier?: import('../coordination/dispatcher.js').DispatchClassifier;\n /**\n * Maximum context load (as a fraction of maxContext) the leader agent\n * is allowed to reach before a new spawn is rejected. Default: 0.85.\n * When the leader's context pressure exceeds this threshold, spawning\n * a new subagent is refused — the leader must compact first.\n * Only used when no `fleetManager` is provided (inline mode).\n * Set to 1.0 to disable this check.\n */\n maxLeaderContextLoad?: number;\n /**\n * Provider's max context window in tokens. Used with `maxLeaderContextLoad`\n * to compute the absolute token threshold. Default: 128_000.\n * Only used when no `fleetManager` is provided (inline mode).\n */\n maxContext?: number;\n /**\n * Per-task model matrix (Config.modelMatrix). When set, a spawn whose\n * config has no explicit `model` is resolved against this matrix by role\n * (→ phase → `*`) before the subagent is built — so the spawned event,\n * manifest, and the agent itself all run the matched model. Explicit\n * per-spawn `model` overrides always win.\n *\n * Pass a **function** (not a snapshot) when the matrix can change at\n * runtime (the CLI passes `() => configStore.get().modelMatrix`) so a\n * mid-session `/setmodel` takes effect on the next spawn. A static record\n * is also accepted for tests and one-shot runs.\n */\n modelMatrix?: ModelMatrixSource;\n}\n\n/** Either a static matrix or a live getter (re-read on every spawn). */\nexport type ModelMatrixSource =\n | Record<string, ModelMatrixEntry>\n | (() => Record<string, ModelMatrixEntry> | undefined);\n\n/**\n * Thrown by `Director.spawn()` when a configured spawn cap (`maxSpawns`,\n * `maxSpawnDepth`) is hit. Distinct error class so callers — including\n * the `spawn_subagent` tool surface — can recognize the budget case and\n * report it cleanly instead of treating it like an unexpected failure.\n */\nexport class FleetSpawnBudgetError extends Error {\n readonly kind: 'max_spawns' | 'max_spawn_depth';\n readonly limit: number;\n readonly observed: number;\n constructor(\n kind: 'max_spawns' | 'max_spawn_depth',\n limit: number,\n observed: number,\n message?: string,\n ) {\n const defaultMsg =\n kind === 'max_spawns'\n ? `Director spawn budget exceeded: tried to spawn #${observed} but maxSpawns is ${limit}`\n : `Director spawn depth budget exceeded: this director is at depth ${observed} and maxSpawnDepth is ${limit}`;\n super(message ?? defaultMsg);\n this.name = 'FleetSpawnBudgetError';\n this.kind = kind;\n this.limit = limit;\n this.observed = observed;\n }\n}\n\n/**\n * Thrown by `Director.spawn()` when the fleet-wide cost cap is exceeded.\n * Distinct from `FleetSpawnBudgetError` (spawn count/depth) — this is a\n * dollar-denominated ceiling that tracks cumulative spend across all\n * subagents in the fleet.\n */\nexport class FleetCostCapError extends Error {\n readonly kind: 'max_cost_usd';\n readonly limit: number;\n readonly observed: number;\n constructor(limit: number, observed: number) {\n super(\n `Director cost cap exceeded: total fleet spend ${observed.toFixed(4)} exceeds maxCostUsd ${limit.toFixed(4)}`,\n );\n this.name = 'FleetCostCapError';\n this.kind = 'max_cost_usd';\n this.limit = limit;\n this.observed = observed;\n }\n}\n\n/**\n * Thrown by `Director.spawn()` when the leader agent's context pressure\n * exceeds the configured threshold. The leader must compact before a new\n * subagent can be spawned — the context window is too full to safely\n * orchestrate additional agents.\n */\nexport class FleetContextOverflowError extends Error {\n readonly kind: 'max_context_load';\n readonly limit: number;\n readonly observed: number;\n constructor(limit: number, observed: number) {\n super(\n `Leader context overflow: leader has ${observed} tokens in flight (limit: ${limit}). Compact the leader context before spawning more subagents.`,\n );\n this.name = 'FleetContextOverflowError';\n this.kind = 'max_context_load';\n this.limit = limit;\n this.observed = observed;\n }\n}\n\nexport class Director implements ICoordinator {\n /** Alias for the ICoordinator contract. `id` is retained for backward compatibility. */\n get coordinatorId(): string {\n return this.id;\n }\n readonly id: string;\n /**\n * The fleet event bus. Backed by `fleetManager?.fleet` when a FleetManager\n * is injected; otherwise own FleetBus instance (preserves existing behavior).\n */\n readonly fleet: FleetBus;\n /**\n * Usage rollup. Backed by `fleetManager?.usage` when a FleetManager is\n * injected; otherwise own FleetUsageAggregator.\n */\n readonly usage: FleetUsageAggregator;\n\n /**\n * Update the leader agent's current context pressure (full request tokens:\n * messages + systemPrompt + toolDefs). The director checks this before every\n * spawn — if the pressure exceeds `maxLeaderContextLoad * maxContext`,\n * spawning is refused with a `FleetContextOverflowError`.\n *\n * Call this after each leader agent iteration to keep the pressure current.\n * The compactor's `CompactReport.fullRequestTokensAfter` is a natural source.\n */\n setLeaderContextPressure(tokens: number): void {\n this.leaderContextPressure = tokens;\n // Mirror to FleetManager when available so the check is centralized.\n this.fleetManager?.setLeaderContextPressure(tokens);\n }\n\n /**\n * Read the leader agent's current context pressure.\n */\n getLeaderContextPressure(): number {\n return this.leaderContextPressure;\n }\n /**\n * Optional fleet-level policy container. When provided the Director\n * delegates spawn budgeting, manifest entries, and checkpointing to it\n * instead of managing those internally. All other behavior is unchanged.\n */\n readonly fleetManager: FleetManager | undefined;\n /**\n * Director-side bridge endpoint. Subagents are wired to the same\n * in-memory transport so the director can `ask()` them synchronously\n * and they can `send()` progress back. Exposed so external code (e.g.\n * the TUI) can subscribe to inbound messages.\n */\n readonly bridge: InMemoryAgentBridge;\n private readonly transport: InMemoryBridgeTransport;\n private readonly coordinator: DefaultMultiAgentCoordinator;\n /** Resolves with the matching `TaskResult` the first time the\n * coordinator emits `task.completed` for a given task id. Each entry\n * is created lazily on first poll/await and cleared once consumed. */\n private readonly taskWaiters = new Map<\n string,\n {\n promise: Promise<TaskResult>;\n resolve: (r: TaskResult) => void;\n }\n >();\n /** Cache of completed results in case the consumer asks AFTER the\n * coordinator already fired the event — `awaitTasks(['t-1'])` after\n * t-1 finished should resolve immediately, not hang. */\n private readonly completed = new Map<string, TaskResult>();\n /** Prevents the completed Map from growing unbounded in long-running directors. */\n private static readonly MAX_COMPLETED = 10_000;\n /** Per-subagent provider/model metadata, captured at spawn time so the\n * FleetUsageAggregator's metaLookup can surface readable rows. */\n private readonly subagentMeta = new Map<string, { provider?: string; model?: string }>();\n private readonly priceLookups = new Map<\n string,\n { input?: number; output?: number; cacheRead?: number; cacheWrite?: number }\n >();\n /** Bridge endpoints we created per subagent (so we can `stop()` them\n * on shutdown and free transport subscriptions). */\n private readonly subagentBridges = new Map<string, InMemoryAgentBridge>();\n /** Tracks per-spawn config + assigned task ids for manifest writing. */\n private readonly manifestEntries = new Map<\n string,\n {\n subagentId: string;\n name: string;\n role?: string;\n provider?: string;\n model?: string;\n taskIds: string[];\n }\n >();\n /** Tracks assigned nicknames so the same name is never reused in one fleet. */\n private readonly _usedNicknames = new Set<string>();\n private readonly manifestPath?: string;\n private readonly roster?: Record<string, SubagentConfig>;\n private readonly directorPreamble: string;\n private readonly subagentBaseline: string;\n /** Absolute path to the fleet's shared scratchpad directory, or null\n * when none was configured. Exposed as a readonly getter for callers\n * that need to surface the path to the user (e.g. the CLI logging\n * the location after `--director` boots). */\n readonly sharedScratchpadPath: string | null;\n /** Spawn cap (lifetime total). Infinity means unlimited. */\n readonly maxSpawns: number;\n /** Nesting cap. The N-th director in a chain has `spawnDepth = N-1`. */\n readonly maxSpawnDepth: number;\n /** This director's position in a director chain. Root director = 0. */\n readonly spawnDepth: number;\n /** Live spawn counter for `maxSpawns` enforcement. */\n private spawnCount = 0;\n /** Optional checkpoint mirror — writes the live task graph + roster to disk. */\n private readonly stateCheckpoint: DirectorStateCheckpoint | null;\n /** Optional session writer for emitting task_* / agent_* lifecycle events. */\n private readonly sessionWriter: SessionWriter | null;\n /** Debounce timer for periodic manifest writes. */\n private manifestTimer: NodeJS.Timeout | null = null;\n private readonly manifestDebounceMs: number;\n /** Fleet-wide cost cap (entire fleet total, distinct from SubagentBudget limits). Infinity means no cap. */\n private readonly maxFleetCostUsd: number;\n /** Max auto-extensions per subagent per budget kind before denying. */\n private readonly maxBudgetExtensions: number;\n /** Sessions root for direct subagent JSONL reads (fleet_session tool). */\n private readonly sessionsRoot?: string;\n /** Director run id for JSONL path resolution. */\n private readonly directorRunId: string;\n /** Resolves task descriptions back from `assign()` so completion events\n * can also carry a human-readable title. */\n private readonly taskDescriptions = new Map<string, string>();\n /** Snapshot of which subagent owns each task — drives state-checkpoint\n * status updates without re-walking the manifest. */\n private readonly taskOwners = new Map<string, string>();\n /** Cumulative auto-extension grants per subagent (all budget kinds). Lets\n * /fleet render \"⚡ extended ×N\" without replaying the event stream. */\n private readonly extendTotals = new Map<string, number>();\n /**\n * Handle to the coordinator-side `task.completed` listener so we can\n * unsubscribe in `shutdown()`. Without this, repeated Director\n * construction (e.g. tests, hot reloads) accumulates listeners on a\n * cached coordinator and slowly drifts the EventEmitter past its\n * default cap.\n */\n private taskCompletedListener:\n | ((payload: { task: TaskSpec; result: TaskResult }) => void)\n | null = null;\n /** Optional LLM classifier for smart dispatch. Passed from options. */\n readonly dispatchClassifier?: import('../coordination/dispatcher.js').DispatchClassifier;\n /** Leader agent's current context pressure (full request tokens). */\n private leaderContextPressure = 0;\n /** Maximum context load fraction before spawn is refused. */\n private readonly maxLeaderContextLoad: number;\n /** Provider's max context window in tokens. */\n private readonly maxContext: number;\n /** Per-task model matrix (static record or live getter); resolved\n * per-spawn when no explicit model is set. */\n private readonly modelMatrix?: ModelMatrixSource;\n /**\n * When set by `workComplete()`, the director stops dispatching new tasks\n * and terminates all running subagents. Used when the director's LLM decides\n * the goal is satisfied and no further spawns are needed — prevents the\n * coordinator from keeping workers alive for tasks that will never arrive.\n */\n private workCompleteFlag = false;\n /** Pending /btw notes stashed by the leader agent (see setLeaderBtwNote). */\n private _leaderBtwNotes: string[] = [];\n /** Active collab sessions tracked by sessionId (see spawnCollab). */\n private readonly _activeCollabSessions = new Map<\n string,\n import('./collab-debug.js').CollabSession\n >();\n /** Prevents large `ask_subagent` answers from bloating the leader's context window. */\n readonly largeAnswerStore: LargeAnswerStore;\n\n constructor(opts: DirectorOptions) {\n this.id = opts.config.coordinatorId || randomUUID();\n this.manifestPath = opts.manifestPath;\n this.roster = opts.roster;\n this.directorPreamble = opts.directorPreamble ?? DEFAULT_DIRECTOR_PREAMBLE;\n this.subagentBaseline = opts.subagentBaseline ?? DEFAULT_SUBAGENT_BASELINE;\n this.sharedScratchpadPath = opts.sharedScratchpadPath ?? null;\n this.maxSpawns = opts.maxSpawns ?? Number.POSITIVE_INFINITY;\n this.maxSpawnDepth = opts.maxSpawnDepth ?? 2;\n this.spawnDepth = opts.spawnDepth ?? 0;\n this.sessionWriter = opts.sessionWriter ?? null;\n this.manifestDebounceMs = opts.manifestDebounceMs ?? 2000;\n this.dispatchClassifier = opts.dispatchClassifier;\n this.maxFleetCostUsd = opts.directorBudget?.maxCostUsd ?? Number.POSITIVE_INFINITY;\n this.maxBudgetExtensions = opts.maxBudgetExtensions ?? 5;\n this.maxLeaderContextLoad = opts.maxLeaderContextLoad ?? 0.85;\n this.maxContext = opts.maxContext ?? 128_000;\n this.modelMatrix = opts.modelMatrix;\n this.sessionsRoot = opts.sessionsRoot;\n this.directorRunId = opts.directorRunId ?? this.id;\n this.stateCheckpoint = opts.stateCheckpointPath\n ? new DirectorStateCheckpoint(\n opts.stateCheckpointPath,\n {\n directorRunId: this.id,\n maxSpawns: opts.maxSpawns,\n spawnDepth: this.spawnDepth,\n maxSpawnDepth: this.maxSpawnDepth,\n directorBudget: opts.directorBudget,\n },\n opts.checkpointDebounceMs ?? 250,\n )\n : null;\n this.fleetManager = opts.fleetManager;\n if (this.sharedScratchpadPath) {\n // Create the directory eagerly so subagents that try to write\n // there on first iteration don't trip on ENOENT. Fire-and-forget,\n // but surface failures via process.emitWarning — the downstream\n // ENOENT a subagent hits is opaque without this signal.\n void fsp\n .mkdir(this.sharedScratchpadPath, { recursive: true })\n .catch((err) => this.logShutdownError('shared_scratchpad_mkdir', err));\n }\n this.transport = new InMemoryBridgeTransport();\n this.bridge = new InMemoryAgentBridge(\n { agentId: this.id, coordinatorId: this.id },\n this.transport,\n );\n // Delegate to FleetManager when injected; otherwise create own instances\n // (preserves existing behavior for callers that don't pass fleetManager).\n if (this.fleetManager) {\n this.fleet = this.fleetManager.fleet;\n this.usage = this.fleetManager.usage;\n } else {\n this.fleet = new FleetBus();\n this.usage = new FleetUsageAggregator(\n this.fleet,\n (_id, provider, model) => {\n if (provider && model) return this.priceLookups.get(`${provider}/${model}`);\n return undefined;\n },\n (id) => this.subagentMeta.get(id),\n );\n }\n this.coordinator = new DefaultMultiAgentCoordinator(\n { ...opts.config, coordinatorId: this.id },\n { runner: opts.runner },\n );\n this.coordinator.setFleetBus(this.fleet);\n this.fleetManager?.setCoordinator(this.coordinator);\n // Mirror coordinator completion events into the waiter table. This\n // lets `awaitTasks([...])` resolve on the *next* completion event\n // without polling — and the `completed` cache covers the case where\n // a caller asks after the fact.\n //\n // The listener is captured in a field (`taskCompletedListener`) so\n // `shutdown()` can `coordinator.off(...)` it cleanly — otherwise\n // repeated Director construction against a cached coordinator\n // (tests, hot reloads) leaks listeners and eventually trips\n // EventEmitter's max-listener warning.\n this.taskCompletedListener = (payload: { task: TaskSpec; result: TaskResult }) => {\n const r = payload.result;\n this.completed.set(r.taskId, r);\n // Trim oldest entries when the cap is exceeded — keep most recent results\n // so rollUp() and completedResults() still have data to return.\n if (this.completed.size > Director.MAX_COMPLETED) {\n const toDelete = this.completed.size - Director.MAX_COMPLETED;\n const keys = [...this.completed.keys()].slice(0, toDelete);\n for (const k of keys) this.completed.delete(k);\n }\n const waiter = this.taskWaiters.get(r.taskId);\n if (waiter) {\n waiter.resolve(r);\n this.taskWaiters.delete(r.taskId);\n }\n // Mirror into the on-disk checkpoint + session event stream so a\n // crashed director leaves a complete picture of which tasks landed.\n const title = this.taskDescriptions.get(r.taskId) ?? payload.task.description ?? r.taskId;\n const failed = r.status !== 'success';\n // Disk-side state-checkpoint and session JSONL both store `error`\n // as a string for historical reasons. The structured SubagentError\n // envelope carries `kind`, `message`, `retryable`, etc. — flatten\n // to a `kind: message` string here so old readers stay valid and\n // grep-friendly. The full envelope is still available live via\n // the EventBus / TaskResult to in-process consumers.\n const errorString = r.error ? `${r.error.kind}: ${r.error.message}` : undefined;\n this.stateCheckpoint?.recordTaskStatus(r.taskId, {\n status: failed ? (r.status as 'failed' | 'timeout' | 'stopped') : 'completed',\n completedAt: new Date().toISOString(),\n iterations: r.iterations,\n toolCalls: r.toolCalls,\n durationMs: r.durationMs,\n error: errorString,\n });\n this.stateCheckpoint?.setUsage(this.usage.snapshot());\n void this.appendSessionEvent(\n failed\n ? {\n type: 'task_failed',\n ts: new Date().toISOString(),\n taskId: r.taskId,\n title,\n error: errorString ?? r.status,\n }\n : {\n type: 'task_completed',\n ts: new Date().toISOString(),\n taskId: r.taskId,\n title,\n },\n );\n // Flush immediately on task completion — the result should be\n // visible in the manifest without waiting for the debounce window.\n // Use flushManifest() so any pending debounce timer is also cleared.\n if (this.fleetManager) {\n this.fleetManager.flushManifest();\n } else {\n this.scheduleManifest();\n }\n };\n this.coordinator.on('task.completed', this.taskCompletedListener);\n\n // Wire budget.threshold_reached events from the FleetBus into the\n // coordinator's task completion path. When a subagent hits a soft\n // limit, the runner emits this event; we intercept it here, resolve\n // the decision promise (via extend/deny), and let the normal\n // task.completed flow handle the rest.\n //\n // Extension guard: a subagent that hits the same soft limit\n // `maxBudgetExtensions` times without completing its task is looping\n // on a prompt/config issue, not running out of budget legitimately.\n // After the configured number of extends we deny and let the task\n // fail — the host agent should then split the work or narrow the\n // scope. We track this per subagent+kind combination.\n const extendCounts = new Map<string, number>();\n // Per-subagent progress heartbeat: counts tool executions so the timeout\n // kind can extend indefinitely WHILE the agent is doing work, yet still\n // deny a wedged agent that produces no new tool calls between grants.\n // Wall-clock time always advances, so timeout alone is never a reliable\n // \"stuck\" signal — tool activity is.\n const progressBySubagent = new Map<string, number>();\n const lastTimeoutProgress = new Map<string, number>();\n this.fleet.filter('tool.executed', (e) => {\n progressBySubagent.set(e.subagentId, (progressBySubagent.get(e.subagentId) ?? 0) + 1);\n });\n this.fleet.filter('budget.threshold_reached', (e) => {\n const payload = e.payload as {\n kind: 'timeout' | 'idle_timeout' | 'iterations' | 'tool_calls' | 'tokens' | 'cost';\n used: number;\n limit: number;\n timeoutMs: number;\n extend: (extra: Record<string, unknown>) => void;\n deny: () => void;\n };\n // -----------------------------------------------------------------------\n // Collab agents are NOT handled here. Their CollabSession owns the\n // budget.threshold_reached routing — it calls session.cancel() (never\n // payload.deny()) when the Director decides to stop, so the agent\n // finishes naturally. The Director's auto-extend/deny logic would\n // conflict with that decision and must not run for collab subagents.\n // -----------------------------------------------------------------------\n if (\n e.subagentId.startsWith('bug-hunter-') ||\n e.subagentId.startsWith('refactor-planner-') ||\n e.subagentId.startsWith('critic-')\n ) {\n // Skip — let the CollabSession's fleet handler deal with it.\n // The session calls session.cancel() on the FleetBus, which causes\n // the subagent to finish naturally without Director intervention.\n return;\n }\n // Timeout is governed by the heartbeat, not the extension cap. While the\n // subagent keeps executing tools it never dies on wall-clock time; once\n // it stops making progress between grants, it's genuinely stuck → deny.\n if (payload.kind === 'timeout') {\n const progress = progressBySubagent.get(e.subagentId) ?? 0;\n const lastProgress = lastTimeoutProgress.get(e.subagentId) ?? -1;\n if (progress <= lastProgress) {\n payload.deny();\n return;\n }\n lastTimeoutProgress.set(e.subagentId, progress);\n setImmediate(() => {\n const newLimit = Math.min(Math.ceil(payload.limit * 2), 24 * 60 * 60_000);\n this.recordExtension(e.subagentId, e.taskId, 'timeout', newLimit);\n payload.extend({ timeoutMs: newLimit });\n });\n return;\n }\n const guardKey = `${e.subagentId}:${payload.kind}`;\n const prior = extendCounts.get(guardKey) ?? 0;\n if (prior >= this.maxBudgetExtensions) {\n payload.deny();\n extendCounts.delete(guardKey);\n return;\n }\n if (payload.kind === 'cost' && this.maxFleetCostUsd < Number.POSITIVE_INFINITY) {\n const totalCost = this.usage.snapshot().total?.cost ?? 0;\n if (totalCost >= this.maxFleetCostUsd) {\n payload.deny();\n return;\n }\n }\n extendCounts.set(guardKey, prior + 1);\n setImmediate(() => {\n const extra: Record<string, unknown> = {};\n const base = Math.max(payload.limit, payload.used);\n const grow = (ceiling: number) => Math.min(Math.ceil(base * 1.5), ceiling);\n let newLimit = base;\n switch (payload.kind) {\n case 'iterations':\n newLimit = grow(50_000);\n extra.maxIterations = newLimit;\n break;\n case 'tool_calls':\n newLimit = grow(100_000);\n extra.maxToolCalls = newLimit;\n break;\n case 'tokens':\n newLimit = grow(5_000_000);\n extra.maxTokens = newLimit;\n break;\n case 'cost':\n newLimit = Math.min(base * 1.5, 100);\n extra.maxCostUsd = newLimit;\n break;\n }\n this.recordExtension(e.subagentId, e.taskId, payload.kind, newLimit);\n payload.extend(extra);\n });\n });\n // Large-answer store: prevents big `ask_subagent` responses from\n // bloating the leader's context window. Responses above 2K chars\n // are stored out-of-band; only a summary goes into ctx.messages.\n this.largeAnswerStore = new LargeAnswerStore(2000);\n }\n\n /**\n * Record a granted budget extension and broadcast it on the FleetBus so\n * the host can re-emit `subagent.budget_extended` for live UI badges.\n * Called from both the timeout heartbeat path and the per-kind grant path.\n */\n private recordExtension(\n subagentId: string,\n taskId: string | undefined,\n kind: string,\n newLimit: number,\n ): void {\n const total = (this.extendTotals.get(subagentId) ?? 0) + 1;\n this.extendTotals.set(subagentId, total);\n this.fleet.emit({\n subagentId,\n taskId,\n ts: Date.now(),\n type: 'budget.extended',\n payload: { kind, newLimit, totalExtensions: total },\n });\n }\n\n /** Cumulative auto-extension count for one subagent (0 when never extended). */\n extensionsFor(subagentId: string): number {\n return this.extendTotals.get(subagentId) ?? 0;\n }\n\n /**\n * Signal that the director's work is done. Once called:\n * - `spawn()` throws `FleetSpawnBudgetError('max_spawns', …)` — no new\n * subagents can be created\n * - Running subagents are NOT forcibly stopped — they finish naturally,\n * but no new tasks are dispatched to them\n *\n * This lets the director LLM say \"I'm satisfied with the results, stop\n * spawning and wind down\" — without killing in-flight work mid-execution.\n * Call `terminateAll()` separately if you need immediate teardown.\n *\n * Idempotent — calling twice is a no-op.\n */\n workComplete(): void {\n this.workCompleteFlag = true;\n this.fleet.emit({\n subagentId: this.id,\n ts: Date.now(),\n type: 'director.work_complete',\n payload: {},\n });\n }\n\n /** Returns true if `workComplete()` has been called on this director. */\n isWorkComplete(): boolean {\n return this.workCompleteFlag;\n }\n\n /**\n * Stashes a /btw note on the leader agent's context. The leader's agent loop\n * calls `consumeBtwNotes()` at each iteration boundary and folds pending notes\n * into the conversation as a visible block — no abort, no restart, just a\n * \"by the way\" nudge the model picks up on its next turn.\n *\n * This is the entry point for the host (CLI, TUI) to inject /btw notes\n * programmatically without going through the slash-command path.\n */\n setLeaderBtwNote(note: string): number {\n const trimmed = note.trim();\n if (!trimmed) return this._leaderBtwNotes.length;\n this._leaderBtwNotes = [...this._leaderBtwNotes, trimmed].slice(-20);\n return this._leaderBtwNotes.length;\n }\n\n /**\n * Read and clear all pending /btw notes the leader has stashed.\n * Returns them in FIFO order (empty array when none).\n *\n * Called by CollabSession when a budget threshold event fires so the\n * Director can inspect accumulated /btw notes before deciding whether\n * to cancel the collab session or let it continue.\n */\n getLeaderBtwNotes(): string[] {\n const notes = this._leaderBtwNotes;\n this._leaderBtwNotes = [];\n return notes;\n }\n\n /**\n * Peek at pending /btw notes without consuming them.\n * Useful for UI to show \"N pending notes\" without clearing them.\n */\n peekLeaderBtwNotes(): string[] {\n return [...this._leaderBtwNotes];\n }\n\n /**\n * Drain (read + clear) all /btw notes in one call.\n * Alias for getLeaderBtwNotes() — kept for symmetry with consumeBtwNotes()\n * in the agent's btw.ts. The Director calls this at the point where it\n * makes a cancellation decision, not on every budget event.\n */\n drainLeaderBtwNotes(): string[] {\n return this.getLeaderBtwNotes();\n }\n\n /**\n * Cancel an active collab session by its id.\n * Emits `director.cancel_collab` on the FleetBus so the session's agents\n * finish early with a 'cancelled' disposition.\n *\n * Returns silently if the session id is not tracked or already settled.\n * The CollabDebugReport will reflect 'cancelled' disposition when awaited.\n */\n cancelCollabSession(sessionId: string, reason = 'Director cancelled'): void {\n const session = this._activeCollabSessions.get(sessionId);\n if (!session || session.isCancelled()) return;\n session.cancel(reason);\n // Stop each collab agent via the coordinator so their run() aborts.\n // This is the critical difference from a natural finish: we call\n // abortController.abort() on each subagent's run signal, which\n // propagates into agent.run() → tool executor and kills the run\n // before the budget or natural iteration limit ends it.\n // The abort is cooperative — the agent finishes its current iteration\n // then sees the signal and exits with status 'aborted', so no context\n // is silently lost.\n for (const [_role, subagentId] of session.getSubagentIds()) {\n this.coordinator.stop(subagentId).catch(() => {\n // Subagent may have already completed naturally — that's fine.\n // The stop() call is best-effort cleanup, not a guarantee.\n });\n }\n }\n\n /**\n * Subscribe a callback to be notified whenever a collab session raises\n * an alert (warning level). The callback receives the full DirectorAlert\n * payload so the host (CLI, TUI) can display it to the user.\n * Returns an unsubscribe function.\n */\n onCollabAlert(handler: (alert: import('./collab-debug.js').DirectorAlert) => void): () => void {\n return this.fleet.filter('collab.warning', (e) => {\n handler(e.payload as import('./collab-debug.js').DirectorAlert);\n });\n }\n\n /**\n * Returns all active (not yet settled) collab session ids.\n * Useful for the TUI to render a \"N active sessions\" badge and for\n * the host to know what can be cancelled.\n */\n activeCollabSessions(): string[] {\n return Array.from(this._activeCollabSessions.keys());\n }\n\n /** Best-effort session-writer append. Swallows failures — the director\n * must not break a fleet run because the session JSONL handle closed. */\n private async appendSessionEvent(event: Parameters<SessionWriter['append']>[0]): Promise<void> {\n if (!this.sessionWriter) return;\n try {\n await this.sessionWriter.append(event);\n } catch {\n // ignore\n }\n }\n\n /** Debounced manifest writer. A burst of spawn/assign/complete events\n * collapses into one write. Set `manifestDebounceMs` to 0 to write\n * synchronously (no debounce); set to negative to disable entirely. */\n private scheduleManifest(): void {\n if (!this.manifestPath) return;\n if (this.manifestDebounceMs === 0) {\n // 0 means instant flush — write synchronously, no timer.\n void this.writeManifest().catch((err) =>\n this.logShutdownError('manifest_write_debounced', err),\n );\n return;\n }\n if (this.manifestDebounceMs < 0) return;\n this.manifestTimer = setTimeout(() => {\n this.manifestTimer = null;\n void this.writeManifest().catch((err) =>\n this.logShutdownError('manifest_write_debounced', err),\n );\n }, this.manifestDebounceMs);\n }\n\n /**\n * Spawn a subagent. Identical to the coordinator's `spawn()` but\n * captures provider/model metadata for the usage aggregator and\n * lets the FleetBus attach to the runner's EventBus when the task\n * actually runs (see `attachSubagentBus`).\n *\n * Caller-supplied `priceLookup` is optional but recommended — without\n * it the `cost` column in `usage.snapshot()` stays at 0.\n */\n async spawn(\n config: SubagentConfig,\n priceLookup?: { input?: number; output?: number; cacheRead?: number; cacheWrite?: number },\n ): Promise<string> {\n // workComplete() signal: once the director decides the work is done,\n // refuse to spawn new subagents so the fleet winds down naturally.\n if (this.workCompleteFlag) {\n throw new FleetSpawnBudgetError(\n 'max_spawns',\n this.maxSpawns,\n this.spawnCount + 1,\n 'workComplete() has been called — director closed further spawning',\n );\n }\n // Per-task model matrix: when the caller didn't pin a model, resolve one\n // from the matrix by role (→ phase → `*`). Done here, before the spawned\n // event + manifest + coordinator handoff, so the fleet UI and the agent\n // itself all reflect the matched model. Explicit per-spawn models win.\n if (!config.model && this.modelMatrix) {\n const matrix = typeof this.modelMatrix === 'function' ? this.modelMatrix() : this.modelMatrix;\n const entry = resolveModelMatrix(matrix, config.role);\n if (entry) {\n config.model = entry.model;\n if (entry.provider) config.provider = entry.provider;\n }\n }\n // Enforce safety caps BEFORE touching the coordinator — a refused\n // spawn must not leak partial state into the manifest or fleet bus.\n // Delegate to FleetManager when available; use inline checks otherwise.\n if (this.fleetManager) {\n const rejection = this.fleetManager.canSpawn(config);\n if (rejection) {\n if (rejection.kind === 'max_spawn_depth')\n throw new FleetSpawnBudgetError('max_spawn_depth', rejection.limit, rejection.observed);\n if (rejection.kind === 'max_spawns')\n throw new FleetSpawnBudgetError('max_spawns', rejection.limit, rejection.observed);\n if (rejection.kind === 'max_cost_usd')\n throw new FleetCostCapError(rejection.limit, rejection.observed);\n if (rejection.kind === 'max_context_load')\n throw new FleetContextOverflowError(rejection.limit, rejection.observed);\n }\n } else {\n if (this.spawnDepth >= this.maxSpawnDepth) {\n throw new FleetSpawnBudgetError('max_spawn_depth', this.maxSpawnDepth, this.spawnDepth);\n }\n if (this.spawnCount >= this.maxSpawns) {\n throw new FleetSpawnBudgetError('max_spawns', this.maxSpawns, this.spawnCount + 1);\n }\n if (this.maxFleetCostUsd < Number.POSITIVE_INFINITY) {\n const totalCost = this.usage.snapshot().total?.cost ?? 0;\n if (totalCost >= this.maxFleetCostUsd) {\n throw new FleetCostCapError(this.maxFleetCostUsd, totalCost);\n }\n }\n // Context pressure check: reject spawn if leader context is too full.\n // maxLeaderContextLoad === 1.0 disables this check.\n if (this.maxLeaderContextLoad < 1.0) {\n const threshold = this.maxContext * this.maxLeaderContextLoad;\n if (this.leaderContextPressure >= threshold) {\n throw new FleetContextOverflowError(threshold, this.leaderContextPressure);\n }\n }\n }\n let result: { subagentId: string };\n // If the config came from the roster with the default \"role-as-name\" pattern,\n // OR the name is one of the synthetic defaults used by ad-hoc spawn paths,\n // upgrade to a memorable nickname before the coordinator sees it. This ensures\n // the manifest, fleet UI, and session logs all display human names like\n // \"Einstein (Bug Hunter)\" instead of \"adhoc\" or \"general\".\n const needsNickname =\n config.name === config.role ||\n !config.name ||\n config.name === 'subagent' ||\n config.name === 'adhoc';\n if (needsNickname) {\n const role = config.role ?? 'subagent';\n if (this.fleetManager) {\n // FleetManager owns the used-nicknames set — just assign the nickname.\n // recordSpawn is called after spawn regardless of needsNickname to ensure\n // the manifest is keyed by the real subagentId.\n this.fleetManager.assignNicknameAndRecord(config);\n } else {\n config.name = assignNickname(role, this._usedNicknames);\n this._usedNicknames.add(\n config.name\n .split(' ')[0]!\n .toLowerCase()\n .replace(/[^a-z0-9-]/g, '-'),\n );\n }\n }\n result = await this.coordinator.spawn(config);\n // Record with FleetManager when available; otherwise manage inline.\n if (this.fleetManager) {\n // Always record the spawn with the real subagentId so the manifest is keyed correctly.\n this.fleetManager.recordSpawn(result.subagentId, config, priceLookup);\n } else {\n this.spawnCount += 1;\n this.subagentMeta.set(result.subagentId, {\n provider: config.provider,\n model: config.model,\n });\n if (priceLookup && config.provider && config.model) {\n this.priceLookups.set(`${config.provider}/${config.model}`, priceLookup);\n }\n }\n // Auto-wire a bridge per spawn — same transport as the director, so\n // `director.ask(subagentId, …)` and the subagent's own `bridge.send()`\n // round-trip without the caller having to plumb anything. Runners\n // grab their bridge from `ctx.bridge` (already populated by the\n // coordinator from `subagent.context.parentBridge`).\n const subagentBridge = new InMemoryAgentBridge(\n { agentId: result.subagentId, coordinatorId: this.id },\n this.transport,\n );\n this.coordinator.setSubagentBridge(result.subagentId, subagentBridge);\n this.subagentBridges.set(result.subagentId, subagentBridge);\n // Emit subagent.spawned on the FleetBus so the TUI can track collab agents\n // (which bypass MultiAgentHost.spawn and go through director.spawn directly).\n this.fleet.emit({\n subagentId: result.subagentId,\n ts: Date.now(),\n type: 'subagent.spawned',\n payload: {\n subagentId: result.subagentId,\n taskId: '', // taskId will be set when assign() is called\n name: config.name,\n role: config.role,\n provider: config.provider,\n model: config.model,\n },\n });\n // Record manifest entry only when not using FleetManager (it manages its own).\n if (!this.fleetManager) {\n this.manifestEntries.set(result.subagentId, {\n subagentId: result.subagentId,\n name: config.name,\n role: config.role,\n provider: config.provider,\n model: config.model,\n taskIds: [],\n });\n const spawnedAt = new Date().toISOString();\n this.stateCheckpoint?.recordSpawn(\n {\n id: result.subagentId,\n name: config.name,\n role: config.role,\n provider: config.provider,\n model: config.model,\n spawnedAt,\n },\n this.spawnCount,\n );\n void this.appendSessionEvent({\n type: 'agent_spawned',\n ts: spawnedAt,\n agentId: result.subagentId,\n role: config.role ?? config.name,\n });\n this.scheduleManifest();\n }\n return result.subagentId;\n }\n\n /**\n * Synchronously ask a subagent something via the bridge. Sends a\n * `task` message addressed to the subagent and awaits a matching\n * reply (matched by message id). Subagent runners that handle these\n * requests subscribe to `ctx.bridge` and reply with a message whose\n * `id` equals the incoming request's id (see `InMemoryAgentBridge`'s\n * `request<T>` implementation).\n *\n * Returns the response payload directly (the bridge wrapper is\n * unwrapped for ergonomics). Times out after `timeoutMs` (default\n * matches the bridge's own default of 30s) — surface those rejections\n * to the caller as actionable errors instead of letting tools hang.\n */\n async ask<T = unknown>(subagentId: string, payload: unknown, timeoutMs?: number): Promise<T> {\n if (!this.subagentBridges.has(subagentId)) {\n throw new Error(\n `ask: unknown subagent \"${subagentId}\" (spawn() it first; current fleet: ${Array.from(this.subagentBridges.keys()).join(', ') || '(empty)'})`,\n );\n }\n const msg: BridgeMessage = {\n id: randomUUID(),\n type: 'task',\n from: this.id,\n to: subagentId,\n payload,\n timestamp: Date.now(),\n priority: 'normal',\n };\n const reply = await this.bridge.request<T>(msg, timeoutMs);\n return reply.payload;\n }\n\n /**\n * Read completed task results and format them as a structured text\n * block the director's LLM can paste into its own context. The\n * Director keeps every completed `TaskResult` in `completed` so this\n * is a pure read — no bridge round-trip, cheap to call.\n *\n * The returned string is intentionally markdown-flavored: headers per\n * subagent, a one-line meta row (iter / tools / ms), and the task's\n * result text. Pass `style: 'json'` for a programmatic shape instead\n * (useful when the director model is doing structured-output work).\n */\n rollUp(taskIds: string[], style: 'markdown' | 'json' = 'markdown'): string {\n const rows = taskIds.map((id) => this.completed.get(id)).filter((r): r is TaskResult => !!r);\n if (style === 'json') {\n return JSON.stringify(\n rows.map((r) => ({\n taskId: r.taskId,\n subagentId: r.subagentId,\n status: r.status,\n iterations: r.iterations,\n toolCalls: r.toolCalls,\n durationMs: r.durationMs,\n result: r.result,\n error: r.error,\n })),\n null,\n 2,\n );\n }\n if (rows.length === 0) {\n return '_No completed tasks for the requested ids — try waiting first._';\n }\n const lines: string[] = [];\n for (const r of rows) {\n const meta = this.subagentMeta.get(r.subagentId);\n const tag = meta?.provider && meta?.model ? ` · ${meta.provider}/${meta.model}` : '';\n lines.push(`### ${r.subagentId}${tag}`);\n lines.push(`_${r.status} — ${r.iterations} iter · ${r.toolCalls} tools · ${r.durationMs}ms_`);\n lines.push('');\n if (r.error) lines.push(`**Error:** ${r.error}`);\n else if (typeof r.result === 'string') lines.push(r.result);\n else if (r.result !== undefined)\n lines.push('```json\\n' + JSON.stringify(r.result, null, 2) + '\\n```');\n else lines.push('_(no output)_');\n lines.push('');\n }\n return lines.join('\\n').trimEnd();\n }\n\n /**\n * Write the fleet manifest to `manifestPath`. Returns the path written\n * or null when no path was configured. Captures every spawn + its\n * assigned tasks — paired with per-subagent JSONLs, this is enough to\n * replay an entire director run.\n */\n async writeManifest(): Promise<string | null> {\n if (!this.manifestPath) return null;\n const manifest = {\n directorRunId: this.id,\n writtenAt: new Date().toISOString(),\n children: Array.from(this.manifestEntries.values()).map((e) => ({\n ...e,\n // Surface final status from `completed` when available — manifest\n // becomes much more useful for replay when it carries the\n // success/failure state.\n results: e.taskIds.map((tid) => {\n const r = this.completed.get(tid);\n return r\n ? {\n taskId: tid,\n status: r.status,\n iterations: r.iterations,\n toolCalls: r.toolCalls,\n durationMs: r.durationMs,\n }\n : { taskId: tid, status: 'pending' as const };\n }),\n })),\n usage: this.usage.snapshot(),\n };\n await fsp.mkdir(path.dirname(this.manifestPath), { recursive: true });\n await atomicWrite(this.manifestPath, JSON.stringify(manifest, null, 2), { mode: 0o600 });\n return this.manifestPath;\n }\n\n /**\n * Tear down the director: stop every subagent, close every bridge\n * endpoint, and (when configured) write the final manifest. Idempotent\n * — calling shutdown twice is a no-op on the second invocation.\n */\n async shutdown(): Promise<void> {\n if (this.manifestTimer) {\n clearTimeout(this.manifestTimer);\n this.manifestTimer = null;\n }\n // Detach the coordinator-side task.completed listener so a Director\n // that lives shorter than its coordinator (rare but possible in\n // tests + delegate auto-promotion) doesn't leak the closure on\n // the EventEmitter for the coordinator's remaining lifetime.\n if (this.taskCompletedListener) {\n this.coordinator.off('task.completed', this.taskCompletedListener);\n this.taskCompletedListener = null;\n }\n await this.coordinator.stopAll();\n for (const b of this.subagentBridges.values()) {\n await b.stop().catch((err) => this.logShutdownError('subagent_bridge_stop', err));\n }\n this.subagentBridges.clear();\n await this.bridge.stop().catch((err) => this.logShutdownError('director_bridge_stop', err));\n if (this.manifestPath)\n await this.writeManifest().catch((err) => this.logShutdownError('manifest_write', err));\n if (this.stateCheckpoint) {\n this.stateCheckpoint.setUsage(this.usage.snapshot());\n await this.stateCheckpoint\n .flush()\n .catch((err) => this.logShutdownError('state_checkpoint_flush', err));\n // Release the lock so a subsequent --resume can claim this checkpoint.\n // Without this, the next director run sees a stale lock and refuses.\n await this.stateCheckpoint\n .releaseLock()\n .catch((err) => this.logShutdownError('state_checkpoint_lock_release', err));\n }\n }\n\n /**\n * Funnel for shutdown-phase errors. We can't throw — `shutdown()` is\n * called from process-exit paths where an uncaught throw would lose\n * the manifest write that comes after. But we MUST NOT silently\n * swallow either — a persistent bridge-close failure would otherwise\n * mask a real bug. `process.emitWarning` is the right tier:\n * surfaces on stderr by default, lets the host plug a warning\n * listener for structured collection, and never affects exit code.\n */\n private logShutdownError(phase: string, err: unknown): void {\n const detail = err instanceof Error ? err.message : String(err);\n process.emitWarning(\n `Director shutdown phase \"${phase}\" failed: ${detail}`,\n 'DirectorShutdownWarning',\n );\n }\n\n /**\n * Hand a task to the coordinator. Returns the assigned task id so\n * callers can wait on it via `awaitTasks([id])`. The coordinator's\n * concurrency limit applies — the task may queue before running.\n */\n async assign(task: TaskSpec): Promise<string> {\n const taskWithId: TaskSpec = task.id ? task : { ...task, id: randomUUID() };\n // When workComplete() has been called, drain the pending queue as aborted\n // rather than dispatching new work. The director has decided the goal is\n // satisfied — queued tasks never get a chance to run, so synthesize their\n // completion now so any caller awaiting them unblocks immediately.\n if (this.workCompleteFlag) {\n const synthetic: TaskResult = {\n subagentId: taskWithId.subagentId ?? 'unassigned',\n taskId: taskWithId.id,\n status: 'stopped',\n error: {\n kind: 'aborted_by_parent',\n message: 'Director called workComplete() — no further tasks will run',\n retryable: false,\n },\n iterations: 0,\n toolCalls: 0,\n durationMs: 0,\n };\n this.completed.set(taskWithId.id, synthetic);\n const waiter = this.taskWaiters.get(taskWithId.id);\n if (waiter) {\n waiter.resolve(synthetic);\n this.taskWaiters.delete(taskWithId.id);\n }\n return taskWithId.id;\n }\n if (task.subagentId) {\n // Update manifest entry — delegate to FleetManager when available.\n if (this.fleetManager) {\n this.fleetManager.addTaskToSubagent(task.subagentId, taskWithId.id);\n } else {\n const entry = this.manifestEntries.get(task.subagentId);\n if (entry) entry.taskIds.push(taskWithId.id);\n }\n }\n await this.coordinator.assign(taskWithId);\n // Snapshot task metadata for completion-event titles + state checkpoint\n // bookkeeping. Done AFTER coordinator.assign() so we don't checkpoint a\n // task the coordinator rejected.\n this.taskDescriptions.set(taskWithId.id, taskWithId.description);\n if (taskWithId.subagentId) this.taskOwners.set(taskWithId.id, taskWithId.subagentId);\n const assignedAt = new Date().toISOString();\n this.stateCheckpoint?.recordTaskAssigned({\n taskId: taskWithId.id,\n subagentId: taskWithId.subagentId,\n description: taskWithId.description,\n status: 'running',\n assignedAt,\n });\n void this.appendSessionEvent({\n type: 'task_created',\n ts: assignedAt,\n taskId: taskWithId.id,\n title: taskWithId.description,\n });\n this.scheduleManifest();\n return taskWithId.id;\n }\n\n /**\n * Block until every task id resolves. Returns results in the same\n * order as the input. If any task hasn't completed by the time this\n * is called, the promise hangs until it does — pair with a timeout\n * at the caller if that's a concern. Resolves immediately for ids\n * whose results were already cached.\n */\n awaitTasks(taskIds: string[]): Promise<TaskResult[]> {\n return Promise.all(\n taskIds.map((id) => {\n const cached = this.completed.get(id);\n if (cached) return cached;\n const existing = this.taskWaiters.get(id);\n if (existing) return existing.promise;\n let resolve!: (r: TaskResult) => void;\n const promise = new Promise<TaskResult>((res) => {\n resolve = res;\n });\n this.taskWaiters.set(id, { promise, resolve });\n return promise;\n }),\n );\n }\n\n async terminate(subagentId: string): Promise<void> {\n await this.coordinator.stop(subagentId);\n }\n\n async terminateAll(): Promise<void> {\n await this.coordinator.stopAll();\n }\n\n async remove(subagentId: string): Promise<void> {\n await this.coordinator.remove(subagentId);\n\n // Clean up the bridge so it stops consuming resources.\n const bridge = this.subagentBridges.get(subagentId);\n if (bridge) {\n await bridge.stop();\n this.subagentBridges.delete(subagentId);\n }\n\n // Clean up the aggregator so terminated subagent data doesn't accumulate.\n this.usage.removeSubagent(subagentId);\n\n // Delegate nickname cleanup to FleetManager when available; otherwise handle\n // it directly here. This frees the slot so the same name can be reused.\n if (this.fleetManager) {\n this.fleetManager.removeSubagent(subagentId);\n } else {\n const entry = this.manifestEntries.get(subagentId);\n if (entry?.name) {\n const nicknameKey = entry.name\n .split(' ')[0]!\n .toLowerCase()\n .replace(/[^a-z0-9-]/g, '-');\n this._usedNicknames.delete(nicknameKey);\n }\n }\n\n // Remove all local state entries for this subagent.\n this.manifestEntries.delete(subagentId);\n this.taskOwners.delete(subagentId);\n this.taskDescriptions.delete(subagentId);\n }\n\n status(): CoordinatorStatus {\n const base = this.coordinator.getStatus();\n // Enrich each row with its cumulative auto-extension count so /fleet can\n // render \"⚡×N\" without a separate lookup.\n return {\n ...base,\n subagents: base.subagents.map((s) => ({\n ...s,\n extensions: this.extendTotals.get(s.id) ?? 0,\n })),\n };\n }\n\n /**\n * Subscribe to coordinator events. Currently only `task.completed` is\n * exposed (the others are internal lifecycle). Returns an unsubscribe\n * function. External callers (e.g. the CLI's `MultiAgentHost`) use this\n * to drive their own pending/results tracking without poking the\n * coordinator directly.\n */\n on(\n event: 'task.completed',\n handler: (payload: { task: TaskSpec; result: TaskResult }) => void,\n ): () => void {\n // EventEmitter.on returns `this`; wrap so callers get a stable\n // unsubscribe closure (matches the rest of our event API).\n this.coordinator.on(event, handler);\n return () => {\n this.coordinator.off(event, handler);\n };\n }\n\n /**\n * Snapshot of every task that has resolved (success, failed, timeout,\n * stopped) since the director started. Returned in completion order\n * via the internal map's iteration order. Used by `/fleet status` to\n * paint the completed table without reaching into private state.\n */\n completedResults(): TaskResult[] {\n return Array.from(this.completed.values());\n }\n\n /**\n * Inject a previously-saved checkpoint snapshot. Call this right after\n * constructing a Director during a `--resume` run so the in-memory state\n * (subagents, tasks, waiters) reflects the pre-crash reality instead of\n * starting from a blank slate. The director then resumes from there —\n * completing any in-flight tasks and ignoring tasks that already reached\n * a terminal state in the prior run.\n */\n setCheckpointState(snapshot: DirectorStateSnapshot): void {\n this.stateCheckpoint?.resume(snapshot);\n }\n\n /**\n * Read a subagent's JSONL transcript directly from disk (no bridge\n * round-trip needed). Returns the last assistant text, stop reason,\n * tool-use count, and line count — or null if the file is unavailable.\n * Requires `sessionsRoot` to be set on construction.\n */\n async readSession(\n subagentId: string,\n tail?: number,\n ): Promise<{\n lastAssistantText?: string;\n lastStopReason?: string;\n toolUsesObserved: number;\n events: number;\n path?: string;\n } | null> {\n if (!this.sessionsRoot) return null;\n const filePath = path.join(this.sessionsRoot, this.directorRunId, `${subagentId}.jsonl`);\n let raw: string;\n try {\n raw = await fsp.readFile(filePath, 'utf8');\n } catch {\n return null;\n }\n const lines = raw.split('\\n').filter((l) => l.trim());\n const targetLines = tail ? lines.slice(-tail) : lines;\n let lastAssistantText: string | undefined;\n let lastStopReason: string | undefined;\n let toolUses = 0;\n for (const line of targetLines) {\n try {\n const ev = JSON.parse(line) as { type?: string; text?: string; stopReason?: string };\n if (ev.type === 'assistant' && typeof ev.text === 'string') {\n lastAssistantText = ev.text;\n } else if (ev.type === 'stop' && ev.stopReason) {\n lastStopReason = ev.stopReason;\n } else if (ev.type === 'tool_use') {\n toolUses++;\n }\n } catch {\n // skip malformed lines\n }\n }\n return {\n lastAssistantText,\n lastStopReason,\n toolUsesObserved: toolUses,\n events: targetLines.length,\n path: filePath,\n };\n }\n\n snapshot(): FleetUsage {\n return this.usage.snapshot();\n }\n\n /**\n * Look up provider/model metadata for a spawned subagent. Returns\n * undefined when the subagent id is unknown (not yet spawned, or\n * already torn down). Callers — notably the TUI fleet panel — use\n * this to render human-readable provider/model tags next to each\n * subagent row without reaching into private state.\n */\n getSubagentMeta(id: string): { provider?: string; model?: string; name?: string } | undefined {\n const usage = this.subagentMeta.get(id);\n const manifest = this.manifestEntries.get(id);\n if (!usage && !manifest) return undefined;\n return {\n provider: usage?.provider ?? manifest?.provider,\n model: usage?.model ?? manifest?.model,\n name: manifest?.name,\n };\n }\n\n /**\n * Compose the leader/director-agent system prompt: fleet preamble +\n * (optional) roster summary + user base prompt. Pass the result to your\n * leader Agent's `ctx.systemPrompt` when constructing it.\n *\n * `basePrompt` defaults to `config.leaderSystemPrompt` so callers can\n * use the no-arg form when the multi-agent config already carries it.\n */\n leaderSystemPrompt(basePrompt?: string): string {\n return composeDirectorPrompt({\n basePrompt: basePrompt ?? this.coordinator.config.leaderSystemPrompt,\n directorPreamble: this.directorPreamble,\n rosterSummary: this.roster ? rosterSummaryFromConfigs(this.roster) : undefined,\n });\n }\n\n /**\n * Compose a subagent's system prompt for a given `SubagentConfig`:\n * baseline + role + task + per-spawn override. Returned by value — does\n * not mutate the config. Factories (the user-supplied `AgentFactory`)\n * should call this when building each subagent's Agent so the bridge\n * contract, role context, and override are all surfaced.\n *\n * When `taskBrief` is omitted the Task section is dropped. Pass the\n * actual task description here to reinforce it in the system prompt\n * (the runner already passes it as user input — duplicating in the\n * system prompt is optional but improves anchoring on small models).\n */\n subagentSystemPrompt(config: SubagentConfig, taskBrief?: string): string {\n return composeSubagentPrompt({\n baseline: this.subagentBaseline,\n role: config.prompt,\n task: taskBrief,\n sharedScratchpad: this.sharedScratchpadPath ?? undefined,\n override: config.systemPromptOverride,\n });\n }\n\n /**\n * Build the tool set the LLM-driven director uses to orchestrate.\n * Returns an array of `Tool` definitions; register these on the\n * director's `Agent` to expose `spawn_subagent`, `assign_task`, etc.\n * Each tool's `execute()` delegates straight to the matching method\n * above.\n *\n * Tools all carry `permission: 'auto'` — the *user* has already\n * approved running the director when they kicked off the run, so\n * gating individual orchestration calls behind a confirm prompt\n * would just be noise. The actual subagent tools they spawn are\n * still permission-checked normally.\n */\n tools(roster?: Record<string, SubagentConfig>): Tool[] {\n // Use stored roster as default — allows `director.tools()` to be\n // called without args when the roster was passed at construction.\n const effectiveRoster = roster ?? this.roster;\n const t: Tool[] = [\n makeSpawnTool(this, effectiveRoster),\n makeAssignTool(this),\n makeAwaitTasksTool(this),\n makeAskTool(this),\n makeAskResultTool(this),\n makeRollUpTool(this),\n makeTerminateTool(this),\n makeTerminateAllTool(this),\n makeFleetStatusTool(this),\n makeFleetUsageTool(this),\n makeFleetSessionTool(this),\n makeFleetHealthTool(this),\n makeCollabDebugTool(this),\n makeFleetEmitTool(this),\n makeWorkCompleteTool(this),\n ];\n return t;\n }\n\n /**\n * Attempt to acquire the checkpoint lock. Must be called before\n * resuming — if another director process is alive, this returns\n * false and the caller should not proceed with the resume.\n */\n async acquireCheckpointLock(): Promise<boolean> {\n return this.stateCheckpoint ? this.stateCheckpoint.acquireLock() : true;\n }\n\n /**\n * Start a collaborative debugging session: BugHunter, RefactorPlanner,\n * and Critic run in parallel on the same target files, with findings\n * flowing through the FleetBus (bug.found → refactor.plan →\n * critic.evaluation). Returns a structured CollabDebugReport when all\n * three agents complete or the session times out.\n */\n async spawnCollab(options: CollabSessionOptions): Promise<CollabDebugReport> {\n const session = new CollabSession(this, this.fleet, {\n ...options,\n onBudgetWarning: (alert) => {\n // Delegate to the host-provided handler if set; 'ignore' by default.\n // Collab agents are excluded from the Director's\n // budget.threshold_reached handler, so the session's own wireFleetBus()\n // budget handler (progress-based timeout logic, session.cancel()) runs\n // instead of the Director's auto-extend/deny logic.\n return options.onBudgetWarning?.(alert) ?? 'ignore';\n },\n });\n // Track so cancelCollabSession(sessionId) works and Director knows what's active\n this._activeCollabSessions.set(session.sessionId, session);\n session.on('session.done', () => this._activeCollabSessions.delete(session.sessionId));\n session.on('session.error', () => this._activeCollabSessions.delete(session.sessionId));\n return session.start();\n }\n\n /**\n * Resume from a prior checkpoint snapshot (loaded via\n * `loadDirectorState()`). Re-attach to the fleet mid-flight so\n * subsequent spawn/assign calls update the checkpoint normally.\n */\n resumeFromCheckpoint(snapshot: DirectorStateSnapshot): void {\n this.stateCheckpoint?.resume(snapshot);\n }\n}\n","import * as fsp from 'node:fs/promises';\r\nimport * as path from 'node:path';\r\nimport { randomUUID } from 'node:crypto';\r\nimport type { SubagentConfig, TaskResult } from '../types/multi-agent.js';\r\nimport type { JSONSchema, Tool } from '../types/tool.js';\r\nimport type { Director } from './director.js';\r\nimport { applyRosterBudget } from './fleet.js';\r\n\r\n/**\r\n * Opaque host interface so this factory doesn't have to depend on the\r\n * CLI's `MultiAgentHost`. Any caller that exposes the same three\r\n * methods can wire `delegate` — including test doubles.\r\n */\r\nexport interface DelegateHost {\r\n /** True if a Director is already attached and running. */\r\n isDirectorMode(): boolean;\r\n /** Build (or return the cached) Director when director mode is on. */\r\n ensureDirector(): Promise<Director | null>;\r\n /**\r\n * Force-promote a non-director session into director mode at runtime.\r\n * Returns the Director, or null when promotion is impossible (e.g. a\r\n * non-director coordinator has already spawned subagents in the\r\n * legacy code path).\r\n */\r\n promoteToDirector(): Promise<Director | null>;\r\n /**\r\n * Optional: when promotion fails, return the human-readable reason.\r\n * Used to render an actionable error to the calling model instead of\r\n * the prior opaque \"Director could not be activated\" message.\r\n * Implementations may return null when they don't track the reason.\r\n */\r\n getPromotionBlockReason?(): string | null;\r\n}\r\n\r\nexport interface CreateDelegateToolOptions {\r\n host: DelegateHost;\r\n /**\r\n * Roster used to resolve `role` strings into full `SubagentConfig`s.\r\n * Typically `FLEET_ROSTER`. When omitted, `delegate({ role })` calls\r\n * fail and only the explicit `name + provider + model` path works.\r\n */\r\n roster?: Record<string, SubagentConfig>;\r\n /**\r\n * Default await timeout in milliseconds. `delegate` blocks until the\r\n * subagent's task resolves; without a cap, a stuck worker would hang\r\n * the host indefinitely. Set generously (default: 4 hours) so the\r\n * orchestrator can run multi-step refactors / monorepo audits\r\n * without being killed for being slow — the orchestrator must\r\n * decide per-call when a task needs to be cut short.\r\n */\r\n defaultTimeoutMs?: number;\r\n /**\r\n * Absolute directory under which per-subagent JSONL transcripts live —\r\n * matches `MultiAgentHostOptions.sessionsRoot`. When set, the delegate\r\n * tool reads the subagent's transcript on timeout / budget-exhaustion\r\n * to extract partial output, so the host LLM gets *something* useful\r\n * back instead of just an error.\r\n */\r\n sessionsRoot?: string;\r\n /**\r\n * The directorRunId used to namespace transcripts (typically the host\r\n * session id). Combined with `sessionsRoot` to locate per-subagent\r\n * JSONLs at `<sessionsRoot>/<runId>/<subagentId>.jsonl`.\r\n */\r\n directorRunId?: string;\r\n /**\r\n * Buffer subtracted from the caller's `timeoutMs` before passing it\r\n * to the subagent. Gives the host a window to detect a subagent that\r\n * has gone silent and surface a partial result rather than a generic\r\n * timeout. Default: 60_000 ms (raised from 30s to give subagents\r\n * more headroom before the host kills them).\r\n */\r\n subagentTimeoutBufferMs?: number;\r\n}\r\n\r\n/**\r\n * `delegate` — the only multi-agent tool a regular (non-director) agent\r\n * ever needs. It bundles spawn + assign + await into a single call and\r\n * transparently auto-promotes the host into director mode on first use.\r\n *\r\n * The model never has to ask \"are we in director mode?\" — it just calls\r\n * `delegate({ role, task })` and gets back a `TaskResult`. The cost of\r\n * that ergonomic packaging is that `delegate` cannot be used for\r\n * parallel work as-is; the model must fire multiple `delegate` calls in\r\n * parallel through the provider's parallel-tool-call surface, or escalate\r\n * to the explicit `spawn_subagent` + `assign_task` + `await_tasks` flow\r\n * when it wants fan-out it controls itself.\r\n */\r\nexport function createDelegateTool(opts: CreateDelegateToolOptions): Tool {\r\n // Conservative default for the LLM's mental model.\r\n // The actual subagent budgets come from FLEET_ROSTER_BUDGETS (x10 higher)\r\n // and are applied in instantiateRosterConfig. This value only appears\r\n // in the schema to guide the LLM's delegation decisions — it does NOT\r\n // override the roster budget unless the caller explicitly passes it.\r\n const defaultTimeoutMs = opts.defaultTimeoutMs ?? 30 * 60 * 1000;\r\n const rosterIds = opts.roster ? Object.keys(opts.roster) : [];\r\n\r\n const inputSchema: JSONSchema = {\r\n type: 'object',\r\n properties: {\r\n task: {\r\n type: 'string',\r\n description:\r\n 'What the subagent should do — natural language, complete sentence(s). The subagent has its own tool slice, its own LLM call, and returns when its task is done.',\r\n },\r\n role: {\r\n type: 'string',\r\n description:\r\n rosterIds.length > 0\r\n ? `Roster role (preferred). One of: ${rosterIds.join(', ')}. Picks a pre-tuned config (prompt, budgets, tools) for that role.`\r\n : 'No roster is configured — pass `name` instead.',\r\n enum: rosterIds.length > 0 ? rosterIds : undefined,\r\n },\r\n name: {\r\n type: 'string',\r\n description:\r\n 'Display name for free-form subagents (not using a roster role). The subagent gets a large default budget (3h, 5000 iter, 15000 tool calls). Required when `role` is omitted.',\r\n },\r\n provider: {\r\n type: 'string',\r\n description:\r\n 'Provider id (e.g. \"anthropic\", \"openai\"). Defaults to the host provider when omitted.',\r\n },\r\n model: {\r\n type: 'string',\r\n description: 'Model id within the provider. Defaults to the host model when omitted.',\r\n },\r\n systemPromptOverride: {\r\n type: 'string',\r\n description: 'Optional extra prompt text appended to the role baseline.',\r\n },\r\n timeoutMs: {\r\n type: 'number',\r\n minimum: 1,\r\n description: `Wall-clock budget for this delegate in milliseconds. No hard cap — set as high as the task realistically needs (a monorepo audit can take hours, a single-file lint takes seconds). Default ${Math.round(defaultTimeoutMs / 1000 / 60)} minutes.`,\r\n },\r\n maxIterations: {\r\n type: 'number',\r\n minimum: 1,\r\n description:\r\n 'Maximum LLM iterations the subagent may take. Unset = use the role/coordinator default. Raise this for tasks with many tool-think-tool cycles (deep code analysis, multi-file refactors).',\r\n },\r\n maxToolCalls: {\r\n type: 'number',\r\n minimum: 1,\r\n description:\r\n 'Maximum number of tool invocations the subagent may make. Unset = use the role/coordinator default. Raise this for tasks that touch many files (large grep + read + report).',\r\n },\r\n idleTimeoutMs: {\r\n type: 'number',\r\n minimum: 1,\r\n description:\r\n 'Idle timeout in ms: reap the subagent after this long with no activity. Resets on every iteration/tool call. Unset = use the role/coordinator default.',\r\n },\r\n maxTokens: {\r\n type: 'number',\r\n minimum: 1,\r\n description:\r\n 'Maximum total tokens (input + output) the subagent may use. Unset = use the role/coordinator default.',\r\n },\r\n maxCostUsd: {\r\n type: 'number',\r\n minimum: 0,\r\n description:\r\n 'Maximum estimated USD cost the subagent may incur. Unset = use the role/coordinator default.',\r\n },\r\n },\r\n required: ['task'],\r\n };\r\n\r\n return {\r\n name: 'delegate',\r\n description:\r\n \"Hand a discrete piece of work to a dedicated subagent and wait for its result. The subagent has its own context, its own LLM call, and its own budget — use this when a task is self-contained, would otherwise blow up your context, or benefits from a specialized role (bug-hunter, security-scanner, refactor-planner, audit-log). For free-form coding tasks (not tied to a pre-defined role), pass `name` + `task` — the subagent runs as a general-purpose coding agent with a large default budget. YOU decide how big the budget is: pass `timeoutMs`, `maxIterations`, and `maxToolCalls` sized to the actual work. There is no hidden cap forcing a 3-minute / 80-iteration limit — if a monorepo audit needs 2 hours and 500 tool calls, ask for that. Call multiple delegates in parallel through the provider's parallel-tool-call surface to fan work out across roles.\",\r\n usageHint:\r\n \"Set `task` to a complete instruction. Either pick `role` from the roster (audit-log, bug-hunter, refactor-planner, security-scanner) or pass `name` to run a free-form coding agent. For non-trivial work, also pass `timeoutMs`, `maxIterations`, and `maxToolCalls`. Returns the subagent's `TaskResult` — including the textual `result`, iteration count, tool count, and duration. Auto-promotes the host into director mode on first call.\",\r\n permission: 'auto',\r\n mutating: false,\r\n inputSchema,\r\n async execute(input: unknown) {\r\n const i = (input ?? {}) as {\r\n task?: string;\r\n role?: string;\r\n name?: string;\r\n provider?: string;\r\n model?: string;\r\n systemPromptOverride?: string;\r\n timeoutMs?: number;\r\n maxIterations?: number;\r\n maxToolCalls?: number;\r\n idleTimeoutMs?: number;\r\n maxTokens?: number;\r\n maxCostUsd?: number;\r\n };\r\n\r\n if (typeof i.task !== 'string' || !i.task.trim()) {\r\n return { ok: false, error: '`task` is required.' };\r\n }\r\n\r\n try {\r\n let director = await opts.host.ensureDirector();\r\n if (!director) {\r\n director = await opts.host.promoteToDirector();\r\n }\r\n if (!director) {\r\n const reason = opts.host.getPromotionBlockReason?.();\r\n return {\r\n ok: false,\r\n error:\r\n reason ??\r\n 'Director could not be activated — multi-agent host already running in legacy non-director mode. Restart with `--director` for fleet support.',\r\n };\r\n }\r\n\r\n const timeoutMs = i.timeoutMs ?? defaultTimeoutMs;\r\n\r\n let cfg: SubagentConfig;\r\n if (i.role) {\r\n const base = opts.roster?.[i.role];\r\n if (!base) {\r\n return {\r\n ok: false,\r\n error: `Unknown role \"${i.role}\". Available: ${rosterIds.join(', ') || '(no roster configured)'}.`,\r\n };\r\n }\r\n cfg = instantiateRosterConfig(i.role, base);\r\n if (i.systemPromptOverride) cfg.systemPromptOverride = i.systemPromptOverride;\r\n if (i.provider) cfg.provider = i.provider;\r\n if (i.model) cfg.model = i.model;\r\n } else {\r\n if (!i.name) {\r\n return {\r\n ok: false,\r\n error: 'Either `role` (from the roster) or `name` is required.',\r\n };\r\n }\r\n cfg = {\r\n name: i.name,\r\n provider: i.provider,\r\n model: i.model,\r\n systemPromptOverride: i.systemPromptOverride,\r\n };\r\n // Apply generic budget so free-form subagents get the x10\r\n // budget even without a roster role.\r\n cfg = applyRosterBudget({ ...cfg, name: i.name });\r\n }\r\n\r\n if (typeof i.maxIterations === 'number') {\r\n cfg.maxIterations = i.maxIterations;\r\n }\r\n if (typeof i.maxToolCalls === 'number') {\r\n cfg.maxToolCalls = i.maxToolCalls;\r\n }\r\n if (typeof i.idleTimeoutMs === 'number') {\r\n cfg.idleTimeoutMs = i.idleTimeoutMs;\r\n }\r\n if (typeof i.maxTokens === 'number') {\r\n cfg.maxTokens = i.maxTokens;\r\n }\r\n if (typeof i.maxCostUsd === 'number') {\r\n cfg.maxCostUsd = i.maxCostUsd;\r\n }\r\n\r\n const SUBAGENT_TIMEOUT_BUFFER_MS = opts.subagentTimeoutBufferMs ?? 60_000;\r\n // Only FILL IN a budget timeout when the config has none — never\r\n // clamp a generous roster/generic budget DOWN to the host's await\r\n // window. The old `cfg.timeoutMs > desiredSubTimeout` clamp is what\r\n // capped 10h roster agents at ~4 minutes. The host await below is\r\n // heartbeat-based, so the subagent's own (auto-extending) budget is\r\n // the real ceiling.\r\n if (!cfg.timeoutMs) {\r\n cfg.timeoutMs = Math.max(30_000, timeoutMs - SUBAGENT_TIMEOUT_BUFFER_MS);\r\n }\r\n\r\n const subagentId = await director.spawn(cfg);\r\n const taskId = await director.assign({\r\n id: `${randomUUID()}`,\r\n description: i.task,\r\n subagentId,\r\n });\r\n // Heartbeat-aware host await: `timeoutMs` is treated as a SILENCE\r\n // tolerance, not a hard wall-clock cap. The deadline resets every\r\n // time the subagent emits a tool/iteration event, so a subagent\r\n // that keeps making progress is never killed for being slow —\r\n // only a genuinely stalled one (no events for `timeoutMs`) trips\r\n // the host timeout. Mirrors the budget's heartbeat auto-extend.\r\n const dir = director;\r\n const result = await new Promise<TaskResult | { __timeout: true }>((resolve) => {\r\n let settled = false;\r\n let timer: ReturnType<typeof setTimeout> | undefined;\r\n const finish = (value: TaskResult | { __timeout: true }) => {\r\n if (settled) return;\r\n settled = true;\r\n if (timer) clearTimeout(timer);\r\n offTool();\r\n offIter();\r\n offProgress();\r\n resolve(value);\r\n };\r\n const arm = () => {\r\n if (timer) clearTimeout(timer);\r\n timer = setTimeout(() => finish({ __timeout: true }), timeoutMs);\r\n };\r\n const bump = (e: { subagentId: string }) => {\r\n if (e.subagentId === subagentId) arm();\r\n };\r\n const offTool = dir.fleet.filter('tool.executed', bump);\r\n const offIter = dir.fleet.filter('iteration.started', bump);\r\n // tool.progress fires for streamed bash output, fetch byte progress,\r\n // and other long-duration tools — these are forward motion events\r\n // that should reset the idle timer just like iteration.started does.\r\n const offProgress = dir.fleet.filter('tool.progress', bump);\r\n arm();\r\n dir\r\n .awaitTasks([taskId])\r\n .then((r) => finish(r[0] ?? { __timeout: true }))\r\n .catch(() => finish({ __timeout: true }));\r\n });\r\n\r\n if ('__timeout' in result) {\r\n const partial = await readSubagentPartial(opts, subagentId);\r\n return {\r\n ok: false,\r\n stopReason: 'host_timeout',\r\n error: `Subagent did not finish within ${timeoutMs}ms.`,\r\n hint: 'Reduce scope of the next delegate, raise timeoutMs, or use spawn_subagent + await_tasks for long-running work.',\r\n subagentId,\r\n taskId,\r\n partial,\r\n };\r\n }\r\n\r\n const baseStopReason: StopReason =\r\n result.status === 'success'\r\n ? 'end_turn'\r\n : result.status === 'timeout'\r\n ? 'subagent_timeout'\r\n : result.status === 'stopped'\r\n ? 'aborted'\r\n : 'budget_exhausted';\r\n const partial =\r\n result.status === 'success' ? undefined : await readSubagentPartial(opts, subagentId);\r\n\r\n const errorKind = result.error?.kind;\r\n const retryable = result.error?.retryable;\r\n const backoffMs = result.error?.backoffMs;\r\n\r\n // Build a short summary for the chat history so the user sees\r\n // what the subagent accomplished without digging into the full result.\r\n const summary = buildDelegateSummary(i.role, result);\r\n\r\n return {\r\n ok: result.status === 'success',\r\n status: result.status,\r\n stopReason: baseStopReason,\r\n errorKind,\r\n retryable,\r\n backoffMs,\r\n subagentId: result.subagentId,\r\n taskId: result.taskId,\r\n result: result.result,\r\n error: result.error,\r\n iterations: result.iterations,\r\n toolCalls: result.toolCalls,\r\n durationMs: result.durationMs,\r\n ...(partial ? { partial } : {}),\r\n ...(hintForKind(errorKind, retryable, backoffMs, partial)\r\n ? { hint: hintForKind(errorKind, retryable, backoffMs, partial) }\r\n : {}),\r\n // Summary is included so callers (TUI, CLI renderer) can surface\r\n // it as a chat history line — the LLM also sees it for continuity.\r\n summary,\r\n };\r\n } catch (err) {\r\n return {\r\n ok: false,\r\n stopReason: 'error' as const,\r\n error: err instanceof Error ? err.message : String(err),\r\n };\r\n }\r\n },\r\n };\r\n}\r\n\r\nfunction instantiateRosterConfig(role: string, base: SubagentConfig): SubagentConfig {\r\n // Apply the x10 roster budget so subagents get far more running time\r\n // and iterations than the LLM is told about in the schema.\r\n // The LLM sees a conservative 30-min default; the subagent actually\r\n // gets 7.5–10 hours depending on role.\r\n const withBudget = applyRosterBudget({ ...base, role });\r\n return {\r\n ...withBudget,\r\n // Give each spawn a fresh id so parallel or repeated delegates\r\n // can use the same role safely.\r\n id: `${role}-${randomUUID().slice(0, 8)}`,\r\n };\r\n}\r\n\r\ntype StopReason =\r\n | 'end_turn'\r\n | 'budget_exhausted'\r\n | 'subagent_timeout'\r\n | 'host_timeout'\r\n | 'aborted'\r\n | 'error';\r\n\r\n/**\r\n * Per-kind orchestrator hint. Returned alongside the structured error\r\n * so the calling model has a concrete next step instead of \"task\r\n * failed, good luck\". Returns undefined for success / unknown kinds —\r\n * the caller checks for presence before including in output.\r\n */\r\nexport function hintForKind(\r\n kind: string | undefined,\r\n retryable: boolean | undefined,\r\n backoffMs: number | undefined,\r\n partial?: { lastAssistantText?: string },\r\n): string | undefined {\r\n if (!kind) return undefined;\r\n switch (kind) {\r\n case 'provider_rate_limit':\r\n return `Provider rate-limited. Retry safe after ${backoffMs ?? 5000}ms backoff. Consider a smaller model or fewer parallel delegates.`;\r\n case 'provider_5xx':\r\n return `Provider server error. Retry safe after ${backoffMs ?? 3000}ms backoff — usually transient.`;\r\n case 'provider_timeout':\r\n return 'Provider network timeout. Retry safe; reduce input size if it persists.';\r\n case 'provider_auth':\r\n return 'Provider rejected credentials. Cannot retry — fix the API key / config and re-invoke.';\r\n case 'context_overflow':\r\n return 'Subagent context exceeded the model limit. Narrow the task, use a larger-context model, or split into multiple delegates.';\r\n case 'budget_iterations':\r\n case 'budget_tool_calls':\r\n case 'budget_tokens':\r\n case 'budget_cost': {\r\n const base = 'Subagent exhausted its budget. The coordinator may auto-extend; otherwise raise the matching `max*` field (e.g. maxToolCalls: 600) on the next delegate, or split the task.';\r\n if (partial?.lastAssistantText) {\r\n return `${base}\\n\\nPartial output produced before budget hit:\\n${partial.lastAssistantText}`;\r\n }\r\n return base;\r\n }\r\n case 'budget_timeout': {\r\n const base = 'Subagent hit its wall-clock budget. Raise `timeoutMs` on the next delegate or split the task.';\r\n if (partial?.lastAssistantText) {\r\n return `${base}\\n\\nPartial output produced before timeout:\\n${partial.lastAssistantText}`;\r\n }\r\n return base;\r\n }\r\n case 'aborted_by_parent':\r\n return 'Subagent was aborted (user Ctrl+C, parent unwound, or sibling failure cascade). Not retryable until the abort condition is resolved.';\r\n case 'empty_response':\r\n return 'Subagent ended its turn with no text and no tool calls. Almost always a prompt / config issue — clarify the task or check the model.';\r\n case 'tool_failed': {\r\n const base = 'A tool inside the subagent returned ok:false. Retry with corrected inputs.';\r\n if (partial?.lastAssistantText) {\r\n return `${base}\\n\\nAgent reasoning before failure:\\n${partial.lastAssistantText}`;\r\n }\r\n return base;\r\n }\r\n case 'bridge_failed':\r\n return 'Parent-child bridge transport failed. This is rare — restart the session and retry.';\r\n default:\r\n return retryable\r\n ? 'Failure classified as retryable. Try again with the same input.'\r\n : undefined;\r\n }\r\n}\r\n\r\n/**\r\n * Compact summary of what a subagent did — shown in chat history so\r\n * the user immediately sees the outcome without parsing the full result.\r\n */\r\nfunction buildDelegateSummary(\r\n role: string | undefined,\r\n result: TaskResult,\r\n): string {\r\n const roleLabel = role ?? 'subagent';\r\n const ms = result.durationMs;\r\n const duration = ms < 60_000\r\n ? `${Math.round(ms / 1000)}s`\r\n : ms < 3_600_000\r\n ? `${Math.round(ms / 60_000)}m`\r\n : `${(ms / 3_600_000).toFixed(1)}h`;\r\n\r\n if (result.status === 'success') {\r\n const preview = typeof result.result === 'string'\r\n ? result.result.trim().slice(0, 120).replace(/\\n+/g, ' ')\r\n : null;\r\n const tail = preview ? ` — ${preview}` : '';\r\n return `[${roleLabel}] done in ${duration} (${result.iterations} iter, ${result.toolCalls} tools)${tail}`;\r\n }\r\n\r\n const errLabel = result.error?.kind ?? result.status;\r\n return `[${roleLabel}] ${result.status} after ${duration} (${result.iterations} iter, ${result.toolCalls} tools) — ${errLabel}`;\r\n}\r\n\r\n/**\r\n * Parse the per-subagent JSONL at `<sessionsRoot>/<runId>/<subagentId>.jsonl`\r\n * and pull out the last few useful pieces — the most recent assistant\r\n * text response, the stop reason, and a count of tool calls. Used by\r\n * `delegate` when the subagent timed out or exhausted budget without\r\n * returning a clean `finalText`, so the host LLM still sees what work\r\n * actually happened.\r\n */\r\nasync function readSubagentPartial(\r\n opts: CreateDelegateToolOptions,\r\n subagentId: string,\r\n): Promise<\r\n | {\r\n lastAssistantText?: string;\r\n lastStopReason?: string;\r\n toolUsesObserved: number;\r\n events: number;\r\n }\r\n | undefined\r\n> {\r\n if (!opts.sessionsRoot) return undefined;\r\n // Locate the JSONL. When `directorRunId` is provided we know the\r\n // exact path; otherwise scan the sessionsRoot for any subdir\r\n // containing this subagent id.\r\n const candidates: string[] = [];\r\n if (opts.directorRunId) {\r\n candidates.push(path.join(opts.sessionsRoot, opts.directorRunId, `${subagentId}.jsonl`));\r\n } else {\r\n try {\r\n const entries = await fsp.readdir(opts.sessionsRoot, { withFileTypes: true });\r\n for (const entry of entries) {\r\n if (entry.isDirectory()) {\r\n candidates.push(path.join(opts.sessionsRoot, entry.name, `${subagentId}.jsonl`));\r\n }\r\n }\r\n } catch {\r\n return undefined;\r\n }\r\n }\r\n for (const file of candidates) {\r\n let raw: string;\r\n try {\r\n raw = await fsp.readFile(file, 'utf8');\r\n } catch {\r\n continue;\r\n }\r\n const lines = raw.split('\\n').filter((l) => l.trim());\r\n let lastAssistantText: string | undefined;\r\n let lastStopReason: string | undefined;\r\n let toolUses = 0;\r\n for (const line of lines) {\r\n try {\r\n const ev = JSON.parse(line) as {\r\n type: string;\r\n content?: unknown;\r\n stopReason?: string;\r\n name?: string;\r\n };\r\n if (ev.type === 'tool_use') toolUses += 1;\r\n if (ev.type === 'llm_response') {\r\n if (typeof ev.stopReason === 'string') lastStopReason = ev.stopReason;\r\n if (Array.isArray(ev.content)) {\r\n const txt = (ev.content as Array<{ type?: string; text?: string }>)\r\n .filter((b) => b.type === 'text')\r\n .map((b) => b.text ?? '')\r\n .join('\\n')\r\n .trim();\r\n if (txt) lastAssistantText = txt;\r\n }\r\n }\r\n } catch {\r\n }\r\n }\r\n return {\r\n lastAssistantText,\r\n lastStopReason,\r\n toolUsesObserved: toolUses,\r\n events: lines.length,\r\n };\r\n }\r\n return undefined;\r\n}\r\n","import type { Agent, AgentInput, RunResult } from '../core/agent.js';\nimport type { EventBus } from '../kernel/events.js';\nimport type {\n SubagentConfig,\n SubagentRunContext,\n SubagentRunOutcome,\n SubagentRunner,\n TaskSpec,\n} from '../types/multi-agent.js';\nimport {\n BudgetExceededError,\n BudgetThresholdSignal,\n} from './subagent-budget.js';\nimport type { FleetBus } from './fleet-bus.js';\n\n/**\n * Caller-supplied factory that builds an isolated `Agent` for a subagent.\n * The factory MUST construct a fresh `Context` per call — sharing context\n * between subagents defeats isolation. Each Agent should also use either\n * its own `EventBus` or a forwarded view, so per-subagent metrics can be\n * attributed correctly.\n */\nexport type AgentFactory = (config: SubagentConfig) => Promise<AgentFactoryResult>;\n\nexport interface AgentFactoryResult {\n agent: Agent;\n /** Event bus the factory wired to this agent — required for budget hookup. */\n events: EventBus;\n /**\n * Optional cleanup hook invoked in the runner's `finally` block once\n * the task ends (success, failure, abort — same exit path). Factories\n * that own resources scoped to a single task (per-subagent JSONL\n * writers, transient providers, throwaway containers) implement this\n * to close them deterministically instead of relying on GC. Errors\n * thrown here are swallowed so a flaky cleanup can't mask the task's\n * real result.\n */\n dispose?: () => Promise<void> | void;\n}\n\nexport interface AgentRunnerOptions {\n factory: AgentFactory;\n /**\n * Format a TaskSpec into the user input the agent will receive. Defaults\n * to `task.description ?? ''`. Override when subagents expect structured\n * input (e.g. JSON contracts, role-prefixed prompts).\n */\n formatTaskInput?: (task: TaskSpec, config: SubagentConfig) => AgentInput;\n /**\n * When set, the runner attaches the subagent's EventBus to this FleetBus\n * on task start and detaches it when the task finishes. This is the\n * injection seam that lets the TUI fleet panel observe subagent activity\n * live — without it, FleetBus stays empty.\n */\n fleetBus?: FleetBus;\n}\n\n/**\n * Builds a `SubagentRunner` that drives a real `Agent` per task while honoring\n * the coordinator's budget and abort signal. This is the production adapter —\n * the coordinator's `runner` option in CLI/TUI assemblies points here.\n *\n * Lifecycle per task:\n * 1. factory(config) → fresh Agent + EventBus.\n * 2. Subscribe to events to feed the budget (tool calls, token usage).\n * 3. Call agent.run(input, { signal }) — the coordinator's signal cancels.\n * 4. Map RunResult.status onto a `SubagentRunOutcome` or throw on failure.\n * 5. Unsubscribe and let the factory's resources be GC'd.\n *\n * The budget is checked synchronously from event handlers — a runaway agent\n * that crosses its tool-call limit triggers `BudgetExceededError`, which the\n * coordinator surfaces as `status: 'failed'` on the task result.\n */\nexport function makeAgentSubagentRunner(opts: AgentRunnerOptions): SubagentRunner {\n const format = opts.formatTaskInput ?? defaultFormatTaskInput;\n\n return async (task: TaskSpec, ctx: SubagentRunContext): Promise<SubagentRunOutcome> => {\n const factoryResult = await opts.factory(ctx.config);\n const { agent, events } = factoryResult;\n\n // Attach subagent EventBus to FleetBus so the TUI fleet panel (and any\n // other FleetBus subscriber) can observe this subagent live. Detach on\n // task finish — each task is a fresh Agent + EventBus, so we never\n // want a stale bus lingering after the run.\n const detachFleet = opts.fleetBus?.attach(ctx.subagentId, events, task.id);\n\n // Hook budget into the agent's event stream. We capture errors thrown by\n // recordToolCall/recordUsage so the budget can short-circuit the run by\n // aborting the controller — the agent then unwinds cooperatively.\n const aborter = new AbortController();\n // Inject the EventBus into the budget so it can emit budget.threshold_reached\n // events when a soft limit is hit and the handler wants to ask the coordinator.\n ctx.budget._events = events;\n // Wire the threshold-negotiation handler. Without this the soft-limit\n // path is dead code: every budget overrun becomes a hard\n // BudgetExceededError and the subagent dies on its first 120-iteration\n // tick instead of asking the Director for headroom. The Director's\n // FleetBus listener (director.ts) auto-grants +50% up to a per-kind\n // ceiling and per-subagent extension count — wiring this is the\n // missing link that activates that flow.\n ctx.budget.onThreshold = ({ requestDecision }) => requestDecision();\n let budgetError: Error | null = null;\n\n /**\n * Common error handler for all budget-triggered events. Distinguishes:\n * - BudgetExceededError → hard stop, set budgetError + abort\n * - BudgetThresholdSignal → soft stop: await the coordinator's\n * decision. If 'stop', abort. If 'extend', the signal handler\n * has already patched the budget so we can continue without\n * actually aborting the agent.\n */\n const onBudgetError = (err: unknown): void => {\n if (err instanceof BudgetThresholdSignal) {\n // Await the coordinator's verdict before deciding whether to abort.\n err.decision\n .then((decision) => {\n if (decision === 'stop') {\n budgetError = new BudgetExceededError(err.kind, err.limit, err.used);\n aborter.abort();\n }\n // If 'extend': the budget limits were already patched by the\n // BudgetThresholdSignal handler (checkLimit → onThreshold →\n // coordinator extend → budget patched). Do NOT abort.\n // The tool call that triggered the signal will be retried.\n })\n .catch(() => {\n // If the decision promise rejects, treat as hard stop.\n budgetError = new BudgetExceededError(err.kind, err.limit, err.used);\n aborter.abort();\n });\n return;\n }\n // Hard stop (BudgetExceededError or other)\n aborter.abort();\n budgetError =\n err instanceof BudgetExceededError\n ? err\n : new BudgetExceededError(\n 'tool_calls',\n 0,\n 0,\n );\n // Attach the real error detail so the task result surfaces\n // something actionable instead of a generic budget message.\n if (budgetError !== err && err instanceof Error) {\n budgetError.message += ` (caused by: ${err.message})`;\n }\n };\n\n // Track the name of the most recent tool that returned ok:false so\n // we can lift it into the SubagentError when the agent ends without\n // recovering. Cleared on every successful tool execution so a tool\n // that later succeeded doesn't taint the final report.\n let lastToolFailed: string | null = null;\n\n const unsub: Array<() => void> = [];\n unsub.push(\n events.on('tool.executed', (e) => {\n // Count tool calls on the PAIRED 'tool.executed' event rather\n // than 'tool.started'. A tool can fire start then crash before\n // emitting executed (process killed, signal aborted mid-exec);\n // counting only the paired event keeps the budget tally honest\n // and matches what the model actually saw in its turn.\n try {\n ctx.budget.recordToolCall();\n } catch (eb) {\n onBudgetError(eb);\n }\n // Track ok:false so we can fail the subagent if it ends without\n // recovering. Successful runs clear it — the model may try a\n // tool, get an error, and self-heal on the next iteration; that\n // path should still report success.\n if (e.ok === false) {\n lastToolFailed = e.name;\n } else if (e.ok === true) {\n lastToolFailed = null;\n }\n }),\n events.on('provider.response', (e) => {\n try {\n ctx.budget.recordUsage(e.usage);\n } catch (e2) {\n void onBudgetError(e2);\n }\n }),\n events.on('iteration.started', () => {\n try {\n ctx.budget.recordIteration();\n } catch (e) {\n void onBudgetError(e);\n }\n // Emit a periodic progress snapshot every SUMMARY_INTERVAL\n // iterations so the leader can surface \"AGENT#2 ● L25 · 47 tools\"\n // in the main chat history without needing the FleetPanel open.\n const u = ctx.budget.usage();\n const since = u.iterations - lastSummaryAtIteration;\n if (since >= SUMMARY_INTERVAL) {\n lastSummaryAtIteration = u.iterations;\n events.emit('subagent.iteration_summary', {\n subagentId: ctx.subagentId,\n iteration: u.iterations,\n toolCalls: u.toolCalls,\n costUsd: u.costUsd,\n currentTool: currentToolName,\n partialText: streamingTextAcc.trim() || undefined,\n });\n }\n }),\n // D3: cooperative timeout enforcement DURING a long tool call.\n // The iteration-loop checkTimeout() only fires between agent\n // iterations — a single `bash sleep 3600` call would otherwise\n // park inside one tool execution while the timeout silently\n // passes, relying solely on the coordinator's hard Promise.race\n // to interrupt. Tools that emit `tool.progress` (bash chunks,\n // fetch byte progress, spawn-stream stdout) give us a heartbeat\n // we can hang the check on. When the budget trips here:\n // 1. onBudgetError sets budgetError + aborter.abort()\n // 2. aborter signal propagates to agent.run → tool executor\n // 3. tool's own signal listener kills the child process\n // Cheap: O(1) per progress event, and the budget short-circuits\n // when timeoutMs is unset (most subagents have one set anyway).\n events.on('tool.progress', () => {\n // Streamed progress (bash chunks, fetch bytes, spawn stdout) is forward\n // motion — reset the idle clock so a long-but-working tool is never\n // mistaken for a stall, THEN check whether a genuine timeout tripped.\n ctx.budget.markActivity();\n try {\n ctx.budget.checkTimeout();\n } catch (e) {\n void onBudgetError(e);\n }\n }),\n );\n\n // Track current tool name + streaming text for the periodic summary.\n let currentToolName: string | undefined;\n let streamingTextAcc = '';\n let lastSummaryAtIteration = 0;\n const SUMMARY_INTERVAL = 25;\n\n unsub.push(\n events.on('tool.started', (e) => {\n currentToolName = e.name;\n }),\n events.on('provider.text_delta', (e) => {\n // Streamed assistant text is forward motion too — keep the idle\n // clock fresh while the model is actively generating.\n ctx.budget.markActivity();\n // Accumulate last ~200 chars for the partial text snapshot.\n streamingTextAcc = (streamingTextAcc + e.text).slice(-200);\n }),\n );\n\n // Forward the coordinator signal so stop() from outside also aborts.\n const onParentAbort = () => aborter.abort();\n ctx.signal.addEventListener('abort', onParentAbort);\n\n let result: RunResult;\n try {\n result = await agent.run(format(task, ctx.config), { signal: aborter.signal });\n } finally {\n detachFleet?.();\n ctx.signal.removeEventListener('abort', onParentAbort);\n for (const u of unsub) u();\n // Per-task resource cleanup. Closes JSONL writers, throwaway\n // providers, etc. that the factory wired up. Swallowed errors —\n // a flaky cleanup must not mask the real task result. The\n // caller can re-emit via observability if needed.\n if (factoryResult.dispose) {\n try {\n await factoryResult.dispose();\n } catch {\n // intentional swallow — see comment above\n }\n }\n }\n\n // A budget violation is the signal — surface it so the coordinator can\n // tag the task with the right failure kind ('failed' for budget; the\n // coordinator separately recognises 'timeout' from BudgetExceededError).\n if (budgetError) {\n // BudgetThresholdSignal: the soft limit was hit but the coordinator\n // hasn't resolved the extension decision yet. If the decision was\n // 'extend', the coordinator patched limits and the agent finished\n // normally — no error to surface. If 'stop', budgetError becomes\n // a BudgetExceededError thrown below.\n // instanceof check on Error subtypes requires 'any' intersection\n // on the union — use a property guard instead.\n if ('decision' in budgetError) {\n const decision = await (budgetError as BudgetThresholdSignal).decision;\n if (decision === 'stop') {\n budgetError = new BudgetExceededError(\n (budgetError as BudgetThresholdSignal).kind,\n (budgetError as BudgetThresholdSignal).limit,\n (budgetError as BudgetThresholdSignal).used,\n );\n } else {\n budgetError = null;\n }\n }\n if (budgetError) throw budgetError;\n }\n\n if (result.status === 'failed') {\n throw result.error instanceof Error\n ? result.error\n : new Error(String(result.error ?? 'agent failed'));\n }\n // 'aborted' and 'max_iterations' aren't successes — let the coordinator\n // classify them. When the parent signal was aborted, coordinator marks\n // the task 'stopped' (matched against subagent.abortController.aborted).\n if (result.status === 'aborted') {\n throw new Error('agent aborted');\n }\n if (result.status === 'max_iterations') {\n throw new Error('agent exhausted iteration limit');\n }\n\n const usage = ctx.budget.usage();\n // Empty-response guard. A \"successful\" run with no text AND no tool\n // calls is almost always a prompt / config issue, not a real\n // success — the agent burned an iteration to say nothing. Surface\n // it as a classified failure so callers can show \"✗ empty_response\"\n // instead of a confusing green ✓ with no output. We only trip on\n // the (no-text AND no-tools) intersection because text-less runs\n // with tool calls are legit (e.g. \"run npm test then end_turn\").\n const finalText = (result.finalText ?? '').trim();\n if (finalText.length === 0 && usage.toolCalls === 0) {\n throw new Error('empty response');\n }\n // Unrecovered-tool-failure guard. If the last executed tool came\n // back ok:false AND the agent ended its turn with no closing text,\n // the agent never acknowledged or recovered from the failure — the\n // task is effectively broken. A model that handles a tool error\n // emits SOME text on the next iteration (\"the read failed, trying\n // an alternate path…\") which clears `lastToolFailed`; the only way\n // both signals can be live at end-of-run is if the model gave up\n // silently. Surface as `tool_failed` so callers see the actual\n // failure mode instead of a clean ✓ with no output.\n if (finalText.length === 0 && lastToolFailed !== null) {\n throw new Error(`tool failed: ${lastToolFailed}`);\n }\n return {\n result: result.finalText,\n iterations: result.iterations,\n toolCalls: usage.toolCalls,\n };\n };\n}\n\nfunction defaultFormatTaskInput(task: TaskSpec): AgentInput {\n return task.description ?? '';\n}\n","import type { ContentBlock, ToolResultBlock, ToolUseBlock } from '../types/blocks.js';\nimport type { Message } from '../types/messages.js';\n\nexport interface MessageRepairReport {\n changed: boolean;\n removedToolUses: string[];\n removedToolResults: string[];\n removedMessages: number;\n}\n\nexport interface MessageRepairResult {\n messages: Message[];\n report: MessageRepairReport;\n}\n\n/**\n * Repair provider-level tool-call adjacency invariants.\n *\n * Anthropic requires every assistant `tool_use` block to have a matching\n * `tool_result` block in the immediately following user message. Manual\n * context surgery (summary/prune) can cut through the middle of such an\n * exchange. This function removes only the now-orphaned protocol blocks,\n * preserving surrounding text/images/thinking blocks where possible.\n */\nexport function repairToolUseAdjacency(messages: Message[]): MessageRepairResult {\n const removedToolUses: string[] = [];\n const removedToolResults: string[] = [];\n let removedMessages = 0;\n let changed = false;\n const out: Message[] = [];\n\n for (let i = 0; i < messages.length; i++) {\n const original = messages[i]!;\n let msg = original;\n\n if (hasToolUse(msg)) {\n const nextIds = toolResultIds(messages[i + 1]);\n const filtered = mapContent(msg, (blocks) => {\n const next: ContentBlock[] = [];\n for (const block of blocks) {\n if (block.type === 'tool_use' && !nextIds.has(block.id)) {\n removedToolUses.push(block.id);\n changed = true;\n continue;\n }\n next.push(block);\n }\n return next;\n });\n msg = filtered ?? msg;\n }\n\n if (hasToolResult(msg)) {\n const allowed = toolUseIds(out[out.length - 1]);\n const filtered = mapContent(msg, (blocks) => {\n const next: ContentBlock[] = [];\n for (const block of blocks) {\n if (block.type === 'tool_result' && !allowed.has(block.tool_use_id)) {\n removedToolResults.push(block.tool_use_id);\n changed = true;\n continue;\n }\n next.push(block);\n }\n return next;\n });\n msg = filtered ?? msg;\n }\n\n if (isEmptyMessage(msg)) {\n removedMessages++;\n changed = true;\n continue;\n }\n out.push(msg);\n }\n\n return {\n messages: changed ? out : messages,\n report: { changed, removedToolUses, removedToolResults, removedMessages },\n };\n}\n\nfunction hasToolUse(msg: Message | undefined): boolean {\n return contentBlocks(msg).some((b): b is ToolUseBlock => b.type === 'tool_use');\n}\n\nfunction hasToolResult(msg: Message | undefined): boolean {\n return contentBlocks(msg).some((b): b is ToolResultBlock => b.type === 'tool_result');\n}\n\nfunction toolUseIds(msg: Message | undefined): Set<string> {\n const ids = new Set<string>();\n if (!msg || msg.role !== 'assistant') return ids;\n for (const block of contentBlocks(msg)) {\n if (block.type === 'tool_use') ids.add(block.id);\n }\n return ids;\n}\n\nfunction toolResultIds(msg: Message | undefined): Set<string> {\n const ids = new Set<string>();\n if (!msg || msg.role !== 'user') return ids;\n for (const block of contentBlocks(msg)) {\n if (block.type === 'tool_result') ids.add(block.tool_use_id);\n }\n return ids;\n}\n\nfunction contentBlocks(msg: Message | undefined): ContentBlock[] {\n return msg && Array.isArray(msg.content) ? msg.content : [];\n}\n\nfunction mapContent(\n msg: Message,\n fn: (blocks: ContentBlock[]) => ContentBlock[],\n): Message | null {\n if (!Array.isArray(msg.content)) return msg;\n const next = fn(msg.content);\n if (next.length === msg.content.length && next.every((b, idx) => b === msg.content[idx])) {\n return msg;\n }\n return { ...msg, content: next };\n}\n\nfunction isEmptyMessage(msg: Message): boolean {\n if (typeof msg.content === 'string') return msg.content.trim().length === 0;\n return msg.content.length === 0;\n}\n","import { randomBytes } from 'node:crypto';\nimport * as fsp from 'node:fs/promises';\nimport * as path from 'node:path';\nimport type { EventBus } from '../kernel/events.js';\nimport type { ContentBlock } from '../types/blocks.js';\nimport type { Message } from '../types/messages.js';\nimport type { SecretScrubber } from '../types/secret-scrubber.js';\nimport type {\n ResumedSession,\n SessionData,\n SessionEvent,\n SessionMetadata,\n SessionStore,\n SessionSummary,\n SessionWriter,\n} from '../types/session.js';\nimport { atomicWrite, ensureDir } from '../utils/atomic-write.js';\nimport { repairToolUseAdjacency } from '../utils/message-invariants.js';\n\nexport interface SessionStoreOptions {\n dir: string;\n /** Optional EventBus for emitting session diagnostics. */\n events?: EventBus;\n /**\n * Optional secret scrubber. When set, `user_input` and `llm_response` event\n * content is scrubbed before being persisted to the JSONL log and the\n * summary sidecar — so a secret a user pastes or the model echoes does not\n * sit in cleartext on disk (and does not ride along in history cloud-sync).\n * Tool output is already scrubbed upstream by the executor; this closes the\n * conversation-turn gap (finding F-06).\n */\n secretScrubber?: SecretScrubber;\n}\n\nexport class DefaultSessionStore implements SessionStore {\n private readonly dir: string;\n private readonly events?: EventBus;\n private readonly secretScrubber?: SecretScrubber;\n\n constructor(opts: SessionStoreOptions) {\n this.dir = opts.dir;\n this.events = opts.events;\n this.secretScrubber = opts.secretScrubber;\n }\n\n /** Join session ID to its absolute path within the store directory. */\n private sessionPath(id: string, ext: '.jsonl' | '.summary.json'): string {\n return path.join(this.dir, `${id}${ext}`);\n }\n\n private async ensureShardDir(_id: string): Promise<string> {\n await ensureDir(this.dir);\n return this.dir;\n }\n\n async create(meta: Omit<SessionMetadata, 'startedAt'>): Promise<SessionWriter> {\n const startedAt = new Date().toISOString();\n const id = meta.id ?? `${startedAt.replace(/[:.]/g, '-')}-${randomBytes(2).toString('hex')}`;\n const shardDir = await this.ensureShardDir(id);\n const file = path.join(shardDir, `${id}.jsonl`);\n let handle: fsp.FileHandle;\n try {\n handle = await fsp.open(file, 'a', 0o600);\n } catch (err) {\n throw new Error(\n `Failed to open session file: ${err instanceof Error ? err.message : String(err)}`,\n { cause: err },\n );\n }\n try {\n return new FileSessionWriter(id, handle, startedAt, meta, this.events, {\n dir: shardDir,\n filePath: file,\n secretScrubber: this.secretScrubber,\n });\n } catch (err) {\n await handle.close().catch(() => {});\n throw err;\n }\n }\n\n async resume(id: string): Promise<ResumedSession> {\n const file = this.sessionPath(id, '.jsonl');\n const data = await this.load(id);\n let handle: fsp.FileHandle;\n try {\n handle = await fsp.open(file, 'a', 0o600);\n } catch (err) {\n throw new Error(\n `Failed to open session \"${id}\" for append: ${err instanceof Error ? err.message : String(err)}`,\n { cause: err },\n );\n }\n try {\n const writer = new FileSessionWriter(\n id,\n handle,\n new Date().toISOString(),\n {\n id,\n model: data.metadata.model,\n provider: data.metadata.provider,\n },\n this.events,\n { resumed: true, dir: this.dir, filePath: file, secretScrubber: this.secretScrubber },\n );\n return { writer, data };\n } catch (err) {\n await handle.close().catch(() => {});\n throw err;\n }\n }\n\n async load(id: string): Promise<SessionData> {\n const file = this.sessionPath(id, '.jsonl');\n const raw = await fsp.readFile(file, 'utf8');\n const lines = raw.split('\\n').filter((l) => l.trim());\n const events: SessionEvent[] = [];\n for (const line of lines) {\n try {\n const parsed: unknown = JSON.parse(line);\n if (\n parsed !== null &&\n typeof parsed === 'object' &&\n typeof (parsed as { type?: unknown }).type === 'string' &&\n typeof (parsed as { ts?: unknown }).ts === 'string'\n ) {\n events.push(parsed as SessionEvent);\n }\n } catch {\n // skip malformed JSON\n }\n }\n const meta = this.metaFromEvents(id, events);\n const { messages, usage } = this.replay(events, id);\n return { metadata: meta, events, messages, usage };\n }\n\n async list(limit = 20): Promise<SessionSummary[]> {\n try {\n await ensureDir(this.dir);\n const ids = await this.collectSessionIds(this.dir);\n const sessions = await Promise.all(ids.map((id) => this.summaryFor(id).catch(() => null)));\n const out = sessions.filter((s): s is SessionSummary => s !== null);\n out.sort((a, b) => {\n if (a.startedAt < b.startedAt) return 1;\n if (a.startedAt > b.startedAt) return -1;\n return a.id.localeCompare(b.id);\n });\n return out.slice(0, limit);\n } catch {\n return [];\n }\n }\n\n /** Recursively collect all session IDs from shard subdirectories. */\n private async collectSessionIds(dir: string): Promise<string[]> {\n const ids: string[] = [];\n const entries = await fsp.readdir(dir, { withFileTypes: true });\n for (const entry of entries) {\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n ids.push(...(await this.collectSessionIds(full)));\n } else if (entry.isFile() && entry.name.endsWith('.jsonl')) {\n ids.push(entry.name.replace(/\\.jsonl$/, ''));\n }\n }\n return ids;\n }\n\n private async summaryFor(id: string): Promise<SessionSummary> {\n const manifest = this.sessionPath(id, '.summary.json');\n try {\n const raw = await fsp.readFile(manifest, 'utf8');\n return JSON.parse(raw) as SessionSummary;\n } catch {\n const full = this.sessionPath(id, '.jsonl');\n const stat = await fsp.stat(full);\n const summary = await this.summarize(id, stat.mtime.toISOString());\n await atomicWrite(manifest, JSON.stringify(summary), { mode: 0o600 }).catch((err) => {\n console.warn(\n `[session-store] Failed to write manifest for \"${id}\":`,\n err instanceof Error ? err.message : String(err),\n );\n });\n return summary;\n }\n }\n\n async delete(id: string): Promise<void> {\n await fsp.unlink(this.sessionPath(id, '.jsonl'));\n await fsp.unlink(this.sessionPath(id, '.summary.json')).catch(() => undefined);\n }\n\n async clearHistory(id: string): Promise<void> {\n await this.ensureShardDir(id);\n const file = this.sessionPath(id, '.jsonl');\n const meta = this.sessionPath(id, '.summary.json');\n const record = `${JSON.stringify({\n type: 'session_start',\n ts: new Date().toISOString(),\n id,\n model: 'unknown',\n provider: 'unknown',\n })}\\n`;\n await fsp.writeFile(file, record, 'utf8');\n await fsp.unlink(meta).catch(() => undefined);\n }\n\n private async summarize(id: string, mtime: string): Promise<SessionSummary> {\n try {\n const data = await this.load(id);\n const firstUser = data.events.find((e) => e.type === 'user_input');\n const title =\n firstUser && firstUser.type === 'user_input'\n ? userInputTitle(firstUser.content)\n : '(empty session)';\n return {\n id,\n title,\n startedAt: data.metadata.startedAt,\n model: data.metadata.model ?? 'unknown',\n provider: data.metadata.provider ?? 'unknown',\n tokenTotal: data.usage.input + data.usage.output,\n };\n } catch {\n return {\n id,\n title: '(damaged)',\n startedAt: mtime,\n model: 'unknown',\n provider: 'unknown',\n tokenTotal: 0,\n };\n }\n }\n\n private metaFromEvents(id: string, events: SessionEvent[]): SessionMetadata {\n const start = events.find((e) => e.type === 'session_start');\n const end = events.find((e) => e.type === 'session_end');\n return {\n id,\n startedAt: start?.ts ?? new Date(0).toISOString(),\n endedAt: end?.ts,\n model: start?.model,\n provider: start?.provider,\n pendingToolUses: end?.pendingToolUses,\n };\n }\n\n private replay(\n events: SessionEvent[],\n sessionId = 'unknown',\n ): { messages: Message[]; usage: SessionData['usage'] } {\n const messages: Message[] = [];\n let usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };\n const openToolUses = new Set<string>();\n for (const e of events) {\n if (e.type === 'user_input') {\n openToolUses.clear();\n messages.push({ role: 'user', content: e.content });\n } else if (e.type === 'llm_response') {\n messages.push({ role: 'assistant', content: e.content });\n for (const b of e.content) {\n if (b.type === 'tool_use') openToolUses.add(b.id);\n }\n usage = {\n input: usage.input + (e.usage.input ?? 0),\n output: usage.output + (e.usage.output ?? 0),\n cacheRead: (usage.cacheRead ?? 0) + (e.usage.cacheRead ?? 0),\n cacheWrite: (usage.cacheWrite ?? 0) + (e.usage.cacheWrite ?? 0),\n };\n } else if (e.type === 'tool_result') {\n if (!openToolUses.has(e.id)) {\n this.events?.emit('session.damaged', {\n sessionId,\n detail: `Orphan tool_result \"${e.id}\" has no matching tool_use`,\n });\n continue;\n }\n openToolUses.delete(e.id);\n const content: ContentBlock[] = [\n {\n type: 'tool_result',\n tool_use_id: e.id,\n content: typeof e.content === 'string' ? e.content : JSON.stringify(e.content),\n is_error: e.isError,\n },\n ];\n const last = messages[messages.length - 1];\n if (last && last.role === 'user') {\n if (Array.isArray(last.content)) {\n last.content.push(...content);\n } else if (typeof last.content === 'string') {\n last.content = [{ type: 'text', text: last.content }, ...content];\n } else {\n messages.push({ role: 'user', content });\n }\n } else {\n messages.push({ role: 'user', content });\n }\n }\n }\n if (openToolUses.size > 0) {\n this.events?.emit('session.damaged', {\n sessionId,\n detail: `${openToolUses.size} tool_use blocks without matching results - replay repaired`,\n });\n }\n const repaired = repairToolUseAdjacency(messages);\n if (repaired.report.changed) {\n this.events?.emit('session.damaged', {\n sessionId,\n detail:\n `Repaired replay adjacency: removed ${repaired.report.removedToolUses.length} tool_use, ` +\n `${repaired.report.removedToolResults.length} tool_result, ` +\n `${repaired.report.removedMessages} empty messages`,\n });\n }\n return { messages: repaired.messages, usage };\n }\n}\n\nclass FileSessionWriter implements SessionWriter {\n private closed = false;\n private closing = false;\n private manifestFile: string;\n private summary: SessionSummary;\n private tokenIn = 0;\n private tokenOut = 0;\n private readonly filePath: string;\n get transcriptPath(): string | undefined {\n return this.filePath || undefined;\n }\n private initDone = false;\n private readonly resumed: boolean;\n private appendFailCount = 0;\n private lastAppendWarnAt = 0;\n private readonly secretScrubber?: SecretScrubber;\n\n /**\n * Scrub secrets out of conversation-turn events before they are observed\n * for the summary, written to the JSONL log, or surfaced on resume. Only\n * `user_input` / `llm_response` carry free-form user/model text; other event\n * types either have no secret-bearing content or are already scrubbed\n * upstream (tool results). Returns the event unchanged when no scrubber is\n * configured.\n */\n private scrubEvent(event: SessionEvent): SessionEvent {\n const s = this.secretScrubber;\n if (!s) return event;\n if (event.type === 'user_input') {\n return {\n ...event,\n content:\n typeof event.content === 'string' ? s.scrub(event.content) : s.scrubObject(event.content),\n };\n }\n if (event.type === 'llm_response') {\n return { ...event, content: s.scrubObject(event.content) };\n }\n return event;\n }\n\n private pendingFileSnapshots: Array<{\n path: string;\n action: 'created' | 'modified' | 'deleted';\n before: string | null;\n after: string | null;\n }> = [];\n /** Tracks open tool_use IDs during the current run to serialize on close for resume. */\n private openToolUses = new Set<string>();\n\n recordFileChange(input: {\n path: string;\n action: 'created' | 'modified' | 'deleted';\n before: string | null;\n after: string | null;\n }): void {\n this.pendingFileSnapshots.push(input);\n }\n\n constructor(\n public readonly id: string,\n private handle: fsp.FileHandle,\n private readonly startedAt: string,\n private readonly meta: Omit<SessionMetadata, 'startedAt'>,\n private readonly events?: EventBus,\n opts: {\n resumed?: boolean;\n dir?: string;\n filePath?: string;\n secretScrubber?: SecretScrubber;\n } = {},\n ) {\n this.resumed = opts.resumed ?? false;\n this.manifestFile = opts.dir ? path.join(opts.dir, `${id}.summary.json`) : '';\n this.filePath = opts.filePath ?? '';\n this.secretScrubber = opts.secretScrubber;\n this.summary = {\n id,\n title: '(empty session)',\n startedAt,\n model: meta.model ?? 'unknown',\n provider: meta.provider ?? 'unknown',\n tokenTotal: 0,\n };\n }\n\n get pendingToolUses(): string[] {\n return Array.from(this.openToolUses);\n }\n\n private async writeSessionStartLazy(): Promise<void> {\n const record = `${JSON.stringify({\n type: this.resumed ? 'session_resumed' : 'session_start',\n ts: this.startedAt,\n id: this.id,\n model: this.meta.model ?? 'unknown',\n provider: this.meta.provider ?? 'unknown',\n })}\\n`;\n try {\n if (this.filePath) {\n await fsp.writeFile(this.filePath, record, { flag: 'a', mode: 0o600 });\n }\n } catch {\n // best-effort\n }\n }\n\n async append(event: SessionEvent): Promise<void> {\n if (this.closed) return;\n if (!this.initDone) {\n this.initDone = true;\n await this.writeSessionStartLazy();\n }\n // Scrub before observing (the summary title is derived from user_input\n // content) and before writing, so neither the JSONL nor the sidecar holds\n // a cleartext secret.\n const scrubbed = this.scrubEvent(event);\n this.observeForSummary(scrubbed);\n try {\n await this.handle.appendFile(`${JSON.stringify(scrubbed)}\\n`, 'utf8');\n } catch (err) {\n this.appendFailCount++;\n const now = Date.now();\n if (now - this.lastAppendWarnAt > 5000) {\n const suppressed = this.appendFailCount - 1;\n const tail = suppressed > 0 ? ` (+${suppressed} suppressed)` : '';\n console.warn(\n '[session] append failed:',\n err instanceof Error ? err.message : String(err),\n tail,\n );\n this.lastAppendWarnAt = now;\n this.appendFailCount = 0;\n }\n }\n }\n\n private observeForSummary(event: SessionEvent): void {\n // Track open tool uses so we can serialize them on close for resume.\n if (event.type === 'tool_use') {\n this.openToolUses.add(event.id);\n } else if (event.type === 'tool_result') {\n this.openToolUses.delete(event.id);\n }\n if (event.type === 'user_input' && this.summary.title === '(empty session)') {\n this.summary = { ...this.summary, title: userInputTitle(event.content) };\n } else if (event.type === 'llm_response') {\n this.tokenIn += event.usage.input;\n this.tokenOut += event.usage.output;\n this.summary = { ...this.summary, tokenTotal: this.tokenIn + this.tokenOut };\n } else if (event.type === 'session_end') {\n const total = event.usage.input + event.usage.output;\n if (total > 0) this.summary = { ...this.summary, tokenTotal: total };\n }\n }\n\n async close(): Promise<void> {\n if (this.closing) return;\n this.closing = true;\n this.closed = true;\n if (this.manifestFile) {\n try {\n await atomicWrite(this.manifestFile, JSON.stringify(this.summary), { mode: 0o600 });\n } catch {\n // manifest write is best-effort\n }\n }\n try {\n await this.handle.close();\n } catch {\n // ignore\n }\n }\n\n async writeCheckpoint(promptIndex: number, promptPreview: string): Promise<void> {\n const fileCount = this.pendingFileSnapshots.length;\n if (fileCount > 0) {\n await this.writeFileSnapshot(promptIndex, [...this.pendingFileSnapshots]);\n this.pendingFileSnapshots = [];\n }\n await this.append({\n type: 'checkpoint',\n ts: new Date().toISOString(),\n promptIndex,\n promptPreview,\n });\n this.events?.emit('checkpoint.written', {\n promptIndex,\n promptPreview,\n ts: new Date().toISOString(),\n fileCount,\n });\n }\n\n async writeFileSnapshot(\n promptIndex: number,\n files: import('../types/session.js').FileSnapshot[],\n ): Promise<void> {\n await this.append({\n type: 'file_snapshot',\n ts: new Date().toISOString(),\n promptIndex,\n files,\n });\n }\n\n async truncateToCheckpoint(targetPromptIndex: number): Promise<number> {\n if (!this.filePath) return 0;\n const raw = await fsp.readFile(this.filePath, 'utf8');\n const lines = raw.split('\\n');\n const kept: string[] = [];\n let removedCount = 0;\n\n let targetCheckpointLine = -1;\n let afterTarget = false;\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!;\n if (!line.trim()) continue;\n\n let event: { type?: string; promptIndex?: number };\n try {\n event = JSON.parse(line);\n } catch {\n kept.push(line);\n continue;\n }\n\n if (event.type === 'checkpoint') {\n if ((event as { promptIndex: number }).promptIndex === targetPromptIndex) {\n targetCheckpointLine = kept.length;\n afterTarget = true;\n } else if ((event as { promptIndex: number }).promptIndex > targetPromptIndex) {\n afterTarget = true;\n }\n }\n\n if (event.promptIndex !== undefined && event.promptIndex > targetPromptIndex) {\n removedCount++;\n } else if (event.promptIndex === undefined) {\n if (!afterTarget || targetCheckpointLine === -1) {\n kept.push(line);\n } else {\n removedCount++;\n }\n } else {\n kept.push(line);\n }\n }\n\n const truncated = kept.join('\\n');\n // Windows EPERM fix: close the append-mode handle, write via temp file\n // and rename, then reopen. This is needed because rename() fails on\n // Windows when the target has an open file handle.\n const tmpPath = `${this.filePath}.rewind.tmp`;\n await fsp.writeFile(tmpPath, truncated + '\\n', 'utf8');\n try {\n await this.handle.close();\n await fsp.rename(tmpPath, this.filePath);\n // Re-open in append mode for continued use of this file.\n this.handle = await fsp.open(this.filePath, 'a', 0o600);\n } catch (err) {\n await fsp.unlink(tmpPath).catch(() => undefined);\n throw err;\n }\n\n await this.append({\n type: 'rewound',\n ts: new Date().toISOString(),\n toPromptIndex: targetPromptIndex,\n revertedFiles: [],\n });\n\n this.events?.emit('session.rewound', {\n toPromptIndex: targetPromptIndex,\n revertedFiles: [],\n removedEvents: removedCount,\n });\n\n return removedCount;\n }\n\n async clearSession(): Promise<void> {\n if (!this.filePath) return;\n const record = `${JSON.stringify({\n type: 'session_start',\n ts: new Date().toISOString(),\n id: this.id,\n model: this.meta.model ?? 'unknown',\n provider: this.meta.provider ?? 'unknown',\n })}\\n`;\n await fsp.writeFile(this.filePath, record, 'utf8');\n }\n\n /**\n * Idea #1 — write an in-flight marker. The agent loop should call\n * this at the start of each long-running operation; a matching\n * `clearInFlightMarker` follows on clean exit. A stale marker\n * (no end) is what `SessionRecovery.detectStale` looks for.\n */\n async writeInFlightMarker(context: string): Promise<void> {\n if (!context || context.length > 500) {\n throw new Error('In-flight context must be 1..500 chars');\n }\n await this.append({\n type: 'in_flight_start',\n ts: new Date().toISOString(),\n context,\n });\n this.events?.emit('in_flight.started', { context, ts: new Date().toISOString() });\n }\n\n /**\n * Idea #1 — close the in-flight marker. Idempotent in spirit\n * (you can call it after a successful iteration even if you\n * didn't open one this round) — but the session log records\n * every call so postmortem tooling can see \"the agent finished\n * cleanly X times, then died without finishing Y\".\n */\n async clearInFlightMarker(reason: 'clean' | 'aborted' | 'recovered'): Promise<void> {\n await this.append({\n type: 'in_flight_end',\n ts: new Date().toISOString(),\n reason,\n });\n this.events?.emit('in_flight.ended', { reason, ts: new Date().toISOString() });\n }\n}\n\nfunction userInputTitle(content: string | ContentBlock[]): string {\n const text =\n typeof content === 'string'\n ? content\n : content\n .filter((b): b is { type: 'text'; text: string } => b.type === 'text')\n .map((b) => b.text)\n .join(' ');\n return (text || '(non-text input)').slice(0, 60);\n}\n","import * as path from 'node:path';\nimport { DefaultSessionStore } from '../storage/session-store.js';\nimport type { SessionStore, SessionWriter } from '../types/session.js';\n\n/**\n * Per-subagent session factory.\n *\n * Director runs produce many parallel transcripts — one per spawned\n * subagent — and we want them all rooted under the same director-run\n * directory so a future `wstack replay <runId>` can rehydrate the whole\n * fleet from a single tree.\n *\n * The factory builds (or accepts) a `SessionStore` whose `dir` points at\n * `<sessionsRoot>/<directorRunId>/`, and returns a small `create()`\n * function that the orchestration layer calls per-spawn. Each call\n * yields a fresh `SessionWriter` whose JSONL file lives in that\n * directory, named by either the caller-supplied `subagentId` (preferred,\n * so the file name is human-readable) or a derived id.\n *\n * **Why a thin factory instead of plumbing options through every spawn\n * site?** Because the director is the only caller that needs this\n * isolation pattern, and shoving `sessionStore` options into\n * `SubagentConfig` would leak storage details into a config shape that\n * agents and the coordinator have no business knowing about.\n */\nexport interface DirectorSessionFactoryOptions {\n /**\n * Either a parent directory where `<directorRunId>/` will be created,\n * or a pre-built `SessionStore` whose `dir` already points at the\n * director run directory. Tests pass an in-memory store for isolation;\n * production code passes the path under `~/.wrongstack/sessions/`.\n */\n store?: SessionStore;\n sessionsRoot?: string;\n /**\n * Director run id — namespaces all subagent JSONLs under one folder.\n * Defaults to a timestamped id; supplied explicitly when resuming a\n * prior fleet manifest.\n */\n directorRunId?: string;\n}\n\nexport interface DirectorSessionFactory {\n /** Absolute directory where this director run's transcripts live. */\n readonly dir: string;\n /** The director run id used to namespace the directory. */\n readonly directorRunId: string;\n /**\n * Create a fresh `SessionWriter` for the named subagent. Each\n * subagent gets its own JSONL file. The writer's `id` matches the\n * supplied `subagentId` so disk paths line up with in-memory ids.\n */\n createSubagentSession(args: {\n subagentId: string;\n provider?: string;\n model?: string;\n title?: string;\n }): Promise<SessionWriter>;\n}\n\n/**\n * Build a `DirectorSessionFactory`. Pass either a pre-configured\n * `SessionStore` (tests) or a `sessionsRoot` path (production). When\n * neither is supplied the factory throws — there's no sane default for\n * \"where do these JSONLs live\".\n */\nexport function makeDirectorSessionFactory(\n opts: DirectorSessionFactoryOptions,\n): DirectorSessionFactory {\n const runId = opts.directorRunId ?? `${new Date().toISOString().replace(/[:.]/g, '-')}-director`;\n\n let store: SessionStore;\n let dir: string;\n if (opts.store) {\n // The caller wired its own store — we trust them on where the\n // files land. We can't introspect a `SessionStore`'s directory\n // without a typed accessor, so we report the run id and let the\n // caller record the path separately if needed.\n store = opts.store;\n dir = opts.sessionsRoot ? path.join(opts.sessionsRoot, runId) : '(caller-managed)';\n } else if (opts.sessionsRoot) {\n dir = path.join(opts.sessionsRoot, runId);\n store = new DefaultSessionStore({ dir });\n } else {\n throw new Error('makeDirectorSessionFactory requires either `store` or `sessionsRoot`');\n }\n\n return {\n dir,\n directorRunId: runId,\n async createSubagentSession({ subagentId, provider, model, title }) {\n // Per-subagent JSONL — DefaultSessionStore generates the file name\n // from the metadata `id`, so we pass `subagentId` directly to\n // keep disk artifacts human-readable.\n return store.create({\n id: subagentId,\n title: title ?? subagentId,\n provider: provider ?? 'unknown',\n model: model ?? 'unknown',\n });\n },\n };\n}\n","/**\n * Default auto-extend policy for subagent budgets.\n *\n * The budget's soft-limit path (`SubagentBudget` → `budget.threshold_reached`)\n * only negotiates an extension when SOMETHING listens on the EventBus. Under a\n * `Director`, that listener is the director's own auto-extend handler. On the\n * plain coordinator path (e.g. a bare `/spawn` with no director) nothing\n * listens, so the budget falls back to a hard stop and the subagent dies the\n * moment it crosses a soft limit.\n *\n * `attachAutoExtend` is the additive fix: wire it to a subagent's EventBus and\n * budget overruns are auto-granted headroom instead of killing the run. It is\n * heartbeat-aware for the timeout kind — wall-clock time always advances, so a\n * naive \"extend timeout forever\" would let a wedged agent run indefinitely.\n * Instead, a timeout extension is granted only when the agent has executed a\n * new tool call or started a new iteration since the last timeout extension.\n * No progress since last time ⇒ the agent is genuinely stuck ⇒ deny and let it\n * fail. The non-timeout kinds (iterations/tool_calls/tokens/cost) extend up to\n * a per-kind cap, then deny — those ceilings are the real runaway guard.\n */\nimport type { EventBus } from '../kernel/events.js';\n\nexport interface AutoExtendCeiling {\n maxIterations?: number;\n maxToolCalls?: number;\n maxTokens?: number;\n maxCostUsd?: number;\n timeoutMs?: number;\n}\n\nexport interface AutoExtendPolicy {\n /** Multiplier applied to the tripped limit when extending. Default 0.5 (+50%). */\n factor?: number;\n /**\n * Max extensions per NON-timeout kind before denying. Timeout is governed by\n * the heartbeat check, not this cap, so it can extend indefinitely while the\n * agent makes progress. Default 8.\n */\n maxExtensionsPerKind?: number;\n /** Absolute ceilings — an extension never pushes a limit past these. */\n ceiling?: AutoExtendCeiling;\n}\n\nconst DEFAULT_CEILING: Required<AutoExtendCeiling> = {\n maxIterations: 50_000,\n maxToolCalls: 100_000,\n maxTokens: 5_000_000,\n maxCostUsd: 100,\n timeoutMs: 24 * 60 * 60 * 1000,\n};\n\nconst FIELD_BY_KIND = {\n iterations: 'maxIterations',\n tool_calls: 'maxToolCalls',\n tokens: 'maxTokens',\n cost: 'maxCostUsd',\n timeout: 'timeoutMs',\n idle_timeout: 'timeoutMs',\n} as const;\n\n/**\n * Attach an auto-extend policy to a subagent's EventBus. Returns an unsubscribe\n * function that detaches all listeners — call it when the subagent task ends.\n */\nexport function attachAutoExtend(events: EventBus, policy: AutoExtendPolicy = {}): () => void {\n const factor = policy.factor ?? 0.5;\n const maxPerKind = policy.maxExtensionsPerKind ?? 8;\n const ceiling = { ...DEFAULT_CEILING, ...policy.ceiling };\n\n const extendCounts = new Map<string, number>();\n // Monotonic progress counter: tool executions + iteration starts. Used to\n // decide whether a timeout extension is warranted (progress) or the agent is\n // wedged (no progress since the last timeout grant).\n let progress = 0;\n let lastTimeoutProgress = -1;\n\n const unsubs: Array<() => void> = [\n events.on('tool.executed', () => {\n progress++;\n }),\n events.on('iteration.started', () => {\n progress++;\n }),\n events.on('budget.threshold_reached', (e) => {\n const { kind, limit, extend, deny } = e;\n\n if (kind === 'timeout' || kind === 'idle_timeout') {\n if (progress > lastTimeoutProgress) {\n lastTimeoutProgress = progress;\n const next = Math.min(Math.ceil(limit * (1 + factor)), ceiling.timeoutMs);\n extend({ timeoutMs: next });\n } else {\n // No new work since the last timeout extension — the agent is stuck.\n deny();\n }\n return;\n }\n\n const count = extendCounts.get(kind) ?? 0;\n if (count >= maxPerKind) {\n deny();\n return;\n }\n extendCounts.set(kind, count + 1);\n const field = FIELD_BY_KIND[kind];\n const cap = ceiling[field];\n const next = Math.min(Math.ceil(limit * (1 + factor)), cap);\n extend({ [field]: next });\n }),\n ];\n\n return () => {\n for (const u of unsubs) u();\n };\n}\n","import { FleetBus } from './fleet-bus.js';\n\n/**\n * A no-op FleetBus that discards all events. Used when no real fleet\n * bus is available (non-director mode) so the runner's `fleetBus`\n * field is always valid and the `attach()` call is always safe.\n *\n * One singleton instance is sufficient — it has no state to reset.\n */\nexport const NULL_FLEET_BUS = new FleetBus();\n","import * as fsp from 'node:fs/promises';\r\nimport * as path from 'node:path';\r\nimport { randomUUID } from 'node:crypto';\r\nimport { atomicWrite } from '../utils/atomic-write.js';\r\nimport { assignNickname } from './subagent-nicknames.js';\r\nimport type { SubagentConfig } from '../types/multi-agent.js';\r\nimport type { SessionWriter } from '../types/session.js';\r\nimport { DirectorStateCheckpoint } from '../storage/director-state.js';\r\nimport { FleetBus, FleetUsageAggregator } from './fleet-bus.js';\r\nimport type { FleetUsage } from './fleet-bus.js';\r\nimport type { IFleetManager } from './ifleet-manager.js';\r\nimport type { DefaultMultiAgentCoordinator } from './multi-agent-coordinator.js';\r\n\r\n/** Options for constructing a FleetManager. */\r\nexport interface FleetManagerOptions {\r\n manifestPath?: string;\r\n sessionsRoot?: string;\r\n directorRunId?: string;\r\n maxSpawns?: number;\r\n maxSpawnDepth?: number;\r\n spawnDepth?: number;\r\n stateCheckpointPath?: string;\r\n sessionWriter?: SessionWriter;\r\n manifestDebounceMs?: number;\r\n checkpointDebounceMs?: number;\r\n directorBudget?: { maxCostUsd?: number };\r\n /**\r\n * Maximum context load (as a fraction of maxContext) the leader agent\r\n * is allowed to reach before a new spawn is rejected. Default: 0.85.\r\n * When the leader's context pressure exceeds this threshold, spawning\r\n * a new subagent is refused — the leader must compact first.\r\n * Set to 1.0 to disable this check.\r\n */\r\n maxLeaderContextLoad?: number;\r\n /**\r\n * Provider's max context window in tokens. Used with `maxLeaderContextLoad`\r\n * to compute the absolute token threshold. Default: 128_000.\r\n */\r\n maxContext?: number;\r\n}\r\n\r\n/**\r\n * Fleet-level policy container extracted from `Director`. Owns:\r\n * - FleetBus + FleetUsageAggregator\r\n * - Spawn caps and counters\r\n * - Manifest entries and debounced writing\r\n * - State checkpointing\r\n *\r\n * This lets the `Director` focus on orchestration (spawn/assign/await/ask)\r\n * while fleet-level decisions live in one place. The class implements\r\n * `IFleetManager` so it remains swappable in future.\r\n *\r\n * @example\r\n * ```typescript\r\n * const fm = new FleetManager({ manifestPath: '/tmp/fleet.json' });\r\n * const err = fm.canSpawn({ name: 'worker' });\r\n * if (!err) fm.recordSpawn('sub-1', { name: 'worker' });\r\n * await fm.writeManifest();\r\n * ```\r\n */\r\nexport class FleetManager implements IFleetManager {\r\n /** The fleet-wide event bus. */\r\n readonly fleet: FleetBus;\r\n /** Usage rollup across all subagents. */\r\n readonly usage: FleetUsageAggregator;\r\n\r\n private readonly manifestPath?: string;\r\n private readonly directorRunId: string;\r\n /** Spawn cap (lifetime total). Infinity means unlimited. */\r\n readonly maxSpawns: number;\r\n /** Nesting cap. */\r\n readonly maxSpawnDepth: number;\r\n /** This director's depth in a director chain. Root = 0. */\r\n readonly spawnDepth: number;\r\n /** Live spawn counter. */\r\n private spawnCount = 0;\r\n private readonly stateCheckpoint: DirectorStateCheckpoint | null;\r\n private readonly sessionWriter: SessionWriter | null;\r\n private manifestTimer: NodeJS.Timeout | null = null;\r\n private readonly manifestDebounceMs: number;\r\n /** Fleet-wide cost cap. Infinity = no cap. Distinct from SubagentBudget limits,\r\n * which track per-subagent spend — this field caps the entire fleet total. */\r\n private readonly maxFleetCostUsd: number;\r\n private readonly manifestEntries = new Map<\r\n string,\r\n { subagentId: string; name: string; role?: string; provider?: string; model?: string; taskIds: string[] }\r\n >();\r\n /** Pending tasks with their descriptions — populated by `addPendingTask`\r\n * and cleared by `removePendingTask`. Replaces the host-side `pending`\r\n * Map so task descriptions live in one place (FleetManager). */\r\n private readonly pendingTasks = new Map<string, { subagentId: string; description: string }>();\r\n private readonly subagentMeta = new Map<string, { provider?: string; model?: string }>();\r\n private readonly priceLookups = new Map<string, { input?: number; output?: number; cacheRead?: number; cacheWrite?: number }>();\r\n /** Tracks which nickname keys are already assigned — prevents collisions. */\r\n private readonly _usedNicknames = new Set<string>();\r\n /** The coordinator (wired via setCoordinator by Director after construction). */\r\n private coordinator: DefaultMultiAgentCoordinator | null = null;\r\n /** Leader agent's current context pressure (full request tokens). */\r\n private leaderContextPressure = 0;\r\n /** Maximum context load fraction before spawn is refused. */\r\n private readonly maxLeaderContextLoad: number;\r\n /** Provider's max context window in tokens. */\r\n private readonly maxContext: number;\r\n\r\n constructor(opts: FleetManagerOptions = {}) {\r\n this.manifestPath = opts.manifestPath;\r\n this.directorRunId = opts.directorRunId ?? randomUUID();\r\n this.maxSpawns = opts.maxSpawns ?? Number.POSITIVE_INFINITY;\r\n this.maxSpawnDepth = opts.maxSpawnDepth ?? 2;\r\n this.spawnDepth = opts.spawnDepth ?? 0;\r\n this.sessionWriter = opts.sessionWriter ?? null;\r\n this.manifestDebounceMs = opts.manifestDebounceMs ?? 2000;\r\n this.maxFleetCostUsd = opts.directorBudget?.maxCostUsd ?? Number.POSITIVE_INFINITY;\r\n this.maxLeaderContextLoad = opts.maxLeaderContextLoad ?? 0.85;\r\n this.maxContext = opts.maxContext ?? 128_000;\r\n this.stateCheckpoint = opts.stateCheckpointPath\r\n ? new DirectorStateCheckpoint(\r\n opts.stateCheckpointPath,\r\n {\r\n directorRunId: this.directorRunId,\r\n maxSpawns: opts.maxSpawns,\r\n spawnDepth: this.spawnDepth,\r\n maxSpawnDepth: this.maxSpawnDepth,\r\n directorBudget: opts.directorBudget,\r\n },\r\n opts.checkpointDebounceMs ?? 250,\r\n )\r\n : null;\r\n\r\n this.fleet = new FleetBus();\r\n this.usage = new FleetUsageAggregator(\r\n this.fleet,\r\n (_id, provider, model) => {\r\n if (provider && model) return this.priceLookups.get(`${provider}/${model}`);\r\n return undefined;\r\n },\r\n (id) => this.subagentMeta.get(id),\r\n );\r\n }\r\n\r\n // -----------------------------------------------------------------------\r\n // IFleetManager surface\r\n // -----------------------------------------------------------------------\r\n\r\n get fleetBus(): FleetBus {\r\n return this.fleet;\r\n }\r\n\r\n /**\r\n * Wire the coordinator after Director construction. The coordinator\r\n * is not available when FleetManager is constructed standalone.\r\n * Once set, `getFleetStats()` delegates to `coordinator.getStats()`.\r\n */\r\n setCoordinator(coordinator: DefaultMultiAgentCoordinator): void {\r\n this.coordinator = coordinator;\r\n }\r\n\r\n snapshot(): FleetUsage {\r\n return this.usage.snapshot();\r\n }\r\n\r\n getSubagentMeta(id: string): { provider?: string; model?: string; name?: string } | undefined {\r\n const meta = this.subagentMeta.get(id);\r\n const manifest = this.manifestEntries.get(id);\r\n if (!meta && !manifest) return undefined;\r\n return {\r\n provider: meta?.provider ?? manifest?.provider,\r\n model: meta?.model ?? manifest?.model,\r\n name: manifest?.name,\r\n };\r\n }\r\n\r\n /**\r\n * Returns null if the spawn is allowed, or an object describing\r\n * which cap was exceeded. Does NOT throw — the caller decides\r\n * how to surface the rejection.\r\n */\r\n canSpawn(_config: SubagentConfig): { kind: 'max_spawns' | 'max_spawn_depth' | 'max_cost_usd' | 'max_context_load'; limit: number; observed: number } | null {\r\n if (this.spawnDepth >= this.maxSpawnDepth) {\r\n return { kind: 'max_spawn_depth', limit: this.maxSpawnDepth, observed: this.spawnDepth };\r\n }\r\n if (this.spawnCount >= this.maxSpawns) {\r\n return { kind: 'max_spawns', limit: this.maxSpawns, observed: this.spawnCount + 1 };\r\n }\r\n if (this.maxFleetCostUsd < Number.POSITIVE_INFINITY) {\r\n const totalCost = this.usage.snapshot().total?.cost ?? 0;\r\n if (totalCost >= this.maxFleetCostUsd) {\r\n return { kind: 'max_cost_usd', limit: this.maxFleetCostUsd, observed: totalCost };\r\n }\r\n }\r\n // Context pressure check: reject spawn if leader context is too full.\r\n // maxLeaderContextLoad === 1.0 disables this check.\r\n if (this.maxLeaderContextLoad < 1.0) {\r\n const threshold = this.maxContext * this.maxLeaderContextLoad;\r\n if (this.leaderContextPressure >= threshold) {\r\n return {\r\n kind: 'max_context_load',\r\n limit: threshold,\r\n observed: this.leaderContextPressure,\r\n };\r\n }\r\n }\r\n return null;\r\n }\r\n\r\n setLeaderContextPressure(tokens: number): void {\r\n this.leaderContextPressure = tokens;\r\n }\r\n\r\n /**\r\n * Assign a memorable nickname (e.g. \"Einstein (Bug Hunter)\") to the config,\r\n * record it so the same name is never reused, then record the spawn.\r\n *\r\n * Call this INSTEAD of `recordSpawn` when you want automatic nicknames.\r\n * The nickname is written back to `config.name` BEFORE the coordinator\r\n * sees the config, so the manifest, logs, and fleet UI all show it.\r\n *\r\n * NOTE: This method ONLY assigns the nickname and marks it used.\r\n * The caller MUST call `recordSpawn(subagentId, config, priceLookup)` AFTER\r\n * `coordinator.spawn()` returns with the real subagentId. This is because\r\n * the subagentId is not known until after the coordinator creates the subagent.\r\n */\r\n assignNicknameAndRecord(\r\n config: SubagentConfig,\r\n ): string {\r\n const role = config.role ?? 'subagent';\r\n const nickname = assignNickname(role, this._usedNicknames);\r\n // Extract the base key (e.g. \"einstein\") from the pool to mark it used.\r\n const baseKey = nickname.split(' ')[0]!.toLowerCase().replace(/[^a-z0-9-]/g, '-');\r\n this._usedNicknames.add(baseKey);\r\n // Write the full nickname back into config so the coordinator\r\n // and manifest both see the human name.\r\n config.name = nickname;\r\n return nickname;\r\n }\r\n\r\n /**\r\n * Returns the set of already-assigned nickname keys — useful for debugging\r\n * and testing.\r\n */\r\n get usedNicknames(): ReadonlySet<string> {\r\n return this._usedNicknames;\r\n }\r\n\r\n /**\r\n * Records a spawn: increments counter, stores metadata, updates state checkpoint,\r\n * and schedules a debounced manifest write. Call AFTER the coordinator\r\n * has successfully spawned the subagent.\r\n *\r\n * @param subagentId The subagent's id (from coordinator.spawn result)\r\n * @param config The SubagentConfig that was used\r\n * @param priceLookup Optional per-subagent pricing data\r\n */\r\n recordSpawn(\r\n subagentId: string,\r\n config: SubagentConfig,\r\n priceLookup?: { input?: number; output?: number; cacheRead?: number; cacheWrite?: number },\r\n ): void {\r\n this.spawnCount += 1;\r\n this.subagentMeta.set(subagentId, {\r\n provider: config.provider,\r\n model: config.model,\r\n });\r\n if (priceLookup && config.provider && config.model) {\r\n this.priceLookups.set(`${config.provider}/${config.model}`, priceLookup);\r\n }\r\n this.manifestEntries.set(subagentId, {\r\n subagentId,\r\n name: config.name,\r\n role: config.role,\r\n provider: config.provider,\r\n model: config.model,\r\n taskIds: [],\r\n });\r\n // State checkpoint: persist the spawn even before any task is assigned\r\n this.stateCheckpoint?.recordSpawn({\r\n id: subagentId,\r\n name: config.name,\r\n role: config.role,\r\n provider: config.provider,\r\n model: config.model,\r\n spawnedAt: new Date().toISOString(),\r\n }, this.spawnCount);\r\n void this.appendSessionEvent({\r\n type: 'agent_spawned',\r\n ts: new Date().toISOString(),\r\n agentId: subagentId,\r\n role: config.role ?? config.name,\r\n });\r\n this.scheduleManifest();\r\n }\r\n\r\n async writeManifest(): Promise<string | null> {\r\n if (!this.manifestPath) return null;\r\n const manifest = {\r\n version: 1,\r\n directorRunId: this.directorRunId,\r\n generatedAt: new Date().toISOString(),\r\n children: Array.from(this.manifestEntries.values()).map((entry) => ({\r\n id: entry.subagentId,\r\n name: entry.name,\r\n role: entry.role,\r\n provider: entry.provider,\r\n model: entry.model,\r\n taskIds: entry.taskIds,\r\n })),\r\n usage: this.usage.snapshot(),\r\n };\r\n await fsp.mkdir(path.dirname(this.manifestPath), { recursive: true });\r\n await atomicWrite(this.manifestPath, JSON.stringify(manifest, null, 2), { mode: 0o600 });\r\n return this.manifestPath;\r\n }\r\n\r\n /**\r\n * Attach task ids to an already-spawned subagent. Called by\r\n * `Director.assign()` after the coordinator assigns a task.\r\n */\r\n addTaskToSubagent(subagentId: string, taskId: string): void {\r\n const entry = this.manifestEntries.get(subagentId);\r\n if (entry) entry.taskIds.push(taskId);\r\n }\r\n\r\n /**\r\n * Debounced manifest write. Call after any state mutation\r\n * (spawn, assign, complete) so a burst collapses into one write.\r\n * When `manifestDebounceMs` is 0, writes are synchronous (no debounce).\r\n */\r\n scheduleManifest(): void {\r\n if (!this.manifestPath) return;\r\n if (this.manifestDebounceMs === 0) {\r\n // 0 means instant flush — write synchronously, no timer.\r\n void this.writeManifest().catch((err) => {\r\n const detail = err instanceof Error ? err.message : String(err);\r\n process.emitWarning(\r\n `FleetManager manifest write failed: ${detail}`,\r\n 'FleetManagerWarning',\r\n );\r\n });\r\n return;\r\n }\r\n if (this.manifestDebounceMs < 0) return;\r\n if (this.manifestTimer) return;\r\n this.manifestTimer = setTimeout(() => {\r\n this.manifestTimer = null;\r\n void this.writeManifest().catch((err) => {\r\n // Surface via process.emitWarning so a persistent manifest-write\r\n // failure doesn't get silently swallowed (e.g. ENOSPC on the\r\n // sessions dir would otherwise leave fleet state un-persisted with\r\n // no signal until shutdown).\r\n const detail = err instanceof Error ? err.message : String(err);\r\n process.emitWarning(\r\n `FleetManager manifest write failed: ${detail}`,\r\n 'FleetManagerWarning',\r\n );\r\n });\r\n }, this.manifestDebounceMs);\r\n }\r\n\r\n /**\r\n * Bypass the debounce timer and write the manifest immediately.\r\n * Clears any pending debounce timer before writing.\r\n */\r\n async flushManifest(): Promise<void> {\r\n if (!this.manifestPath) return;\r\n if (this.manifestTimer) {\r\n clearTimeout(this.manifestTimer);\r\n this.manifestTimer = null;\r\n }\r\n await this.writeManifest().catch((err) => {\r\n const detail = err instanceof Error ? err.message : String(err);\r\n process.emitWarning(\r\n `FleetManager manifest write failed: ${detail}`,\r\n 'FleetManagerWarning',\r\n );\r\n });\r\n }\r\n\r\n /** Best-effort session event writer. Swallows failures. */\r\n private async appendSessionEvent(event: Parameters<SessionWriter['append']>[0]): Promise<void> {\r\n if (!this.sessionWriter) return;\r\n try {\r\n await this.sessionWriter.append(event);\r\n } catch {\r\n // ignore\r\n }\r\n }\r\n\r\n // -----------------------------------------------------------------------\r\n // Pending task management — eliminates host-side state duplication\r\n // -----------------------------------------------------------------------\r\n\r\n addPendingTask(taskId: string, subagentId: string, description: string): void {\r\n this.pendingTasks.set(taskId, { subagentId, description });\r\n }\r\n\r\n removePendingTask(taskId: string): void {\r\n this.pendingTasks.delete(taskId);\r\n }\r\n\r\n getFleetStats(): {\r\n total: number;\r\n running: number;\r\n idle: number;\r\n stopped: number;\r\n inFlight: number;\r\n pending: number;\r\n completed: number;\r\n subagentStatuses: { subagentId: string; taskId: string; status: string; assigned: boolean }[];\r\n } {\r\n if (!this.coordinator) {\r\n return {\r\n total: 0, running: 0, idle: 0, stopped: 0,\r\n inFlight: 0, pending: 0, completed: 0,\r\n subagentStatuses: [],\r\n };\r\n }\r\n const stats = this.coordinator.getStats();\r\n const subagentStatuses: { subagentId: string; taskId: string; status: string; assigned: boolean }[] = [];\r\n for (const [subagentId, s] of this.coordinator['subagents']) {\r\n subagentStatuses.push({\r\n subagentId,\r\n taskId: s.currentTask ?? '',\r\n status: s.status,\r\n assigned: s.context.parentBridge !== null,\r\n });\r\n }\r\n return { ...stats, subagentStatuses };\r\n }\r\n\r\n getFleetStatus(): {\r\n pending: { taskId: string; description: string; subagentId: string }[];\r\n live: { subagentId: string; status: string; task?: string }[];\r\n } {\r\n const pending = Array.from(this.pendingTasks.entries()).map(([taskId, v]) => ({\r\n taskId,\r\n description: v.description,\r\n subagentId: v.subagentId,\r\n }));\r\n // live is populated by MultiAgentHost from the coordinator — fleet\r\n // manager has no direct visibility into subagent status\r\n return { pending, live: [] };\r\n }\r\n\r\n /**\r\n * Clean up all fleet-manager state associated with a removed subagent:\r\n * - Frees the nickname slot so the same name can be reused\r\n * - Removes any pending tasks for this subagent\r\n */\r\n removeSubagent(subagentId: string): void {\r\n // Free the nickname slot so the same name can be reused.\r\n const entry = this.manifestEntries.get(subagentId);\r\n if (entry?.name) {\r\n const nicknameKey = entry.name.split(' ')[0]!.toLowerCase().replace(/[^a-z0-9-]/g, '-');\r\n this._usedNicknames.delete(nicknameKey);\r\n }\r\n // Remove any pending tasks assigned to this subagent.\r\n for (const [taskId, task] of this.pendingTasks) {\r\n if (task.subagentId === subagentId) {\r\n this.pendingTasks.delete(taskId);\r\n }\r\n }\r\n }\r\n\r\n /** Release all resources: clear the manifest debounce timer and dispose the usage aggregator. */\r\n dispose(): void {\r\n if (this.manifestTimer) {\r\n clearTimeout(this.manifestTimer);\r\n this.manifestTimer = null;\r\n }\r\n this.usage.dispose();\r\n }\r\n}"]}
|
|
1
|
+
{"version":3,"sources":["../../src/coordination/brain.ts","../../src/utils/atomic-write.ts","../../src/storage/director-state.ts","../../src/coordination/in-memory-transport.ts","../../src/coordination/agent-bridge.ts","../../src/utils/glob-expand.ts","../../src/coordination/collab-debug.ts","../../src/coordination/director-prompts.ts","../../src/coordination/agents/types.ts","../../src/coordination/agents/phase1-discovery.ts","../../src/coordination/agents/phase2-planning.ts","../../src/coordination/agents/phase3-build.ts","../../src/coordination/agents/phase4-verify.ts","../../src/coordination/agents/phase5-review.ts","../../src/coordination/agents/phase6-domain.ts","../../src/coordination/agents/phase7-knowledge.ts","../../src/coordination/agents/phase8-delivery.ts","../../src/coordination/agents/phase9-meta.ts","../../src/coordination/agents/index.ts","../../src/coordination/dispatcher.ts","../../src/coordination/director-tools.ts","../../src/coordination/fleet-bus.ts","../../src/coordination/large-answer-store.ts","../../src/coordination/model-matrix.ts","../../src/types/errors.ts","../../src/types/provider.ts","../../src/coordination/subagent-budget.ts","../../src/coordination/fleet.ts","../../src/coordination/subagent-nicknames.ts","../../src/coordination/multi-agent-coordinator.ts","../../src/coordination/director.ts","../../src/coordination/delegate-tool.ts","../../src/coordination/agent-subagent-runner.ts","../../src/utils/message-invariants.ts","../../src/storage/session-store.ts","../../src/coordination/director-session.ts","../../src/coordination/auto-extend.ts","../../src/coordination/null-fleet-bus.ts","../../src/coordination/fleet-manager.ts"],"names":["resolve","path","fs","stat","fsp","lock","handlers","fsp2","DirectorAlertLevel","randomUUID","fsp3","first","decision","kind","EventEmitter","baseMessage","fsp4","path2","instantiateRosterConfig","partial","path3","fsp5","randomBytes","path5","next","fsp7","path6"],"mappings":";;;;;;;;;;;;;;AA+DO,IAAM,yBAAN,MAAqD;AAAA,EAC1D,WAAA,CACmB,OACA,MAAA,EACjB;AAFiB,IAAA,IAAA,CAAA,KAAA,GAAA,KAAA;AACA,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAAA,EAChB;AAAA,EAFgB,KAAA;AAAA,EACA,MAAA;AAAA,EAGnB,MAAM,OAAO,OAAA,EAAuD;AAClE,IAAA,IAAA,CAAK,MAAA,CAAO,KAAK,0BAAA,EAA4B,EAAE,SAAS,EAAA,EAAI,IAAA,CAAK,GAAA,EAAI,EAAG,CAAA;AACxE,IAAA,MAAM,QAAA,GAAW,MAAM,IAAA,CAAK,KAAA,CAAM,OAAO,OAAO,CAAA;AAChD,IAAA,MAAM,KAAA,GACJ,SAAS,IAAA,KAAS,WAAA,GACd,6BACA,QAAA,CAAS,IAAA,KAAS,SAChB,uB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;AACf,MAAA,MAAM,WAAA,GAAc,KAAA,CAAM,IAAA,CAAK,KAAA,CAAM,GAAG,CAAA,CAAE,CAAC,CAAA,CAAG,WAAA,EAAY,CAAE,OAAA,CAAQ,aAAA,EAAe,GAAG,CAAA;AACtF,MAAA,IAAA,CAAK,cAAA,CAAe,OAAO,WAAW,CAAA;AAAA,IACxC;AAEA,IAAA,KAAA,MAAW,CAAC,MAAA,EAAQ,IAAI,CAAA,IAAK,KAAK,YAAA,EAAc;AAC9C,MAAA,IAAI,IAAA,CAAK,eAAe,UAAA,EAAY;AAClC,QAAA,IAAA,CAAK,YAAA,CAAa,OAAO,MAAM,CAAA;AAAA,MACjC;AAAA,IACF;AAAA,EACF;AAAA;AAAA,EAGA,OAAA,GAAgB;AACd,IAAA,IAAI,KAAK,aAAA,EAAe;AACtB,MAAA,YAAA,CAAa,KAAK,aAAa,CAAA;AAC/B,MAAA,IAAA,CAAK,aAAA,GAAgB,IAAA;AAAA,IACvB;AACA,IAAA,IAAA,CAAK,MAAM,OAAA,EAAQ;AAAA,EACrB;AACF","file":"index.js","sourcesContent":["/**\n * Brain coordination primitives.\n *\n * Brain is an authority layer above a leader/director but below the human. It is\n * intentionally modeled as a decision interface first, not as an autonomous\n * bypass: callers ask for a decision, Brain either answers within policy or\n * escalates to the human.\n */\n\nimport type { EventBus } from '../kernel/events.js';\n\nexport type BrainDecisionSource = 'autophase' | 'director' | 'tool' | 'user' | 'system';\n\nexport type BrainRisk = 'low' | 'medium' | 'high' | 'critical';\n\nexport type BrainFallback = 'ask_human' | 'deny' | 'continue';\n\nexport interface BrainDecisionOption {\n id: string;\n label: string;\n consequence?: string;\n risk?: BrainRisk;\n recommended?: boolean;\n}\n\nexport interface BrainDecisionRequest {\n id: string;\n source: BrainDecisionSource;\n question: string;\n context?: string;\n options?: BrainDecisionOption[];\n risk: BrainRisk;\n /** What a non-LLM/default Brain should do when policy cannot decide safely. */\n fallback: BrainFallback;\n}\n\nexport type BrainDecision =\n | {\n type: 'answer';\n optionId?: string;\n text: string;\n rationale?: string;\n }\n | {\n type: 'ask_human';\n prompt: string;\n options?: BrainDecisionOption[];\n rationale?: string;\n }\n | {\n type: 'deny';\n reason: string;\n };\n\nexport interface BrainArbiter {\n decide(request: BrainDecisionRequest): Promise<BrainDecision>;\n}\n\n/**\n * Event-emitting decorator for any Brain implementation. Hosts wire this around\n * their actual arbiter so TUI/session surfaces can render Brain decisions\n * without coupling to the caller that requested the decision.\n */\nexport class ObservableBrainArbiter implements BrainArbiter {\n constructor(\n private readonly inner: BrainArbiter,\n private readonly events: EventBus,\n ) {}\n\n async decide(request: BrainDecisionRequest): Promise<BrainDecision> {\n this.events.emit('brain.decision_requested', { request, at: Date.now() });\n const decision = await this.inner.decide(request);\n const event =\n decision.type === 'ask_human'\n ? 'brain.decision_ask_human'\n : decision.type === 'deny'\n ? 'brain.decision_denied'\n : 'brain.decision_answered';\n this.events.emit(event, { request, decision, at: Date.now() });\n return decision;\n }\n}\n\nexport interface BrainDecisionQueueOptions {\n /** Safety fallback if the human never answers. Default: no timeout. */\n timeoutMs?: number;\n}\n\n/**\n * Bridge between an `ask_human` Brain decision and the UI. It emits the visible\n * ask-human event, then resolves when the TUI emits `brain.human_answered`.\n */\nexport class BrainDecisionQueue {\n private readonly pending = new Map<\n string,\n {\n request: BrainDecisionRequest;\n resolve: (decision: BrainDecision) => void;\n timer?: ReturnType<typeof setTimeout>;\n }\n >();\n private readonly offAnswer: () => void;\n\n constructor(\n private readonly events: EventBus,\n private readonly opts: BrainDecisionQueueOptions = {},\n ) {\n this.offAnswer = this.events.on('brain.human_answered', (answer) => {\n const pending = this.pending.get(answer.id);\n if (!pending) return;\n this.pending.delete(answer.id);\n if (pending.timer) clearTimeout(pending.timer);\n if (answer.deny) {\n pending.resolve({ type: 'deny', reason: answer.text ?? 'Denied by human.' });\n return;\n }\n const option = pending.request.options?.find((o) => o.id === answer.optionId);\n pending.resolve({\n type: 'answer',\n optionId: answer.optionId,\n text: answer.text ?? option?.label ?? answer.optionId ?? 'Human answered.',\n rationale: 'Human answered a Brain escalation prompt.',\n });\n });\n }\n\n async requestHumanDecision(request: BrainDecisionRequest): Promise<BrainDecision> {\n const ask: BrainDecision = {\n type: 'ask_human',\n prompt: formatHumanPrompt(request),\n options: request.options,\n rationale: 'Decision escalated to human authority.',\n };\n const pending = new Promise<BrainDecision>((resolve) => {\n const entry: {\n request: BrainDecisionRequest;\n resolve: (decision: BrainDecision) => void;\n timer?: ReturnType<typeof setTimeout>;\n } = { request, resolve };\n if (this.opts.timeoutMs && this.opts.timeoutMs > 0) {\n entry.timer = setTimeout(() => {\n this.pending.delete(request.id);\n resolve({ type: 'deny', reason: 'Brain human decision timed out.' });\n }, this.opts.timeoutMs);\n }\n this.pending.set(request.id, entry);\n });\n this.events.emit('brain.decision_ask_human', { request, decision: ask, at: Date.now() });\n return pending;\n }\n\n dispose(): void {\n this.offAnswer();\n for (const [id, pending] of this.pending) {\n if (pending.timer) clearTimeout(pending.timer);\n pending.resolve({ type: 'deny', reason: 'Brain decision queue disposed.' });\n this.pending.delete(id);\n }\n }\n}\n\n/**\n * Decorator that turns `ask_human` into an actual awaited human decision.\n * The wrapped Brain remains policy-only; this layer owns the UI/event bridge.\n */\nexport class HumanEscalatingBrainArbiter implements BrainArbiter {\n constructor(\n private readonly inner: BrainArbiter,\n private readonly queue: BrainDecisionQueue,\n ) {}\n\n async decide(request: BrainDecisionRequest): Promise<BrainDecision> {\n const decision = await this.inner.decide(request);\n if (decision.type !== 'ask_human') return decision;\n return this.queue.requestHumanDecision(request);\n }\n}\n\nexport interface DefaultBrainArbiterOptions {\n /** Allow deterministic auto-answering for low-risk requests. Default true. */\n allowLowRiskAutoAnswer?: boolean;\n}\n\n/**\n * Conservative deterministic Brain implementation.\n *\n * It only auto-answers low-risk requests when the caller provided a recommended\n * option. Everything else follows the request fallback. This gives hosts a safe\n * policy object to wire before an LLM-backed Brain exists.\n */\nexport class DefaultBrainArbiter implements BrainArbiter {\n private readonly allowLowRiskAutoAnswer: boolean;\n\n constructor(opts: DefaultBrainArbiterOptions = {}) {\n this.allowLowRiskAutoAnswer = opts.allowLowRiskAutoAnswer ?? true;\n }\n\n async decide(request: BrainDecisionRequest): Promise<BrainDecision> {\n const recommended = request.options?.find((option) => option.recommended);\n if (this.allowLowRiskAutoAnswer && request.risk === 'low' && recommended) {\n return {\n type: 'answer',\n optionId: recommended.id,\n text: recommended.label,\n rationale: 'Low-risk request with an explicit recommended option.',\n };\n }\n\n switch (request.fallback) {\n case 'deny':\n return {\n type: 'deny',\n reason: `Brain could not safely decide: ${request.question}`,\n };\n case 'continue':\n return {\n type: 'answer',\n text: 'Continue with the caller default.',\n rationale: 'No safe Brain decision was available; request fallback is continue.',\n };\n case 'ask_human':\n return {\n type: 'ask_human',\n prompt: formatHumanPrompt(request),\n options: request.options,\n rationale: 'Decision requires human authority or lacks a safe automatic option.',\n };\n }\n }\n}\n\nexport function formatHumanPrompt(request: BrainDecisionRequest): string {\n const lines = [\n `Brain requires human decision for ${request.source}:`,\n `Question: ${request.question}`,\n ];\n if (request.context?.trim()) {\n lines.push('', 'Context:', request.context.trim());\n }\n if (request.options?.length) {\n lines.push('', 'Options:');\n for (const option of request.options) {\n const risk = option.risk ? ` [risk: ${option.risk}]` : '';\n const consequence = option.consequence ? ` — ${option.consequence}` : '';\n lines.push(`- ${option.id}: ${option.label}${risk}${consequence}`);\n }\n }\n lines.push('', `Risk: ${request.risk}`);\n return lines.join('\\n');\n}\n","import { randomBytes } from 'node:crypto';\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\n\nexport interface AtomicWriteOptions {\n mode?: number;\n encoding?: BufferEncoding;\n}\n\nexport async function atomicWrite(\n targetPath: string,\n content: string | Uint8Array,\n opts: AtomicWriteOptions = {},\n): Promise<void> {\n const dir = path.dirname(targetPath);\n await fs.mkdir(dir, { recursive: true });\n const tmp = path.join(dir, `.${path.basename(targetPath)}.${randomBytes(6).toString('hex')}.tmp`);\n\n // Write content to tmp first; 'wx' ensures exclusive creation (fails if\n // tmp already exists — extremely unlikely with 6-byte random suffix).\n try {\n if (typeof content === 'string') {\n await fs.writeFile(tmp, content, { flag: 'wx', encoding: opts.encoding ?? 'utf8' });\n } else {\n await fs.writeFile(tmp, content, { flag: 'wx' });\n }\n try {\n const fh = await fs.open(tmp, 'r+');\n try {\n await fh.sync();\n } finally {\n await fh.close();\n }\n } catch {\n // fsync best-effort\n }\n // Now safely read mode from target (if it exists) and apply to tmp before rename.\n // Prefer opts.mode for new files; for existing files preserve their mode.\n let mode: number | undefined;\n try {\n const stat = await fs.stat(targetPath);\n mode = stat.mode & 0o777;\n } catch {\n mode = opts.mode;\n }\n if (mode !== undefined) {\n await fs.chmod(tmp, mode);\n }\n await renameWithRetry(tmp, targetPath);\n } catch (err) {\n try {\n await fs.unlink(tmp);\n } catch {\n // ignore cleanup error\n }\n throw err;\n }\n}\n\nexport async function ensureDir(dir: string): Promise<void> {\n await fs.mkdir(dir, { recursive: true });\n}\n\n// On Windows, fs.rename over an existing file can fail with EPERM/EBUSY/EACCES\n// when antivirus, file indexers, editor file watchers, or a concurrent writer\n// briefly hold a handle on the destination. These are transient — retry with a\n// short backoff before giving up. POSIX renames are atomic and won't hit this.\nconst TRANSIENT_RENAME_CODES = new Set(['EPERM', 'EBUSY', 'EACCES', 'ENOTEMPTY']);\n\nasync function renameWithRetry(from: string, to: string): Promise<void> {\n if (process.platform !== 'win32') {\n await fs.rename(from, to);\n return;\n }\n const delays = [10, 25, 60, 120, 250];\n let lastErr: unknown;\n for (let i = 0; i <= delays.length; i++) {\n try {\n await fs.rename(from, to);\n return;\n } catch (err) {\n lastErr = err;\n const code = (err as NodeJS.ErrnoException)?.code;\n if (!code || !TRANSIENT_RENAME_CODES.has(code) || i === delays.length) {\n throw err;\n }\n await new Promise((resolve) => setTimeout(resolve, delays[i]));\n }\n }\n throw lastErr;\n}\n","import * as fsp from 'node:fs/promises';\nimport { atomicWrite } from '../utils/atomic-write.js';\n\n/**\n * Director state checkpoint — written incrementally throughout a fleet\n * run so a crashed director can be inspected (and eventually resumed)\n * instead of leaving only a final `fleet.json` manifest after `shutdown()`.\n *\n * Schema is JSON-friendly and deliberately denormalized. Each mutation\n * triggers an atomic-write of the whole file — small payloads (typically\n * < 10 KB even with dozens of subagents) make this cheap.\n */\nexport interface DirectorSubagentState {\n id: string;\n name?: string;\n role?: string;\n provider?: string;\n model?: string;\n spawnedAt: string;\n}\n\nexport interface DirectorTaskState {\n taskId: string;\n subagentId?: string;\n description?: string;\n status: 'pending' | 'running' | 'completed' | 'failed' | 'stopped' | 'timeout';\n assignedAt?: string;\n completedAt?: string;\n iterations?: number;\n toolCalls?: number;\n durationMs?: number;\n error?: string;\n}\n\nexport interface DirectorStateSnapshot {\n version: 1;\n directorRunId: string;\n updatedAt: string;\n spawnCount: number;\n maxSpawns?: number;\n spawnDepth: number;\n maxSpawnDepth: number;\n directorBudget?: {\n maxCostUsd?: number;\n };\n subagents: DirectorSubagentState[];\n tasks: DirectorTaskState[];\n /** Aggregated usage snapshot. Optional — populated by the Director on save when available. */\n usage?: unknown;\n}\n\nexport async function loadDirectorState(filePath: string): Promise<DirectorStateSnapshot | null> {\n let raw: string;\n try {\n raw = await fsp.readFile(filePath, 'utf8');\n } catch {\n return null;\n }\n try {\n const parsed = JSON.parse(raw) as DirectorStateSnapshot;\n if (parsed?.version !== 1) return null;\n return parsed;\n } catch {\n return null;\n }\n}\n\n/**\n * Lock file entry written when a director starts. Prevents two directors\n * from resuming the same run — the second one sees the lock and refuses\n * rather than corrupting the checkpoint by writing concurrently.\n */\nexport interface DirectorStateLock {\n pid: number;\n hostname: string;\n startedAt: string;\n}\n\n/**\n * Write a lock file to claim this checkpoint. Returns false if the lock\n * is already held by a live process; returns true if the lock was acquired\n * (either the file didn't exist, or the previous holder is dead).\n */\nexport async function acquireDirectorStateLock(\n lockPath: string,\n processId = process.pid,\n): Promise<boolean> {\n let existing: string | undefined;\n try {\n existing = await fsp.readFile(lockPath, 'utf8');\n } catch {\n // No lock file — we're safe to claim\n }\n\n if (existing) {\n try {\n const lock = JSON.parse(existing) as DirectorStateLock;\n // Check if the process is still alive\n try {\n process.kill(lock.pid, 0);\n // Signal success means the process is alive — another director\n // owns this checkpoint. Refuse.\n return false;\n } catch {\n // ESRCH means the process is dead — stale lock. We'll overwrite.\n }\n } catch {\n // Malformed lock — treat as stale.\n }\n }\n\n const lock: DirectorStateLock = {\n pid: processId,\n hostname: require('node:os').hostname(),\n startedAt: new Date().toISOString(),\n };\n await atomicWrite(lockPath, JSON.stringify(lock), { mode: 0o600 });\n return true;\n}\n\n/**\n * Remove the lock file. Call this on graceful Director.shutdown() so the\n * next director run can claim the checkpoint without stale-lock checks.\n */\nexport async function releaseDirectorStateLock(lockPath: string): Promise<void> {\n try {\n await fsp.unlink(lockPath);\n } catch {\n // ignore\n }\n}\n\n/**\n * In-memory accumulator with atomic-write checkpoint. The Director keeps\n * an instance, mutates it on every spawn/assign/complete/fail event, and\n * the instance debounces writes so a burst of activity collapses into a\n * single disk hit.\n *\n * Supports crash recovery: use `loadDirectorState()` to read an existing\n * checkpoint, then call `DirectorStateCheckpoint.resume(snapshot)` to\n * re-attach to a fleet mid-flight. The lock mechanism ensures no two\n * directors can claim the same checkpoint.\n */\nexport class DirectorStateCheckpoint {\n private snapshot: DirectorStateSnapshot;\n private readonly filePath: string;\n private readonly lockPath: string;\n private timer: NodeJS.Timeout | null = null;\n private readonly debounceMs: number;\n private writing = false;\n private rewriteRequested = false;\n\n constructor(\n filePath: string,\n init: {\n directorRunId: string;\n maxSpawns?: number;\n spawnDepth: number;\n maxSpawnDepth: number;\n directorBudget?: {\n maxCostUsd?: number;\n };\n },\n debounceMs = 250,\n ) {\n this.filePath = filePath;\n // Lock file lives alongside the checkpoint — `<path>.lock`\n this.lockPath = `${filePath}.lock`;\n this.debounceMs = debounceMs;\n this.snapshot = {\n version: 1,\n directorRunId: init.directorRunId,\n updatedAt: new Date().toISOString(),\n spawnCount: 0,\n maxSpawns: init.maxSpawns,\n spawnDepth: init.spawnDepth,\n maxSpawnDepth: init.maxSpawnDepth,\n directorBudget: init.directorBudget,\n subagents: [],\n tasks: [],\n };\n }\n\n /**\n * Attempt to acquire the lock for this checkpoint. Call this before\n * resuming a crashed director run. If it returns false, another\n * director process is still running this fleet — do not resume.\n */\n async acquireLock(): Promise<boolean> {\n return acquireDirectorStateLock(this.lockPath);\n }\n\n /**\n * Release the lock on graceful shutdown. Call `flush()` first to ensure\n * the final checkpoint state is on disk before removing the lock.\n * Without this, the next resume will see a stale-lock and refuse.\n */\n async releaseLock(): Promise<void> {\n return releaseDirectorStateLock(this.lockPath);\n }\n\n /**\n * Resume from a snapshot previously loaded via `loadDirectorState()`.\n * Use this when `--resume <runId>` is triggered — the snapshot has\n * the full fleet state (subagents, tasks) from before the crash; the\n * checkpoint continues from there.\n */\n resume(snapshot: DirectorStateSnapshot): void {\n this.snapshot = snapshot;\n }\n\n current(): DirectorStateSnapshot {\n return this.snapshot;\n }\n\n recordSpawn(sub: DirectorSubagentState, spawnCount: number): void {\n this.snapshot = {\n ...this.snapshot,\n spawnCount,\n subagents: [...this.snapshot.subagents.filter((s) => s.id !== sub.id), sub],\n };\n this.bumpUpdatedAt();\n this.schedule();\n }\n\n recordTaskAssigned(task: DirectorTaskState): void {\n const exists = this.snapshot.tasks.some((t) => t.taskId === task.taskId);\n this.snapshot = {\n ...this.snapshot,\n tasks: exists\n ? this.snapshot.tasks.map((t) => (t.taskId === task.taskId ? { ...t, ...task } : t))\n : [...this.snapshot.tasks, task],\n };\n this.bumpUpdatedAt();\n this.schedule();\n }\n\n recordTaskStatus(\n taskId: string,\n patch: Partial<DirectorTaskState> & { status: DirectorTaskState['status'] },\n ): void {\n this.snapshot = {\n ...this.snapshot,\n tasks: this.snapshot.tasks.map((t) =>\n t.taskId === taskId ? { ...t, ...patch } : t,\n ),\n };\n this.bumpUpdatedAt();\n this.schedule();\n }\n\n setUsage(usage: unknown): void {\n this.snapshot = { ...this.snapshot, usage };\n this.bumpUpdatedAt();\n this.schedule();\n }\n\n /** Force a synchronous flush — used by Director.shutdown(). */\n async flush(): Promise<void> {\n if (this.timer) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n await this.persist();\n // If a rewrite was requested while we waited, persist() scheduled\n // a follow-up write. Loop until no more rewrites are requested so\n // shutdown doesn't return before the most recent state lands on disk.\n while (this.rewriteRequested) {\n this.rewriteRequested = false;\n await this.persist();\n }\n }\n\n private bumpUpdatedAt(): void {\n this.snapshot = { ...this.snapshot, updatedAt: new Date().toISOString() };\n }\n\n private schedule(): void {\n if (this.timer) return;\n this.timer = setTimeout(() => {\n this.timer = null;\n void this.persist();\n }, this.debounceMs);\n }\n\n private async persist(): Promise<void> {\n if (this.writing) {\n // A write is already in flight — defer to a follow-up flush so the\n // most recent state still lands. Without this guard, simultaneous\n // burst mutations can drop the latest snapshot if rename races.\n this.rewriteRequested = true;\n return;\n }\n this.writing = true;\n try {\n await atomicWrite(this.filePath, JSON.stringify(this.snapshot, null, 2), {\n mode: 0o600,\n });\n } catch (err) {\n console.warn(\n '[director-state] checkpoint write failed:',\n err instanceof Error ? err.message : String(err),\n );\n } finally {\n this.writing = false;\n if (this.rewriteRequested) {\n this.rewriteRequested = false;\n this.schedule();\n }\n }\n }\n}\n","import type { BridgeMessage, BridgeTransport } from '../types/agent-bridge.js';\n\n/**\n * In-memory pub/sub transport for agent-to-agent messaging.\n * Subscribers register by agentId and receive messages via callback.\n */\nexport class InMemoryBridgeTransport implements BridgeTransport {\n private readonly subs = new Map<string, Set<(msg: BridgeMessage) => void>>();\n\n send(msg: BridgeMessage, to: string): Promise<void> {\n // Broadcast: deliver to every subscriber except the sender.\n if (to === '*') {\n for (const [id, handlers] of this.subs) {\n if (id === msg.from) continue;\n for (const h of handlers) {\n try {\n h(msg);\n } catch {\n /* ignore */\n }\n }\n }\n return Promise.resolve();\n }\n const handlers = this.subs.get(to);\n if (handlers) {\n for (const h of handlers) {\n try {\n h(msg);\n } catch {\n /* ignore */\n }\n }\n }\n return Promise.resolve();\n }\n\n subscribe(agentId: string, handler: (msg: BridgeMessage) => void): () => void {\n if (!this.subs.has(agentId)) this.subs.set(agentId, new Set());\n this.subs.get(agentId)!.add(handler);\n return () => this.subs.get(agentId)?.delete(handler);\n }\n\n close(agentId: string): Promise<void> {\n this.subs.delete(agentId);\n return Promise.resolve();\n }\n}\n","import { randomUUID } from 'node:crypto';\nimport type {\n AgentBridge,\n AgentBridgeConfig,\n BridgeMessage,\n BridgeTransport,\n} from '../types/agent-bridge.js';\nimport { InMemoryBridgeTransport } from './in-memory-transport.js';\n\n// Re-export for backwards compatibility\nexport { InMemoryBridgeTransport };\n\nexport class InMemoryAgentBridge implements AgentBridge {\n readonly agentId: string;\n readonly coordinatorId: string;\n private readonly transport: BridgeTransport;\n private readonly subscriptions: Set<(msg: BridgeMessage) => void> = new Set();\n private readonly pendingRequests = new Map<\n string,\n {\n resolve: (msg: BridgeMessage) => void;\n reject: (e: Error) => void;\n timer: ReturnType<typeof setTimeout>;\n }\n >();\n private stopped = false;\n private timeoutMs: number;\n /** Guards request() so concurrent calls on the same id can't silently overwrite. */\n private readonly inflightGuards = new Set<string>();\n /** Stores the transport unsubscribe function so it can be called on stop(). */\n private _transportUnsubscribe?: () => void;\n\n constructor(config: AgentBridgeConfig, transport: BridgeTransport) {\n this.agentId = config.agentId;\n this.coordinatorId = config.coordinatorId;\n this.transport = transport;\n this.timeoutMs = config.timeoutMs ?? 30_000;\n\n this._transportUnsubscribe = this.transport.subscribe(this.agentId, (msg) => {\n if (msg.type === 'heartbeat') return;\n\n const pending = this.pendingRequests.get(msg.id);\n if (pending) {\n clearTimeout(pending.timer);\n this.pendingRequests.delete(msg.id);\n this.inflightGuards.delete(msg.id);\n pending.resolve(msg);\n return;\n }\n\n for (const h of this.subscriptions) {\n try {\n h(msg);\n } catch {\n /* ignore */\n }\n }\n });\n }\n\n async send(msg: BridgeMessage): Promise<void> {\n msg.timestamp = Date.now();\n await this.transport.send(msg, msg.to ?? this.coordinatorId);\n }\n\n async broadcast(msg: BridgeMessage): Promise<void> {\n msg.timestamp = Date.now();\n msg.to = '*';\n await this.transport.send(msg, '*');\n }\n\n subscribe(handler: (msg: BridgeMessage) => void | Promise<void>): () => void {\n this.subscriptions.add(handler as (msg: BridgeMessage) => void);\n return () => this.subscriptions.delete(handler as (msg: BridgeMessage) => void);\n }\n\n async request<T>(msg: BridgeMessage, timeoutMs?: number): Promise<BridgeMessage<T>> {\n if (this.stopped) throw new Error('Bridge is stopped');\n const timeout = timeoutMs ?? this.timeoutMs;\n const correlationId = msg.id;\n\n // Guard against concurrent calls reusing the same id. Without this check,\n // a second .set() would silently overwrite the first record — the original\n // caller's timer fires, deletes the entry, and resolves its promise, but\n // the second caller now has no entry to resolve when its timer fires.\n // Throwing here surfaces the caller bug rather than letting it hang.\n if (this.inflightGuards.has(correlationId)) {\n throw new Error(\n `Bridge request id \"${correlationId}\" collides with an in-flight request — caller is reusing message ids`,\n );\n }\n this.inflightGuards.add(correlationId);\n\n return new Promise((resolve, reject) => {\n // Declare timer first so we can reference it in the stopped-check below.\n const timer = setTimeout(() => {\n this.inflightGuards.delete(correlationId);\n this.pendingRequests.delete(correlationId);\n reject(new Error(`Request ${correlationId} timed out after ${timeout}ms`));\n }, timeout);\n\n // Double-check stopped after setting up the pending entry, so stop()\n // can't miss a request that was enqueued before it acquired the lock.\n // Reject if stop() was called after the initial check and cleared\n // the guard — this prevents a request from being enqueued after\n // stop() has already released the lock on pendingRequests.\n if (!this.inflightGuards.has(correlationId)) {\n clearTimeout(timer);\n reject(new Error('Bridge stopped'));\n return;\n }\n\n this.pendingRequests.set(correlationId, {\n resolve: resolve as (msg: BridgeMessage) => void,\n reject,\n timer,\n });\n\n msg.timestamp = Date.now();\n this.transport.send(msg, msg.to ?? this.coordinatorId).catch((e) => {\n clearTimeout(timer);\n this.inflightGuards.delete(correlationId);\n this.pendingRequests.delete(correlationId);\n reject(e);\n });\n });\n }\n\n async stop(): Promise<void> {\n this.stopped = true;\n for (const [, p] of this.pendingRequests) {\n clearTimeout(p.timer);\n p.reject(new Error('Bridge stopped'));\n }\n this.pendingRequests.clear();\n this.inflightGuards.clear();\n this.subscriptions.clear();\n // Call the transport unsubscribe to clean up the subscription handler.\n // This prevents memory leaks when bridges are created and destroyed frequently.\n this._transportUnsubscribe?.();\n this._transportUnsubscribe = undefined;\n await this.transport.close(this.agentId);\n }\n}\n\nexport function createMessage<T = unknown>(\n type: BridgeMessage['type'],\n from: string,\n payload: T,\n to?: string,\n): BridgeMessage<T> {\n return {\n id: randomUUID(),\n type,\n from,\n to,\n payload,\n timestamp: Date.now(),\n priority: 'normal',\n };\n}\n","/**\n * Glob pattern → concrete file path expansion.\n *\n * Supports: *, **, ?, [...]\n * Does NOT support brace expansion {a,b}.\n *\n * Returns the input as-is if it contains no glob metacharacters.\n * On Windows, both / and \\ are accepted as path separators.\n */\n\nimport * as fsp from 'node:fs/promises';\nimport { isAbsolute, resolve } from 'node:path';\n\nconst GLOB_CHARS = new Set(['*', '?', '[']);\nconst IS_WINDOWS = process.platform === 'win32';\nconst SEP = IS_WINDOWS ? '\\\\' : '/';\n\nfunction isGlob(p: string): boolean {\n for (const c of p) {\n if (GLOB_CHARS.has(c)) return true;\n }\n return false;\n}\n\nfunction globToRegex(pat: string): RegExp {\n let i = 0, re = '^';\n while (i < pat.length) {\n const c = pat[i]!;\n if (c === '*') {\n if (pat[i + 1] === '*') {\n re += '.*';\n i += 2;\n if (pat[i] === '/') i++;\n } else {\n re += '[^/\\\\\\\\]*';\n i++;\n }\n } else if (c === '?') {\n re += '[^/\\\\\\\\]';\n i++;\n } else if (c === '[') {\n let cls = '[';\n i++;\n if (pat[i] === '!' || pat[i] === '^') {\n cls += '^';\n i++;\n }\n while (i < pat.length && pat[i] !== ']') {\n const ch = pat[i] ?? '';\n if (ch === '\\\\') cls += '\\\\\\\\';\n else if (ch === ']' || ch === '^') cls += `\\\\${ch}`;\n else cls += ch;\n i++;\n }\n cls += ']';\n re += cls;\n i++;\n } else {\n re += c.replace(/[.+^${}()|\\\\]/g, '\\\\$&');\n i++;\n }\n }\n return new RegExp(re + '$');\n}\n\nfunction baseDir(pat: string): string {\n let i = pat.length - 1;\n while (i >= 0 && !GLOB_CHARS.has(pat[i]!) && pat[i] !== SEP && pat[i] !== '/') i--;\n const cut = i >= 0 ? pat.lastIndexOf(SEP, i) : pat.lastIndexOf('/', i);\n return cut < 0 ? '.' : pat.slice(0, cut);\n}\n\n/**\n * Resolve `pattern` to the set of concrete file paths it matches.\n * Literal paths (no glob chars) are returned as-is.\n *\n * @example\n * await expandGlob('src/**\\/*.ts') // → ['src/a.ts', 'src/b/c.ts', ...]\n * await expandGlob('foo.txt') // → ['foo.txt']\n */\nexport async function expandGlob(pattern: string): Promise<string[]> {\n if (!isGlob(pattern)) return [pattern];\n\n const results = new Set<string>();\n const abs = isAbsolute(pattern);\n const base = abs ? baseDir(pattern) : baseDir(pattern);\n const relPat = base === '.' ? pattern : pattern.slice(base.length + 1);\n\n async function walk(dir: string, pat: string): Promise<void> {\n let entries: string[];\n try {\n entries = await fsp.readdir(dir);\n } catch {\n return;\n }\n\n const firstGlob = pat.search(/[*?[\\[]/);\n\n if (firstGlob < 0) {\n const re = globToRegex(pat);\n for (const e of entries) {\n if (re.test(e)) {\n const full = `${dir}${SEP}${e}`;\n results.add(abs ? resolve(full) : full);\n }\n }\n return;\n }\n\n const before = pat.slice(0, firstGlob);\n const rest = pat.slice(firstGlob);\n\n if (before.endsWith('**')) {\n // Match at current dir then recurse into subdirs\n await walk(dir, rest);\n for (const e of entries) {\n const full = `${dir}${SEP}${e}`;\n try {\n const stat = await fsp.stat(full);\n if (stat.isDirectory()) await walk(full, rest);\n } catch {\n /* skip inaccessible */\n }\n }\n } else if (before === '') {\n // Pattern starts with a glob char — match files in current dir only\n const re = globToRegex(rest);\n for (const e of entries) {\n if (re.test(e)) {\n const full = `${dir}${SEP}${e}`;\n results.add(abs ? resolve(full) : full);\n }\n }\n } else {\n // Literal segment(s) before the glob — descend into matching subdir\n const seg = before.replace(/[*?[\\]]/g, '').replace(/\\/$/, '');\n if (entries.includes(seg)) {\n const full = `${dir}${SEP}${seg}`;\n try {\n const stat = await fsp.stat(full);\n if (stat.isDirectory()) await walk(full, rest);\n } catch {\n /* skip */\n }\n }\n }\n }\n\n await walk(base === '.' ? '.' : base, relPat);\n return [...results];\n}\n","/**\n * Collaborative Debugging Session — parallel multi-agent debugging on the same problem.\n *\n * Architecture:\n * - BugHunter, RefactorPlanner, and Critic run in parallel on shared file snapshots.\n * - Findings flow through the FleetBus via structured events: bug.found → refactor.plan → critic.evaluation.\n * - The Director acts as ResultRouter, collecting outputs and routing them to dependents.\n * - A shared scratchpad stores intermediate results so agents can read each other's\n * conclusions without needing each other's full transcripts.\n *\n * Flow:\n * 1. Director.spawnCollab() creates a CollabSession with a SharedFileSnapshot.\n * 2. All three agents are spawned simultaneously and receive the same file snapshot.\n * 3. BugHunter emits bug.found events → Director routes to RefactorPlanner.\n * 4. RefactorPlanner subscribes to bug.found and emits refactor.plan events.\n * 5. Critic subscribes to both bug.found and refactor.plan and emits critic.evaluation.\n * 6. Director collects all results and produces a structured CollabDebugReport.\n *\n * Timeout and cancellation:\n * - CollabSession agents report budget threshold events to the Director via fleet events.\n * - The Director's collabAlert() handler receives warnings for timeout/iteration/tool_call\n * thresholds and can decide to cancel the session or let it continue.\n * - Director.cancelCollabSession() sends director.cancel_collab to all collab agents,\n * causing them to finish early with a 'cancelled' status in the report.\n * - The Director reads /btw notes via getLeaderBtwNotes() and can inject them into\n * collab agents via task context before making cancellation decisions.\n */\n\nimport { EventEmitter } from 'node:events';\nimport * as fsp from 'node:fs/promises';\nimport { randomUUID } from 'node:crypto';\nimport type { SubagentConfig, TaskResult } from '../types/multi-agent.js';\nimport { expandGlob } from '../utils/glob-expand.js';\n\n/**\n * Default maximum number of files a collab_debug session may target.\n * Each of the three agents (BugHunter, RefactorPlanner, Critic) receives\n * the full file snapshot as context — a large target causes token overflow\n * and timeout failures. Keep this low (20-30) for reliable sessions.\n * Used when neither `maxTargetFiles` nor `contextWindow` is provided.\n */\nexport const DEFAULT_MAX_TARGET_FILES = 30;\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * Alert levels the Director can emit when a collab session needs attention.\n * These flow through the FleetBus so the host can display them in the UI.\n */\nexport enum DirectorAlertLevel {\n /** The agent is still making progress but has hit a soft budget limit. */\n WARNING = 'warning',\n /** The agent has hit a hard limit and the session cannot continue. */\n CRITICAL = 'critical',\n /** The Director has decided to cancel the session (user request or policy). */\n CANCELLED = 'cancelled',\n}\n\nexport interface DirectorAlert {\n sessionId: string;\n subagentId: string;\n role: string;\n level: DirectorAlertLevel;\n /** Human-readable message for UI/logs */\n message: string;\n /** Budget kind that triggered this alert, if any */\n budgetKind?: 'timeout' | 'idle_timeout' | 'iterations' | 'tool_calls' | 'tokens' | 'cost';\n /** Elapsed ms at time of alert */\n elapsedMs?: number;\n /** Limit that was hit */\n limit?: number;\n /** /btw notes the director has collected (may be empty) */\n btwNotes?: string[];\n}\n\n/**\n * Immutable snapshot of target files at the start of a collab session.\n * All agents in the session read from this snapshot — they see the same baseline.\n */\nexport interface SharedFileSnapshot {\n id: string;\n createdAt: string;\n files: SharedFileEntry[];\n}\n\nexport interface SharedFileEntry {\n path: string;\n content: string;\n language?: string;\n}\n\n/**\n * Bug finding emitted by BugHunter and consumed by RefactorPlanner + Critic.\n */\nexport interface BugFinding {\n id: string;\n type: string;\n severity: 'critical' | 'high' | 'medium' | 'low';\n location: { file: string; line: number };\n description: string;\n suggestedFix?: string;\n}\n\n/**\n * Refactoring plan emitted by RefactorPlanner, consuming BugFinding(s).\n */\nexport interface RefactorPlan {\n id: string;\n basedOnBugIds: string[];\n phases: RefactorPhase[];\n riskScore: 'low' | 'medium' | 'high';\n estimatedChangeCount: number;\n rollbackStrategy: string;\n}\n\n/** One phase within a refactor plan. */\nexport interface RefactorPhase {\n number: number;\n title: string;\n tasks: string[];\n risk: 'low' | 'medium' | 'high';\n}\n\n/**\n * Critic evaluation of a bug finding or refactor plan.\n */\nexport interface CriticEvaluation {\n id: string;\n subjectType: 'bug_finding' | 'refactor_plan';\n subjectId: string;\n score: number; // 0-10\n verdict: 'approve' | 'needs_revision' | 'reject';\n strengths: string[];\n weaknesses: string[];\n concerns: CriticConcern[];\n}\n\nexport interface CriticConcern {\n description: string;\n location?: { file: string; line: number };\n severity: 'blocking' | 'advisory';\n}\n\n/**\n * Full structured report produced when a CollabSession resolves.\n */\nexport interface CollabDebugReport {\n sessionId: string;\n startedAt: string;\n completedAt: string;\n targetPaths: string[];\n /** How the session ended. 'completed' = all agents finished normally.\n * 'cancelled' = Director called cancelCollabSession().\n * 'timeout' = session-level timeout elapsed before all agents finished.\n * 'critical_alert' = Director escalated a warning to a cancel decision.\n */\n disposition: 'completed' | 'cancelled' | 'timeout' | 'critical_alert';\n bugs: BugFinding[];\n refactorPlans: RefactorPlan[];\n evaluations: CriticEvaluation[];\n /** Alerts that were raised during the session (may be empty). */\n alerts: DirectorAlert[];\n /** Overall verdict from the Critic across all evaluated subjects. */\n overallVerdict: 'approve' | 'needs_revision' | 'reject';\n /** Markdown-formatted summary for the director's context window. */\n summary: string;\n}\n\n/**\n * Per-agent budget configuration for collab sessions.\n * Allows the caller (Director) to control the exact limits instead of\n * using hard-coded defaults that may not match the director's policy.\n */\nexport interface CollabBudgetConfig {\n maxIterations: number;\n maxToolCalls: number;\n timeoutMs: number;\n}\n\n/**\n * Budget overrides for specific roles in a collab session.\n * When a role is not present in the map, the default budget is used.\n */\nexport type CollabBudgetOverrides = Partial<Record<string, CollabBudgetConfig>>;\n\n// ---------------------------------------------------------------------------\n// Event payload types (what gets put on the FleetBus)\n// ---------------------------------------------------------------------------\n\nexport interface BugFoundPayload {\n finding: BugFinding;\n}\n\nexport interface RefactorPlanPayload {\n plan: RefactorPlan;\n}\n\nexport interface CriticEvaluationPayload {\n evaluation: CriticEvaluation;\n}\n\n/**\n * Emitted by a collab agent when it hits a soft budget limit.\n * The Director's fleet handler receives this and calls collabAlert().\n */\nexport interface CollabBudgetWarningPayload {\n sessionId: string;\n role: string;\n kind: 'timeout' | 'idle_timeout' | 'iterations' | 'tool_calls' | 'tokens' | 'cost';\n used: number;\n limit: number;\n timeoutMs?: number;\n elapsedMs: number;\n}\n\n/**\n * Emitted by the Director to cancel all agents in a collab session.\n * CollabSession listens for this and causes its agent pool to finish early.\n */\nexport interface DirectorCancelCollabPayload {\n sessionId: string;\n reason: string;\n cancelledAt: string;\n}\n\n// ---------------------------------------------------------------------------\n// CollabSessionOptions — extends base with budget + alert callbacks\n// ---------------------------------------------------------------------------\n\nexport interface CollabSessionOptions {\n /** Paths to scan — used to build the SharedFileSnapshot. */\n targetPaths: string[];\n /** Files already read and snapshot. When provided, snapshot is skipped. */\n prebuiltSnapshot?: SharedFileSnapshot;\n /** Max time to wait for the session to resolve (ms). Default: 10 min. */\n timeoutMs?: number;\n /**\n * Maximum number of files to include in the snapshot.\n * - If set explicitly: use this value (hard override).\n * - If `contextWindow` is set: calculate dynamically from estimated token budget.\n * - If neither: use `DEFAULT_MAX_TARGET_FILES` (30).\n */\n maxTargetFiles?: number;\n /**\n * Context window size (in tokens) of the model running the subagents.\n * When provided and `maxTargetFiles` is not set, the limit is computed\n * dynamically: `floor((contextWindow * 0.4) / AVG_TOKENS_PER_FILE)`.\n * If not provided, `DEFAULT_MAX_TARGET_FILES` is used as the fallback.\n */\n contextWindow?: number;\n /**\n * Budget overrides per role. When provided, these override the hard-coded\n * defaults so the Director can enforce fleet-wide budget policy.\n * Keys must match role names: 'bug-hunter', 'refactor-planner', 'critic'.\n */\n budgetOverrides?: CollabBudgetOverrides;\n /**\n * Called by the Director when a collab agent hits a soft budget limit.\n * The Director uses this to decide whether to cancel the session or extend.\n * Return 'cancel' to stop the session immediately; 'extend' to continue\n * with the agent's proposed new limits; 'ignore' to let the default\n * auto-extend logic handle it.\n */\n onBudgetWarning?: (alert: DirectorAlert) => 'cancel' | 'extend' | 'ignore';\n}\n\n// ---------------------------------------------------------------------------\n// CollabSession — coordinates the three-agent pipeline\n// ---------------------------------------------------------------------------\n\nexport class CollabSession extends EventEmitter {\n readonly sessionId: string;\n readonly options: CollabSessionOptions;\n readonly snapshot: SharedFileSnapshot;\n\n private readonly director: import('./director.js').Director;\n private readonly fleetBus: import('./fleet-bus.js').FleetBus;\n private readonly subagentIds = new Map<string, string>(); // role → subagentId\n private readonly bugs = new Map<string, BugFinding>();\n private readonly plans = new Map<string, RefactorPlan>();\n private readonly evaluations = new Map<string, CriticEvaluation>();\n private readonly disposers = new Array<() => void>();\n private settled = false;\n private readonly timeoutMs: number;\n private cancelled = false;\n private readonly alerts: DirectorAlert[] = [];\n\n /** Tracks tool call counts per subagent for progress-based timeout decisions. */\n private readonly progressBySubagent = new Map<string, number>();\n /** Last tool call count when a timeout warning was handled. */\n private readonly lastTimeoutProgress = new Map<string, number>();\n /** Session-level timeout timer handle (cleared on cancel or natural completion). */\n private _timeoutTimer?: NodeJS.Timeout;\n\n constructor(\n director: import('./director.js').Director,\n fleetBus: import('./fleet-bus.js').FleetBus,\n options: CollabSessionOptions,\n ) {\n super();\n this.sessionId = randomUUID();\n this.options = options;\n this.director = director;\n this.fleetBus = fleetBus;\n this.timeoutMs = options.timeoutMs ?? 10 * 60 * 1000;\n\n if (options.prebuiltSnapshot) {\n this.snapshot = options.prebuiltSnapshot;\n } else {\n this.snapshot = {\n id: this.sessionId,\n createdAt: new Date().toISOString(),\n files: [],\n };\n }\n }\n\n get id(): string { return this.sessionId; }\n\n getSessionAlerts(): DirectorAlert[] {\n return [...this.alerts];\n }\n\n isCancelled(): boolean {\n return this.cancelled;\n }\n\n /**\n * Snapshot of role → subagentId map. The Director calls coordinator.stop()\n * for each agent when cancelling the session, using this map to enumerate\n * all three collab agents.\n */\n getSubagentIds(): ReadonlyMap<string, string> {\n return new Map(this.subagentIds);\n }\n\n /**\n * Returns the effective file limit for this session.\n * Priority: explicit `maxTargetFiles` > dynamic from `contextWindow` > `DEFAULT_MAX_TARGET_FILES`.\n */\n effectiveFileLimit(): number {\n if (this.options.maxTargetFiles !== undefined) {\n return this.options.maxTargetFiles;\n }\n if (this.options.contextWindow !== undefined) {\n // Reserve 40% of context window for the file snapshot.\n // Heuristic: ~2000 tokens per average source file.\n return Math.max(5, Math.floor((this.options.contextWindow * 0.4) / 2000));\n }\n return DEFAULT_MAX_TARGET_FILES;\n }\n\n async buildSnapshot(): Promise<SharedFileSnapshot> {\n if (this.snapshot.files.length > 0) return this.snapshot;\n const allFiles: string[] = [];\n for (const pattern of this.options.targetPaths) {\n const expanded = await expandGlob(pattern);\n allFiles.push(...expanded);\n }\n const limit = this.effectiveFileLimit();\n if (allFiles.length > limit) {\n const hint = this.options.contextWindow\n ? `contextWindow=${this.options.contextWindow} → calculated limit=${limit}`\n : `default limit=${DEFAULT_MAX_TARGET_FILES}`;\n throw new Error(\n `[collab_debug] Target has ${allFiles.length} files, which exceeds the ` +\n `limit (${hint}). Narrow the target or pass maxTargetFiles / contextWindow ` +\n `to override. For large codebases, run package-by-package or ` +\n `module-by-module sessions instead of targeting the entire repo.`,\n );\n }\n for (const filePath of allFiles) {\n try {\n const content = await fsp.readFile(filePath, 'utf8');\n const ext = filePath.split('.').pop() ?? '';\n const language = ext === 'ts' || ext === 'tsx' ? 'typescript'\n : ext === 'js' || ext === 'jsx' ? 'javascript'\n : ext === 'md' ? 'markdown'\n : ext === 'json' ? 'json'\n : undefined;\n this.snapshot.files.push({ path: filePath, content, language });\n } catch {\n this.snapshot.files.push({ path: filePath, content: '', language: undefined });\n }\n }\n return this.snapshot;\n }\n\n /**\n * Cancel the session. Emits director.cancel_collab on the FleetBus so all\n * collab agents finish early. The session-level timeout timer is also cleared.\n * Safe to call multiple times (idempotent after first call).\n */\n cancel(reason = 'Director cancelled collab session'): void {\n if (this.settled) return;\n this.cancelled = true;\n if (this._timeoutTimer) {\n clearTimeout(this._timeoutTimer);\n this._timeoutTimer = undefined;\n }\n this.fleetBus.emit({\n subagentId: this.director.id,\n ts: Date.now(),\n type: 'director.cancel_collab',\n payload: { sessionId: this.sessionId, reason, cancelledAt: new Date().toISOString() } as DirectorCancelCollabPayload,\n });\n this.fleetBus.emit({\n subagentId: this.director.id,\n ts: Date.now(),\n type: 'collab.cancelled',\n payload: { sessionId: this.sessionId, reason },\n });\n }\n\n async start(): Promise<CollabDebugReport> {\n if (this.settled) throw new Error('session already settled');\n this.settled = true;\n\n await this.buildSnapshot();\n this.wireFleetBus();\n\n const [bugHunterId, refactorPlannerId, criticId] = await Promise.all([\n this.spawnAgent('bug-hunter', this.buildBugHunterTask()),\n this.spawnAgent('refactor-planner', this.buildRefactorPlannerTask()),\n this.spawnAgent('critic', this.buildCriticTask()),\n ]);\n\n this.subagentIds.set('bug-hunter', bugHunterId);\n this.subagentIds.set('refactor-planner', refactorPlannerId);\n this.subagentIds.set('critic', criticId);\n\n const timeout = new Promise<never>((_, reject) => {\n this._timeoutTimer = setTimeout(() => {\n this.cancel('Session-level timeout reached');\n reject(new Error(`CollabSession timed out after ${this.timeoutMs}ms`));\n }, this.timeoutMs);\n });\n\n let results: TaskResult[][] | null = null;\n try {\n results = await Promise.race([\n Promise.all([\n this.director.awaitTasks([bugHunterId]),\n this.director.awaitTasks([refactorPlannerId]),\n this.director.awaitTasks([criticId]),\n ]),\n timeout,\n ]);\n } catch (err) {\n // Promise.race rejected — either the timeout fired or one of the\n // awaitTasks failed. In both cases `results` is unassigned. Clear the\n // timer if the timeout won the race, always clean up, then re-throw.\n // NOTE: we cannot distinguish timeout from awaitTasks failure here\n // without additional state. Both are treated as session failure.\n if (this._timeoutTimer) {\n clearTimeout(this._timeoutTimer);\n this._timeoutTimer = undefined;\n }\n this.cleanup();\n const error = err instanceof Error ? err : new Error(String(err));\n this.emit('session.error', error);\n throw error;\n }\n\n // If we are here, Promise.race resolved (not rejected) — results were assigned.\n // Guard with non-null assertion since TypeScript doesn't know the try/catch\n // guarantees this when we reach this line.\n for (const result of results!.flat()) {\n await this.parseAndEmit(result);\n }\n\n const report = this.assembleReport();\n this.cleanup();\n this.emit('session.done', report);\n return report;\n }\n\n private async parseAndEmit(result: TaskResult): Promise<void> {\n if (result.status !== 'success' || result.result == null) return;\n const text =\n typeof result.result === 'string' ? result.result : JSON.stringify(result.result);\n\n for (const obj of this.extractJsonObjects(text)) {\n const type =\n 'finding' in obj\n ? 'bug.found'\n : 'plan' in obj\n ? 'refactor.plan'\n : 'evaluation' in obj\n ? 'critic.evaluation'\n : null;\n if (!type) continue;\n this.fleetBus.emit({\n subagentId: result.subagentId,\n taskId: result.taskId,\n ts: Date.now(),\n type,\n payload: obj,\n });\n }\n }\n\n private extractJsonObjects(text: string): Array<Record<string, unknown>> {\n const objects: Array<Record<string, unknown>> = [];\n let depth = 0;\n let start = -1;\n let inString = false;\n let escaped = false;\n for (let i = 0; i < text.length; i++) {\n const ch = text[i];\n if (inString) {\n if (escaped) escaped = false;\n else if (ch === '\\\\') escaped = true;\n else if (ch === '\"') inString = false;\n continue;\n }\n if (ch === '\"') {\n inString = true;\n } else if (ch === '{') {\n if (depth === 0) start = i;\n depth++;\n } else if (ch === '}' && depth > 0) {\n depth--;\n if (depth === 0 && start >= 0) {\n const candidate = text.slice(start, i + 1);\n try {\n const parsed = JSON.parse(candidate);\n if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {\n objects.push(parsed as Record<string, unknown>);\n }\n } catch {\n // skip malformed span\n }\n start = -1;\n }\n }\n }\n return objects;\n }\n\n private budgetForRole(role: string): { maxIterations: number; maxToolCalls: number; timeoutMs: number } {\n if (this.options.budgetOverrides?.[role]) {\n return this.options.budgetOverrides[role]!;\n }\n const defaults: Record<string, { maxIterations: number; maxToolCalls: number; timeoutMs: number }> = {\n 'bug-hunter': { maxIterations: 2000, maxToolCalls: 5000, timeoutMs: 10 * 60 * 1000 },\n 'refactor-planner': { maxIterations: 1500, maxToolCalls: 4000, timeoutMs: 8 * 60 * 1000 },\n 'critic': { maxIterations: 1000, maxToolCalls: 3000, timeoutMs: 6 * 60 * 1000 },\n };\n return defaults[role] ?? { maxIterations: 1500, maxToolCalls: 4000, timeoutMs: 8 * 60 * 1000 };\n }\n\n private async spawnAgent(role: string, taskBrief: string): Promise<string> {\n const budget = this.budgetForRole(role);\n const cfg: SubagentConfig = {\n id: `${role}-${this.sessionId}`,\n name: role,\n role,\n tools: ['fleet_emit', 'fleet_status', 'read', 'grep', 'glob', 'bash', 'write'],\n maxIterations: budget.maxIterations,\n maxToolCalls: budget.maxToolCalls,\n timeoutMs: budget.timeoutMs,\n };\n const subagentId = await this.director.spawn(cfg);\n await this.director.assign({ id: randomUUID(), subagentId, description: taskBrief });\n return subagentId;\n }\n\n private buildBugHunterTask(): string {\n const scratchpad = this.director.sharedScratchpadPath ?? '/tmp';\n const fileContents = this.snapshot.files\n .map((f) => `=== ${f.path} ===\\n${f.content}`)\n .join('\\n\\n');\n return (\n `You are BugHunter. Scan the following files for bugs and code smells.\\n\\n` +\n `Target files:\\n${fileContents}\\n\\n` +\n `For each bug found, emit it using the fleet_emit tool immediately:\\n` +\n `{ \"type\": \"bug.found\", \"payload\": { \"finding\": { \"id\": \"<uuid>\", \"type\": \"<pattern>\", ` +\n `\"severity\": \"<critical|high|medium|low>\", ` +\n `\"location\": { \"file\": \"<path>\", \"line\": <n> }, \"description\": \"<explain>\", \"suggestedFix\": \"<optional>\" } } }\\n\\n` +\n `After scanning all files, write your full markdown bug report to:\\n` +\n `${scratchpad}/bug-hunter-report-${this.sessionId}.md\\n\\n` +\n `Important: emit each finding as soon as you find it. Do not batch or wait until the end.`\n );\n }\n\n private buildRefactorPlannerTask(): string {\n const scratchpad = this.director.sharedScratchpadPath ?? '/tmp';\n const bugHunterReportPath = `${scratchpad}/bug-hunter-report-${this.sessionId}.md`;\n const fileContents = this.snapshot.files\n .map((f) => `=== ${f.path} ===\\n${f.content}`)\n .join('\\n\\n');\n return (\n `You are RefactorPlanner. Plan refactorings for the following files.\\n\\n` +\n `Target files:\\n${fileContents}\\n\\n` +\n `Read the BugHunter report at: ${bugHunterReportPath}\\n\\n` +\n `For each bug you can address, emit a refactor plan using fleet_emit:\\n` +\n `{ \"type\": \"refactor.plan\", \"payload\": { \"plan\": { \"id\": \"<uuid>\", \"basedOnBugIds\": [\"<bug-id>\"], ` +\n `\"phases\": [{ \"number\": 1, \"title\": \"<phase>\", \"tasks\": [\"<task>\"], \"risk\": \"<low|medium|high>\" }], ` +\n `\"riskScore\": \"<low|medium|high>\", \"estimatedChangeCount\": <n>, \"rollbackStrategy\": \"<text>\" } } }\\n\\n` +\n `Also write your full markdown plan to:\\n` +\n `${scratchpad}/refactor-plan-${this.sessionId}.md\\n\\n` +\n `Emit each plan immediately. Do not wait until planning is complete.`\n );\n }\n\n private buildCriticTask(): string {\n const scratchpad = this.director.sharedScratchpadPath ?? '/tmp';\n const bugHunterReportPath = `${scratchpad}/bug-hunter-report-${this.sessionId}.md`;\n const refactorPlanPath = `${scratchpad}/refactor-plan-${this.sessionId}.md`;\n const fileContents = this.snapshot.files\n .map((f) => `=== ${f.path} ===\\n${f.content}`)\n .join('\\n\\n');\n return (\n `You are Critic. Evaluate bug findings and refactor plans.\\n\\n` +\n `Target files:\\n${fileContents}\\n\\n` +\n `Read the BugHunter report at: ${bugHunterReportPath}\\n` +\n `Read the RefactorPlanner report at: ${refactorPlanPath}\\n\\n` +\n `For each bug and refactor plan, emit your evaluation using fleet_emit:\\n` +\n `{ \"type\": \"critic.evaluation\", \"payload\": { \"evaluation\": { \"id\": \"<uuid>\", ` +\n `\"subjectType\": \"<bug_finding|refactor_plan>\", \"subjectId\": \"<id>\", ` +\n `\"score\": <0-10>, \"verdict\": \"<approve|needs_revision|reject>\", ` +\n `\"strengths\": [\"<strength>\"], \"weaknesses\": [\"<weakness>\"], ` +\n `\"concerns\": [{ \"description\": \"<concern>\", \"severity\": \"<blocking|advisory>\" }] } } }\\n\\n` +\n `After all evaluations, write your markdown report to:\\n` +\n `${scratchpad}/critic-report-${this.sessionId}.md\\n\\n` +\n `Emit each evaluation immediately. Do not wait until you have read all reports.`\n );\n }\n\n private wireFleetBus(): void {\n // Track tool executions for progress-based timeout decisions\n const dTool = this.fleetBus.filter('tool.executed', (e) => {\n this.progressBySubagent.set(e.subagentId, (this.progressBySubagent.get(e.subagentId) ?? 0) + 1);\n });\n this.disposers.push(dTool);\n\n // budget.threshold_reached → Director's alert handler\n const dBudget = this.fleetBus.filter('budget.threshold_reached', (e) => {\n const payload = e.payload as {\n kind: 'timeout' | 'idle_timeout' | 'iterations' | 'tool_calls' | 'tokens' | 'cost';\n used: number;\n limit: number;\n timeoutMs?: number;\n extend: (extra: Record<string, unknown>) => void;\n deny: () => void;\n };\n const role = this.roleFromSubagentId(e.subagentId);\n if (!role) return;\n\n // Gather /btw notes so the Director can inspect them before deciding\n const btwNotes = this.director.getLeaderBtwNotes();\n\n const alert: DirectorAlert = {\n sessionId: this.sessionId,\n subagentId: e.subagentId,\n role,\n level: DirectorAlertLevel.WARNING,\n message: `${role} hit ${payload.kind} soft limit (${payload.used}/${payload.limit})`,\n budgetKind: payload.kind,\n elapsedMs: payload.timeoutMs,\n limit: payload.limit,\n btwNotes,\n };\n\n this.alerts.push(alert);\n\n this.fleetBus.emit({\n subagentId: e.subagentId,\n ts: Date.now(),\n type: 'collab.warning',\n payload: alert,\n });\n\n const decision = this.options.onBudgetWarning?.(alert) ?? 'ignore';\n\n if (decision === 'cancel') {\n this.cancel(`Director cancelled: ${role} ${payload.kind} threshold`);\n return;\n }\n\n // Progress-based timeout handling: extend if agent is doing work,\n // deny only if genuinely stuck (no tool calls since last grant).\n // Both wall-clock timeout and idle timeout use this heartbeat-aware path.\n if (payload.kind === 'timeout' || payload.kind === 'idle_timeout') {\n const progress = this.progressBySubagent.get(e.subagentId) ?? 0;\n const lastProgress = this.lastTimeoutProgress.get(e.subagentId) ?? -1;\n if (progress <= lastProgress) {\n payload.deny();\n return;\n }\n this.lastTimeoutProgress.set(e.subagentId, progress);\n const newLimit = Math.min(Math.ceil((payload.timeoutMs ?? payload.limit) * 2), 24 * 60 * 60_000);\n setImmediate(() => {\n payload.extend({ timeoutMs: newLimit });\n });\n return;\n }\n\n if (decision === 'extend') {\n setImmediate(() => {\n const base = Math.max(payload.limit, payload.used);\n const extra: Record<string, unknown> = {};\n switch (payload.kind) {\n case 'iterations': extra.maxIterations = Math.min(Math.ceil(base * 1.5), 50_000); break;\n case 'tool_calls': extra.maxToolCalls = Math.min(Math.ceil(base * 1.5), 100_000); break;\n case 'tokens': extra.maxTokens = Math.min(Math.ceil(base * 1.5), 5_000_000); break;\n case 'cost': extra.maxCostUsd = Math.min(base * 1.5, 100); break;\n }\n payload.extend(extra);\n });\n return;\n }\n\n // 'ignore' (or any unrecognized decision): apply a conservative\n // auto-extension for non-timeout kinds so the session keeps making\n // progress rather than hitting a hard limit. The Director sees the\n // collab.warning event and can always call cancelCollabSession() if the\n // pattern looks like a bad infinite loop. Timeout kind is already handled\n // above by the progress-based logic.\n if ((payload.kind as string) !== 'timeout') {\n setImmediate(() => {\n const base = Math.max(payload.limit, payload.used);\n const extra: Record<string, unknown> = {};\n switch (payload.kind) {\n case 'iterations': extra.maxIterations = Math.min(Math.ceil(base * 1.25), 50_000); break;\n case 'tool_calls': extra.maxToolCalls = Math.min(Math.ceil(base * 1.25), 100_000); break;\n case 'tokens': extra.maxTokens = Math.min(Math.ceil(base * 1.25), 5_000_000); break;\n case 'cost': extra.maxCostUsd = Math.min(base * 1.25, 100); break;\n }\n payload.extend(extra);\n });\n }\n });\n this.disposers.push(dBudget);\n\n // Director cancel signal\n const dCancel = this.fleetBus.filter('director.cancel_collab', (e) => {\n const payload = e.payload as DirectorCancelCollabPayload;\n if (payload.sessionId !== this.sessionId) return;\n this.cancelled = true;\n if (this._timeoutTimer) {\n clearTimeout(this._timeoutTimer);\n this._timeoutTimer = undefined;\n }\n this.fleetBus.emit({\n subagentId: this.director.id,\n ts: Date.now(),\n type: 'collab.cancelled',\n payload: { sessionId: this.sessionId, reason: payload.reason },\n });\n });\n this.disposers.push(dCancel);\n\n // bug.found → RefactorPlanner + Critic\n const d1 = this.fleetBus.filter('bug.found', (e) => {\n const payload = e.payload as BugFoundPayload;\n if (payload?.finding) {\n this.bugs.set(payload.finding.id, payload.finding);\n this.emit('bug.found', payload);\n }\n });\n this.disposers.push(d1);\n\n // refactor.plan → Critic\n const d2 = this.fleetBus.filter('refactor.plan', (e) => {\n const payload = e.payload as RefactorPlanPayload;\n if (payload?.plan) {\n this.plans.set(payload.plan.id, payload.plan);\n this.emit('refactor.plan', payload);\n }\n });\n this.disposers.push(d2);\n\n // critic.evaluation\n const d3 = this.fleetBus.filter('critic.evaluation', (e) => {\n const payload = e.payload as CriticEvaluationPayload;\n if (payload?.evaluation) {\n this.evaluations.set(payload.evaluation.id, payload.evaluation);\n this.emit('critic.evaluation', payload);\n }\n });\n this.disposers.push(d3);\n }\n\n private roleFromSubagentId(subagentId: string): string | null {\n // Fast path: check tracked subagentIds map first (normal case during session).\n for (const [role, id] of this.subagentIds) {\n if (id === subagentId) return role;\n }\n // Fallback: derive from id prefix pattern used in spawnAgent.\n // Handles budget events that fire before subagentIds entry is populated\n // (edge case at session start — race between first tool call and map insert).\n const match = subagentId.match(/^(bug-hunter|refactor-planner|critic)/);\n return match?.[1] ?? null;\n }\n\n private assembleReport(): CollabDebugReport {\n const bugList = Array.from(this.bugs.values());\n const planList = Array.from(this.plans.values());\n const evalList = Array.from(this.evaluations.values());\n\n let disposition: CollabDebugReport['disposition'] = 'completed';\n if (this.cancelled) disposition = 'cancelled';\n\n const verdictOrder: Record<CollabDebugReport['overallVerdict'], number> = {\n approve: 0, needs_revision: 1, reject: 2,\n };\n const overallVerdict = evalList.reduce<CollabDebugReport['overallVerdict']>(\n (worst, eval_) => {\n const w = verdictOrder[worst];\n const c = verdictOrder[eval_.verdict];\n return c > w ? eval_.verdict : worst;\n },\n 'approve',\n );\n\n const summary = this.buildMarkdownSummary(bugList, planList, evalList, overallVerdict, disposition);\n\n return {\n sessionId: this.sessionId,\n startedAt: this.snapshot.createdAt,\n completedAt: new Date().toISOString(),\n targetPaths: this.options.targetPaths,\n disposition,\n bugs: bugList,\n refactorPlans: planList,\n evaluations: evalList,\n alerts: [...this.alerts],\n overallVerdict,\n summary,\n };\n }\n\n private buildMarkdownSummary(\n bugs: BugFinding[],\n plans: RefactorPlan[],\n evals: CriticEvaluation[],\n overallVerdict: CollabDebugReport['overallVerdict'],\n disposition: CollabDebugReport['disposition'],\n ): string {\n const lines: string[] = [\n `## Collaborative Debugging Report — ${this.sessionId}`,\n '',\n `**Target:** ${this.options.targetPaths.join(', ')}`,\n `**Disposition:** ${disposition.toUpperCase()}`,\n `**Overall Verdict:** **${overallVerdict.toUpperCase()}**`,\n '',\n ];\n\n if (this.alerts.length > 0) {\n lines.push('### Alerts', '');\n for (const alert of this.alerts) {\n lines.push(`- **[${alert.level.toUpperCase()}]** ${alert.role}: ${alert.message}`);\n }\n lines.push('');\n }\n\n if (bugs.length > 0) {\n lines.push('### Bugs Found', '');\n for (const b of bugs) {\n lines.push(`- **[${b.severity.toUpperCase()}]** \\`${b.location.file}:${b.location.line}\\` — ${b.description}`);\n }\n lines.push('');\n }\n\n if (plans.length > 0) {\n lines.push('### Refactor Plans', '');\n for (const p of plans) {\n lines.push(`- **Phase plan** (risk: ${p.riskScore}, ~${p.estimatedChangeCount} changes)`);\n for (const phase of p.phases) {\n lines.push(` - Phase ${phase.number}: ${phase.title} [${phase.risk}]`);\n }\n }\n lines.push('');\n }\n\n if (evals.length > 0) {\n lines.push('### Critic Evaluations', '');\n for (const e of evals) {\n lines.push(`- [${e.subjectType}] score=${e.score}/10 — **${e.verdict.toUpperCase()}**`);\n for (const c of e.concerns) {\n if (c.severity === 'blocking') lines.push(` - ${c.description}`);\n }\n }\n lines.push('');\n }\n\n return lines.join('\\n');\n }\n\n private cleanup(): void {\n for (const dispose of this.disposers) dispose();\n this.disposers.length = 0;\n }\n}","/**\n * System-prompt composition helpers for the Director ecosystem.\n *\n * Two callers need composed prompts:\n *\n * 1. The **leader** (the director's own Agent) — needs a preamble that\n * explains the fleet protocol: when to spawn, when to await, how to\n * roll up, and the eight orchestration tools it owns.\n *\n * 2. Each **subagent** — needs a baseline that explains it has a parent\n * it can call via the bridge, a role-specific block, the task brief,\n * and finally any per-spawn `systemPromptOverride` from `SubagentConfig`.\n *\n * Both composers are pure functions: feed them parts, they return a string.\n * No I/O, no side effects, no implicit defaults beyond the ones exported\n * here. Callers (CLI multi-agent factory, Director itself) decide which\n * parts to fill in — that keeps the composition seam visible and testable.\n */\n\n/**\n * Default fleet-protocol preamble injected at the **front** of the\n * director-agent's system prompt. Kept deliberately short — long preambles\n * crowd out the user's leader prompt and the LLM stops attending. The tool\n * descriptions live on the tool definitions themselves; this preamble only\n * teaches *when* to reach for them.\n */\nexport const DEFAULT_DIRECTOR_PREAMBLE = `\\\nYou are the Director of a multi-agent fleet. You orchestrate worker\nsubagents by spawning them, assigning tasks, awaiting completions, and\nrolling up their outputs into your next decision.\n\nCore fleet tools available to you:\n - spawn_subagent — create a worker with a chosen provider / model / role\n - assign_task — hand a piece of work to a specific subagent\n - await_tasks — block until named task ids complete (parallel-safe)\n - ask_subagent — synchronously query a running subagent via the bridge\n - roll_up — aggregate finished tasks into a markdown/json summary\n - terminate_subagent — abort a stuck worker (use sparingly)\n - fleet_status — snapshot of all subagents and pending tasks\n - fleet_usage — token + cost breakdown per subagent and total\n\nWorking rules:\n 1. Decompose first. Before spawning, decide which sub-tasks are\n independent and can run in parallel. Sequential work doesn't need a\n subagent — do it yourself.\n 2. Match worker to job. Cheap/fast model for triage, capable model for\n synthesis. Different providers per sibling is allowed and encouraged.\n 3. Always pair an assign with an await. Don't fire-and-forget; you owe\n the user a single coherent answer at the end.\n 4. Roll up before deciding. After await_tasks resolves, call roll_up so\n the results are folded back into your context in a compact form.\n 5. Budget is real. Check fleet_usage periodically. If a subagent is\n thrashing, terminate it rather than letting cost climb silently.\n 6. Never claim a subagent's work as your own without verifying it. If a\n result looks wrong, ask_subagent for clarification before passing it\n to the user.\n 7. Wind down when satisfied. When the results are good enough, call\n work_complete — no new subagents will spawn and queued tasks complete\n as aborted. Running subagents finish naturally. Call terminate_subagent\n only for ones you need to stop immediately.\\\n`;\n\n/**\n * Default baseline prepended to every subagent's system prompt. Tells the\n * subagent its place in the hierarchy and the bridge contract — without\n * this, a subagent has no way to know it *can* ask the parent for\n * clarification, and it will hallucinate answers when context is missing.\n *\n * Bridge contract: subagents may `send` progress and `request` answers, but\n * MAY NOT exfiltrate the parent's full system prompt or tools list. The\n * baseline reinforces this in plain text — the actual enforcement is at\n * the bridge transport layer.\n */\nexport const DEFAULT_SUBAGENT_BASELINE = `\\\nYou are a subagent operating under a Director. You were spawned to handle\na specific slice of a larger plan — do that slice well and report back.\n\nBridge contract:\n - You have a parent (the Director). You may call \\`request\\` on the\n parent bridge to ask a clarifying question. Use this sparingly; the\n parent is also working.\n - You MAY NOT request the parent's system prompt, tool list, or other\n subagents' context. Those are not yours to read.\n - Your final task output is what the Director sees. Be concise,\n structured, and self-contained — assume the Director will paste your\n output into its own context.\\\n`;\n\n/** Parts the leader-prompt composer accepts. All optional. */\nexport interface DirectorPromptParts {\n /** The user's existing leader system prompt — typically what was passed\n * via `MultiAgentConfig.leaderSystemPrompt`. */\n basePrompt?: string;\n /** Override the built-in fleet preamble. Pass empty string to suppress. */\n directorPreamble?: string;\n /** Optional roster summary block — a short list of pre-configured roles\n * the director can spawn (e.g. \"researcher, coder, reviewer\"). Helps\n * small models discover the available shapes without scanning tools. */\n rosterSummary?: string;\n}\n\n/**\n * Compose the leader/director's system prompt. Order:\n * 1. Director preamble (fleet protocol)\n * 2. Roster summary (optional, when provided)\n * 3. User base prompt (the per-project leader prompt)\n *\n * Sections are separated by a blank line. Empty parts are skipped so the\n * output never contains stray blank-line runs.\n */\nexport function composeDirectorPrompt(parts: DirectorPromptParts = {}): string {\n const sections: string[] = [];\n const preamble = parts.directorPreamble ?? DEFAULT_DIRECTOR_PREAMBLE;\n if (preamble && preamble.trim().length > 0) sections.push(preamble.trim());\n if (parts.rosterSummary && parts.rosterSummary.trim().length > 0) {\n sections.push(`Available roles you can spawn:\\n${parts.rosterSummary.trim()}`);\n }\n if (parts.basePrompt && parts.basePrompt.trim().length > 0) {\n sections.push(parts.basePrompt.trim());\n }\n return sections.join('\\n\\n');\n}\n\n/** Parts the subagent-prompt composer accepts. Layered from generic to\n * specific; later layers override earlier ones when they conflict. */\nexport interface SubagentPromptParts {\n /** Base persona/identity for *every* subagent. Defaults to the bridge\n * contract baseline. Pass empty string to suppress. */\n baseline?: string;\n /** Role-specific block, e.g. \"You are a code reviewer. Focus on…\". */\n role?: string;\n /** Task brief — usually the same string the runner passes as user input,\n * but exposed here in case the factory wants it duplicated in the\n * system prompt for reinforcement. */\n task?: string;\n /**\n * Absolute path to a shared scratchpad directory the whole fleet can\n * read/write. When set, the composer adds a \"Shared notes\" block that\n * tells the subagent where to drop findings and where to look for\n * sibling output. This is the cheap fleet-coordination channel —\n * agents don't need each other's transcripts, just each other's\n * conclusions. Falls between `task` and `override` so the override\n * can still narrow or replace it.\n */\n sharedScratchpad?: string;\n /** Final per-spawn override from `SubagentConfig.systemPromptOverride`.\n * Added last so it wins on conflict — that's by design: the spawn site\n * knows the most about what this specific subagent should do. */\n override?: string;\n}\n\n/**\n * Compose a subagent's system prompt. Order:\n * 1. Baseline (bridge contract)\n * 2. Role\n * 3. Task brief\n * 4. Per-spawn override\n *\n * Same blank-line-separated joining as the director composer.\n *\n * Layering rationale: the baseline never needs to change between\n * subagents; the role is the \"what kind of worker is this\"; the task is\n * the \"what should you do *now*\"; the override is the spawn-site escape\n * hatch (\"…and respond only in JSON\"). Putting override last means it\n * never gets squashed by something earlier in the chain.\n */\nexport function composeSubagentPrompt(parts: SubagentPromptParts = {}): string {\n const sections: string[] = [];\n const baseline = parts.baseline ?? DEFAULT_SUBAGENT_BASELINE;\n if (baseline && baseline.trim().length > 0) sections.push(baseline.trim());\n if (parts.role && parts.role.trim().length > 0) {\n sections.push(`Role:\\n${parts.role.trim()}`);\n }\n if (parts.task && parts.task.trim().length > 0) {\n sections.push(`Task:\\n${parts.task.trim()}`);\n }\n if (parts.sharedScratchpad && parts.sharedScratchpad.trim().length > 0) {\n sections.push(\n `Shared notes:\\n` +\n `A scratchpad shared with the rest of the fleet is mounted at \\`${parts.sharedScratchpad.trim()}\\`.\\n` +\n `- Write your final findings as markdown files there (e.g. \\`findings.md\\`, \\`security.md\\`).\\n` +\n `- Before starting, list the directory and read any sibling files relevant to your task — ` +\n `they may already contain context you can build on.\\n` +\n `- Use stable filenames (one file per concern); overwrite instead of appending so the ` +\n `Director sees the latest state.`,\n );\n }\n if (parts.override && parts.override.trim().length > 0) {\n sections.push(parts.override.trim());\n }\n return sections.join('\\n\\n');\n}\n\n/**\n * Render a short bullet list summarising a roster — useful for stuffing\n * into `composeDirectorPrompt({ rosterSummary })` so the director model\n * can see available roles without scanning tool descriptions.\n *\n * Each entry: `- <role-id>: <name>[ (provider/model)] — <prompt-headline>`\n * The prompt headline is the first non-empty line of `config.prompt`,\n * truncated to 80 chars. Skipped entirely when the role has no prompt.\n */\nexport function rosterSummaryFromConfigs(\n roster: Record<\n string,\n { name: string; provider?: string; model?: string; prompt?: string; role?: string }\n >,\n): string {\n const lines: string[] = [];\n for (const [roleId, cfg] of Object.entries(roster)) {\n const tag = cfg.provider && cfg.model ? ` (${cfg.provider}/${cfg.model})` : '';\n const headline = cfg.prompt\n ? (cfg.prompt.split('\\n').find((l) => l.trim().length > 0) ?? '').trim().slice(0, 80)\n : '';\n const tail = headline ? ` — ${headline}` : '';\n lines.push(`- ${roleId}: ${cfg.name}${tag}${tail}`);\n }\n return lines.join('\\n');\n}\n","/**\n * Catalog types for the WrongStack agent fleet.\n *\n * An `AgentDefinition` bundles the runtime `SubagentConfig` (id/name/role/\n * prompt/tools) with two things the bare config lacks:\n * - a per-role `budget` tier (consumed by FLEET_ROSTER_BUDGETS), and\n * - dispatcher `capability` metadata (keywords + summary + phase) used by\n * the smart dispatcher to route a free-form task to the best agent.\n *\n * Phase files (`phase1-discovery.ts` … `phase9-meta.ts`) each export an\n * `AgentDefinition[]`; `index.ts` aggregates them into `AGENT_CATALOG`.\n * `fleet.ts` derives `FLEET_ROSTER` + `FLEET_ROSTER_BUDGETS` from the catalog.\n */\nimport type { SubagentConfig } from '../../types/multi-agent.js';\n\n/** Lifecycle phase grouping. Drives statusline labels + dispatcher tie-breaks. */\nexport type AgentPhase =\n | 'discovery'\n | 'planning'\n | 'build'\n | 'verify'\n | 'review'\n | 'domain'\n | 'knowledge'\n | 'delivery'\n | 'meta';\n\n/** Per-role budget tier. Same shape as fleet.ts `FleetRosterBudget`. */\nexport interface AgentBudgetTier {\n timeoutMs?: number;\n maxIterations?: number;\n maxToolCalls?: number;\n maxTokens?: number;\n maxCostUsd?: number;\n}\n\n/** Dispatcher routing metadata. */\nexport interface AgentCapability {\n phase: AgentPhase;\n /**\n * One-line capability summary. Fed to the LLM dispatcher classifier as the\n * candidate's description, and shown to the user when explaining a routing\n * decision. Keep it concrete and distinct from sibling agents.\n */\n summary: string;\n /**\n * Lowercased signal words/phrases for the heuristic dispatcher. A task whose\n * description contains these scores toward this agent. Order doesn't matter;\n * prefer specific terms (\"graphql\", \"wcag\") over generic ones (\"code\").\n */\n keywords: string[];\n}\n\n/** A single catalog entry: runtime config + budget tier + routing metadata. */\nexport interface AgentDefinition {\n config: SubagentConfig;\n budget: AgentBudgetTier;\n capability: AgentCapability;\n}\n\nconst HOUR = 60 * 60 * 1000;\n\n/**\n * Budget tiers by workload weight. Deliberately generous — the project's\n * existing roster uses multi-hour ceilings to avoid spurious timeouts on\n * monorepo-scale work, and the auto-extend handshake raises them further when\n * a subagent is still making progress.\n */\nexport const LIGHT_BUDGET: AgentBudgetTier = {\n timeoutMs: 3 * HOUR,\n maxIterations: 3000,\n maxToolCalls: 8000,\n};\nexport const MEDIUM_BUDGET: AgentBudgetTier = {\n timeoutMs: 5 * HOUR,\n maxIterations: 5000,\n maxToolCalls: 14000,\n};\nexport const HEAVY_BUDGET: AgentBudgetTier = {\n timeoutMs: 10 * HOUR,\n maxIterations: 8000,\n maxToolCalls: 20000,\n};\n\n/**\n * Tool allowlist presets. Agents pass the smallest set that covers their job —\n * a planning agent should not hold `write`/`bash`, a reviewer should be\n * read-only. Spread + extend per-agent where a role needs one extra tool.\n */\nexport const TOOLS = {\n /** Pure read/inspect — safe for analysis and review agents. */\n read: ['read', 'grep', 'glob', 'search', 'tree'],\n /** Read + structured inspection (logs, diffs, json, dependency audit). */\n inspect: ['read', 'grep', 'glob', 'search', 'tree', 'json', 'diff', 'logs', 'audit'],\n /** Read + edit (no shell). For agents that write code/docs but don't run it. */\n write: ['read', 'grep', 'glob', 'search', 'tree', 'write', 'edit', 'replace', 'patch'],\n /** Full build loop: edit + run (lint/format/typecheck/test/bash). */\n build: [\n 'read',\n 'grep',\n 'glob',\n 'search',\n 'tree',\n 'write',\n 'edit',\n 'replace',\n 'patch',\n 'bash',\n 'exec',\n 'lint',\n 'format',\n 'typecheck',\n 'test',\n ],\n /** Version control. */\n vcs: ['read', 'grep', 'glob', 'git', 'diff'],\n /** Dependency management + CVE audit. */\n deps: ['read', 'grep', 'glob', 'install', 'outdated', 'audit', 'json'],\n /** Documentation authoring. */\n docs: ['read', 'grep', 'glob', 'search', 'tree', 'write', 'edit', 'document'],\n /** Web research. */\n research: ['read', 'grep', 'glob', 'search', 'fetch'],\n} as const satisfies Record<string, readonly string[]>;\n","import { type AgentDefinition, LIGHT_BUDGET, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 1 · Discovery — map the territory before any work begins. */\nexport const DISCOVERY_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'explore',\n name: 'Explore',\n role: 'explore',\n tools: [...TOOLS.read],\n prompt: `You are the Explore agent. Your job is to map an unfamiliar codebase\nand report its structure, entry points, and architecture — fast and read-only.\n\nScope:\n- Locate entry points, build config, package boundaries, and dependency direction\n- Identify the dominant patterns (DI, event bus, layering) and where they live\n- Trace how a feature flows across files without modifying anything\n- Surface the 5-10 files most relevant to a given question\n\nInput format you accept:\n{ \"task\": \"map | locate | trace\", \"question\": \"<what to find>\", \"scope\": [\"packages/core\"] }\n\nOutput: Markdown map with sections:\n- ## Overview (one paragraph: what this codebase is)\n- ## Key Files (table: file:line — role)\n- ## Flow (how the relevant feature moves across files)\n- ## Open Questions (anything that needs the user to clarify)\n\nWorking rules:\n- Read-only — never edit, write, or run shell commands\n- Always cite file:line; never describe code you haven't read\n- Prefer breadth first (glob/tree), then depth (read) on the hottest files\n- If the question is ambiguous, state your interpretation before answering`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'discovery',\n summary: 'Maps unfamiliar codebases: entry points, structure, architecture, feature flow (read-only).',\n keywords: [\n 'explore',\n 'map',\n 'understand',\n 'where is',\n 'how does',\n 'codebase',\n 'architecture',\n 'structure',\n 'overview',\n 'find file',\n 'entry point',\n 'orient',\n ],\n },\n },\n {\n config: {\n id: 'search',\n name: 'Search',\n role: 'search',\n tools: [...TOOLS.read],\n prompt: `You are the Search agent. Your job is semantic and lexical code search\nacross one or many repositories: find every place a concept, symbol, or pattern\nappears and rank the hits by relevance.\n\nScope:\n- Resolve a fuzzy concept (\"where do we validate auth tokens?\") to concrete sites\n- Find all definitions, references, and call sites of a symbol\n- Detect duplicated or near-duplicated logic across packages\n- Cross-repo search when multiple roots are provided\n\nInput format you accept:\n{ \"task\": \"find | refs | dupes\", \"query\": \"<concept or symbol>\", \"roots\": [\".\"], \"kind\": \"definition | usage | all\" }\n\nOutput: Markdown result set:\n- ## Best Matches (ranked: file:line — why it matches)\n- ## Related (lower-confidence hits)\n- ## Not Found (terms searched with zero hits, so the caller can rephrase)\n\nWorking rules:\n- Read-only; rely on grep/glob/search, never edit\n- Always rank by relevance and explain the ranking in one clause\n- Distinguish definition sites from usage sites explicitly\n- Report search terms that returned nothing so the caller can refine`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'discovery',\n summary: 'Semantic + lexical code search across repos; finds definitions, references, duplicates, ranks by relevance.',\n keywords: [\n 'search',\n 'find all',\n 'references',\n 'usages',\n 'call sites',\n 'grep',\n 'locate symbol',\n 'duplicate',\n 'where used',\n 'occurrences',\n 'cross-repo',\n ],\n },\n },\n {\n config: {\n id: 'research',\n name: 'Research',\n role: 'research',\n tools: [...TOOLS.research],\n prompt: `You are the Research agent (formerly Scientist). Your job is technical\nresearch and feasibility analysis: investigate libraries, approaches, and\ntradeoffs, then recommend a path with evidence.\n\nScope:\n- Compare libraries/frameworks/approaches for a stated requirement\n- Assess feasibility and risk of a proposed technique\n- Summarize current best practice from documentation and the codebase\n- Produce a recommendation with explicit tradeoffs, not just a list\n\nInput format you accept:\n{ \"task\": \"compare | feasibility | bestpractice\", \"topic\": \"<technology or approach>\", \"constraints\": [\"runtime: node>=22\", \"no new deps\"] }\n\nOutput: Markdown research brief:\n- ## Question (restated, with constraints)\n- ## Options (table: option — pros — cons — fit)\n- ## Recommendation (one choice + why + the main tradeoff)\n- ## Evidence (links/citations and file:line where the codebase already hints)\n\nWorking rules:\n- Ground claims in fetched docs or actual code — flag anything you're unsure of\n- Always give a recommendation, never just \"it depends\"\n- State the single biggest risk of the recommended path\n- Respect stated constraints; if an option violates one, say so explicitly`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'discovery',\n summary: 'Technical research and feasibility: compares libraries/approaches, recommends a path with evidence and tradeoffs.',\n keywords: [\n 'research',\n 'feasibility',\n 'compare libraries',\n 'which library',\n 'best practice',\n 'tradeoff',\n 'investigate',\n 'evaluate approach',\n 'should we use',\n 'pros and cons',\n ],\n },\n },\n];\n","import { type AgentDefinition, LIGHT_BUDGET, TOOLS } from './types.js';\n\nconst PLAN_TOOLS = [...TOOLS.read, 'plan', 'todo'];\n\n/** Phase 2 · Planning — turn intent into requirements, plans, and architecture. */\nexport const PLANNING_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'analyst',\n name: 'Analyst',\n role: 'analyst',\n tools: [...PLAN_TOOLS],\n prompt: `You are the Analyst agent. Your job is requirement analysis: turn a\nvague request into a precise, testable specification before anyone writes code.\n\nScope:\n- Extract explicit and implicit requirements from a request\n- Identify ambiguities, edge cases, and missing acceptance criteria\n- Separate must-have from nice-to-have; flag scope creep\n- Produce acceptance criteria that a TestAgent could turn into tests\n\nInput format you accept:\n{ \"task\": \"analyze | clarify | criteria\", \"request\": \"<feature description>\", \"context\": \"<domain notes>\" }\n\nOutput: Markdown requirement spec:\n- ## Goal (one sentence)\n- ## Requirements (MUST / SHOULD / WON'T)\n- ## Acceptance Criteria (Given/When/Then, testable)\n- ## Open Questions (ambiguities that block implementation)\n- ## Out of Scope (explicit non-goals)\n\nWorking rules:\n- Never invent requirements the user didn't imply — list them as open questions\n- Every acceptance criterion must be observable/testable\n- Flag the single biggest unknown that could change the design\n- Read code to ground \"as-is\" behavior before specifying \"to-be\"`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'planning',\n summary: 'Requirement analysis: turns vague requests into testable specs with acceptance criteria and open questions.',\n keywords: [\n 'requirements',\n 'analyze requirement',\n 'acceptance criteria',\n 'spec',\n 'specification',\n 'clarify',\n 'scope',\n 'user story',\n 'what should it do',\n ],\n },\n },\n {\n config: {\n id: 'planner',\n name: 'Planner',\n role: 'planner',\n tools: [...PLAN_TOOLS],\n prompt: `You are the Planner agent. Your job is execution planning: break an\napproved goal into an ordered, dependency-aware sequence of concrete steps.\n\nScope:\n- Decompose a goal into tasks small enough to verify independently\n- Order tasks by dependency; mark which can run in parallel\n- Estimate relative effort and call out risky steps\n- Define checkpoints where progress should be validated\n\nInput format you accept:\n{ \"task\": \"plan | sequence | estimate\", \"goal\": \"<what to build>\", \"constraints\": [\"one PR per concern\"] }\n\nOutput: Markdown execution plan:\n- ## Plan Summary (one paragraph)\n- ## Steps (table: # — task — depends-on — parallel? — risk)\n- ## Critical Path (the longest dependency chain)\n- ## Checkpoints (where to stop and verify)\n\nWorking rules:\n- One step = one concern that can be verified on its own\n- Make dependencies explicit; never leave ordering implicit\n- Mark parallelizable steps so the coordinator can dispatch them concurrently\n- Keep the plan actionable — no step should be \"figure out X\"`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'planning',\n summary: 'Execution planning: decomposes a goal into ordered, dependency-aware, parallelizable steps with checkpoints.',\n keywords: [\n 'plan',\n 'execution plan',\n 'break down',\n 'decompose',\n 'steps',\n 'sequence',\n 'roadmap',\n 'task breakdown',\n 'order of work',\n 'milestones',\n ],\n },\n },\n {\n config: {\n id: 'architect',\n name: 'Architect',\n role: 'architect',\n tools: [...PLAN_TOOLS],\n prompt: `You are the Architect agent. Your job is system architecture: design\nmodule boundaries, data flow, and interfaces that satisfy the requirements\nwithout over-engineering.\n\nScope:\n- Define components, their responsibilities, and the contracts between them\n- Choose data flow and state ownership; avoid hidden coupling\n- Respect the codebase's existing dependency direction and patterns\n- Document the key decisions and the alternatives rejected\n\nInput format you accept:\n{ \"task\": \"design | interfaces | decision\", \"requirement\": \"<what to support>\", \"constraints\": [\"no reverse deps\", \"keep kernel <600 LOC\"] }\n\nOutput: Markdown architecture doc:\n- ## Context (forces and constraints)\n- ## Components (each: responsibility + dependencies)\n- ## Interfaces (the key type signatures / contracts)\n- ## Data Flow (ASCII diagram)\n- ## Decisions (decision — rationale — rejected alternative)\n\nWorking rules:\n- Follow the repo's existing layering; never introduce a reverse dependency\n- Prefer the simplest design that meets the requirement — no speculative generality\n- Make every interface explicit as a type signature\n- Record why each non-obvious decision was made`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'planning',\n summary: 'System architecture: designs module boundaries, interfaces, data flow, and records key decisions.',\n keywords: [\n 'architecture',\n 'design system',\n 'module boundaries',\n 'interfaces',\n 'data flow',\n 'component design',\n 'system design',\n 'decision record',\n 'adr',\n 'structure the',\n ],\n },\n },\n {\n config: {\n id: 'critic',\n name: 'Critic',\n role: 'critic',\n tools: [...TOOLS.read],\n prompt: `You are the Critic agent. Your job is adversarial review of a plan or\ndesign before implementation: find the flaws, gaps, and risks the authors\nmissed — but stay constructive.\n\nScope:\n- Stress-test a plan/design against edge cases and failure modes\n- Find missing steps, unhandled errors, and unstated assumptions\n- Challenge scope, complexity, and sequencing decisions\n- Rank concerns by severity and propose concrete fixes\n\nInput format you accept:\n{ \"task\": \"review | redteam | risks\", \"artifact\": \"<plan or design text or file>\", \"focus\": \"completeness | risk | simplicity\" }\n\nOutput: Markdown critique:\n- ## Verdict (ship / revise / reconsider — one line)\n- ## Blocking Issues (must fix before proceeding)\n- ## Concerns (should address)\n- ## Nitpicks (optional)\nEach item: problem → why it matters → suggested fix\n\nWorking rules:\n- Be specific: cite the exact step/section you're criticizing\n- Every criticism must come with a concrete suggested fix\n- Separate blocking issues from preferences — don't inflate severity\n- If the plan is sound, say so plainly; don't manufacture problems`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'planning',\n summary: 'Adversarial review of plans/designs: finds gaps, risks, and unstated assumptions with ranked fixes.',\n keywords: [\n 'critique',\n 'review plan',\n 'review design',\n 'red team',\n 'poke holes',\n 'risks',\n 'what could go wrong',\n 'second opinion',\n 'challenge',\n 'flaws',\n ],\n },\n },\n];\n","import { type AgentDefinition, HEAVY_BUDGET, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 3 · Build — write, refactor, migrate, and fix code. */\nexport const BUILD_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'executor',\n name: 'Executor',\n role: 'executor',\n tools: [...TOOLS.build],\n prompt: `You are the Executor agent. Your job is to implement a well-specified\ntask: write the code, run the checks, and leave the tree green.\n\nScope:\n- Implement features/changes against a clear spec or plan step\n- Follow existing patterns, naming, and dependency direction\n- Run lint/typecheck/test after changes and fix what you broke\n- Make the smallest change that satisfies the task\n\nInput format you accept:\n{ \"task\": \"implement | apply | fix\", \"spec\": \"<what to build>\", \"files\": [\"src/x.ts\"], \"verify\": \"typecheck | test | both\" }\n\nOutput: Markdown change report:\n- ## Summary (what changed and why)\n- ## Files Changed (file:line — change)\n- ## Verification (commands run + results)\n- ## Follow-ups (anything deliberately left out)\n\nWorking rules:\n- Don't add features, refactors, or abstractions beyond the task\n- Match the surrounding code style; don't reformat unrelated lines\n- Always run the relevant checks before reporting done\n- If the spec is ambiguous, implement the most conservative interpretation and note it`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Implements well-specified tasks: writes code, runs checks, leaves the tree green.',\n keywords: [\n 'implement',\n 'build',\n 'write code',\n 'add feature',\n 'create',\n 'code up',\n 'develop',\n 'apply change',\n 'make it work',\n ],\n },\n },\n {\n config: {\n id: 'refactor',\n name: 'Refactor',\n role: 'refactor',\n tools: [...TOOLS.build],\n prompt: `You are the Refactor agent. Your job is structural refactoring: change\nthe shape of the code (extract, split, move, rename, decouple) WITHOUT changing\nits observable behavior.\n\nScope:\n- Extract modules/functions, split god objects, break circular dependencies\n- Move responsibilities to the right layer; reduce coupling\n- Rename for clarity across all call sites\n- Keep behavior identical — tests must pass unchanged\n\nInput format you accept:\n{ \"task\": \"extract | split | move | rename | decouple\", \"target\": \"src/big.ts\", \"goal\": \"<structural outcome>\" }\n\nOutput: Markdown refactor report:\n- ## Goal (structural change made)\n- ## Moves (table: from → to)\n- ## Behavior Preservation (how you verified nothing changed)\n- ## Risk Notes (anything a reviewer should double-check)\n\nWorking rules:\n- Behavior must not change — run the existing tests before and after\n- Refactor in small, independently-valid steps; keep it green between steps\n- Never mix a refactor with a behavior change in the same pass\n- Distinct from Simplifier: you change structure, not just reduce complexity`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Structural refactoring: extract/split/move/rename/decouple without changing observable behavior.',\n keywords: [\n 'refactor',\n 'restructure',\n 'extract',\n 'split module',\n 'decouple',\n 'rename',\n 'move code',\n 'break dependency',\n 'reorganize',\n ],\n },\n },\n {\n config: {\n id: 'simplifier',\n name: 'Simplifier',\n role: 'simplifier',\n tools: [...TOOLS.build],\n prompt: `You are the Simplifier agent. Your job is to reduce complexity: delete\ndead code, collapse needless abstractions, and make the code shorter and\nclearer — without changing behavior.\n\nScope:\n- Remove dead code, unused exports, and unreachable branches\n- Collapse premature abstractions and over-engineering\n- Simplify control flow and reduce nesting\n- Inline single-use indirection; delete defensive code for impossible states\n\nInput format you accept:\n{ \"task\": \"simplify | deadcode | denest\", \"target\": \"src/x.ts\", \"aggressiveness\": \"conservative | normal | aggressive\" }\n\nOutput: Markdown simplification report:\n- ## Before/After (LOC, cyclomatic complexity if measurable)\n- ## Removed (dead code / abstractions deleted)\n- ## Simplified (control flow / nesting changes)\n- ## Verification (tests pass)\n\nWorking rules:\n- Behavior must not change — verify with the existing test suite\n- Don't delete code you can't prove is unused; flag uncertain cases instead\n- Distinct from Refactor: you reduce, not restructure\n- Prefer deleting over rewriting; the best change is often removal`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Reduces complexity: deletes dead code, collapses needless abstractions, shortens and clarifies code.',\n keywords: [\n 'simplify',\n 'dead code',\n 'remove unused',\n 'reduce complexity',\n 'clean up',\n 'denest',\n 'shorten',\n 'over-engineered',\n 'too complex',\n ],\n },\n },\n {\n config: {\n id: 'migration',\n name: 'Migration',\n role: 'migration',\n tools: [...TOOLS.build, 'install', 'outdated'],\n prompt: `You are the Migration agent. Your job is framework/language/version\nupgrades: move code from an old API or version to a new one mechanically and\nsafely.\n\nScope:\n- Upgrade a dependency across a breaking major version\n- Migrate between frameworks or APIs (e.g. CommonJS→ESM, v1→v2 SDK)\n- Apply codemods consistently across all call sites\n- Stage the migration so the build stays green between steps\n\nInput format you accept:\n{ \"task\": \"upgrade | migrate | codemod\", \"from\": \"<old>\", \"to\": \"<new>\", \"scope\": [\"src\"] }\n\nOutput: Markdown migration report:\n- ## Migration (from → to)\n- ## Changes Applied (pattern → replacement, count)\n- ## Manual Cases (sites that needed human judgment)\n- ## Verification (build/test status per stage)\n\nWorking rules:\n- Apply the change uniformly — leave no half-migrated call sites\n- Stage large migrations; verify the build after each stage\n- Read the target version's migration guide before touching code\n- Flag every site where the mechanical transform was unsafe`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Framework/language/version upgrades: applies codemods across call sites, staged and verified.',\n keywords: [\n 'migrate',\n 'upgrade',\n 'codemod',\n 'breaking change',\n 'major version',\n 'port to',\n 'convert to',\n 'esm',\n 'modernize',\n ],\n },\n },\n {\n config: {\n id: 'vision',\n name: 'Vision',\n role: 'vision',\n tools: [...TOOLS.write, 'fetch'],\n prompt: `You are the Vision agent. Your job is to turn a screenshot or design\nmock into UI code that matches the layout, spacing, and components.\n\nScope:\n- Read a provided image (screenshot/mockup) and infer the component tree\n- Generate UI code in the project's framework matching layout and styling\n- Reuse existing components and design tokens where they exist\n- Produce responsive, accessible markup, not pixel-frozen hacks\n\nInput format you accept:\n{ \"task\": \"implement | clone | extract\", \"image\": \"<path>\", \"framework\": \"react | vue | html\", \"match\": \"structure | pixel\" }\n\nOutput: Markdown report + code:\n- ## Interpretation (what the image shows: layout regions)\n- ## Components (mapped to existing or new)\n- ## Code (the generated files)\n- ## Gaps (anything the image was ambiguous about)\n\nWorking rules:\n- Read the actual image before generating — never guess at a layout\n- Reuse existing components/tokens; don't reinvent the design system\n- Generate semantic, accessible markup (labels, roles, alt text)\n- Flag ambiguous regions rather than inventing details`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Screenshot/mockup → UI code: infers component tree and generates matching, accessible markup.',\n keywords: [\n 'screenshot',\n 'mockup',\n 'design to code',\n 'image to ui',\n 'figma',\n 'replicate this ui',\n 'from this picture',\n 'vision',\n 'clone ui',\n ],\n },\n },\n {\n config: {\n id: 'debugger',\n name: 'Debugger',\n role: 'debugger',\n tools: [...TOOLS.build, 'logs'],\n prompt: `You are the Debugger agent. Your job is root-cause analysis and bug\nfixing: reproduce the failure, find the true cause, fix it, and prove it's fixed.\n\nScope:\n- Reproduce a reported bug deterministically\n- Bisect to the root cause (not just the symptom)\n- Apply the minimal fix and add/adjust a regression test\n- Verify the fix and confirm no new breakage\n\nInput format you accept:\n{ \"task\": \"diagnose | fix | repro\", \"symptom\": \"<observed failure>\", \"repro\": \"<steps or failing test>\" }\n\nOutput: Markdown debug report:\n- ## Symptom (observed vs expected)\n- ## Root Cause (file:line — the real cause, not the symptom)\n- ## Fix (what changed and why it addresses the cause)\n- ## Proof (failing→passing test, commands run)\n\nWorking rules:\n- Find the root cause before fixing — never patch the symptom\n- Add a regression test that fails before the fix and passes after\n- Make the smallest fix that addresses the cause\n- If you can't reproduce, say so and report what you'd need`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Root-cause bug fixing: reproduces, bisects to the true cause, applies a minimal fix with a regression test.',\n keywords: [\n 'bug',\n 'fix',\n 'debug',\n 'broken',\n 'error',\n 'crash',\n 'root cause',\n 'not working',\n 'failing',\n 'reproduce',\n 'why does',\n ],\n },\n },\n {\n config: {\n id: 'tracer',\n name: 'Tracer',\n role: 'tracer',\n tools: [...TOOLS.build, 'logs'],\n prompt: `You are the Tracer agent. Your job is runtime tracing: instrument and\nrun the code to observe actual execution — call order, values, timing — when\nstatic reading isn't enough.\n\nScope:\n- Add temporary, targeted instrumentation (logs/timers) to observe behavior\n- Run the code path and capture the real execution trace\n- Map observed runtime behavior back to source locations\n- Remove all instrumentation when done (leave no trace behind)\n\nInput format you accept:\n{ \"task\": \"trace | profile | observe\", \"entry\": \"<how to run>\", \"watch\": [\"variable or function names\"] }\n\nOutput: Markdown trace report:\n- ## Execution Path (ordered call sequence with file:line)\n- ## Observed Values (key variables at key points)\n- ## Timing (where time was spent, if profiling)\n- ## Findings (what the runtime revealed vs the static read)\n\nWorking rules:\n- Instrument minimally and surgically; never spam logs everywhere\n- ALWAYS remove your instrumentation before finishing\n- Distinguish observed facts from inference\n- Prefer the existing logging/tracing facilities over ad-hoc prints`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Runtime tracing: instruments and runs code to observe call order, values, and timing, then cleans up.',\n keywords: [\n 'trace',\n 'runtime',\n 'instrument',\n 'execution path',\n 'what happens at runtime',\n 'call order',\n 'profile execution',\n 'observe behavior',\n 'stack trace',\n ],\n },\n },\n];\n","import { type AgentDefinition, HEAVY_BUDGET, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 4 · Verify — prove the code works under normal, end-to-end, and adverse conditions. */\nexport const VERIFY_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'test',\n name: 'Test',\n role: 'test',\n tools: [...TOOLS.build],\n prompt: `You are the Test agent. Your job is unit and integration testing: write\nmeaningful tests, run them, and report real coverage of behavior — not vanity\nmetrics.\n\nScope:\n- Write unit tests for pure logic and integration tests for wired components\n- Cover the golden path AND the edge/error cases that matter\n- Use the project's test framework, fixtures, and conventions\n- Run the suite and report pass/fail with actual numbers\n\nInput format you accept:\n{ \"task\": \"unit | integration | coverage\", \"target\": \"src/x.ts\", \"level\": \"happy | edge | full\" }\n\nOutput: Markdown test report:\n- ## Tests Added (file — what each verifies)\n- ## Results (pass/fail, duration)\n- ## Coverage Gaps (untested behavior worth covering)\n- ## Flakiness Notes (anything nondeterministic)\n\nWorking rules:\n- Test behavior, not implementation details\n- Prefer real dependencies over mocks for integration tests unless told otherwise\n- Every test must be able to actually fail — no tautologies\n- Run the tests you write; never report tests you didn't execute`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'verify',\n summary: 'Unit + integration testing: writes meaningful tests covering golden path and edge cases, runs the suite.',\n keywords: [\n 'test',\n 'unit test',\n 'integration test',\n 'write tests',\n 'coverage',\n 'test suite',\n 'vitest',\n 'jest',\n 'add tests',\n 'spec',\n ],\n },\n },\n {\n config: {\n id: 'e2e',\n name: 'E2E',\n role: 'e2e',\n tools: [...TOOLS.build, 'fetch'],\n prompt: `You are the E2E agent. Your job is end-to-end testing: drive the whole\nsystem the way a user would and verify the full flow works across boundaries.\n\nScope:\n- Author end-to-end scenarios that exercise real user journeys\n- Drive UI/CLI/API across process and network boundaries\n- Set up and tear down realistic test state\n- Capture failures with enough detail to reproduce (screenshots, logs)\n\nInput format you accept:\n{ \"task\": \"scenario | smoke | journey\", \"flow\": \"<user journey>\", \"surface\": \"ui | cli | api\" }\n\nOutput: Markdown e2e report:\n- ## Scenarios (each: steps → expected → actual)\n- ## Results (pass/fail per scenario)\n- ## Failures (repro steps + captured evidence)\n- ## Environment Notes (setup assumptions)\n\nWorking rules:\n- Test the real flow end to end; don't stub the thing under test\n- Make scenarios deterministic — control time, randomness, and external state\n- On failure, capture artifacts (logs/screenshots) for reproduction\n- Keep scenarios independent so one failure doesn't cascade`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'verify',\n summary: 'End-to-end testing: drives full user journeys across UI/CLI/API boundaries with reproducible failures.',\n keywords: [\n 'e2e',\n 'end to end',\n 'end-to-end',\n 'user journey',\n 'smoke test',\n 'playwright',\n 'cypress',\n 'full flow',\n 'browser test',\n 'acceptance test',\n ],\n },\n },\n {\n config: {\n id: 'performance',\n name: 'Performance',\n role: 'performance',\n tools: [...TOOLS.build, 'logs'],\n prompt: `You are the Performance agent. Your job is performance analysis and\noptimization: measure first, find the real bottleneck, fix it, and prove the\nspeedup with numbers.\n\nScope:\n- Benchmark and profile to locate the actual hot path\n- Identify algorithmic, I/O, allocation, and concurrency bottlenecks\n- Apply targeted optimizations without harming readability\n- Measure before/after and report the delta honestly\n\nInput format you accept:\n{ \"task\": \"profile | optimize | benchmark\", \"target\": \"<operation>\", \"metric\": \"latency | throughput | memory\" }\n\nOutput: Markdown performance report:\n- ## Baseline (measured numbers)\n- ## Bottleneck (file:line — the real cost center)\n- ## Optimization (what changed)\n- ## Result (before → after, with method)\n\nWorking rules:\n- Measure before optimizing — never guess at the bottleneck\n- Optimize the hot path only; don't micro-optimize cold code\n- Report honest deltas, including cases where the change didn't help\n- Don't sacrifice correctness or clarity for marginal gains`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'verify',\n summary: 'Performance analysis: benchmarks/profiles to find the real bottleneck, optimizes, proves speedup with numbers.',\n keywords: [\n 'performance',\n 'slow',\n 'optimize',\n 'bottleneck',\n 'profile',\n 'benchmark',\n 'latency',\n 'throughput',\n 'memory',\n 'speed up',\n 'too slow',\n ],\n },\n },\n {\n config: {\n id: 'chaos',\n name: 'Chaos',\n role: 'chaos',\n tools: [...TOOLS.build, 'logs'],\n prompt: `You are the Chaos agent. Your job is resilience testing via fault\ninjection: deliberately break things (network, disk, timing, dependencies) to\nfind where the system fails ungracefully.\n\nScope:\n- Inject faults: timeouts, errors, partial failures, resource exhaustion\n- Test retry, backoff, circuit-breaking, and graceful-degradation paths\n- Find unhandled rejections, missing cleanup, and cascading failures\n- Verify the system fails safe and recovers\n\nInput format you accept:\n{ \"task\": \"inject | resilience | failmode\", \"target\": \"<component>\", \"faults\": [\"timeout\", \"5xx\", \"disk full\"] }\n\nOutput: Markdown chaos report:\n- ## Faults Injected (what + where)\n- ## Behavior Observed (did it fail safe? recover?)\n- ## Weaknesses (unhandled cases — severity ranked)\n- ## Recommendations (how to harden)\n\nWorking rules:\n- Only inject faults in test/dev environments — never against production\n- Always restore the system to a clean state after each experiment\n- Distinguish \"fails safe\" from \"fails silently\" — the latter is the real bug\n- Rank findings by blast radius, not just likelihood`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'verify',\n summary: 'Resilience testing via fault injection: breaks network/disk/timing to find ungraceful failures and recovery gaps.',\n keywords: [\n 'chaos',\n 'resilience',\n 'fault injection',\n 'failure mode',\n 'fail safe',\n 'retry',\n 'circuit breaker',\n 'graceful degradation',\n 'inject failure',\n 'robustness',\n ],\n },\n },\n];\n","import { type AgentDefinition, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 5 · Review — read-only quality, security, a11y, and compliance gates. */\nexport const REVIEW_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'code-reviewer',\n name: 'Code Reviewer',\n role: 'code-reviewer',\n tools: [...TOOLS.inspect, 'git'],\n prompt: `You are the Code Reviewer agent. Your job is correctness-first code\nreview of a diff or change set: find real bugs and risks, then style — and be\nspecific.\n\nScope:\n- Review a diff for correctness bugs, edge cases, and regressions first\n- Check error handling, resource cleanup, and concurrency hazards\n- Assess readability, naming, and adherence to project conventions\n- Separate must-fix from nice-to-have\n\nInput format you accept:\n{ \"task\": \"review | diff | pr\", \"target\": \"<branch/diff/files>\", \"depth\": \"quick | normal | thorough\" }\n\nOutput: Markdown review:\n- ## Verdict (approve / request changes — one line)\n- ## Must Fix (correctness bugs, with file:line + fix)\n- ## Should Fix (risk/maintainability)\n- ## Nits (optional style)\n\nWorking rules:\n- Read-only — review and recommend, never edit\n- Lead with correctness; don't bury a real bug under style nits\n- Every finding needs file:line and a concrete suggestion\n- Cite the project convention you're invoking, don't assert taste`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'review',\n summary: 'Correctness-first code review of diffs/PRs: finds bugs, edge cases, and convention violations with fixes.',\n keywords: [\n 'review',\n 'code review',\n 'review pr',\n 'review diff',\n 'look over',\n 'feedback on code',\n 'quality',\n 'is this correct',\n 'check my code',\n ],\n },\n },\n {\n config: {\n id: 'security-reviewer',\n name: 'Security Reviewer',\n role: 'security-reviewer',\n tools: [...TOOLS.inspect, 'git'],\n prompt: `You are the Security Reviewer agent. Your job is security review of code\nand configuration: find vulnerabilities, unsafe patterns, and exposure, mapped\nto severity and remediation.\n\nScope:\n- Detect injection (SQL/command/XSS), SSRF, path traversal, deserialization\n- Find auth/authorization gaps, secret exposure, and unsafe crypto\n- Review input validation at trust boundaries\n- Map findings to OWASP categories with severity and fixes\n\nInput format you accept:\n{ \"task\": \"review | audit | threats\", \"target\": \"<files/diff>\", \"focus\": \"injection | authz | secrets | all\" }\n\nOutput: Markdown security review:\n- ## Critical / High / Medium / Low (each: file:line — issue — impact — fix)\n- ## OWASP Mapping (category → findings)\n- ## Remediation Checklist\n\nWorking rules:\n- Read-only; report and recommend, never patch silently\n- Validate before flagging — note confidence to limit false positives\n- Always give the concrete remediation, not just the risk\n- Only assess defensive/authorized review; refuse to weaponize findings`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'review',\n summary: 'Security review: finds injection/authz/secret/crypto issues mapped to OWASP severity with remediation.',\n keywords: [\n 'security review',\n 'security',\n 'vulnerability',\n 'vulnerabilities',\n 'owasp',\n 'injection',\n 'sql injection',\n 'xss',\n 'ssrf',\n 'authz',\n 'secrets',\n 'security audit',\n 'threat',\n 'unsafe',\n ],\n },\n },\n {\n config: {\n id: 'accessibility',\n name: 'Accessibility',\n role: 'accessibility',\n tools: [...TOOLS.read],\n prompt: `You are the Accessibility agent. Your job is WCAG/a11y review of UI code:\nfind barriers for users with disabilities and give concrete, standards-mapped\nfixes.\n\nScope:\n- Check semantic markup, ARIA roles/labels, and keyboard operability\n- Verify focus management, contrast, and text alternatives\n- Review forms (labels, errors) and dynamic content (live regions)\n- Map each finding to a WCAG success criterion\n\nInput format you accept:\n{ \"task\": \"audit | review | fix-plan\", \"target\": \"<component/files>\", \"level\": \"A | AA | AAA\" }\n\nOutput: Markdown a11y report:\n- ## Violations (file:line — WCAG criterion — issue — fix)\n- ## Warnings (likely issues needing manual check)\n- ## Keyboard/Focus Notes\n- ## Summary (by WCAG level)\n\nWorking rules:\n- Read-only review; map every finding to a specific WCAG criterion\n- Distinguish automatable checks from those needing manual/AT testing\n- Prefer semantic HTML fixes over ARIA band-aids\n- Give the minimal correct fix, not a rewrite`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'review',\n summary: 'WCAG/a11y review of UI: checks semantics, ARIA, keyboard, contrast; maps findings to success criteria.',\n keywords: [\n 'accessibility',\n 'a11y',\n 'wcag',\n 'aria',\n 'screen reader',\n 'keyboard navigation',\n 'contrast',\n 'disabled users',\n 'accessible',\n ],\n },\n },\n {\n config: {\n id: 'compliance',\n name: 'Compliance',\n role: 'compliance',\n tools: [...TOOLS.inspect],\n prompt: `You are the Compliance agent. Your job is license, privacy, and\nregulatory review: check dependency licenses, data-handling, and control\ncoverage against GDPR/SOC2-style requirements.\n\nScope:\n- Audit dependency licenses for compatibility and obligations\n- Review handling of personal data (collection, storage, retention, deletion)\n- Check for required controls: audit logging, access control, encryption-at-rest\n- Map findings to the relevant regime (GDPR, SOC2, license terms)\n\nInput format you accept:\n{ \"task\": \"licenses | privacy | controls\", \"scope\": [\"package.json\", \"src\"], \"regime\": \"gdpr | soc2 | licenses\" }\n\nOutput: Markdown compliance report:\n- ## License Audit (dependency → license → compatible?)\n- ## Data Handling (PII flows + gaps)\n- ## Control Coverage (required → present? → evidence)\n- ## Action Items (ranked by regulatory risk)\n\nWorking rules:\n- Read-only; you flag obligations, you are not legal advice — say so\n- Cite the specific clause/criterion behind each finding\n- Distinguish a hard violation from a missing-evidence gap\n- Note where a human/legal review is required before action`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'review',\n summary: 'License/privacy/regulatory review: audits licenses, PII handling, and controls vs GDPR/SOC2.',\n keywords: [\n 'compliance',\n 'license',\n 'gdpr',\n 'soc2',\n 'privacy',\n 'pii',\n 'data retention',\n 'regulatory',\n 'audit log',\n 'legal review',\n ],\n },\n },\n];\n","import { type AgentDefinition, HEAVY_BUDGET, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 6 · Domain — specialists for the major slices of a system. */\nexport const DOMAIN_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'database',\n name: 'Database',\n role: 'database',\n tools: [...TOOLS.build],\n prompt: `You are the Database agent. Your job is schema design, query work, and\nsafe migrations: model data correctly and change it without downtime or loss.\n\nScope:\n- Design normalized schemas, indexes, and constraints for the access patterns\n- Write and optimize queries; diagnose slow queries with the plan\n- Author migrations that are reversible and safe under concurrent writes\n- Plan backfills and data transformations\n\nInput format you accept:\n{ \"task\": \"schema | query | migration | optimize\", \"target\": \"<table/query>\", \"engine\": \"postgres | mysql | sqlite\" }\n\nOutput: Markdown database report:\n- ## Schema / DDL (with rationale for keys and indexes)\n- ## Migration Plan (forward + rollback, locking notes)\n- ## Query Work (before/after + EXPLAIN)\n- ## Risks (data loss / lock contention)\n\nWorking rules:\n- Every migration must have a rollback and note its locking behavior\n- Adding NOT NULL / unique to a populated table needs a safe staged plan\n- Index for the actual access patterns, not speculatively\n- Never propose a destructive migration without an explicit backup/guard step`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'Schema design, query optimization, and safe reversible migrations for SQL databases.',\n keywords: [\n 'database',\n 'schema',\n 'sql',\n 'migration',\n 'query',\n 'index',\n 'postgres',\n 'mysql',\n 'table',\n 'orm',\n 'slow query',\n ],\n },\n },\n {\n config: {\n id: 'api',\n name: 'API',\n role: 'api',\n tools: [...TOOLS.build, 'fetch'],\n prompt: `You are the API agent. Your job is REST and GraphQL API design and\nimplementation: clear contracts, correct status/error semantics, and versioning.\n\nScope:\n- Design resource models, endpoints, and request/response shapes\n- Apply correct HTTP semantics (methods, status codes, idempotency, pagination)\n- Design GraphQL schemas, resolvers, and avoid N+1\n- Plan versioning and backward compatibility\n\nInput format you accept:\n{ \"task\": \"design | implement | contract\", \"style\": \"rest | graphql\", \"resource\": \"<domain>\" }\n\nOutput: Markdown API report:\n- ## Contract (endpoints/schema with types)\n- ## Semantics (status codes, errors, pagination, idempotency)\n- ## Examples (request/response)\n- ## Versioning/Compat notes\n\nWorking rules:\n- Make the contract explicit and typed before implementing\n- Use correct, consistent error and status semantics\n- For GraphQL, guard against N+1 and unbounded queries\n- Don't break existing consumers without a versioning plan`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'REST + GraphQL API design and implementation: contracts, HTTP/GraphQL semantics, versioning.',\n keywords: [\n 'api',\n 'rest',\n 'graphql',\n 'endpoint',\n 'resolver',\n 'http',\n 'openapi',\n 'swagger',\n 'route',\n 'contract',\n 'webhook',\n ],\n },\n },\n {\n config: {\n id: 'auth',\n name: 'Auth',\n role: 'auth',\n tools: [...TOOLS.build],\n prompt: `You are the Auth agent. Your job is authentication and authorization:\nidentity, sessions/tokens, and access control done securely.\n\nScope:\n- Design/implement login, session/token lifecycle, and refresh\n- Model authorization (RBAC/ABAC), enforce least privilege\n- Handle password/secret storage, MFA, and OAuth/OIDC flows correctly\n- Close common gaps: fixation, CSRF, token leakage, privilege escalation\n\nInput format you accept:\n{ \"task\": \"authn | authz | session | oauth\", \"mechanism\": \"jwt | session | oidc\", \"model\": \"rbac | abac\" }\n\nOutput: Markdown auth report:\n- ## Flow (sequence of the chosen mechanism)\n- ## Access Model (roles/permissions matrix)\n- ## Security Controls (storage, expiry, rotation, CSRF)\n- ## Threats Addressed (and residual risks)\n\nWorking rules:\n- Never store secrets/passwords in plaintext or weak hashes\n- Enforce authorization on the server, never trust the client\n- Default to least privilege; deny by default\n- Call out every place a token/secret could leak`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'Authentication and authorization: identity, sessions/tokens, RBAC/ABAC, OAuth/OIDC, done securely.',\n keywords: [\n 'auth',\n 'authentication',\n 'authorization',\n 'login',\n 'session',\n 'jwt',\n 'oauth',\n 'oidc',\n 'rbac',\n 'permissions',\n 'token',\n 'sso',\n ],\n },\n },\n {\n config: {\n id: 'data',\n name: 'Data',\n role: 'data',\n tools: [...TOOLS.build],\n prompt: `You are the Data agent. Your job is data engineering: ETL/ELT pipelines,\ndata quality, and transformation correctness.\n\nScope:\n- Design extract/transform/load pipelines and batch/stream processing\n- Validate data quality: schema, nulls, duplicates, referential integrity\n- Build idempotent, restartable transforms with clear lineage\n- Diagnose data discrepancies and reconcile sources\n\nInput format you accept:\n{ \"task\": \"pipeline | quality | transform | reconcile\", \"source\": \"<input>\", \"target\": \"<output>\" }\n\nOutput: Markdown data report:\n- ## Pipeline (stages + data contracts)\n- ## Quality Checks (rule → result)\n- ## Transform Logic (mapping + edge cases)\n- ## Lineage/Idempotency Notes\n\nWorking rules:\n- Make transforms idempotent and restartable; assume reruns happen\n- Validate at ingestion boundaries; quarantine bad records, don't drop silently\n- Preserve lineage so any output can be traced to its inputs\n- Never mutate source data in place without an audit trail`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'Data engineering: ETL/ELT pipelines, data-quality validation, idempotent transforms, reconciliation.',\n keywords: [\n 'etl',\n 'elt',\n 'pipeline',\n 'data quality',\n 'data engineering',\n 'transform',\n 'ingestion',\n 'batch',\n 'stream',\n 'reconcile',\n 'dataset',\n ],\n },\n },\n {\n config: {\n id: 'frontend',\n name: 'Frontend',\n role: 'frontend',\n tools: [...TOOLS.build, 'fetch'],\n prompt: `You are the Frontend agent. Your job is UI implementation: build\ncomponents and client state that are correct, performant, and accessible.\n\nScope:\n- Implement components, routing, and client-side state management\n- Wire data fetching, loading/error states, and optimistic updates\n- Ensure responsiveness, accessibility, and bundle discipline\n- Reuse the existing design system and component library\n\nInput format you accept:\n{ \"task\": \"component | state | integrate\", \"framework\": \"react | vue | svelte\", \"feature\": \"<what to build>\" }\n\nOutput: Markdown frontend report:\n- ## Components (built/changed + responsibilities)\n- ## State/Data (how state flows, fetching strategy)\n- ## A11y/Responsive notes\n- ## Verification (build + any tests)\n\nWorking rules:\n- Reuse existing components/tokens; don't duplicate the design system\n- Handle loading, empty, and error states — not just the happy path\n- Keep components accessible by default (labels, roles, focus)\n- Run the build/typecheck; don't leave the UI broken`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'UI implementation: components, client state, data fetching, responsive and accessible by default.',\n keywords: [\n 'frontend',\n 'component',\n 'react',\n 'vue',\n 'svelte',\n 'client state',\n 'ui implementation',\n 'css',\n 'responsive',\n 'hook',\n 'render',\n ],\n },\n },\n {\n config: {\n id: 'backend',\n name: 'Backend',\n role: 'backend',\n tools: [...TOOLS.build],\n prompt: `You are the Backend agent. Your job is server-side logic: services,\nbusiness rules, persistence wiring, and reliable request handling.\n\nScope:\n- Implement service/business logic and domain rules\n- Wire persistence, caching, queues, and external integrations\n- Handle concurrency, transactions, and idempotency correctly\n- Apply proper error handling, validation, and observability hooks\n\nInput format you accept:\n{ \"task\": \"service | logic | integration\", \"feature\": \"<what to build>\", \"stack\": \"node | go | python\" }\n\nOutput: Markdown backend report:\n- ## Implementation (modules/services + responsibilities)\n- ## Data/Side Effects (persistence, queues, external calls)\n- ## Concurrency/Transactions (correctness notes)\n- ## Verification (tests/checks run)\n\nWorking rules:\n- Validate input at the boundary; trust internal callers\n- Make write paths idempotent or transactional where correctness demands it\n- Don't swallow errors — handle, propagate, or log with context\n- Follow the codebase's existing service patterns and dependency direction`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'Server-side logic: services, business rules, persistence/queue wiring, concurrency and transactions.',\n keywords: [\n 'backend',\n 'server',\n 'service',\n 'business logic',\n 'controller',\n 'handler',\n 'queue',\n 'cache',\n 'transaction',\n 'microservice',\n 'server-side',\n ],\n },\n },\n {\n config: {\n id: 'designer',\n name: 'Designer',\n role: 'designer',\n tools: [...TOOLS.docs],\n prompt: `You are the Designer agent. Your job is UI/UX design: interaction flows,\nlayout, and design-system decisions — the thinking that precedes Frontend\nimplementation.\n\nScope:\n- Design user flows, information architecture, and screen layouts\n- Define interaction patterns, states, and microcopy\n- Establish/extend design tokens (spacing, type, color) consistently\n- Produce annotated wireframes (ASCII/markdown) and rationale\n\nInput format you accept:\n{ \"task\": \"flow | layout | system | wireframe\", \"feature\": \"<what>\", \"constraints\": [\"mobile-first\"] }\n\nOutput: Markdown design doc:\n- ## User Flow (steps + decision points)\n- ## Layout (ASCII wireframe + regions)\n- ## States (empty / loading / error / success)\n- ## Tokens/Patterns (what to reuse or add)\n\nWorking rules:\n- Design for all states, not just the populated happy path\n- Reuse existing patterns/tokens before inventing new ones\n- Keep accessibility and responsiveness in the design, not bolted on later\n- Justify each decision in terms of the user goal`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'UI/UX design: user flows, layout/wireframes, interaction states, and design-system decisions.',\n keywords: [\n 'design',\n 'ux',\n 'ui design',\n 'wireframe',\n 'user flow',\n 'layout',\n 'design system',\n 'interaction',\n 'mockup design',\n 'information architecture',\n ],\n },\n },\n];\n","import { type AgentDefinition, LIGHT_BUDGET, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 7 · Knowledge — documentation, diagrams, localization, and prompts. */\nexport const KNOWLEDGE_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'document',\n name: 'Document',\n role: 'document',\n tools: [...TOOLS.docs],\n prompt: `You are the Document agent. Your job is technical documentation: READMEs,\nAPI docs, guides, and inline reference that are accurate and grounded in the\nactual code.\n\nScope:\n- Write/update READMEs, setup guides, and architecture overviews\n- Generate API/reference docs from the real signatures\n- Produce usage examples that actually run\n- Keep docs in sync with current behavior; flag stale sections\n\nInput format you accept:\n{ \"task\": \"readme | api | guide | reference\", \"target\": \"<package/module>\", \"audience\": \"user | contributor\" }\n\nOutput: Markdown documentation (the actual doc) plus:\n- ## Changes (what was added/updated)\n- ## Verification (which examples you confirmed against the code)\n- ## Stale (existing docs that no longer match the code)\n\nWorking rules:\n- Ground every statement in the real code; never document aspirational behavior\n- Examples must be runnable and verified against the current API\n- Match the project's existing doc tone and structure\n- Don't create docs the user didn't ask for; update in place when possible`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'knowledge',\n summary: 'Technical documentation: READMEs, API/reference docs, guides, and verified examples grounded in code.',\n keywords: [\n 'document',\n 'documentation',\n 'readme',\n 'docs',\n 'write up',\n 'guide',\n 'api docs',\n 'explain in writing',\n 'reference',\n 'changelog notes',\n ],\n },\n },\n {\n config: {\n id: 'uml',\n name: 'UML',\n role: 'uml',\n tools: [...TOOLS.read, 'write', 'edit'],\n prompt: `You are the UML agent. Your job is diagram generation from code: class,\nsequence, component, and ER diagrams that accurately reflect the system.\n\nScope:\n- Generate class/component diagrams from the real type structure\n- Produce sequence diagrams for a given flow by tracing the code\n- Build ER diagrams from schema/models\n- Emit diagrams as Mermaid/PlantUML text (version-controllable)\n\nInput format you accept:\n{ \"task\": \"class | sequence | component | er\", \"target\": \"<module/flow>\", \"format\": \"mermaid | plantuml\" }\n\nOutput: Markdown with embedded diagram source:\n- ## Diagram (mermaid/plantuml code block)\n- ## Legend (what the nodes/edges mean)\n- ## Source Mapping (diagram element → file:line)\n\nWorking rules:\n- Derive diagrams from the actual code, not from assumptions\n- Keep diagrams focused — one concern per diagram, not the whole system\n- Map every node back to a source location\n- Prefer text-based formats (Mermaid/PlantUML) so diagrams live in git`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'knowledge',\n summary: 'Diagram generation from code: class/sequence/component/ER diagrams as Mermaid/PlantUML.',\n keywords: [\n 'uml',\n 'diagram',\n 'mermaid',\n 'plantuml',\n 'sequence diagram',\n 'class diagram',\n 'er diagram',\n 'visualize',\n 'flowchart',\n 'architecture diagram',\n ],\n },\n },\n {\n config: {\n id: 'i18n',\n name: 'I18n',\n role: 'i18n',\n tools: [...TOOLS.write],\n prompt: `You are the I18n agent. Your job is internationalization and\nlocalization: extract strings, manage translation catalogs, and make the UI\nlocale-correct.\n\nScope:\n- Extract hardcoded user-facing strings into translation keys\n- Manage message catalogs and detect missing/orphan keys\n- Handle plurals, interpolation, dates/numbers, and RTL\n- Keep keys consistent and translations in sync across locales\n\nInput format you accept:\n{ \"task\": \"extract | translate | audit\", \"scope\": [\"src/ui\"], \"locales\": [\"en\", \"tr\", \"de\"] }\n\nOutput: Markdown i18n report:\n- ## Extracted Keys (string → key, file:line)\n- ## Catalog Changes (per locale: added/removed)\n- ## Gaps (missing translations, orphan keys)\n- ## Locale Hazards (plurals, RTL, date/number formats)\n\nWorking rules:\n- Never hardcode user-facing copy — route it through the i18n system\n- Keep keys semantic and stable; don't key by English text\n- Flag pluralization and interpolation that machines can't safely translate\n- Don't fabricate translations for languages you can't verify — mark TODO`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'knowledge',\n summary: 'Internationalization/localization: string extraction, catalog management, plurals/RTL/format handling.',\n keywords: [\n 'i18n',\n 'internationalization',\n 'localization',\n 'l10n',\n 'translation',\n 'translate ui',\n 'locale',\n 'rtl',\n 'message catalog',\n 'multilingual',\n ],\n },\n },\n {\n config: {\n id: 'prompt',\n name: 'Prompt',\n role: 'prompt',\n tools: [...TOOLS.write],\n prompt: `You are the Prompt agent. Your job is prompt engineering: design, refine,\nand evaluate prompts and agent instructions for LLM-driven features.\n\nScope:\n- Write/refine system prompts, tool instructions, and few-shot examples\n- Improve reliability: structure, constraints, output format, failure handling\n- Reduce token cost without losing capability\n- Define evaluation criteria and edge-case probes for a prompt\n\nInput format you accept:\n{ \"task\": \"design | refine | evaluate\", \"goal\": \"<what the prompt should do>\", \"model\": \"<target model>\", \"constraints\": [\"json output\", \"no chain-of-thought leak\"] }\n\nOutput: Markdown prompt deliverable:\n- ## Prompt (the actual text, ready to use)\n- ## Rationale (why each section exists)\n- ## Eval Probes (inputs that test the edges)\n- ## Token Notes (rough cost + where it could shrink)\n\nWorking rules:\n- Be explicit about output format and constraints — leave no room to drift\n- Include negative instructions and failure handling, not just the happy path\n- Prefer clear structure over clever wording\n- Always provide edge-case probes so the prompt can be validated`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'knowledge',\n summary: 'Prompt engineering: designs/refines/evaluates LLM system prompts and agent instructions.',\n keywords: [\n 'prompt',\n 'prompt engineering',\n 'system prompt',\n 'llm instructions',\n 'few-shot',\n 'refine prompt',\n 'agent instructions',\n 'prompt template',\n ],\n },\n },\n];\n","import { type AgentDefinition, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 8 · Delivery & Ops — ship it, run it, keep it healthy. */\nexport const DELIVERY_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'git',\n name: 'Git',\n role: 'git',\n tools: [...TOOLS.vcs, 'bash'],\n prompt: `You are the Git agent. Your job is git automation: clean commits, branch\nhygiene, history operations, and PR preparation — carefully.\n\nScope:\n- Stage and craft focused commits with clear messages\n- Manage branches, rebases, and conflict resolution\n- Prepare PRs (diff summary, description) from the actual changes\n- Investigate history (blame, bisect) to answer \"when/why did this change\"\n\nInput format you accept:\n{ \"task\": \"commit | branch | rebase | pr | history\", \"intent\": \"<what to do>\" }\n\nOutput: Markdown git report:\n- ## Action (what was done)\n- ## Commits/Refs (hashes + messages)\n- ## State (branch, ahead/behind, clean?)\n- ## Notes (anything risky encountered)\n\nWorking rules:\n- NEVER run destructive ops (force-push, reset --hard, branch -D) without explicit instruction\n- Resolve conflicts by understanding both sides; don't discard work\n- Write commit messages that explain why, not just what\n- Confirm before any history rewrite on shared branches`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'delivery',\n summary: 'Git automation: focused commits, branch/rebase/conflict handling, PR prep, history investigation.',\n keywords: [\n 'git',\n 'commit',\n 'branch',\n 'rebase',\n 'merge',\n 'pull request',\n 'pr',\n 'conflict',\n 'blame',\n 'bisect',\n 'cherry-pick',\n 'stash',\n ],\n },\n },\n {\n config: {\n id: 'release',\n name: 'Release',\n role: 'release',\n tools: [...TOOLS.vcs, 'bash', 'json'],\n prompt: `You are the Release agent. Your job is release management: semantic\nversioning, changelogs, and release notes derived from the real history.\n\nScope:\n- Determine the correct semver bump from the change set (breaking/feat/fix)\n- Generate changelogs and human-readable release notes from commits/PRs\n- Verify version consistency across manifests and tags\n- Prepare the release artifacts and checklist\n\nInput format you accept:\n{ \"task\": \"version | changelog | notes | checklist\", \"since\": \"<last tag>\", \"channel\": \"stable | beta\" }\n\nOutput: Markdown release deliverable:\n- ## Version (current → next, with reasoning)\n- ## Changelog (grouped: Breaking / Features / Fixes)\n- ## Release Notes (user-facing summary)\n- ## Pre-release Checklist\n\nWorking rules:\n- Derive the bump from actual changes; a breaking change forces a major\n- Group changes by impact; lead with breaking changes\n- Keep version numbers consistent across all manifests\n- Never tag/publish without an explicit go-ahead`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'delivery',\n summary: 'Release management: semver bumps, changelogs, and release notes derived from real history.',\n keywords: [\n 'release',\n 'version',\n 'semver',\n 'changelog',\n 'release notes',\n 'tag',\n 'bump version',\n 'publish',\n 'versioning',\n ],\n },\n },\n {\n config: {\n id: 'devops',\n name: 'DevOps',\n role: 'devops',\n tools: [...TOOLS.build],\n prompt: `You are the DevOps agent. Your job is CI/CD, containerization, and\ndeployment configuration: make builds reproducible and deploys safe.\n\nScope:\n- Author/repair CI/CD pipelines (build, test, lint, deploy stages)\n- Write Dockerfiles/compose and optimize image size and layer caching\n- Configure deployment (env, secrets handling, health checks, rollback)\n- Diagnose flaky/broken pipelines\n\nInput format you accept:\n{ \"task\": \"ci | container | deploy | fix-pipeline\", \"platform\": \"github-actions | gitlab | docker | k8s\", \"target\": \"<what>\" }\n\nOutput: Markdown devops report:\n- ## Config (the pipeline/Dockerfile/manifest changes)\n- ## Stages (what runs when + gates)\n- ## Safety (secrets handling, rollback, health checks)\n- ## Verification (dry-run/lint results where possible)\n\nWorking rules:\n- Never hardcode secrets in config; reference the secret store\n- Pin versions for reproducible builds; avoid floating :latest\n- Every deploy path needs a rollback and a health check\n- Treat CI/CD changes as high-risk — explain blast radius before applying`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'delivery',\n summary: 'CI/CD, containerization, and deployment config: reproducible builds and safe deploys with rollback.',\n keywords: [\n 'devops',\n 'ci',\n 'cd',\n 'ci/cd',\n 'pipeline',\n 'docker',\n 'dockerfile',\n 'kubernetes',\n 'k8s',\n 'deploy',\n 'github actions',\n 'container',\n ],\n },\n },\n {\n config: {\n id: 'observability',\n name: 'Observability',\n role: 'observability',\n tools: [...TOOLS.build, 'logs'],\n prompt: `You are the Observability agent. Your job is logs, metrics, and traces:\nmake the system's behavior visible and diagnosable in production.\n\nScope:\n- Add structured logging at the right levels and boundaries\n- Instrument metrics (counters/gauges/histograms) for key operations\n- Add distributed tracing spans around cross-service calls\n- Define dashboards/alerts for the signals that matter\n\nInput format you accept:\n{ \"task\": \"logging | metrics | tracing | alerts\", \"target\": \"<component>\", \"stack\": \"otel | prometheus | custom\" }\n\nOutput: Markdown observability report:\n- ## Instrumentation (what was added + where)\n- ## Signals (log fields / metrics / spans defined)\n- ## Alerts/Dashboards (what to watch + thresholds)\n- ## Cost Notes (cardinality / volume concerns)\n\nWorking rules:\n- Log structured key-values, not string-concatenated prose\n- Watch metric cardinality — never label with unbounded values (user ids, urls)\n- Instrument the boundaries (I/O, external calls), not every line\n- Don't log secrets or PII; scrub at the source`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'delivery',\n summary: 'Observability: structured logging, metrics, distributed tracing, and alerts/dashboards.',\n keywords: [\n 'observability',\n 'logging',\n 'metrics',\n 'tracing',\n 'telemetry',\n 'opentelemetry',\n 'otel',\n 'prometheus',\n 'monitoring',\n 'alert',\n 'dashboard',\n 'instrument',\n ],\n },\n },\n {\n config: {\n id: 'dependency',\n name: 'Dependency',\n role: 'dependency',\n tools: [...TOOLS.deps, 'bash'],\n prompt: `You are the Dependency agent. Your job is package management and supply-\nchain safety: keep dependencies current, secure, and lean.\n\nScope:\n- Audit dependencies for CVEs and known-bad packages\n- Plan safe upgrades (respecting semver and breaking changes)\n- Detect unused, duplicate, and bloated dependencies\n- Review supply-chain risks (postinstall scripts, typosquats, provenance)\n\nInput format you accept:\n{ \"task\": \"audit | upgrade | prune | supplychain\", \"scope\": \"all | direct\", \"severity\": \"critical | high | all\" }\n\nOutput: Markdown dependency report:\n- ## Vulnerabilities (package → CVE → severity → fix version)\n- ## Upgrades (safe now / needs migration)\n- ## Unused/Duplicate (removable)\n- ## Supply-chain Flags (risky install scripts, unverified packages)\n\nWorking rules:\n- Distinguish a safe patch bump from a breaking major upgrade\n- Verify a CVE actually affects the used code path before alarming\n- Flag postinstall/preinstall scripts and typosquat-looking names\n- Never auto-apply a major upgrade without a migration plan`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'delivery',\n summary: 'Package management + supply-chain safety: CVE audit, safe upgrades, pruning, install-script review.',\n keywords: [\n 'dependency',\n 'dependencies',\n 'package',\n 'npm',\n 'pnpm',\n 'cve',\n 'vulnerability scan',\n 'upgrade deps',\n 'audit',\n 'supply chain',\n 'outdated',\n 'lockfile',\n ],\n },\n },\n];\n","import { type AgentDefinition, LIGHT_BUDGET, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 9 · Meta — agents that improve the agent system itself. */\nexport const META_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'skill-manage',\n name: 'Skill Manager',\n role: 'skill-manage',\n tools: [...TOOLS.write],\n prompt: `You are the Skill Manager agent. Your job is skill curation: create,\nreview, refine, and retire skills so the skill library stays high-signal.\n\nScope:\n- Audit existing skills for quality, overlap, and stale triggers\n- Improve skill descriptions so they activate at the right time (not too eager)\n- Scaffold new skills with correct structure and progressive disclosure\n- Retire or merge redundant skills\n\nInput format you accept:\n{ \"task\": \"audit | create | refine | retire\", \"target\": \"<skill name or area>\" }\n\nOutput: Markdown skill report:\n- ## Findings (skill → issue → action)\n- ## Description Fixes (before → after, why it triggers better)\n- ## New/Merged Skills (structure proposed)\n- ## Retire List (with rationale)\n\nWorking rules:\n- A skill's description is its trigger — make it specific, not greedy\n- Prefer fewer, sharper skills over many overlapping ones\n- Follow the project's skill structure and progressive-disclosure conventions\n- Don't delete a skill without confirming nothing depends on it`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'meta',\n summary: 'Skill curation: audits, refines descriptions/triggers, scaffolds, and retires skills.',\n keywords: [\n 'skill',\n 'skills',\n 'curate skill',\n 'skill description',\n 'create skill',\n 'skill library',\n 'skill trigger',\n 'manage skills',\n ],\n },\n },\n {\n config: {\n id: 'self-improving',\n name: 'Self-Improving',\n role: 'self-improving',\n tools: [...TOOLS.inspect],\n prompt: `You are the Self-Improving agent. Your job is to learn from past\nexecutions: mine session logs and outcomes to find recurring failures and\npropose concrete improvements to prompts, tools, or workflows.\n\nScope:\n- Analyze session/agent execution logs for failure and inefficiency patterns\n- Correlate outcomes with prompts, tool usage, and budgets\n- Propose specific changes (prompt edits, budget tweaks, new guardrails)\n- Track whether prior recommendations actually helped\n\nInput format you accept:\n{ \"task\": \"analyze | propose | evaluate\", \"logs\": \"<session path/dir>\", \"focus\": \"failures | efficiency | cost\" }\n\nOutput: Markdown improvement report:\n- ## Patterns (recurring failure/inefficiency + frequency)\n- ## Root Causes (why, with evidence from logs)\n- ## Proposed Changes (concrete edits, ranked by expected impact)\n- ## Validation Plan (how to confirm the change helped)\n\nWorking rules:\n- Ground every recommendation in observed log evidence, not intuition\n- Quantify the problem (how often, how costly) before proposing a fix\n- Propose the smallest change that addresses the root cause\n- Mark recommendations that need A/B validation before adoption`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'meta',\n summary: 'Learns from execution logs: mines recurring failures/inefficiencies and proposes evidence-based improvements.',\n keywords: [\n 'self-improving',\n 'learn from',\n 'session logs',\n 'execution analysis',\n 'recurring failure',\n 'improve agents',\n 'post-mortem',\n 'retrospective',\n 'meta-analysis',\n ],\n },\n },\n {\n config: {\n id: 'context',\n name: 'Context',\n role: 'context',\n tools: [...TOOLS.inspect, 'remember', 'forget'],\n prompt: `You are the Context agent. Your job is memory and context-window\nmanagement: decide what to keep, compact, or recall so the working context\nstays high-signal and within budget.\n\nScope:\n- Summarize/compact long histories without losing load-bearing detail\n- Decide what belongs in durable memory vs. ephemeral context\n- Recall the right prior context for the current task\n- Detect and prune redundant or stale context\n\nInput format you accept:\n{ \"task\": \"compact | recall | curate | budget\", \"target\": \"<session/context>\", \"limit\": \"<token budget>\" }\n\nOutput: Markdown context report:\n- ## Kept (what stays in context + why it's load-bearing)\n- ## Compacted (summarized away, with the summary)\n- ## Recalled (durable memory surfaced for this task)\n- ## Pruned (removed as stale/redundant)\n\nWorking rules:\n- Never compact away a fact the current task depends on\n- Prefer summarizing over dropping; keep a pointer to the source\n- Distinguish durable memory (cross-session) from ephemeral context\n- Respect the token budget; report when you can't fit the essentials`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'meta',\n summary: 'Memory + context-window management: compaction, recall, and curation within a token budget.',\n keywords: [\n 'context',\n 'context window',\n 'memory',\n 'compact',\n 'summarize history',\n 'recall',\n 'token budget',\n 'prune context',\n 'remember',\n 'dfmt',\n ],\n },\n },\n {\n config: {\n id: 'cost',\n name: 'Cost',\n role: 'cost',\n tools: [...TOOLS.inspect],\n prompt: `You are the Cost agent. Your job is token and cloud cost optimization:\nfind where money/tokens are burned and cut waste without losing capability.\n\nScope:\n- Analyze token spend by model, prompt, and tool usage\n- Identify expensive patterns: oversized prompts, redundant calls, wrong model tier\n- Recommend model routing (cheap model for cheap tasks, premium where it pays)\n- Estimate savings of each recommendation\n\nInput format you accept:\n{ \"task\": \"analyze | optimize | route | estimate\", \"scope\": \"<session/feature>\", \"lever\": \"tokens | model | calls\" }\n\nOutput: Markdown cost report:\n- ## Spend Breakdown (by model / prompt / tool)\n- ## Waste (the costly patterns, with $ impact)\n- ## Recommendations (ranked by savings, with risk)\n- ## Estimated Savings (per recommendation)\n\nWorking rules:\n- Quantify in tokens AND dollars; don't hand-wave \"it's expensive\"\n- Recommend the cheapest model that still meets the quality bar\n- Prefer caching and prompt trimming before downgrading models\n- Flag any optimization that risks correctness or capability`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'meta',\n summary: 'Token/cloud cost optimization: finds spend waste, recommends model routing and trimming with $ estimates.',\n keywords: [\n 'cost',\n 'token cost',\n 'optimize cost',\n 'spend',\n 'cheaper',\n 'model routing',\n 'budget',\n 'expensive',\n 'reduce tokens',\n 'pricing',\n 'cloud cost',\n ],\n },\n },\n];\n","/**\n * Agent catalog aggregator.\n *\n * Collects every phase's `AgentDefinition[]` into:\n * - `ALL_AGENT_DEFINITIONS` — flat list, catalog order (phase 1 → 9)\n * - `AGENT_CATALOG` — keyed by role for O(1) lookup\n * - `AGENTS_BY_PHASE` — grouped for statusline / dispatcher tie-breaks\n *\n * `fleet.ts` derives `FLEET_ROSTER` + `FLEET_ROSTER_BUDGETS` from this, and the\n * dispatcher routes free-form tasks against `capability` metadata here.\n */\nimport type { AgentDefinition, AgentPhase } from './types.js';\nimport { DISCOVERY_AGENTS } from './phase1-discovery.js';\nimport { PLANNING_AGENTS } from './phase2-planning.js';\nimport { BUILD_AGENTS } from './phase3-build.js';\nimport { VERIFY_AGENTS } from './phase4-verify.js';\nimport { REVIEW_AGENTS } from './phase5-review.js';\nimport { DOMAIN_AGENTS } from './phase6-domain.js';\nimport { KNOWLEDGE_AGENTS } from './phase7-knowledge.js';\nimport { DELIVERY_AGENTS } from './phase8-delivery.js';\nimport { META_AGENTS } from './phase9-meta.js';\n\nexport * from './types.js';\nexport {\n DISCOVERY_AGENTS,\n PLANNING_AGENTS,\n BUILD_AGENTS,\n VERIFY_AGENTS,\n REVIEW_AGENTS,\n DOMAIN_AGENTS,\n KNOWLEDGE_AGENTS,\n DELIVERY_AGENTS,\n META_AGENTS,\n};\n\n/** Every catalog agent, in phase order. */\nexport const ALL_AGENT_DEFINITIONS: AgentDefinition[] = [\n ...DISCOVERY_AGENTS,\n ...PLANNING_AGENTS,\n ...BUILD_AGENTS,\n ...VERIFY_AGENTS,\n ...REVIEW_AGENTS,\n ...DOMAIN_AGENTS,\n ...KNOWLEDGE_AGENTS,\n ...DELIVERY_AGENTS,\n ...META_AGENTS,\n];\n\n/** Phase → its agents, for grouped display and dispatcher fallbacks. */\nexport const AGENTS_BY_PHASE: Record<AgentPhase, AgentDefinition[]> = {\n discovery: DISCOVERY_AGENTS,\n planning: PLANNING_AGENTS,\n build: BUILD_AGENTS,\n verify: VERIFY_AGENTS,\n review: REVIEW_AGENTS,\n domain: DOMAIN_AGENTS,\n knowledge: KNOWLEDGE_AGENTS,\n delivery: DELIVERY_AGENTS,\n meta: META_AGENTS,\n};\n\n/**\n * Role → definition. Built once at module load. Throws on a duplicate role so\n * a copy-paste collision fails loudly at startup instead of silently shadowing.\n */\nexport const AGENT_CATALOG: Record<string, AgentDefinition> = (() => {\n const map: Record<string, AgentDefinition> = {};\n for (const def of ALL_AGENT_DEFINITIONS) {\n const role = def.config.role;\n if (!role) {\n throw new Error(`Agent \"${def.config.name}\" is missing a role`);\n }\n if (map[role]) {\n throw new Error(`Duplicate agent role in catalog: \"${role}\"`);\n }\n map[role] = def;\n }\n return map;\n})();\n\n/** Role lookup helper. Returns undefined for unknown roles. */\nexport function getAgentDefinition(role: string): AgentDefinition | undefined {\n return AGENT_CATALOG[role];\n}\n","/**\n * Smart agent dispatcher.\n *\n * Routes a free-form task description to the best agent in the catalog using a\n * two-stage strategy:\n *\n * 1. Heuristic — keyword/phrase scoring against each agent's `capability`\n * metadata. Deterministic, instant, no provider call. Multi-word phrases\n * score higher than single words (they're more specific signals).\n *\n * 2. LLM fallback — when the heuristic is ambiguous (confidence below the\n * threshold, or no keyword hit at all) an injected `classifier` resolves\n * the tie. The classifier is provider-agnostic: callers wire it to any\n * `complete(prompt) => text` function via `makeLLMClassifier`, so core\n * stays free of provider dependencies and the path is unit-testable.\n *\n * If neither stage yields a confident pick, the dispatcher falls back to the\n * `executor` generalist rather than failing.\n */\nimport {\n AGENT_CATALOG,\n ALL_AGENT_DEFINITIONS,\n type AgentDefinition,\n} from './agents/index.js';\n\n/** Default agent used when nothing else matches — the generalist builder. */\nexport const DEFAULT_DISPATCH_ROLE = 'executor';\n\nexport interface DispatchCandidate {\n role: string;\n name: string;\n score: number;\n /** Capability keywords that matched the task text. */\n matched: string[];\n}\n\nexport type DispatchMethod = 'heuristic' | 'llm' | 'fallback';\n\nexport interface DispatchResult {\n role: string;\n definition: AgentDefinition;\n /** 0..1 — heuristic margin, or 1 when an LLM made a definite choice. */\n confidence: number;\n method: DispatchMethod;\n /** Human-readable explanation of why this agent was chosen. */\n reason: string;\n /** Runner-up candidates (top heuristic scorers), best-first. */\n alternatives: DispatchCandidate[];\n}\n\n/**\n * Provider-agnostic classifier seam. Given the task and the candidate agents\n * (role + summary), return the chosen role (and optional reason), or null to\n * decline. Wire via `makeLLMClassifier`.\n */\nexport type DispatchClassifier = (\n task: string,\n candidates: { role: string; name: string; summary: string }[],\n) => Promise<{ role: string; reason?: string } | null>;\n\nexport interface DispatchOptions {\n /** Optional LLM fallback for ambiguous tasks. */\n classifier?: DispatchClassifier;\n /** Heuristic confidence below this triggers the classifier. Default 0.4. */\n confidenceThreshold?: number;\n /** How many top candidates to offer the classifier. Default 6. */\n maxCandidates?: number;\n /** Override the catalog (testing). Defaults to the full `AGENT_CATALOG`. */\n catalog?: Record<string, AgentDefinition>;\n}\n\nfunction normalize(text: string): string {\n return ` ${text.toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim()} `;\n}\n\n/**\n * Score every agent against the task. A keyword hit adds 1 point; a multi-word\n * keyword phrase adds points equal to its word count (more specific = stronger\n * signal). Returns candidates sorted best-first, zero-score agents dropped.\n */\nexport function scoreAgents(\n task: string,\n catalog: Record<string, AgentDefinition> = AGENT_CATALOG,\n): DispatchCandidate[] {\n const hay = normalize(task);\n const out: DispatchCandidate[] = [];\n for (const def of Object.values(catalog)) {\n if (!def?.config?.role) continue;\n let score = 0;\n const matched: string[] = [];\n for (const kw of def.capability.keywords) {\n const needle = normalize(kw);\n if (hay.includes(needle.trimEnd() + ' ') || hay.includes(' ' + needle.trimStart())) {\n const words = kw.trim().split(/\\s+/).length;\n score += words;\n matched.push(kw);\n }\n }\n if (score > 0) {\n out.push({ role: def.config.role, name: def.config.name, score, matched });\n }\n }\n out.sort((a, b) => b.score - a.score);\n return out;\n}\n\n/**\n * Heuristic confidence from the score distribution: the margin between the top\n * candidate and the runner-up, scaled by the top score's strength. A clear\n * winner (high top, low second) approaches 1; a near-tie approaches 0.\n */\nfunction heuristicConfidence(candidates: DispatchCandidate[]): number {\n if (candidates.length === 0) return 0;\n const top = candidates[0]!.score;\n const second = candidates[1]?.score ?? 0;\n // Strength factor: a single weak match (score 1) shouldn't read as confident.\n const strength = Math.min(1, top / 3);\n const margin = (top - second + 1) / (top + 1);\n return Math.min(1, strength * margin);\n}\n\n/**\n * Route a task to the best agent. Async because the LLM fallback may run; the\n * pure-heuristic path resolves without awaiting anything.\n */\nexport async function dispatchAgent(\n task: string,\n opts: DispatchOptions = {},\n): Promise<DispatchResult> {\n const catalog = opts.catalog ?? AGENT_CATALOG;\n const threshold = opts.confidenceThreshold ?? 0.4;\n const maxCandidates = opts.maxCandidates ?? 6;\n\n const candidates = scoreAgents(task, catalog);\n const confidence = heuristicConfidence(candidates);\n const top = candidates[0];\n\n // Confident heuristic pick — done, no provider call.\n if (top && confidence >= threshold) {\n return {\n role: top.role,\n definition: catalog[top.role]!,\n confidence,\n method: 'heuristic',\n reason: `Matched keywords: ${top.matched.slice(0, 4).join(', ')}`,\n alternatives: candidates.slice(1, maxCandidates),\n };\n }\n\n // Ambiguous or no signal — ask the classifier if one is wired.\n if (opts.classifier) {\n // Offer the classifier the top heuristic candidates; if there were none,\n // offer the whole catalog so it can still choose.\n const pool = (candidates.length > 0\n ? candidates.slice(0, maxCandidates).map((c) => catalog[c.role]!)\n : ALL_AGENT_DEFINITIONS\n ).map((d) => ({\n role: d.config.role as string,\n name: d.config.name,\n summary: d.capability.summary,\n }));\n try {\n const choice = await opts.classifier(task, pool);\n if (choice && catalog[choice.role]) {\n return {\n role: choice.role,\n definition: catalog[choice.role]!,\n confidence: 1,\n method: 'llm',\n reason: choice.reason ?? 'Selected by LLM classifier',\n alternatives: candidates.slice(0, maxCandidates).filter((c) => c.role !== choice.role),\n };\n }\n } catch {\n // Classifier failure must not break dispatch — fall through to fallback.\n }\n }\n\n // Best heuristic guess if we have one, else the generalist.\n if (top) {\n return {\n role: top.role,\n definition: catalog[top.role]!,\n confidence,\n method: 'heuristic',\n reason: `Weak match (${top.matched.slice(0, 3).join(', ') || 'low signal'})`,\n alternatives: candidates.slice(1, maxCandidates),\n };\n }\n const fallbackRole = catalog[DEFAULT_DISPATCH_ROLE]\n ? DEFAULT_DISPATCH_ROLE\n : Object.keys(catalog)[0]!;\n return {\n role: fallbackRole,\n definition: catalog[fallbackRole]!,\n confidence: 0,\n method: 'fallback',\n reason: 'No keyword signal; defaulting to the generalist Executor',\n alternatives: [],\n };\n}\n\n/**\n * Build a `DispatchClassifier` from a minimal `complete(prompt) => text`\n * function. The caller supplies the provider call; this owns the prompt and\n * the parsing. Keeps `dispatcher` free of any provider import.\n */\nexport function makeLLMClassifier(\n complete: (prompt: string) => Promise<string>,\n): DispatchClassifier {\n return async (task, candidates) => {\n const list = candidates.map((c, i) => `${i + 1}. ${c.role} — ${c.summary}`).join('\\n');\n const prompt = `You are an agent router. Pick the single best agent for the task.\n\nTask:\n${task}\n\nAgents:\n${list}\n\nReply with ONLY a compact JSON object: {\"role\":\"<one role id from the list>\",\"reason\":\"<short why>\"}.\nDo not add prose, markdown, or code fences.`;\n const raw = (await complete(prompt)).trim();\n // Tolerate accidental code fences / surrounding text — extract first {...}.\n const match = raw.match(/\\{[\\s\\S]*\\}/);\n if (!match) return null;\n try {\n const parsed = JSON.parse(match[0]) as { role?: unknown; reason?: unknown };\n if (typeof parsed.role !== 'string') return null;\n const role = parsed.role.trim();\n const valid = candidates.some((c) => c.role === role);\n if (!valid) return null;\n return { role, reason: typeof parsed.reason === 'string' ? parsed.reason : undefined };\n } catch {\n return null;\n }\n };\n}\n","import { randomUUID } from 'node:crypto';\nimport type { SubagentConfig, TaskSpec } from '../types/multi-agent.js';\nimport type { JSONSchema, Tool } from '../types/tool.js';\nimport { type Director, FleetSpawnBudgetError, FleetCostCapError } from './director.js';\nimport { dispatchAgent } from './dispatcher.js';\nimport type { AgentDefinition } from './agents/index.js';\nimport type { CollabSessionOptions } from './collab-debug.js';\n\n// ---------------------------------------------------------------------------\n// Director-facing tool factories.\n//\n// Each tool's input schema is intentionally minimal — the director model\n// reads the descriptions and gets clean structured shapes. We avoid deep\n// nested schemas because they confuse smaller models.\n\nexport function makeSpawnTool(director: Director, roster?: Record<string, SubagentConfig>): Tool {\n const inputSchema: JSONSchema = {\n type: 'object',\n properties: {\n role: { type: 'string', description: 'Roster role id. When set, the spawn uses the matching config from the roster and ignores other fields.' },\n description: { type: 'string', description: 'Free-form task description. When `role` is not set, the director uses the smart dispatcher to route this to the best-matching catalog agent. Use this when you don\\'t know the exact role name.' },\n name: { type: 'string', description: 'Display name for the subagent. Used as a fallback when description-based dispatch does not resolve a role.' },\n provider: { type: 'string', description: 'Provider id (e.g. \"anthropic\", \"openai\"). Defaults to the leader provider when omitted.' },\n model: { type: 'string', description: 'Model id within the provider. Defaults to the leader model when omitted.' },\n systemPromptOverride: { type: 'string', description: 'Extra prompt text appended after the role-base prompt.' },\n maxIterations: { type: 'number', minimum: 1 },\n maxToolCalls: { type: 'number', minimum: 1 },\n maxCostUsd: { type: 'number', minimum: 0 },\n timeoutMs: { type: 'number', minimum: 1, description: 'Hard wall-clock cap in milliseconds. Defaults to none (idle timeout is the default reaper).' },\n idleTimeoutMs: { type: 'number', minimum: 1, description: 'Idle timeout in ms: reap the subagent after this long with no activity. Resets on every iteration/tool call. Default is role/coordinator-specific.' },\n maxTokens: { type: 'number', minimum: 1, description: 'Maximum total tokens (input + output) the subagent may use.' },\n },\n required: [],\n };\n return {\n name: 'spawn_subagent',\n description: 'Create a new subagent under this director. Returns the subagent id.',\n usageHint: 'Pass `role` (matches the roster), `description` (smart dispatch to best agent), or `name` + `provider`/`model`. Returns `{ subagentId }`.',\n permission: 'auto',\n mutating: false,\n inputSchema,\n async execute(input: unknown) {\n const i = (input ?? {}) as Record<string, unknown>;\n const role = typeof i.role === 'string' ? i.role : undefined;\n const description = typeof i.description === 'string' ? i.description : undefined;\n\n // Resolve base config from roster, explicit role, or dispatch-by-description\n let cfg: SubagentConfig | undefined;\n\n if (role && roster) {\n const base = roster[role];\n if (!base) return { error: `unknown role \"${role}\". roster has: ${Object.keys(roster).join(', ')}` };\n cfg = instantiateRosterConfig(role, base);\n } else if (description && !role) {\n // Smart dispatch: route description to best catalog agent using dispatcher\n const dispatchResult = await dispatchAgent(description, {\n classifier: director.dispatchClassifier,\n catalog: roster as unknown as Record<string, AgentDefinition> | undefined,\n });\n const dispatchRole = dispatchResult.role;\n // If we have a matching roster entry for the dispatched role, use it\n if (roster?.[dispatchRole]) {\n cfg = instantiateRosterConfig(dispatchRole, roster[dispatchRole]!);\n } else {\n // Dispatch found a catalog agent but there's no roster entry — use the\n // catalog definition's config as a base template (role name + defaults).\n // We must not mutate the original definition, so spread it.\n const def = dispatchResult.definition;\n cfg = {\n name: def.config.name ?? dispatchRole,\n role: dispatchRole,\n provider: def.config.provider,\n model: def.config.model,\n };\n }\n }\n\n // Fall back to name-only config when neither role nor description dispatch resolved\n cfg ??= { name: (i.name as string) ?? 'subagent' };\n\n if (typeof i.name === 'string') cfg.name = i.name;\n if (typeof i.provider === 'string') cfg.provider = i.provider;\n if (typeof i.model === 'string') cfg.model = i.model;\n if (typeof i.systemPromptOverride === 'string') cfg.systemPromptOverride = i.systemPromptOverride;\n if (typeof i.maxIterations === 'number') cfg.maxIterations = i.maxIterations;\n if (typeof i.maxToolCalls === 'number') cfg.maxToolCalls = i.maxToolCalls;\n if (typeof i.maxCostUsd === 'number') cfg.maxCostUsd = i.maxCostUsd;\n if (typeof i.timeoutMs === 'number') cfg.timeoutMs = i.timeoutMs;\n if (typeof i.idleTimeoutMs === 'number') cfg.idleTimeoutMs = i.idleTimeoutMs;\n if (typeof i.maxTokens === 'number') cfg.maxTokens = i.maxTokens;\n try {\n const subagentId = await director.spawn(cfg);\n return { subagentId, provider: cfg.provider, model: cfg.model, name: cfg.name, role: cfg.role };\n } catch (err) {\n if (err instanceof FleetSpawnBudgetError) {\n return { error: err.message, kind: err.kind, limit: err.limit, observed: err.observed };\n }\n if (err instanceof FleetCostCapError) {\n return { error: err.message, kind: err.kind, limit: err.limit, observed: err.observed };\n }\n return { error: err instanceof Error ? err.message : String(err) };\n }\n },\n };\n}\n\nfunction instantiateRosterConfig(role: string, base: SubagentConfig): SubagentConfig {\n return {\n ...base,\n // Roster entries are templates. A director may spawn several\n // workers with the same role, so never reuse the template id.\n id: `${role}-${randomUUID().slice(0, 8)}`,\n };\n}\n\nexport function makeAssignTool(director: Director): Tool {\n const inputSchema: JSONSchema = {\n type: 'object',\n properties: {\n subagentId: { type: 'string', minLength: 1, description: 'Target subagent id. Required.' },\n description: { type: 'string', minLength: 1, description: 'The task in natural language — what you want this subagent to do.' },\n maxToolCalls: { type: 'number', minimum: 1, description: 'Optional per-task tool-call budget override.' },\n timeoutMs: { type: 'number', minimum: 1, description: 'Optional per-task timeout in ms.' },\n },\n required: ['subagentId', 'description'],\n };\n return {\n name: 'assign_task',\n description: 'Hand a task to a previously spawned subagent. Returns the task id.',\n permission: 'auto',\n mutating: false,\n inputSchema,\n async execute(input: unknown) {\n const i = input as { subagentId: string; description: string; maxToolCalls?: number; timeoutMs?: number };\n const task: TaskSpec = { id: randomUUID(), description: i.description, subagentId: i.subagentId, maxToolCalls: i.maxToolCalls, timeoutMs: i.timeoutMs };\n const taskId = await director.assign(task);\n return { taskId, subagentId: i.subagentId };\n },\n };\n}\n\nexport function makeAwaitTasksTool(director: Director): Tool {\n return {\n name: 'await_tasks',\n description: 'Block until every named task completes. Returns the array of TaskResult.',\n permission: 'auto',\n mutating: false,\n inputSchema: { type: 'object', properties: { taskIds: { type: 'array', items: { type: 'string' }, description: 'One or more task ids returned by `assign_task`.' } }, required: ['taskIds'] },\n async execute(input: unknown) {\n const i = input as { taskIds: string[] };\n const results = await director.awaitTasks(i.taskIds);\n return { results };\n },\n };\n}\n\nexport function makeAskTool(director: Director): Tool {\n return {\n name: 'ask_subagent',\n description: 'Synchronously ask a subagent a question. Blocks until the subagent replies via the bridge.',\n permission: 'auto',\n mutating: false,\n inputSchema: {\n type: 'object',\n properties: {\n subagentId: { type: 'string', minLength: 1, description: 'Subagent to ask. Must be a previously spawned id.' },\n question: { type: 'string', minLength: 1, description: 'The question or instruction.' },\n timeoutMs: { type: 'number', minimum: 1, description: 'Optional timeout in ms (default 30s).' },\n },\n required: ['subagentId', 'question'],\n },\n async execute(input: unknown) {\n const i = input as { subagentId: string; question: string; timeoutMs?: number };\n try {\n const answer = await director.ask(i.subagentId, { question: i.question }, i.timeoutMs);\n // Store large answers out-of-band; return only a summary string in ctx.\n const stored = director.largeAnswerStore.storeAnswer(answer);\n if (stored.inline) {\n return { ok: true, answer: stored.summary };\n }\n return {\n ok: true,\n answer: stored.summary,\n _answerKey: stored.key,\n _hint: 'Response was large and stored. Use ask_result with the key to retrieve it.',\n };\n } catch (err) {\n return { ok: false, error: err instanceof Error ? err.message : String(err) };\n }\n },\n };\n}\n\n/**\n * Retrieve a previously stored `ask_subagent` answer by its store key.\n * The key was returned as `_answerKey` in the ask_subagent response.\n * Use this only for large responses that were stored out-of-context.\n */\nexport function makeAskResultTool(director: Director): Tool {\n return {\n name: 'ask_result',\n description: 'Retrieve a large `ask_subagent` response that was stored out-of-context (>2K chars). Returns the full stored value.',\n permission: 'auto',\n mutating: false,\n inputSchema: {\n type: 'object',\n properties: {\n key: {\n type: 'string',\n minLength: 1,\n description: 'The `_answerKey` returned by `ask_subagent` for a large response.',\n },\n },\n required: ['key'],\n },\n async execute(input: unknown) {\n const i = input as { key: string };\n const value = director.largeAnswerStore.retrieveAnswer(i.key);\n if (value === undefined) {\n return { ok: false, error: `No stored answer found for key \"${i.key}\" — it may have been cleared or the key is invalid.` };\n }\n return { ok: true, value };\n },\n };\n}\n\nexport function makeRollUpTool(director: Director): Tool {\n return {\n name: 'roll_up',\n description: \"Aggregate completed task results into a single formatted summary.\",\n permission: 'auto',\n mutating: false,\n inputSchema: {\n type: 'object',\n properties: {\n taskIds: { type: 'array', items: { type: 'string' }, description: 'Completed task ids to aggregate.' },\n style: { type: 'string', enum: ['markdown', 'json'], description: 'Output flavor — markdown (default) or json.' },\n },\n required: ['taskIds'],\n },\n async execute(input: unknown) {\n const i = input as { taskIds: string[]; style?: 'markdown' | 'json' };\n const summary = director.rollUp(i.taskIds, i.style ?? 'markdown');\n return { summary, count: i.taskIds.length };\n },\n };\n}\n\nexport function makeTerminateTool(director: Director): Tool {\n return {\n name: 'terminate_subagent',\n description: 'Forcibly abort a subagent. The subagent finishes its current iteration then exits with status \"stopped\".',\n permission: 'auto',\n mutating: true,\n inputSchema: { type: 'object', properties: { subagentId: { type: 'string', description: 'Subagent to abort.' } }, required: ['subagentId'] },\n async execute(input: unknown) {\n const i = input as { subagentId: string };\n await director.terminate(i.subagentId);\n return { ok: true };\n },\n };\n}\n\nexport function makeTerminateAllTool(director: Director): Tool {\n return {\n name: 'terminate_all',\n description:\n 'Forcibly stop every subagent in the fleet and drain the pending task queue. ' +\n 'In-flight tasks are terminated mid-execution; pending tasks receive ' +\n '\"aborted_by_parent\" completion immediately. ' +\n 'Use this when the fleet is wedged, looping, or you need a clean slate. ' +\n 'Compare: work_complete stops spawning but lets running agents finish naturally.',\n permission: 'auto',\n mutating: true,\n inputSchema: { type: 'object', properties: {}, required: [] },\n async execute() {\n await director.terminateAll();\n return { ok: true, message: `Fleet shutdown complete — all subagents stopped, pending tasks drained.` };\n },\n };\n}\n\nexport function makeFleetStatusTool(director: Director): Tool {\n return {\n name: 'fleet_status',\n description: \"Snapshot of the fleet — every subagent's current status, coordinator counts (total/running/idle/stopped), pending task descriptions, and usage rollup.\",\n permission: 'auto',\n mutating: false,\n inputSchema: { type: 'object', properties: {}, required: [] },\n async execute() {\n const base = director.status();\n const fm = director.fleetManager;\n const stats = fm?.getFleetStats();\n const fleetStatus = fm?.getFleetStatus();\n return {\n subagents: base.subagents,\n coordinatorStats: stats\n ? { total: stats.total, running: stats.running, idle: stats.idle, stopped: stats.stopped }\n : undefined,\n pending: fleetStatus?.pending ?? [],\n usage: fm?.snapshot(),\n };\n },\n };\n}\n\nexport function makeFleetUsageTool(director: Director): Tool {\n return {\n name: 'fleet_usage',\n description: 'Token + cost breakdown across the fleet, per-subagent and totals.',\n permission: 'auto',\n mutating: false,\n inputSchema: { type: 'object', properties: {}, required: [] },\n async execute() { return director.snapshot(); },\n };\n}\n\n/**\n * Read a subagent's JSONL transcript and return the last assistant text,\n * stop reason, and tool-use count. The director can call this on a\n * running or timed-out subagent to see what it actually produced without\n * having to wait for natural completion.\n */\nexport function makeFleetSessionTool(director: Director): Tool {\n return {\n name: 'fleet_session',\n description:\n 'Read a subagent\\'s JSONL transcript and extract its last assistant text, stop reason, and tool-use count. Use this to see what a running or timed-out subagent actually produced.',\n permission: 'auto',\n mutating: false,\n inputSchema: {\n type: 'object',\n properties: {\n subagentId: { type: 'string', description: 'Subagent id to read the transcript of.' },\n tail: { type: 'number', description: 'Number of trailing JSONL lines to return. Omit for the full transcript.' },\n },\n required: ['subagentId'],\n },\n async execute(input: unknown) {\n const i = input as { subagentId: string; tail?: number };\n const result = await director.readSession(i.subagentId, i.tail);\n if (!result) {\n return {\n error: `fleet_session: transcript unavailable for \"${i.subagentId}\". Is sessionsRoot configured?`,\n };\n }\n return result;\n },\n };\n}\n\n/**\n * Health snapshot per subagent — budget pressure (how close to limits),\n * last activity timestamp, and current status. Lets the director make\n * smarter routing decisions without having to call fleet_usage + fleet_status separately.\n */\nexport function makeFleetHealthTool(director: Director): Tool {\n return {\n name: 'fleet_health',\n description:\n 'Per-subagent health report: budget pressure (pct of limits consumed), last activity timestamp, and current status. Use to decide whether to assign more work to a subagent or spawn a fresh one.',\n permission: 'auto',\n mutating: false,\n inputSchema: { type: 'object', properties: {}, required: [] },\n async execute() {\n const status = director.status();\n const snapshot = director.snapshot();\n const subagents = status.subagents ?? [];\n const perSubagent = snapshot.perSubagent ?? {};\n return {\n subagents: subagents.map((s) => {\n const usage = perSubagent[s.id];\n return {\n id: s.id,\n status: s.status,\n lastEventAt: usage?.lastEventAt,\n budgetPressure: {\n iterations: usage?.iterations,\n toolCalls: usage?.toolCalls,\n costUsd: usage?.cost,\n },\n };\n }),\n };\n },\n };\n}\n\n/**\n * Collaborative debugging session: BugHunter, RefactorPlanner, and Critic\n * run in parallel on the same target files, with findings flowing through\n * the FleetBus (bug.found → refactor.plan → critic.evaluation).\n *\n * Returns a structured CollabDebugReport containing all bug findings,\n * refactor plans, critic evaluations, and an overall verdict.\n */\nexport function makeCollabDebugTool(director: Director): Tool {\n return {\n name: 'collab_debug',\n description:\n 'Start a collaborative debugging session: BugHunter, RefactorPlanner, and Critic ' +\n 'run in parallel on the same target files. BugHunter finds bugs and emits bug.found events. ' +\n 'RefactorPlanner listens for bug.found and emits refactor.plan events. ' +\n 'Critic evaluates both and emits critic.evaluation events. ' +\n 'Returns a structured report with overall verdict (approve / needs_revision / reject).',\n permission: 'auto',\n mutating: false,\n inputSchema: {\n type: 'object',\n properties: {\n targetPaths: {\n type: 'array',\n items: { type: 'string' },\n description: 'File paths / glob patterns to scan for bugs.',\n },\n timeoutMs: {\n type: 'number',\n minimum: 1,\n description: 'Timeout in ms. Default: 600000 (10 minutes).',\n },\n maxTargetFiles: {\n type: 'number',\n minimum: 1,\n description:\n 'Maximum number of files to include in the snapshot. ' +\n 'If not set, the limit is computed dynamically from contextWindow ' +\n 'or falls back to the default (30).',\n },\n contextWindow: {\n type: 'number',\n minimum: 1,\n description:\n 'Context window size (tokens) of the model. When provided and ' +\n 'maxTargetFiles is not set, the file limit is computed dynamically ' +\n 'as floor((contextWindow * 0.4) / 2000).',\n },\n },\n required: ['targetPaths'],\n },\n async execute(input: unknown) {\n const i = input as { targetPaths?: string[]; timeoutMs?: number; maxTargetFiles?: number; contextWindow?: number };\n if (!i.targetPaths?.length) {\n return { error: 'collab_debug: targetPaths is required and must be non-empty.' };\n }\n const options: CollabSessionOptions = {\n targetPaths: i.targetPaths,\n timeoutMs: i.timeoutMs,\n maxTargetFiles: i.maxTargetFiles,\n contextWindow: i.contextWindow,\n };\n try {\n const report = await director.spawnCollab(options);\n return {\n sessionId: report.sessionId,\n overallVerdict: report.overallVerdict,\n bugCount: report.bugs.length,\n planCount: report.refactorPlans.length,\n evaluationCount: report.evaluations.length,\n summary: report.summary,\n bugs: report.bugs,\n refactorPlans: report.refactorPlans,\n evaluations: report.evaluations,\n };\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n return { error: 'collab_debug failed: ' + msg };\n }\n },\n };\n}\n\n/**\n * Tool for subagents to emit structured events on the FleetBus.\n * Any agent can emit any event type; the Director routes it to all listeners.\n * Common event types in collaborative sessions:\n * bug.found — BugHunter emits per-finding\n * refactor.plan — RefactorPlanner emits per-plan\n * critic.evaluation — Critic emits per-evaluation\n *\n * The payload structure is event-type-specific. Use null for empty payloads.\n */\nexport function makeFleetEmitTool(director: Director): Tool {\n return {\n name: 'fleet_emit',\n description:\n 'Emit a structured event on the FleetBus. Any subagent can emit any event type; the Director routes it to all listeners. Use it to stream findings, progress updates, or final results to other agents in real time.',\n permission: 'auto',\n mutating: false,\n inputSchema: {\n type: 'object',\n properties: {\n type: {\n type: 'string',\n description: 'Event type string (e.g. bug.found, refactor.plan, critic.evaluation, progress, result).',\n },\n payload: {\n type: 'object',\n description: 'Event payload. Structure depends on event type. Use null if no payload.',\n },\n },\n required: ['type'],\n },\n async execute(input: unknown) {\n const i = input as { type: string; payload?: Record<string, unknown> | null };\n director.fleet.emit({\n subagentId: director.id,\n ts: Date.now(),\n type: i.type,\n payload: i.payload ?? {},\n });\n return { ok: true, event: i.type };\n },\n };\n}\n\n/**\n * Signal that the director's work is satisfied and the fleet should wind down.\n *\n * Once called:\n * - `spawn_subagent` throws — no new subagents can be created\n * - `assign_task` synthesizes an immediate `aborted_by_parent` completion\n * for any queued task (callers awaiting those tasks unblock immediately)\n * - Running subagents are NOT killed — they finish naturally; no new\n * tasks are dispatched to them\n *\n * Use this when you are satisfied with the results and want the fleet to\n * stop spawning without forcibly stopping in-flight work. Call\n * `terminate_subagent` separately for any subagent you need to stop immediately.\n */\nexport function makeWorkCompleteTool(director: Director): Tool {\n return {\n name: 'work_complete',\n description:\n \"Signal that the director is satisfied with the results and the fleet should wind down. \" +\n \"After calling this, spawn_subagent will refuse with a budget error and assign_task \" +\n \"will instantly complete any queued tasks as aborted. Running subagents finish naturally. \" +\n \"Call terminate_subagent separately to stop specific subagents immediately.\",\n permission: 'auto',\n mutating: false,\n inputSchema: { type: 'object', properties: {}, required: [] },\n async execute() {\n director.workComplete();\n return { ok: true, message: 'Fleet wind-down signaled. No new spawns or task dispatches.' };\n },\n };\n}\n","import type { EventBus } from '../kernel/events.js';\r\n\r\n/**\r\n * Single fleet-wide event with subagent attribution. Whatever a child\r\n * agent emits on its own EventBus gets re-published here, prefixed with\r\n * `subagentId` so a single subscriber can multiplex across the fleet.\r\n *\r\n * The director uses `FleetBus.filter('tool.executed', …)` to see every\r\n * tool call across the fleet; the TUI uses\r\n * `FleetBus.subscribe(id, handler)` to render a per-subagent panel.\r\n */\r\nexport interface FleetEvent {\r\n subagentId: string;\r\n taskId?: string;\r\n ts: number;\r\n type: string;\r\n payload: unknown;\r\n}\r\n\r\nexport type FleetHandler = (event: FleetEvent) => void;\r\n\r\n/**\r\n * Fan-in for per-subagent EventBuses. Each subagent's bus is plugged in\r\n * via `attach()`; the FleetBus re-emits every event with subagent\r\n * attribution. Detachment is automatic via the returned disposer — call\r\n * it when a subagent terminates so we don't leak listeners.\r\n *\r\n * The bus exposes two subscription modes: by `subagentId` (everything\r\n * from one child) and by `type` (one event-type across the fleet). They\r\n * compose — if you need a per-subagent + per-type slice, subscribe by\r\n * type and filter on `event.subagentId` in your handler.\r\n */\r\nexport class FleetBus {\r\n private readonly byId = new Map<string, Set<FleetHandler>>();\r\n private readonly byType = new Map<string, Set<FleetHandler>>();\r\n private readonly any = new Set<FleetHandler>();\r\n\r\n /**\r\n * Hook a subagent's EventBus into the fleet. Uses `onAny()` (an alias for\r\n * `onPattern('*')`) to forward all events with subagent attribution, so\r\n * new kernel event types are automatically forwarded without any manual\r\n * registration. `subagent.*` events are excluded because they originate\r\n * from MultiAgentHost on the parent bus, not the subagent's own bus.\r\n *\r\n * Returns a disposer that detaches every subscription; call on\r\n * subagent teardown so the listeners don't outlive the run.\r\n */\r\n attach(subagentId: string, bus: EventBus, taskId?: string): () => void {\r\n // Subscribe to every event on the subagent's EventBus and re-emit with\r\n // attribution via the onAny() alias for onPattern('*'). The payload is\r\n // typed as `unknown` in the FleetEvent — use the type guard in the\r\n // handler to narrow it.\r\n //\r\n // Skip subagent lifecycle events (subagent.*) — those are emitted by\r\n // MultiAgentHost on the parent EventBus, not on the subagent's own bus.\r\n // Forwarding them would create duplicate fleet events for the same logical\r\n // occurrence. Use the parent EventBus path (events.on('subagent.*')) for\r\n // lifecycle events instead.\r\n const off = bus.onAny((type, payload) => {\r\n if (type.startsWith('subagent.')) return;\r\n this.emit({ subagentId, taskId, ts: Date.now(), type, payload });\r\n });\r\n\r\n return () => {\r\n off();\r\n };\r\n }\r\n\r\n /** Subscribe to every event from one subagent. */\r\n subscribe(subagentId: string, handler: FleetHandler): () => void {\r\n let set = this.byId.get(subagentId);\r\n if (!set) {\r\n set = new Set();\r\n this.byId.set(subagentId, set);\r\n }\r\n set.add(handler);\r\n return () => {\r\n set!.delete(handler);\r\n };\r\n }\r\n\r\n /** Subscribe to one event type across all subagents. */\r\n filter(type: string, handler: FleetHandler): () => void {\r\n let set = this.byType.get(type);\r\n if (!set) {\r\n set = new Set();\r\n this.byType.set(type, set);\r\n }\r\n set.add(handler);\r\n return () => {\r\n set!.delete(handler);\r\n };\r\n }\r\n\r\n /** Subscribe to literally everything. The fleet roll-up uses this. */\r\n onAny(handler: FleetHandler): () => void {\r\n this.any.add(handler);\r\n return () => {\r\n this.any.delete(handler);\r\n };\r\n }\r\n\r\n emit(event: FleetEvent): void {\r\n // Each fan-out is best-effort — a misbehaving handler must not\r\n // bring down the bus or other handlers. Errors are swallowed\r\n // (matching the rest of the project's listener-error policy).\r\n const byId = this.byId.get(event.subagentId);\r\n if (byId)\r\n for (const h of byId) {\r\n try {\r\n h(event);\r\n } catch {\r\n /* ignore */\r\n }\r\n }\r\n const byType = this.byType.get(event.type);\r\n if (byType)\r\n for (const h of byType) {\r\n try {\r\n h(event);\r\n } catch {\r\n /* ignore */\r\n }\r\n }\r\n for (const h of this.any) {\r\n try {\r\n h(event);\r\n } catch {\r\n /* ignore */\r\n }\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Roll-up of token usage + cost across an entire director run. The\r\n * director's `fleet_status` tool returns this so the model can reason\r\n * about budget in its next turn (\"the researcher already burned $0.40,\r\n * lean on summaries for the next task\").\r\n */\r\nexport interface FleetUsage {\r\n total: {\r\n input: number;\r\n output: number;\r\n cacheRead: number;\r\n cacheWrite: number;\r\n cost: number;\r\n };\r\n perSubagent: Record<string, SubagentUsageSnapshot>;\r\n}\r\n\r\nexport interface SubagentUsageSnapshot {\r\n subagentId: string;\r\n provider?: string;\r\n model?: string;\r\n input: number;\r\n output: number;\r\n cacheRead: number;\r\n cacheWrite: number;\r\n cost: number;\r\n toolCalls: number;\r\n iterations: number;\r\n startedAt: number;\r\n lastEventAt: number;\r\n}\r\n\r\n/**\r\n * Aggregates provider.response + tool.executed events from the FleetBus\r\n * into a live `FleetUsage` snapshot. Costs are computed by the caller\r\n * via a `priceLookup(subagentId)` so we don't bake provider-pricing\r\n * coupling into core; the CLI/tests supply a function that resolves\r\n * each subagent's per-token rates from the models registry.\r\n */\r\nexport class FleetUsageAggregator {\r\n private readonly perSubagent = new Map<string, SubagentUsageSnapshot>();\r\n private readonly total = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };\r\n private readonly unsub = new Array<() => void>();\r\n\r\n constructor(\r\n bus: FleetBus,\r\n private readonly priceLookup?: (\r\n subagentId: string,\r\n provider?: string,\r\n model?: string,\r\n ) => { input?: number; output?: number; cacheRead?: number; cacheWrite?: number } | undefined,\r\n private readonly metaLookup?: (\r\n subagentId: string,\r\n ) => { provider?: string; model?: string } | undefined,\r\n ) {\r\n this.unsub.push(bus.filter('provider.response', (e) => this.onProviderResponse(e)));\r\n this.unsub.push(bus.filter('tool.executed', (e) => this.onToolExecuted(e)));\r\n this.unsub.push(bus.filter('iteration.started', (e) => this.onIterationStarted(e)));\r\n }\r\n\r\n /**\r\n * Remove a terminated subagent's data from the aggregator and subtract its\r\n * contribution from the running totals. Call this when a subagent is removed\r\n * from the fleet so the aggregator doesn't accumulate unbounded data for\r\n * entities that will never emit events again.\r\n */\r\n removeSubagent(subagentId: string): void {\r\n const snap = this.perSubagent.get(subagentId);\r\n if (!snap) return;\r\n this.perSubagent.delete(subagentId);\r\n this.total.input -= snap.input;\r\n this.total.output -= snap.output;\r\n this.total.cacheRead -= snap.cacheRead;\r\n this.total.cacheWrite -= snap.cacheWrite;\r\n this.total.cost -= snap.cost;\r\n }\r\n\r\n /** Disposes all fleet-bus subscriptions. Call when the aggregator is no longer needed. */\r\n dispose(): void {\r\n for (const off of this.unsub) off();\r\n this.unsub.length = 0;\r\n }\r\n\r\n /** Live snapshot — safe to call from a tool's execute() body. */\r\n snapshot(): FleetUsage {\r\n return {\r\n total: { ...this.total },\r\n perSubagent: Object.fromEntries(\r\n Array.from(this.perSubagent.entries()).map(([k, v]) => [k, { ...v }]),\r\n ),\r\n };\r\n }\r\n\r\n private ensure(subagentId: string): SubagentUsageSnapshot {\r\n let snap = this.perSubagent.get(subagentId);\r\n if (!snap) {\r\n const meta = this.metaLookup?.(subagentId);\r\n snap = {\r\n subagentId,\r\n provider: meta?.provider,\r\n model: meta?.model,\r\n input: 0,\r\n output: 0,\r\n cacheRead: 0,\r\n cacheWrite: 0,\r\n cost: 0,\r\n toolCalls: 0,\r\n iterations: 0,\r\n startedAt: Date.now(),\r\n lastEventAt: Date.now(),\r\n };\r\n this.perSubagent.set(subagentId, snap);\r\n }\r\n return snap;\r\n }\r\n\r\n private onProviderResponse(e: FleetEvent): void {\r\n const snap = this.ensure(e.subagentId);\r\n const p = e.payload as {\r\n usage?: { input?: number; output?: number; cacheRead?: number; cacheWrite?: number };\r\n };\r\n const usage = p?.usage;\r\n if (!usage) return;\r\n snap.input += usage.input ?? 0;\r\n snap.output += usage.output ?? 0;\r\n snap.cacheRead += usage.cacheRead ?? 0;\r\n snap.cacheWrite += usage.cacheWrite ?? 0;\r\n this.total.input += usage.input ?? 0;\r\n this.total.output += usage.output ?? 0;\r\n this.total.cacheRead += usage.cacheRead ?? 0;\r\n this.total.cacheWrite += usage.cacheWrite ?? 0;\r\n const price = this.priceLookup?.(e.subagentId, snap.provider, snap.model);\r\n if (price) {\r\n const delta =\r\n ((usage.input ?? 0) / 1_000_000) * (price.input ?? 0) +\r\n ((usage.output ?? 0) / 1_000_000) * (price.output ?? 0) +\r\n ((usage.cacheRead ?? 0) / 1_000_000) * (price.cacheRead ?? 0) +\r\n ((usage.cacheWrite ?? 0) / 1_000_000) * (price.cacheWrite ?? 0);\r\n snap.cost += delta;\r\n this.total.cost += delta;\r\n }\r\n snap.lastEventAt = e.ts;\r\n }\r\n\r\n private onToolExecuted(e: FleetEvent): void {\r\n const snap = this.ensure(e.subagentId);\r\n snap.toolCalls += 1;\r\n snap.lastEventAt = e.ts;\r\n }\r\n\r\n private onIterationStarted(e: FleetEvent): void {\r\n const snap = this.ensure(e.subagentId);\r\n snap.iterations += 1;\r\n snap.lastEventAt = e.ts;\r\n }\r\n}\r\n","/**\n * LargeAnswerStore — prevents `ask_subagent` results from bloating the\n * director's context window.\n *\n * Problem: `ask_subagent` returns full subagent responses as tool_result\n * content. A single response can be 10-50K+ tokens. When the director\n * calls `ask` multiple times, these accumulate in ctx.messages and can\n * push context pressure past 100%, causing provider overflow errors or\n * silent quality degradation.\n *\n * Solution: responses above `sizeThreshold` chars are stored here\n * (in-memory Map keyed by stable id). The tool result returns only a\n * compact summary + the store key. Callers retrieve the full result\n * via `retrieveAnswer(key)` when they need it.\n *\n * The store is scoped to a single Director.run() lifecycle.\n * It is NOT persisted — if the process crashes the results are lost,\n * which is acceptable since the subagent already finished and the\n * summary is in context.\n */\n\nexport interface AnswerEntry {\n key: string;\n value: unknown;\n size: number;\n storedAt: number;\n}\n\nexport class LargeAnswerStore {\n /**\n * Responses above this size (in characters) are stored out-of-context.\n * Below this, the full answer is returned inline (no overhead).\n * Default: 2000 chars ≈ 400-600 tokens.\n */\n readonly sizeThreshold: number;\n\n private readonly store = new Map<string, AnswerEntry>();\n\n constructor(sizeThreshold = 2000) {\n this.sizeThreshold = sizeThreshold;\n }\n\n /**\n * Store a value, returning a summary + key for inline use.\n * If the value is below sizeThreshold, returns it as-is (no store entry).\n */\n storeAnswer(value: unknown): { key?: string; summary: string; inline: boolean } {\n if (value === undefined || value === null) {\n return { summary: String(value), inline: true };\n }\n\n const serialized = typeof value === 'string' ? value : JSON.stringify(value);\n const size = serialized.length;\n\n if (size <= this.sizeThreshold) {\n return { summary: serialized.slice(0, 500), inline: true };\n }\n\n // Stable key derived from content hash — same value always gets same key\n // within this store's lifetime.\n const key = `a-${hashStr(serialized)}`;\n\n this.store.set(key, {\n key,\n value,\n size,\n storedAt: Date.now(),\n });\n\n return {\n key,\n summary: `[stored: ${size} chars — use roll_up or ask_result tool to retrieve, key=${key}]`,\n inline: false,\n };\n }\n\n /**\n * Retrieve a previously stored answer by its key.\n * Returns undefined if the key is unknown or the store was cleared.\n */\n retrieveAnswer(key: string): unknown | undefined {\n return this.store.get(key)?.value;\n }\n\n /**\n * Check if a key exists in the store.\n */\n hasAnswer(key: string): boolean {\n return this.store.has(key);\n }\n\n /** Number of stored entries. */\n get size(): number {\n return this.store.size;\n }\n\n /** Total characters stored. */\n get totalChars(): number {\n let total = 0;\n for (const e of this.store.values()) total += e.size;\n return total;\n }\n\n /** Clear all stored entries. Call at the end of a director run. */\n clear(): void {\n this.store.clear();\n }\n}\n\n/** Fast string hash for stable key derivation. Not cryptographic. */\nfunction hashStr(s: string): string {\n let h = 5381;\n for (let i = 0; i < s.length; i++) {\n h = (h * 33) ^ s.charCodeAt(i);\n }\n return (h >>> 0).toString(36);\n}\n","/**\n * Per-task model matrix resolution.\n *\n * The matrix (Config.modelMatrix) maps a catalog **role**, a **phase** name, or\n * the `*` default to a {@link ModelMatrixEntry} (model + optional provider).\n * At subagent spawn time we resolve the most specific match so different task\n * types can run on different models — e.g. `security-scanner` on one model,\n * `documentation` on another — while the leader keeps its own model.\n *\n * Resolution precedence (most → least specific):\n * 1. exact role (matrix[\"security-scanner\"])\n * 2. the role's phase (matrix[\"review\"])\n * 3. the `*` default (matrix[\"*\"])\n * 4. undefined (caller falls back to the leader model)\n *\n * Set via the `/setmodel` slash command; this module is the single source of\n * truth both that command and the spawn path use to validate + resolve keys.\n */\nimport type { ModelMatrixEntry } from '../types/config.js';\nimport { AGENTS_BY_PHASE, AGENT_CATALOG } from './agents/index.js';\n\n/** All valid phase keys, in catalog order. */\nexport const MATRIX_PHASE_KEYS: readonly string[] = Object.keys(AGENTS_BY_PHASE);\n\n/** Role → phase lookup, built once from the catalog. */\nconst ROLE_TO_PHASE: Record<string, string> = (() => {\n const map: Record<string, string> = {};\n for (const [phase, defs] of Object.entries(AGENTS_BY_PHASE)) {\n for (const def of defs) {\n const role = def.config.role;\n if (role) map[role] = phase;\n }\n }\n return map;\n})();\n\n/** The phase a catalog role belongs to, or undefined for unknown roles. */\nexport function phaseForRole(role: string | undefined): string | undefined {\n return role ? ROLE_TO_PHASE[role] : undefined;\n}\n\n/**\n * Resolve the matrix entry for a subagent role. Returns the most specific\n * match (role → phase → `*`), or undefined when nothing matches.\n */\nexport function resolveModelMatrix(\n matrix: Record<string, ModelMatrixEntry> | undefined,\n role: string | undefined,\n): ModelMatrixEntry | undefined {\n if (!matrix) return undefined;\n if (role && matrix[role]) return matrix[role];\n const phase = phaseForRole(role);\n if (phase && matrix[phase]) return matrix[phase];\n if (matrix['*']) return matrix['*'];\n return undefined;\n}\n\nexport type MatrixKeyKind = 'role' | 'phase' | 'default' | 'unknown';\n\n/** Classify a matrix key so `/setmodel` can reject typos before persisting. */\nexport function matrixKeyKind(key: string): MatrixKeyKind {\n if (key === '*') return 'default';\n if (key in AGENT_CATALOG) return 'role';\n if (MATRIX_PHASE_KEYS.includes(key)) return 'phase';\n return 'unknown';\n}\n\n/** True when `key` is a usable matrix key (role, phase, or `*`). */\nexport function isValidMatrixKey(key: string): boolean {\n return matrixKeyKind(key) !== 'unknown';\n}\n","/**\n * WrongStack error hierarchy.\n *\n * Every error thrown by the framework is a `WrongStackError` with a\n * machine-readable `code`, a `subsystem` tag, and a `severity` level.\n * This lets consumers (CLI, TUI, plugins, tests) branch on structured\n * data instead of parsing error messages.\n */\n\n// ── Error codes ──────────────────────────────────────────────────────\n\n/**\n * Machine-readable error codes as frozen constants.\n *\n * Use `ERROR_CODES.X` instead of raw string literals for:\n * - IDE autocomplete and compile-time validation\n * - Safe refactoring (rename updates all usages)\n * - Plugin extensibility (extend the object to add custom codes)\n *\n * The `ErrorCode` type is derived from this object, so adding a new\n * code here automatically updates the type without extra changes.\n */\nexport const ERROR_CODES = {\n // Provider\n PROVIDER_RATE_LIMITED: 'PROVIDER_RATE_LIMITED',\n PROVIDER_AUTH_FAILED: 'PROVIDER_AUTH_FAILED',\n PROVIDER_OVERLOADED: 'PROVIDER_OVERLOADED',\n PROVIDER_INVALID_REQUEST: 'PROVIDER_INVALID_REQUEST',\n PROVIDER_SERVER_ERROR: 'PROVIDER_SERVER_ERROR',\n PROVIDER_NETWORK_ERROR: 'PROVIDER_NETWORK_ERROR',\n PROVIDER_CONTEXT_OVERFLOW: 'PROVIDER_CONTEXT_OVERFLOW',\n // Tool\n TOOL_NOT_FOUND: 'TOOL_NOT_FOUND',\n TOOL_PERMISSION_DENIED: 'TOOL_PERMISSION_DENIED',\n TOOL_EXECUTION_FAILED: 'TOOL_EXECUTION_FAILED',\n TOOL_TIMEOUT: 'TOOL_TIMEOUT',\n TOOL_INPUT_INVALID: 'TOOL_INPUT_INVALID',\n // Config\n CONFIG_INVALID: 'CONFIG_INVALID',\n CONFIG_NOT_FOUND: 'CONFIG_NOT_FOUND',\n CONFIG_PARSE_FAILED: 'CONFIG_PARSE_FAILED',\n CONFIG_MIGRATION_NEEDED: 'CONFIG_MIGRATION_NEEDED',\n // Plugin\n PLUGIN_LOAD_FAILED: 'PLUGIN_LOAD_FAILED',\n PLUGIN_API_MISMATCH: 'PLUGIN_API_MISMATCH',\n PLUGIN_MISSING_DEPENDENCY: 'PLUGIN_MISSING_DEPENDENCY',\n // Agent\n AGENT_ITERATION_LIMIT: 'AGENT_ITERATION_LIMIT',\n AGENT_CONTEXT_OVERFLOW: 'AGENT_CONTEXT_OVERFLOW',\n AGENT_ABORTED: 'AGENT_ABORTED',\n AGENT_RUN_FAILED: 'AGENT_RUN_FAILED',\n // Session\n SESSION_NOT_FOUND: 'SESSION_NOT_FOUND',\n SESSION_CORRUPTED: 'SESSION_CORRUPTED',\n SESSION_WRITE_FAILED: 'SESSION_WRITE_FAILED',\n // Container / Registry\n CONTAINER_TOKEN_ALREADY_BOUND: 'CONTAINER_TOKEN_ALREADY_BOUND',\n CONTAINER_TOKEN_NOT_BOUND: 'CONTAINER_TOKEN_NOT_BOUND',\n CONTAINER_CIRCULAR_DEPENDENCY: 'CONTAINER_CIRCULAR_DEPENDENCY',\n REGISTRY_DUPLICATE: 'REGISTRY_DUPLICATE',\n REGISTRY_NOT_FOUND: 'REGISTRY_NOT_FOUND',\n REGISTRY_INVALID: 'REGISTRY_INVALID',\n // File system\n FS_READ_FAILED: 'FS_READ_FAILED',\n FS_WRITE_FAILED: 'FS_WRITE_FAILED',\n FS_MKDIR_FAILED: 'FS_MKDIR_FAILED',\n FS_DELETE_FAILED: 'FS_DELETE_FAILED',\n FS_ATOMIC_WRITE_FAILED: 'FS_ATOMIC_WRITE_FAILED',\n // General\n UNKNOWN: 'UNKNOWN',\n} as const;\n\n/**\n * Union type derived from `ERROR_CODES`. Using `typeof ERROR_CODES[keyof typeof ERROR_CODES]`\n * instead of a string literal union means TypeScript auto-updates the type whenever\n * a new code is added to `ERROR_CODES` — no need to keep two lists in sync.\n */\nexport type ErrorCode = (typeof ERROR_CODES)[keyof typeof ERROR_CODES];\n\nexport type ErrorSubsystem =\n | 'provider'\n | 'tool'\n | 'config'\n | 'plugin'\n | 'agent'\n | 'session'\n | 'container'\n | 'fs'\n | 'general';\nexport type ErrorSeverity = 'fatal' | 'error' | 'warning';\n\n// ── Base error class ─────────────────────────────────────────────────\n\nexport class WrongStackError extends Error {\n readonly code: ErrorCode;\n readonly subsystem: ErrorSubsystem;\n readonly severity: ErrorSeverity;\n readonly recoverable: boolean;\n readonly context?: Record<string, unknown>;\n\n constructor(opts: {\n message: string;\n code: ErrorCode;\n subsystem: ErrorSubsystem;\n severity?: ErrorSeverity;\n recoverable?: boolean;\n context?: Record<string, unknown>;\n cause?: unknown;\n }) {\n super(opts.message, { cause: opts.cause });\n this.name = 'WrongStackError';\n this.code = opts.code;\n this.subsystem = opts.subsystem;\n this.severity = opts.severity ?? 'error';\n this.recoverable = opts.recoverable ?? false;\n this.context = opts.context;\n }\n\n /**\n * Render a one-line user-facing description.\n * Subclasses should override for domain-specific formatting.\n */\n describe(): string {\n const ctx = this.context ? ` ${formatContext(this.context)}` : '';\n return `${this.code}: ${this.message}${ctx}`;\n }\n}\n\nfunction formatContext(ctx: Record<string, unknown>): string {\n const parts = Object.entries(ctx)\n .filter(([, v]) => v !== undefined)\n .slice(0, 3)\n .map(([k, v]) => `${k}=${String(v)}`);\n return parts.length > 0 ? `[${parts.join(' ')}]` : '';\n}\n\n// ── Specific error classes ───────────────────────────────────────────\n\n/**\n * Tool execution errors — thrown by ToolExecutor and individual tools.\n */\nexport class ToolError extends WrongStackError {\n readonly toolName: string;\n\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n | 'TOOL_NOT_FOUND'\n | 'TOOL_PERMISSION_DENIED'\n | 'TOOL_EXECUTION_FAILED'\n | 'TOOL_TIMEOUT'\n | 'TOOL_INPUT_INVALID'\n >;\n toolName: string;\n recoverable?: boolean;\n context?: Record<string, unknown>;\n cause?: unknown;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'tool',\n recoverable: opts.recoverable,\n context: { tool: opts.toolName, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'ToolError';\n this.toolName = opts.toolName;\n }\n}\n\n/**\n * Config loading / validation errors.\n */\nexport class ConfigError extends WrongStackError {\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'CONFIG_INVALID' | 'CONFIG_NOT_FOUND' | 'CONFIG_PARSE_FAILED' | 'CONFIG_MIGRATION_NEEDED'\n >;\n context?: Record<string, unknown>;\n cause?: unknown;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'config',\n severity: 'fatal',\n recoverable: false,\n context: opts.context,\n cause: opts.cause,\n });\n this.name = 'ConfigError';\n }\n}\n\n/**\n * Plugin loading / lifecycle errors.\n */\nexport class PluginError extends WrongStackError {\n readonly pluginName: string;\n\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'PLUGIN_LOAD_FAILED' | 'PLUGIN_API_MISMATCH' | 'PLUGIN_MISSING_DEPENDENCY'\n >;\n pluginName: string;\n context?: Record<string, unknown>;\n cause?: unknown;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'plugin',\n severity: 'error',\n recoverable: opts.code === ERROR_CODES.PLUGIN_MISSING_DEPENDENCY,\n context: { plugin: opts.pluginName, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'PluginError';\n this.pluginName = opts.pluginName;\n }\n}\n\n/**\n * Agent runtime errors — thrown by Agent.run when a non-WrongStackError\n * escapes the inner loop, so callers always see a structured error.\n */\nexport class AgentError extends WrongStackError {\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'AGENT_ITERATION_LIMIT' | 'AGENT_CONTEXT_OVERFLOW' | 'AGENT_ABORTED' | 'AGENT_RUN_FAILED'\n >;\n recoverable?: boolean;\n context?: Record<string, unknown>;\n cause?: unknown;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'agent',\n severity: opts.code === ERROR_CODES.AGENT_ABORTED ? 'warning' : 'error',\n recoverable: opts.recoverable ?? opts.code === ERROR_CODES.AGENT_ITERATION_LIMIT,\n context: opts.context,\n cause: opts.cause,\n });\n this.name = 'AgentError';\n }\n}\n\n/**\n * Wrap an arbitrary thrown value into a `WrongStackError` so the caller\n * always gets a structured error. Pass-throughs WrongStackError instances\n * unchanged; raw `Error`s and primitives get an `AGENT_RUN_FAILED` wrapper\n * with the original preserved as `cause`.\n */\nexport function toWrongStackError(\n err: unknown,\n code: Extract<ErrorCode, 'AGENT_RUN_FAILED' | 'AGENT_ABORTED' | 'UNKNOWN'> = ERROR_CODES.AGENT_RUN_FAILED,\n): WrongStackError {\n if (err instanceof WrongStackError) return err;\n const message = err instanceof Error ? err.message : String(err);\n return new AgentError({\n message,\n code: code === 'UNKNOWN' ? ERROR_CODES.AGENT_RUN_FAILED : code,\n cause: err,\n });\n}\n\n/**\n * Session storage errors.\n */\nexport class SessionError extends WrongStackError {\n readonly sessionId?: string;\n\n constructor(opts: {\n message: string;\n code: Extract<ErrorCode, 'SESSION_NOT_FOUND' | 'SESSION_CORRUPTED' | 'SESSION_WRITE_FAILED'>;\n sessionId?: string;\n context?: Record<string, unknown>;\n cause?: unknown;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'session',\n severity: opts.code === ERROR_CODES.SESSION_WRITE_FAILED ? 'error' : 'warning',\n recoverable: opts.code !== ERROR_CODES.SESSION_CORRUPTED,\n context: { sessionId: opts.sessionId, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'SessionError';\n this.sessionId = opts.sessionId;\n }\n}\n\n/**\n * File system operation errors.\n */\nexport class FsError extends WrongStackError {\n readonly path?: string;\n\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'FS_READ_FAILED' | 'FS_WRITE_FAILED' | 'FS_MKDIR_FAILED' | 'FS_DELETE_FAILED' | 'FS_ATOMIC_WRITE_FAILED'\n >;\n path?: string;\n context?: Record<string, unknown>;\n cause?: unknown;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'fs',\n severity: 'error',\n recoverable: opts.code !== ERROR_CODES.FS_READ_FAILED,\n context: { path: opts.path, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'FsError';\n this.path = opts.path;\n }\n}\n\n// ── Type guards ──────────────────────────────────────────────────────\n\nexport function isWrongStackError(err: unknown): err is WrongStackError {\n return err instanceof WrongStackError;\n}\n\nexport function isToolError(err: unknown): err is ToolError {\n return err instanceof ToolError;\n}\n\nexport function isConfigError(err: unknown): err is ConfigError {\n return err instanceof ConfigError;\n}\n\nexport function isPluginError(err: unknown): err is PluginError {\n return err instanceof PluginError;\n}\n\nexport function isSessionError(err: unknown): err is SessionError {\n return err instanceof SessionError;\n}\n\nexport function isAgentError(err: unknown): err is AgentError {\n return err instanceof AgentError;\n}\n\nexport function isFsError(err: unknown): err is FsError {\n return err instanceof FsError;\n}\n","import type { ContentBlock, TextBlock } from './blocks.js';\nimport type { ErrorCode } from './errors.js';\nimport { WrongStackError, ERROR_CODES } from './errors.js';\nimport type { Message } from './messages.js';\nimport type { Tool } from './tool.js';\n\n/**\n * Token usage for a single provider call, normalized across providers.\n *\n * Disjoint semantics: the four fields never overlap. `input` is the count\n * of FRESH input tokens (billed at the full input rate); `cacheRead` and\n * `cacheWrite` are separate cached subsets each priced at their own rate.\n * The total context the model loaded for this turn is\n * `input + (cacheRead ?? 0) + (cacheWrite ?? 0)`.\n *\n * Provider quirks normalized at the adapter layer:\n * - Anthropic: returns `input_tokens` already disjoint from cache fields.\n * - OpenAI / OpenAI-compatible: `prompt_tokens` is the TOTAL including\n * cached portion; the adapter subtracts `cached_tokens` to stay disjoint.\n * - Google: `promptTokenCount` likewise includes cache; adapter subtracts\n * `cachedContentTokenCount`.\n *\n * Cost math and the context-fullness chip both depend on the disjoint\n * invariant — a TOTAL `input` plus a separate `cacheRead` count would bill\n * cached tokens twice and skew cache-hit-ratio reporting.\n */\nexport interface Usage {\n input: number;\n output: number;\n cacheRead?: number;\n cacheWrite?: number;\n}\n\nexport interface Capabilities {\n tools: boolean;\n parallelTools: boolean;\n vision: boolean;\n streaming: boolean;\n promptCache: boolean;\n systemPrompt: boolean;\n jsonMode: boolean;\n maxContext: number;\n cacheControl: 'native' | 'auto' | 'none';\n}\n\nexport interface Request {\n model: string;\n system?: TextBlock[];\n messages: Message[];\n tools?: Tool[];\n maxTokens: number;\n temperature?: number;\n topP?: number;\n stopSequences?: string[];\n toolChoice?: 'auto' | 'required' | 'none' | { type: 'tool'; name: string };\n}\n\nexport type StopReason = 'end_turn' | 'tool_use' | 'max_tokens' | 'stop_sequence' | 'refusal';\n\nexport interface Response {\n content: ContentBlock[];\n stopReason: StopReason;\n usage: Usage;\n model: string;\n}\n\nexport type StreamEvent =\n | { type: 'message_start'; model: string }\n | {\n type: 'content_block_start';\n kind: 'text' | 'tool_use' | 'thinking';\n id?: string;\n name?: string;\n }\n | { type: 'content_block_stop'; index: number }\n | { type: 'text_delta'; text: string }\n | { type: 'tool_use_start'; id: string; name: string }\n | { type: 'tool_use_input_delta'; id: string; partial: string }\n | { type: 'tool_use_stop'; id: string; input: unknown; providerMeta?: Record<string, unknown> }\n | { type: 'thinking_start'; providerMeta?: Record<string, unknown> }\n | { type: 'thinking_delta'; text: string }\n | { type: 'thinking_signature'; signature: string }\n | { type: 'thinking_stop' }\n | { type: 'message_stop'; stopReason: StopReason; usage: Usage };\n\nexport interface Provider {\n readonly id: string;\n readonly capabilities: Capabilities;\n /** Canonical streaming entry point. `complete()` defaults to a wrapper that\n * aggregates this stream — providers may override for non-streaming wires. */\n stream(req: Request, opts: { signal: AbortSignal }): AsyncIterable<StreamEvent>;\n complete(req: Request, opts: { signal: AbortSignal }): Promise<Response>;\n}\n\n/**\n * Structured body parsed from a provider's HTTP error response. Populated\n * best-effort: providers return JSON shaped differently (Anthropic uses\n * `{error: {type, message}}`, OpenAI uses `{error: {message, code}}`,\n * Google uses `{error: {status, message}}`), so the fields here are the\n * intersection that's usable for rendering and routing.\n */\nexport interface ProviderErrorBody {\n /** Provider-specific kind, e.g. \"overloaded_error\", \"rate_limit_error\", \"invalid_request_error\". */\n type?: string;\n /** Human-readable explanation from the provider. */\n message?: string;\n /** Provider request id, when present in the body or headers. */\n requestId?: string;\n /** Parsed Retry-After header (or equivalent body hint) in milliseconds. */\n retryAfterMs?: number;\n /** The raw response body (truncated to ~2 KB), kept for debugging. */\n raw?: string;\n /** True when `raw` was truncated; check `rawLength` for the original size. */\n truncated?: boolean;\n /** Original length of the response body in bytes, when `truncated` is true. */\n rawLength?: number;\n}\n\nexport class ProviderError extends WrongStackError {\n public readonly status: number;\n public readonly retryable: boolean;\n public readonly providerId: string;\n public readonly body?: ProviderErrorBody;\n\n constructor(\n message: string,\n status: number,\n retryable: boolean,\n providerId: string,\n opts: { body?: ProviderErrorBody; cause?: unknown } = {},\n ) {\n super({\n message,\n code: providerStatusToCode(status, opts.body?.type),\n subsystem: 'provider',\n severity: status >= 500 ? 'error' : 'warning',\n recoverable: retryable,\n context: { providerId, status },\n cause: opts.cause,\n });\n this.name = 'ProviderError';\n this.status = status;\n this.retryable = retryable;\n this.providerId = providerId;\n this.body = opts.body;\n }\n\n /**\n * Render a one-line, user-facing description. Designed for the CLI/TUI\n * status line and the agent's retry warning. Avoids dumping raw JSON\n * (which is what users see today when a 529 lands and the log message\n * includes the full `{\"type\":\"error\",...}` body).\n *\n * Examples:\n * \"minimax-coding-plan overloaded (529): High traffic detected. Upgrade for highspeed model. [req 06534785201de9c0…]\"\n * \"openai rate limited (429): Retry after 12s\"\n * \"anthropic invalid request (400): messages.0.role must be one of 'user'|'assistant'\"\n * \"groq HTTP 500 (server error)\"\n */\n override describe(): string {\n const kind = describeStatus(this.status, this.body?.type);\n const head = `${this.providerId} ${kind}`;\n const detail = this.body?.message?.trim();\n const reqId = this.body?.requestId\n ? ` [req ${this.body.requestId.slice(0, 16)}${this.body.requestId.length > 16 ? '…' : ''}]`\n : '';\n if (detail && detail.length > 0) {\n return `${head}: ${truncate(detail, 240)}${reqId}`;\n }\n return `${head}${reqId}`;\n }\n}\n\nfunction describeStatus(status: number, type?: string): string {\n if (status === 0) return 'network error';\n if (type === 'overloaded_error' || status === 529) return `overloaded (${status})`;\n if (type === 'rate_limit_error' || status === 429) return `rate limited (${status})`;\n if (type === 'authentication_error' || status === 401) return `auth failed (${status})`;\n if (type === 'permission_error' || status === 403) return `forbidden (${status})`;\n if (type === 'not_found_error' || status === 404) return `not found (${status})`;\n if (type === 'invalid_request_error' || status === 400) return `invalid request (${status})`;\n if (status === 408) return `timeout (${status})`;\n if (status >= 500 && status < 600) return `HTTP ${status} (server error)`;\n if (type) return `${type} (${status})`;\n return `HTTP ${status}`;\n}\n\nfunction truncate(s: string, n: number): string {\n return s.length <= n ? s : `${s.slice(0, n - 1)}…`;\n}\n\nfunction providerStatusToCode(status: number, type?: string): ErrorCode {\n if (status === 0) return ERROR_CODES.PROVIDER_NETWORK_ERROR;\n if (type === 'rate_limit_error' || status === 429) return ERROR_CODES.PROVIDER_RATE_LIMITED;\n if (type === 'authentication_error' || status === 401) return ERROR_CODES.PROVIDER_AUTH_FAILED;\n if (type === 'overloaded_error' || status === 529) return ERROR_CODES.PROVIDER_OVERLOADED;\n if (type === 'invalid_request_error' || status === 400) return ERROR_CODES.PROVIDER_INVALID_REQUEST;\n if (status === 408) return ERROR_CODES.PROVIDER_NETWORK_ERROR;\n if (status >= 500) return ERROR_CODES.PROVIDER_SERVER_ERROR;\n return ERROR_CODES.PROVIDER_INVALID_REQUEST;\n}\n","import type { Usage } from '../types/provider.js';\nimport type { EventBus } from '../kernel/events.js';\n\nexport type BudgetKind = 'tool_calls' | 'iterations' | 'tokens' | 'timeout' | 'idle_timeout' | 'cost';\n\nexport class BudgetExceededError extends Error {\n readonly kind: BudgetKind;\n readonly limit: number;\n readonly observed: number;\n\n constructor(kind: BudgetKind, limit: number, observed: number) {\n super(`Budget exceeded: ${kind} (limit=${limit}, observed=${observed})`);\n this.name = 'BudgetExceededError';\n this.kind = kind;\n this.limit = limit;\n this.observed = observed;\n }\n}\n\nexport interface BudgetLimits {\n maxIterations?: number;\n maxToolCalls?: number;\n maxTokens?: number;\n /** Estimated USD cost ceiling. */\n maxCostUsd?: number;\n /**\n * Hard wall-clock timeout measured from `start()`. Off by default — set it\n * explicitly only when a task must finish within an absolute window. For\n * the everyday \"don't kill an agent that's still working\" guard, prefer\n * `idleTimeoutMs`, which resets on activity.\n */\n timeoutMs?: number;\n /**\n * Idle timeout: the maximum gap (ms) between activity signals (iterations,\n * tool calls, token usage, streamed progress) before the subagent is\n * considered hung and reaped. Unlike `timeoutMs`, an actively-working\n * agent continuously resets this clock via `markActivity()`, so it never\n * trips on a long-but-productive run — only on a genuine stall.\n */\n idleTimeoutMs?: number;\n}\n\n/**\n * Controls how the budget behaves when `onThreshold` is set and a limit is hit.\n *\n * `'auto'` — emit `budget.threshold_reached` on the EventBus and wait for a\n * coordinator response (extend/stop). If no listener responds within\n * `DECISION_TIMEOUT_MS` the decision defaults to `'stop'`.\n * `'sync'` — do not emit any event; treat the threshold as a hard stop and\n * throw `BudgetExceededError` synchronously. Useful for fire-and-forget\n * subagents that have an `onThreshold` handler for logging/metrics but are\n * not wired into a coordinator.\n *\n * @default 'auto'\n */\nexport type BudgetNegotiationMode = 'auto' | 'sync';\n\nexport interface BudgetUsage {\n iterations: number;\n toolCalls: number;\n tokens: { input: number; output: number; total: number };\n costUsd: number;\n elapsedMs: number;\n}\n\n/**\n * Thrown by `SubagentBudget.record*` when a soft limit is hit and\n * an `onThreshold` handler is configured that wants to ask the\n * coordinator (via `budget.threshold_reached` event). The runner\n * catches this and awaits the embedded `decision` promise to get\n * the coordinator's extend/stop decision.\n *\n * Distinct from `BudgetExceededError` which is a hard stop.\n */\nexport class BudgetThresholdSignal extends Error {\n readonly kind: BudgetKind;\n readonly limit: number;\n readonly used: number;\n /** Resolves to 'extend' (with optional new limits) or 'stop' */\n readonly decision: Promise<BudgetThresholdDecision>;\n\n constructor(\n kind: BudgetKind,\n limit: number,\n used: number,\n decision: Promise<BudgetThresholdDecision>,\n ) {\n super(`Budget soft limit: ${kind} (limit=${limit}, used=${used})`);\n this.name = 'BudgetThresholdSignal';\n this.kind = kind;\n this.limit = limit;\n this.used = used;\n this.decision = decision;\n }\n}\n\nexport type BudgetThresholdDecision =\n | 'stop'\n | { extend: Partial<BudgetLimits> };\n\n/**\n * Callback invoked when a budget limit is about to be exceeded.\n * Return 'throw' for hard stop (default — throws BudgetExceededError).\n * Return 'continue' to allow one more unit and re-check next time.\n * Return a Promise to ask the coordinator via `budget.threshold_reached`\n * event (uses the same grant/deny pattern as `iteration.limit_reached`).\n */\nexport type BudgetThresholdHandler = (info: {\n kind: BudgetKind;\n used: number;\n limit: number;\n requestDecision: () => Promise<BudgetThresholdDecision>;\n}) => 'throw' | 'continue' | Promise<BudgetThresholdDecision>;\n\n/**\n * Per-subagent budget enforcement. Each subagent gets its own instance so a\n * runaway agent can't drain the cost ceiling of its siblings. All record/check\n * methods are O(1) and safe to call from hot paths.\n *\n * Behavior without `onThreshold`: hard stops synchronously on every limit hit.\n *\n * Behavior with `onThreshold` and `_mode === 'auto'`: emits `budget.threshold_reached`\n * on the EventBus and throws `BudgetThresholdSignal`. The coordinator's verdict\n * (extend/stop) resolves the embedded promise. If no listener responds within\n * `DECISION_TIMEOUT_MS` the decision defaults to `'stop'`.\n *\n * Behavior with `onThreshold` and `_mode === 'sync'`: throws `BudgetExceededError`\n * synchronously regardless of EventBus state or listener presence. This is useful\n * for fire-and-forget subagents that have an `onThreshold` handler for logging/metrics\n * but are not wired into a coordinator — the `'sync'` mode makes the hard-stop\n * behavior explicit and means tests can use `expect().toThrow()` even without\n * a fully-wired EventBus.\n */\nexport class SubagentBudget {\n readonly limits: Readonly<BudgetLimits>;\n private iterations = 0;\n private toolCalls = 0;\n private tokenInput = 0;\n private tokenOutput = 0;\n private costUsd = 0;\n private startTime: number | null = null;\n /**\n * Timestamp of the most recent activity (iteration / tool call / token\n * usage / streamed progress). Drives the idle timeout — reset by\n * `markActivity()`. Initialised to `start()` time so a never-active agent\n * still eventually trips its idle window.\n */\n private lastActivityTime: number | null = null;\n private _onThreshold: BudgetThresholdHandler | undefined;\n /**\n * Hard cap on how long `_negotiateExtension` waits for the coordinator to\n * respond before defaulting to 'stop'. Without this fallback an absent\n * or hung listener (Director not built / event filter detached mid-run)\n * leaves the budget over-limit and never enforces anything.\n */\n private static readonly DECISION_TIMEOUT_MS = 60_000;\n /**\n * Injected by the runner when wiring the budget to its EventBus.\n * Used to emit `budget.threshold_reached` events in `'auto'` mode.\n */\n _events?: EventBus;\n\n /**\n * Negotiation mode — controls whether a threshold hit tries to emit\n * `budget.threshold_reached` and wait for a coordinator decision, or\n * falls straight through to a synchronous hard stop.\n *\n * `'auto'` (default) — emit on the EventBus and wait; times out to 'stop'.\n * `'sync'` — throw `BudgetExceededError` immediately regardless of listeners.\n */\n private _mode: BudgetNegotiationMode;\n\n /**\n * Optional callback for soft-limit handling. When set, the budget will\n * invoke it rather than throw immediately. The handler decides whether to\n * throw synchronously, continue, or ask the coordinator for an extension.\n */\n get onThreshold(): BudgetThresholdHandler | undefined {\n return this._onThreshold;\n }\n set onThreshold(fn: BudgetThresholdHandler | undefined) {\n this._onThreshold = fn;\n }\n\n /** Returns the current negotiation mode. */\n get mode(): BudgetNegotiationMode {\n return this._mode;\n }\n\n constructor(limits: BudgetLimits = {}, mode: BudgetNegotiationMode = 'auto') {\n this._mode = mode;\n // NOT frozen: `negotiateExtension` patches these limits in place when the\n // coordinator grants an auto-extension. Freezing made every granted\n // extension throw `TypeError: Cannot assign to read only property` in\n // strict mode, which the runner caught as a hard stop — so extensions\n // silently became kills. The `readonly limits: Readonly<BudgetLimits>`\n // typing still blocks external mutation at compile time.\n this.limits = { ...limits };\n }\n\n start(): void {\n this.startTime = Date.now();\n this.lastActivityTime = this.startTime;\n }\n\n /**\n * Reset the idle clock. Called on any sign of forward progress —\n * iterations, tool calls, token usage, and streamed tool/text progress —\n * so a long-but-productive subagent never trips its `idleTimeoutMs`.\n */\n markActivity(): void {\n this.lastActivityTime = Date.now();\n }\n\n /**\n * Milliseconds since the last activity signal. Returns 0 before `start()`\n * (nothing to measure yet). Used by the coordinator watchdog to decide\n * whether to re-arm (still active) or reap (genuinely idle).\n */\n idleMs(): number {\n const since = this.lastActivityTime ?? this.startTime;\n return since === null ? 0 : Date.now() - since;\n }\n\n /** Returns true if we're within 10% of any limit — useful for pre-flight checks. */\n isNearLimit(): boolean {\n const { maxIterations, maxToolCalls, maxTokens, maxCostUsd } = this.limits;\n if (maxIterations && this.iterations >= maxIterations * 0.9) return true;\n if (maxToolCalls && this.toolCalls >= maxToolCalls * 0.9) return true;\n if (maxTokens && this.tokenInput + this.tokenOutput >= maxTokens * 0.9) return true;\n if (maxCostUsd && this.costUsd >= maxCostUsd * 0.9) return true;\n return false;\n }\n\n /**\n * Synchronous budget check. Always throws synchronously so callers (especially\n * test event handlers using `expect().toThrow()`) get an unhandled rejection\n * when the budget is exceeded without a handler.\n *\n * Decision table:\n * - no `onThreshold` handler → throw `BudgetExceededError` (hard stop, always)\n * - `mode === 'sync'` → throw `BudgetExceededError` (hard stop, always)\n * - `mode === 'auto'` + no listener → throw `BudgetExceededError` (hard stop; no one to ask)\n * - `mode === 'auto'` + listener → throw `BudgetThresholdSignal` with async decision promise\n */\n /**\n * Collects all exceeded budget kinds into a single NOOP-free negotiation.\n * Called by recordIteration / recordToolCall / recordUsage — each may call\n * this for its own kind. The first call starts the negotiation and stores\n * the Promise in _pendingNegotiation. Subsequent calls for DIFFERENT\n * kinds (while a negotiation is in flight) are NOOPs — they don't start\n * new conversations with the coordinator. This prevents an EventBus flood\n * when multiple budget kinds are exceeded simultaneously in one iteration.\n *\n * Returns the kinds that were found to be exceeded (for logging/debugging).\n */\n private checkLimits(elapsedMs?: number): { kind: BudgetKind; used: number; limit: number }[] {\n const exceeded: { kind: BudgetKind; used: number; limit: number }[] = [];\n\n if (this.limits.maxIterations !== undefined && this.iterations > this.limits.maxIterations) {\n exceeded.push({ kind: 'iterations', used: this.iterations, limit: this.limits.maxIterations });\n }\n if (this.limits.maxToolCalls !== undefined && this.toolCalls > this.limits.maxToolCalls) {\n exceeded.push({ kind: 'tool_calls', used: this.toolCalls, limit: this.limits.maxToolCalls });\n }\n const totalTokens = this.tokenInput + this.tokenOutput;\n if (this.limits.maxTokens !== undefined && totalTokens > this.limits.maxTokens) {\n exceeded.push({ kind: 'tokens', used: totalTokens, limit: this.limits.maxTokens });\n }\n if (this.limits.maxCostUsd !== undefined && this.costUsd > this.limits.maxCostUsd) {\n exceeded.push({ kind: 'cost', used: this.costUsd, limit: this.limits.maxCostUsd });\n }\n // Timeout: called from checkTimeout() with elapsedMs (wall-clock) and the\n // current idle gap. Either crossing its limit trips its own kind so the\n // coordinator and auto-extend policy can distinguish them.\n // Wall-clock (`timeoutMs`) is an explicit hard cap; idle (`idleTimeoutMs`)\n // is the default guard that resets on activity. Both can be exceeded in\n // the same call — we push both entries so all violated limits are reported.\n if (elapsedMs !== undefined) {\n const idle = this.idleMs();\n if (this.limits.idleTimeoutMs !== undefined && idle > this.limits.idleTimeoutMs) {\n exceeded.push({ kind: 'idle_timeout', used: idle, limit: this.limits.idleTimeoutMs });\n }\n if (this.limits.timeoutMs !== undefined && elapsedMs > this.limits.timeoutMs) {\n exceeded.push({ kind: 'timeout', used: elapsedMs, limit: this.limits.timeoutMs });\n }\n }\n\n if (exceeded.length === 0) return [];\n\n if (!this._onThreshold) {\n // Hard stop — throw on the first exceeded kind.\n const first = exceeded[0]!;\n throw new BudgetExceededError(first.kind, first.limit, first.used);\n }\n if (this._mode === 'sync') {\n // Hard stop in sync mode.\n const first = exceeded[0]!;\n throw new BudgetExceededError(first.kind, first.limit, first.used);\n }\n const bus = this._events;\n if (!bus || !bus.hasListenerFor('budget.threshold_reached')) {\n const first = exceeded[0]!;\n throw new BudgetExceededError(first.kind, first.limit, first.used);\n }\n\n // Start a negotiation for each exceeded kind that doesn't already have one.\n // The first exceeded kind throws BudgetThresholdSignal so the caller sees\n // the soft-limit event. Subsequent exceeded kinds (in the same call) start\n // their own negotiations silently — they won't throw again.\n for (const entry of exceeded) {\n if (this._pendingNegotiations.has(entry.kind)) continue; // already negotiating this kind\n const decision = this._negotiateExtension(entry.kind, exceeded);\n this._pendingNegotiations.set(entry.kind, decision);\n }\n\n const first = exceeded[0]!;\n const decision = this._pendingNegotiations.get(first.kind)!;\n throw new BudgetThresholdSignal(first.kind, first.limit, first.used, decision);\n }\n\n /**\n * Per-kind in-flight negotiation Promises. Each budget kind can have its\n * own concurrent negotiation — e.g. iterations and timeout can both\n * be exceeded simultaneously without blocking each other. The same kind\n * cannot start two concurrent negotiations (dedup guard).\n * Cleared in `_negotiateExtension`'s `finally` block.\n */\n private _pendingNegotiations = new Map<BudgetKind, Promise<BudgetThresholdDecision>>();\n\n /**\n * Drive the threshold handler to a decision. Resolves with `'stop'`\n * (signal the runner to abort) or `{ extend: ... }` (limits already\n * patched in-place; the runner should not abort). Clears the\n * per-kind slot in `_pendingNegotiations` in `finally`.\n *\n * The 'continue' return from a sync handler is treated as\n * `{ extend: {} }` — keep going without patching; next overrun fires\n * a fresh signal.\n */\n private async _negotiateExtension(\n kind: BudgetKind,\n exceeded: { kind: BudgetKind; used: number; limit: number }[],\n ): Promise<BudgetThresholdDecision> {\n try {\n // Use the first exceeded kind for the handler call.\n const first = exceeded[0]!;\n const result = this._onThreshold!({\n kind: first.kind,\n used: first.used,\n limit: first.limit,\n requestDecision: (): Promise<BudgetThresholdDecision> => {\n const bus = this._events;\n if (!bus || !bus.hasListenerFor('budget.threshold_reached')) {\n return Promise.resolve('stop');\n }\n return new Promise<BudgetThresholdDecision>((resolve) => {\n let resolved = false;\n const respond = (d: BudgetThresholdDecision) => {\n if (resolved) return;\n resolved = true;\n resolve(d);\n };\n const fallback = setTimeout(\n () => respond('stop'),\n SubagentBudget.DECISION_TIMEOUT_MS,\n );\n // Emit one event per exceeded kind so the FleetBus routes them.\n for (const { kind, used, limit } of exceeded) {\n bus.emit('budget.threshold_reached', {\n kind: kind as 'iterations' | 'tool_calls' | 'tokens' | 'cost' | 'timeout' | 'idle_timeout',\n used,\n limit,\n timeoutMs: SubagentBudget.DECISION_TIMEOUT_MS,\n extend: (extra: Partial<BudgetLimits>) => {\n clearTimeout(fallback);\n respond({ extend: extra });\n },\n deny: () => {\n clearTimeout(fallback);\n respond('stop');\n },\n });\n }\n });\n },\n });\n\n if (result === 'throw') return 'stop';\n if (result === 'continue') return { extend: {} };\n\n const decision = await result;\n if (decision === 'stop') return 'stop';\n\n // 'extend' — patch in-place limits BEFORE resolving so the runner's\n // continue path sees the new ceiling.\n const ext = decision.extend;\n if (ext.maxIterations !== undefined) {\n (this.limits as Record<string, unknown>).maxIterations = ext.maxIterations;\n }\n if (ext.maxToolCalls !== undefined) {\n (this.limits as Record<string, unknown>).maxToolCalls = ext.maxToolCalls;\n }\n if (ext.maxTokens !== undefined) {\n (this.limits as Record<string, unknown>).maxTokens = ext.maxTokens;\n }\n if (ext.maxCostUsd !== undefined) {\n (this.limits as Record<string, unknown>).maxCostUsd = ext.maxCostUsd;\n }\n if (ext.timeoutMs !== undefined) {\n (this.limits as Record<string, unknown>).timeoutMs = ext.timeoutMs;\n }\n if (ext.idleTimeoutMs !== undefined) {\n (this.limits as Record<string, unknown>).idleTimeoutMs = ext.idleTimeoutMs;\n }\n return decision;\n } finally {\n this._pendingNegotiations.delete(kind);\n }\n }\n\n recordIteration(): void {\n this.iterations++;\n this.markActivity();\n void this.checkLimits();\n }\n\n recordToolCall(): void {\n this.toolCalls++;\n this.markActivity();\n void this.checkLimits();\n }\n\n recordUsage(usage: Usage, costUsd = 0): void {\n this.tokenInput += usage.input;\n this.tokenOutput += usage.output;\n this.costUsd += costUsd;\n this.markActivity();\n void this.checkLimits();\n }\n\n /**\n * Wall-clock budget check. Unlike other limits, timeout is always a hard stop\n * — wall-clock time cannot be \"extended\" by the coordinator, so it throws\n * synchronously rather than entering the negotiation flow.\n *\n * Decision table:\n * - no `onThreshold` handler → throw `BudgetExceededError`\n * - `mode === 'sync'` → throw `BudgetExceededError`\n * - `mode === 'auto'` + no listener → throw `BudgetExceededError`\n * - `mode === 'auto'` + listener → throw `BudgetExceededError` (timeout is not extendable)\n */\n checkTimeout(): void {\n if (this.startTime === null) return;\n const { timeoutMs, idleTimeoutMs } = this.limits;\n if (timeoutMs === undefined && idleTimeoutMs === undefined) return;\n const elapsed = Date.now() - this.startTime;\n const wallTripped = timeoutMs !== undefined && elapsed > timeoutMs;\n const idleTripped = idleTimeoutMs !== undefined && this.idleMs() > idleTimeoutMs;\n if (!wallTripped && !idleTripped) return;\n void this.checkLimits(elapsed);\n }\n\n /** Returns true if a wall-clock or idle timeout has occurred without throwing. */\n isTimedOut(): boolean {\n if (this.startTime === null) return false;\n const { timeoutMs, idleTimeoutMs } = this.limits;\n if (timeoutMs !== undefined && Date.now() - this.startTime > timeoutMs) return true;\n if (idleTimeoutMs !== undefined && this.idleMs() > idleTimeoutMs) return true;\n return false;\n }\n\n usage(): BudgetUsage {\n return {\n iterations: this.iterations,\n toolCalls: this.toolCalls,\n tokens: {\n input: this.tokenInput,\n output: this.tokenOutput,\n total: this.tokenInput + this.tokenOutput,\n },\n costUsd: this.costUsd,\n elapsedMs: this.startTime === null ? 0 : Date.now() - this.startTime,\n };\n }\n}\n","/**\r\n * Pre-built subagent role configurations for the WrongStack fleet.\r\n * These can be passed to `MultiAgentHost.spawn()` or used as templates\r\n * for the director's roster.\r\n */\r\nimport type { SubagentConfig } from '../types/multi-agent.js';\r\nimport { ALL_AGENT_DEFINITIONS } from './agents/index.js';\r\n\r\n/**\r\n * Audit Log Agent — analyzes session logs, event streams, and traces.\r\n * Use for: post-mortems, trend analysis, operational insights.\r\n */\r\nexport const AUDIT_LOG_AGENT: SubagentConfig = {\r\n id: 'audit-log',\r\n name: 'Audit Log',\r\n role: 'audit-log',\r\n prompt: `You are the Audit Log agent. Your job is to analyze structured JSONL\r\nsession logs and produce actionable markdown reports.\r\n\r\nScope:\r\n- Parse session logs (iteration counts, tool calls, errors, usage)\r\n- Detect repeated failure patterns across multiple runs\r\n- Identify tool usage anomalies (over-use, failures, unexpected chains)\r\n- Track token consumption trends\r\n- Generate structured audit reports with severity ratings\r\n\r\nInput format you accept:\r\n{ \"task\": \"analyze | report | trends\", \"sessionPath\": \"<path>\", \"focus\": \"errors | tools | usage | all\" }\r\n\r\nOutput: Markdown audit report with sections:\r\n- ## Summary (totals, error rate)\r\n- ## Top Errors (count + context)\r\n- ## Tool Usage (table with calls, failures, avg duration)\r\n- ## Anomalies (pattern → severity)\r\n\r\nWorking rules:\r\n- Never fabricate numbers — read the actual logs first\r\n- Always include file:line references for errors\r\n- If sessionPath is missing, ask the director to provide it\r\n- Report confidence level: high (>90% accuracy), medium, low`,\r\n\r\n // No hardcoded budgets — the orchestrator (delegate tool or\r\n // spawn_subagent) decides per-task how much room a subagent gets.\r\n // A monorepo audit needs hours; a single-file lint check needs\r\n // seconds. Pinning a number here forces the orchestrator to fight\r\n // the role's default instead of just asking for what it needs.\r\n};\r\n\r\n/**\r\n * Bug Hunter Agent — systematic bug and code smell detection.\r\n * Use for: pre-refactoring health checks, code review, regression prevention.\r\n */\r\nexport const BUG_HUNTER_AGENT: SubagentConfig = {\r\n id: 'bug-hunter',\r\n name: 'Bug Hunter',\r\n role: 'bug-hunter',\r\n prompt: `You are the Bug Hunter agent. Your job is to systematically scan\r\nsource code for bugs, anti-patterns, and code smells using pattern matching\r\nand heuristics. Output a prioritized hit list with file:line references.\r\n\r\nScope:\r\n- Detect common bug patterns (uncaught errors, resource leaks, race conditions)\r\n- Identify anti-patterns (callback hell, God objects, circular deps)\r\n- Find TypeScript-specific issues (unsafe any, missing null checks, branded types)\r\n- Flag security-sensitive constructs (eval, innerHTML, hardcoded secrets)\r\n- Rank findings: critical > high > medium > low\r\n\r\nInput format you accept:\r\n{ \"task\": \"scan | hunt | check\", \"paths\": [\"src/**/*.ts\"], \"focus\": \"bugs | patterns | security | all\", \"severityThreshold\": \"medium\" }\r\n\r\nOutput: Markdown bug hunt report:\r\n- ## Critical (must fix first)\r\n- ## High (should fix)\r\n- ## Medium\r\n- ## Low (consider)\r\nEach entry: **[TYPE]** \\`file:line\\` — description + suggested fix\r\n\r\nBug pattern reference you know:\r\n| Pattern | Regex hint | Severity |\r\n|---------|------------|----------|\r\n| Uncaught promise | /\\.then\\\\(.*\\\\)/ without catch | high |\r\n| Event leak | on\\\\( without off/removeListener | high |\r\n| Hardcoded secret | [a-zA-Z0-9/_-]{20,} in config files | critical |\r\n| unsafe any | : any\\\\b or <any> | medium |\r\n| innerHTML | innerHTML\\\\s*= | high |\r\n\r\nWorking rules:\r\n- Never scan node_modules — it's noise\r\n- Always include file:line for every finding\r\n- If >30% of findings are false positives, note the confidence level\r\n- Ask director for clarification if paths are ambiguous`,\r\n\r\n // Budgets are set by the orchestrator per task — see fleet.ts header.\r\n};\r\n\r\n/**\r\n * Refactor Planner Agent — structured refactoring planning.\r\n * Use for: large rewrites, technical debt reduction, architecture improvements.\r\n */\r\nexport const REFACTOR_PLANNER_AGENT: SubagentConfig = {\r\n id: 'refactor-planner',\r\n name: 'Refactor Planner',\r\n role: 'refactor-planner',\r\n prompt: `You are the Refactor Planner agent. Your job is to analyze code\r\nstructure and produce a concrete, phased refactoring plan with risk\r\nassessment, dependency ordering, and rollback strategy.\r\n\r\nScope:\r\n- Map module-level dependencies (import graph)\r\n- Identify coupling hotspots (high fan-in/out modules)\r\n- Assess refactoring risk by complexity and test coverage\r\n- Generate phased plans with checkpoint milestones\r\n- Produce diff-friendly task lists (one task = one concern)\r\n\r\nInput format you accept:\r\n{ \"task\": \"plan | assess | roadmap\", \"target\": \"src/core\", \"constraint\": \"no-breaking-changes | minimal-downtime | full-rewrite\", \"focus\": \"architecture | performance | maintainability\" }\r\n\r\nOutput: Markdown refactor plan:\r\n- ## Phase 1: Low Risk / High Payoff (do first)\r\n Table: | # | Task | Module | Risk | Est. Time |\r\n- ## Phase 2: Medium Risk\r\n- ## Phase 3: High Risk (requires full regression)\r\n- ## Dependency Graph (abbreviated ASCII)\r\n- ## Rollback Strategy\r\n- ## Exit Criteria (checkbox list)\r\n\r\nRisk scoring criteria:\r\n| Factor | Low | Medium | High |\r\n|--------|-----|--------|------|\r\n| Cyclomatic complexity | <10 | 10-20 | >20 |\r\n| Test coverage | >80% | 50-80% | <50% |\r\n| Fan-out (imports) | <5 | 5-15 | >15 |\r\n\r\nWorking rules:\r\n- Always include rollback strategy — every refactor can fail\r\n- Merge tasks that take <1h into a single phase\r\n- Respect team constraints (reviewer availability, parallelization)\r\n- Never plan without analyzing the actual code first`,\r\n\r\n // Budgets are set by the orchestrator per task — see fleet.ts header.\r\n};\r\n\r\n/**\r\n * Security Scanner Agent — vulnerability and secret detection.\r\n * Use for: CI checks, pre-release audits, dependency vulnerability scanning.\r\n */\r\nexport const SECURITY_SCANNER_AGENT: SubagentConfig = {\r\n id: 'security-scanner',\r\n name: 'Security Scanner',\r\n role: 'security-scanner',\r\n prompt: `You are the Security Scanner agent. Your job is to scan code,\r\nconfigs, and dependencies for security issues from hardcoded secrets to\r\nsupply chain risks.\r\n\r\nScope:\r\n- Detect hardcoded secrets: API keys, tokens, passwords, private keys\r\n- Find injection vectors: eval, innerHTML, SQL concat, shell injection\r\n- Identify insecure patterns: weak crypto, hardcoded IVs, disabled TLS\r\n- Scan dependencies for known CVEs (via npm/pnpm audit)\r\n- Flag supply chain risks: postinstall hooks, unverified scripts, .npmrc\r\n\r\nInput format you accept:\r\n{ \"task\": \"scan | audit | secrets | dependencies\", \"paths\": [\"src\", \"config\"], \"depth\": \"quick | normal | deep\" }\r\n\r\nOutput: Markdown security report:\r\n- ## CRITICAL: Secrets Found (with code snippets)\r\n- ## HIGH: Injection Vectors\r\n- ## MEDIUM: Insecure Patterns\r\n- ## Dependency Issues (CVE list)\r\n- ## Summary table (severity → count)\r\n- ## Remediation Checklist (with checkboxes)\r\n\r\nSecret patterns you detect:\r\n| Pattern | Example | Severity |\r\n|---------|---------|----------|\r\n| AWS Access Key | AKIAIOSFODNN7EXAMPLE | critical |\r\n| AWS Secret Key | [a-zA-Z0-9/+=]{40} base64 | critical |\r\n| GitHub Token | ghp_[a-zA-Z0-9]{36} | critical |\r\n| Private Key PEM | -----BEGIN.*PRIVATE KEY----- | critical |\r\n| JWT | eyJ[a-zA-Z0-9_-]+ | high |\r\n\r\nInjection patterns:\r\n| Construct | Safe alternative |\r\n|-----------|-----------------|\r\n| eval(str) | new Function() or parse |\r\n| innerHTML = x | textContent or sanitize |\r\n| exec(\\`cmd \\${x}\\`) | execFile with args array |\r\n\r\nWorking rules:\r\n- Never scan node_modules — use npm audit instead\r\n- Always provide remediation steps, not just findings\r\n- Verify regex-based secrets before flagging (false positive risk)\r\n- When in doubt, flag as medium rather than ignoring potential issues`,\r\n\r\n // Budgets are set by the orchestrator per task — see fleet.ts header.\r\n};\r\n\r\n/**\r\n * Critic Agent — evaluates code quality, architecture decisions, and\r\n * refactoring plans against project conventions and engineering standards.\r\n * Use for: real-time evaluation of bug reports, refactor plans, and\r\n * architectural proposals during collaborative debugging sessions.\r\n */\r\nexport const CRITIC_AGENT: SubagentConfig = {\r\n id: 'critic',\r\n name: 'Critic',\r\n role: 'critic',\r\n prompt: `You are the Critic agent. Your job is to evaluate code quality,\r\narchitectural decisions, and proposed changes against project conventions,\r\nengineering standards, and known quality gates. You do not write code —\r\nyou judge it.\r\n\r\nScope:\r\n- Evaluate bug severity and fix quality from Bug Hunter reports\r\n- Score refactoring plans from Refactor Planner (risk, completeness, trade-offs)\r\n- Flag gaps in test coverage, error handling, and edge case coverage\r\n- Assess whether a proposed change aligns with existing project patterns\r\n- Detect over-engineering or under-engineering relative to the problem scope\r\n\r\nInput format you accept:\r\n{ \"task\": \"evaluate | score | review\", \"subject\": \"bug_report | refactor_plan | diff\", \"focus\": \"correctness | maintainability | risk | all\" }\r\n\r\nOutput: Markdown critic report:\r\n- ## Overall Score (0-10 with rationale)\r\n- ## Strengths (what's solid)\r\n- ## Weaknesses (what needs work)\r\n- ## Specific Concerns (with file:line when applicable)\r\n- ## Verdict: **Approve / Needs Revision / Reject**\r\n\r\nWorking rules:\r\n- Be specific — \"looks fine\" is not a review. Cite concrete evidence.\r\n- When scoring, explain the delta from a perfect score.\r\n- If you have no basis to evaluate a concern, say so rather than speculating.\r\n- Prioritise correctness over style; correctness issues block approval.\r\n- Score thresholds: ≥7 = Approve, 4-6 = Needs Revision, <4 = Reject`,\r\n\r\n // Budgets are set by the orchestrator per task — see fleet.ts header.\r\n};\r\n\r\n/**\r\n * All agents in a map for easy lookup by role. The four legacy pre-built\r\n * agents plus the phase 1-9 catalog (`ALL_AGENT_DEFINITIONS`). Catalog roles\r\n * are guaranteed collision-free by the catalog builder; none overlap the\r\n * legacy four.\r\n */\r\nexport const FLEET_ROSTER: Record<string, SubagentConfig> = {\r\n 'audit-log': AUDIT_LOG_AGENT,\r\n 'bug-hunter': BUG_HUNTER_AGENT,\r\n 'refactor-planner': REFACTOR_PLANNER_AGENT,\r\n 'security-scanner': SECURITY_SCANNER_AGENT,\r\n 'critic': CRITIC_AGENT,\r\n ...Object.fromEntries(\r\n ALL_AGENT_DEFINITIONS.map((d) => [d.config.role as string, d.config] as const),\r\n ),\r\n};\r\n\r\n// ---------------------------------------------------------------------------\r\n// Default per-role budgets.\r\n//\r\n// MASSIVELY RAISED from earlier values. User requested x5–x10 multiplier\r\n// to prevent any timeout or budget exhaustion on long-running tasks\r\n// like monorepo audits, deep refactors, and security scans.\r\n//\r\n// x10 values (realistic upper bound for a single subagent task):\r\n// audit-log: 7.5 hours, 5000 iterations, 15000 tool calls\r\n// bug-hunter: 10 hours, 8000 iterations, 20000 tool calls\r\n// refactor-planner: 7.5 hours, 6000 iterations, 18000 tool calls\r\n// security-scanner: 10 hours, 8000 iterations, 20000 tool calls\r\n//\r\n// These can be overridden per-call via delegate tool parameters.\r\n// ---------------------------------------------------------------------------\r\nexport interface FleetRosterBudget {\r\n timeoutMs?: number;\r\n /** Idle reap window (ms). Resets on activity — see `applyRosterBudget`. */\r\n idleTimeoutMs?: number;\r\n maxIterations?: number;\r\n maxToolCalls?: number;\r\n maxTokens?: number;\r\n maxCostUsd?: number;\r\n}\r\n\r\n/**\r\n * Default idle window for delegated subagents: reap only after this long with\r\n * NO activity (no iteration / tool call / streamed progress). An actively-\r\n * working agent resets this clock continuously, so it runs until its task\r\n * naturally ends — no more wall-clock kills of productive runs. Power users\r\n * can still impose a hard `timeoutMs` per delegate.\r\n */\r\nexport const DEFAULT_IDLE_TIMEOUT_MS = 15 * 60 * 1000;\r\n\r\nexport const FLEET_ROSTER_BUDGETS: Record<string, FleetRosterBudget> = {\r\n 'audit-log': { timeoutMs: 7.5 * 60 * 60 * 1000, maxIterations: 5000, maxToolCalls: 15000 },\r\n 'bug-hunter': { timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000 },\r\n 'refactor-planner': { timeoutMs: 7.5 * 60 * 60 * 1000, maxIterations: 6000, maxToolCalls: 18000 },\r\n 'security-scanner': { timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000 },\r\n 'critic': { timeoutMs: 5 * 60 * 60 * 1000, maxIterations: 4000, maxToolCalls: 12000 },\r\n ...Object.fromEntries(\r\n ALL_AGENT_DEFINITIONS.map((d) => [d.config.role as string, d.budget] as const),\r\n ),\r\n};\r\n\r\n/**\r\n * Apply roster budget to a config (only when the config has no explicit\r\n * budget fields set). This is called by the coordinator before dispatch.\r\n */\r\n// Generic default budget applied when no role matches and no explicit budget\r\n// fields are set. Used for `name` / free-form delegates. There is no default\r\n// wall-clock timeout — a delegated agent runs until its task naturally ends\r\n// (`end_turn`) or it stalls past the idle window. Iteration / tool-call ceilings\r\n// remain as a runaway backstop.\r\nconst GENERIC_SUBAGENT_BUDGET: FleetRosterBudget = {\r\n idleTimeoutMs: DEFAULT_IDLE_TIMEOUT_MS,\r\n maxIterations: 5000,\r\n maxToolCalls: 15000,\r\n};\r\n\r\nexport function applyRosterBudget(cfg: SubagentConfig): SubagentConfig {\r\n // First try role-specific budget; fall back to generic for name-only delegates.\r\n const roleBudget = cfg.role ? FLEET_ROSTER_BUDGETS[cfg.role] : undefined;\r\n const defaultBudget = roleBudget ?? (cfg.name ? GENERIC_SUBAGENT_BUDGET : undefined);\r\n if (!defaultBudget) return cfg;\r\n return {\r\n ...cfg,\r\n // Wall-clock cap is opt-in only: forward an explicit `cfg.timeoutMs`, but\r\n // do NOT impose the roster's historical multi-hour wall-clock default — it\r\n // killed agents that were still actively working. Reaping is idle-based.\r\n timeoutMs: cfg.timeoutMs,\r\n // Idle window is the default reaper. Resets on activity, so a long-but-\r\n // productive run is never killed; only a genuine stall is reaped.\r\n idleTimeoutMs: cfg.idleTimeoutMs ?? defaultBudget.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS,\r\n maxIterations: cfg.maxIterations ?? defaultBudget.maxIterations,\r\n maxToolCalls: cfg.maxToolCalls ?? defaultBudget.maxToolCalls,\r\n maxTokens: cfg.maxTokens ?? defaultBudget.maxTokens,\r\n maxCostUsd: cfg.maxCostUsd ?? defaultBudget.maxCostUsd,\r\n };\r\n}\r\n\r\n/** Quick-access list for spawning all at once. */\r\nexport const ALL_FLEET_AGENTS = Object.values(FLEET_ROSTER);\r\n\r\n// ---------------------------------------------------------------------------\r\n// ACP external agents — WrongStack spawns these as subagents via ACP protocol.\r\n// Each agent runs its own loop; WrongStack sends tasks as ACP messages and\r\n// receives results. These don't go through makeAgentSubagentRunner — they\r\n// are handled by makeACPSubagentRunner in the CLI multi-agent layer.\r\n// ---------------------------------------------------------------------------\r\n\r\n/**\r\n * Cline — ACP-compatible coding agent by @asonix.\r\n * Spawned as: `npx @agentify/cline`\r\n */\r\nexport const CLINE_AGENT: SubagentConfig = {\r\n id: 'cline',\r\n name: 'Cline',\r\n role: 'cline',\r\n prompt: `You are Cline, a coding agent. You help write, edit, and navigate code.\r\nYou operate by receiving tasks via ACP and returning results.\r\nWhen asked to code, make focused changes and explain them briefly.`,\r\n provider: 'acp',\r\n};\r\n\r\n/**\r\n * Gemini CLI — Google's ACP-compatible command-line agent.\r\n * Spawned as: `gemini` (when gemini CLI is installed and in PATH)\r\n */\r\nexport const GEMINI_CLI_AGENT: SubagentConfig = {\r\n id: 'gemini-cli',\r\n name: 'Gemini CLI',\r\n role: 'gemini-cli',\r\n prompt: `You are Gemini CLI, a coding agent powered by Google's Gemini model.\r\nYou help with code generation, editing, debugging, and best practices.\r\nYou operate by receiving tasks via ACP and returning results.`,\r\n provider: 'acp',\r\n};\r\n\r\n/**\r\n * GitHub Copilot (public preview) — ACP-compatible Copilot CLI agent.\r\n * Spawned as: `gh copilot` (when gh CLI with copilot extension is installed)\r\n */\r\nexport const COPILOT_AGENT: SubagentConfig = {\r\n id: 'copilot',\r\n name: 'GitHub Copilot',\r\n role: 'copilot',\r\n prompt: `You are GitHub Copilot, an AI coding assistant.\r\nYou help write, explain, refactor, and review code.\r\nYou operate by receiving tasks via ACP and returning results.`,\r\n provider: 'acp',\r\n};\r\n\r\n/**\r\n * OpenHands — AI coding agent by all-in.ai, ACP-compatible.\r\n * Spawned as: `openhands` (when installed)\r\n */\r\nexport const OPENHANDS_AGENT: SubagentConfig = {\r\n id: 'openhands',\r\n name: 'OpenHands',\r\n role: 'openhands',\r\n prompt: `You are OpenHands, an AI coding agent that can use tools to interact\r\nwith files, terminals, browsers, and other resources.\r\nYou operate by receiving tasks via ACP and returning results.`,\r\n provider: 'acp',\r\n};\r\n\r\n/**\r\n * Goose — IDE agent by ExoRL, ACP-compatible.\r\n * Spawned as: `goose` (when goose CLI is installed)\r\n */\r\nexport const GOOSE_AGENT: SubagentConfig = {\r\n id: 'goose',\r\n name: 'Goose',\r\n role: 'goose',\r\n prompt: `You are Goose, an AI agent that helps with coding tasks.\r\nYou operate by receiving tasks via ACP and returning results.\r\nFocus on writing high-quality, well-tested code.`,\r\n provider: 'acp',\r\n};\r\n\r\n/** All ACP external agents. */\r\nexport const ACP_AGENTS: SubagentConfig[] = [\r\n CLINE_AGENT,\r\n GEMINI_CLI_AGENT,\r\n COPILOT_AGENT,\r\n OPENHANDS_AGENT,\r\n GOOSE_AGENT,\r\n];\r\n\r\n// ACP agents share the same generous budgets as the built-in fleet agents.\r\n// External ACP agents may need more time than typical in-process subagents\r\n// since they run their own loops and may do tool-call round-trips.\r\nFLEET_ROSTER_BUDGETS['cline'] = {timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000};\r\nFLEET_ROSTER_BUDGETS['gemini-cli'] = {timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000};\r\nFLEET_ROSTER_BUDGETS['copilot'] = {timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000};\r\nFLEET_ROSTER_BUDGETS['openhands'] = {timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000};\r\nFLEET_ROSTER_BUDGETS['goose'] = {timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000};\r\n\r\n/** Extended roster including ACP agents. */\r\nexport const FLEET_ROSTER_WITHACP: Record<string, SubagentConfig> = {\r\n ...FLEET_ROSTER,\r\n ...Object.fromEntries(ACP_AGENTS.map((a) => [a.role as string, a])),\r\n};\r\n","/**\n * Subagent nickname pool — famous scientists, mathematicians, and computing pioneers.\n * Names are grouped by domain affinity so the nickname hints at the agent's role.\n */\n\nconst NICKNAME_POOL = {\n // Physics & fundamental sciences\n 'einstein': { name: 'Einstein', domain: 'physics' },\n 'newton': { name: 'Newton', domain: 'physics' },\n 'feynman': { name: 'Feynman', domain: 'physics' },\n 'dirac': { name: 'Dirac', domain: 'physics' },\n 'bohr': { name: 'Bohr', domain: 'physics' },\n 'planck': { name: 'Planck', domain: 'physics' },\n 'curie': { name: 'Curie', domain: 'physics' },\n 'fermi': { name: 'Fermi', domain: 'physics' },\n 'heisenberg': { name: 'Heisenberg', domain: 'physics' },\n 'schrodinger': { name: 'Schrödinger', domain: 'physics' },\n\n // Mathematics\n 'euclid': { name: 'Euclid', domain: 'math' },\n 'gauss': { name: 'Gauss', domain: 'math' },\n 'turing': { name: 'Turing', domain: 'math' },\n 'poincare': { name: 'Poincaré', domain: 'math' },\n 'riemann': { name: 'Riemann', domain: 'math' },\n 'hilbert': { name: 'Hilbert', domain: 'math' },\n 'pythagoras': { name: 'Pythagoras', domain: 'math' },\n\n // Computing & information theory\n 'von-neumann': { name: 'Von Neumann', domain: 'computing' },\n 'shannon': { name: 'Shannon', domain: 'computing' },\n 'hopper': { name: 'Hopper', domain: 'computing' },\n 'backus': { name: 'Backus', domain: 'computing' },\n 'knuth': { name: 'Knuth', domain: 'computing' },\n 'torvalds': { name: 'Torvalds', domain: 'computing' },\n 'stallman': { name: 'Stallman', domain: 'computing' },\n 'berners-lee': { name: 'Berners-Lee', domain: 'computing' },\n 'babbage': { name: 'Babbage', domain: 'computing' },\n 'lovelace': { name: 'Lovelace', domain: 'computing' },\n 'klein': { name: 'Klein', domain: 'computing' },\n\n // Electronics & electrical engineering\n 'edison': { name: 'Edison', domain: 'ee' },\n 'tesla': { name: 'Tesla', domain: 'ee' },\n 'faraday': { name: 'Faraday', domain: 'ee' },\n 'maxwell': { name: 'Maxwell', domain: 'ee' },\n 'ohm': { name: 'Ohm', domain: 'ee' },\n 'bell': { name: 'Bell', domain: 'ee' },\n 'marconi': { name: 'Marconi', domain: 'ee' },\n 'lamarr': { name: 'Lamarr', domain: 'ee' },\n\n // General science / multi-disciplinary\n 'darwin': { name: 'Darwin', domain: 'biology' },\n 'mendel': { name: 'Mendel', domain: 'biology' },\n 'pasteur': { name: 'Pasteur', domain: 'biology' },\n 'hawking': { name: 'Hawking', domain: 'cosmology' },\n 'sagan': { name: 'Sagan', domain: 'cosmology' },\n\n // Exploration & navigation\n 'columbus': { name: 'Columbus', domain: 'exploration' },\n 'polo': { name: 'Polo', domain: 'exploration' },\n 'magellan': { name: 'Magellan', domain: 'exploration' },\n\n // Chemistry / materials\n 'lavoisier': { name: 'Lavoisier', domain: 'chemistry' },\n 'mendeleev': { name: 'Mendeleev', domain: 'chemistry' },\n} as const;\n\n/** Flat ordered list of all available nicknames — used for round-robin. */\nconst ALL_NICKNAMES = Object.values(NICKNAME_POOL);\n\n/** Domain → preferred nickname keys (fallback chain). */\nconst DOMAIN_PREFERENCES: Record<string, string[]> = {\n 'security': ['shannon', 'turing', 'lamarr', 'stallman'],\n 'bug-hunter': ['darwin', 'curie', 'feynman', 'fermi'],\n 'refactor': ['gauss', 'hilbert', 'euclid', 'planck'],\n 'audit-log': ['sagan', 'hawking', 'poincare', 'newton'],\n 'planner': ['hilbert', 'gauss', 'turing', 'euclid'],\n 'researcher': ['sagan', 'hawking', 'darwin', 'pasteur'],\n 'explorer': ['marconi', 'bell', 'columbus', 'polo'],\n 'testing': ['pasteur', 'curie', 'fermi', 'bohr'],\n 'frontend': ['lovelace', 'hopper', 'babbage', 'backus'],\n 'backend': ['torvalds', 'stallman', 'von-neumann', 'backus'],\n 'database': ['turing', 'shannon', 'backus', 'knuth'],\n 'devops': ['tesla', 'edison', 'faraday', 'bell'],\n 'security-scanner': ['shannon', 'turing', 'lamarr', 'stallman'],\n 'refactor-planner': ['gauss', 'hilbert', 'planck', 'newton'],\n 'architect': ['von-neumann', 'turing', 'gauss', 'hilbert'],\n 'critic': ['einstein', 'feynman', 'dirac', 'bohr'],\n 'e2e': ['hopper', 'bell', 'marconi', 'tesla'],\n 'performance': ['knuth', 'gauss', 'planck', 'feynman'],\n 'chaos': ['tesla', 'edison', 'curie', 'fermi'],\n 'cost': ['ohm', 'bell', 'marconi', 'tesla'],\n // default fallback\n 'default': ['einstein', 'newton', 'curie', 'tesla', 'edison', 'turing', 'shannon', 'hopper', 'knuth', 'stallman'],\n};\n\ntype NicknameKey = keyof typeof NICKNAME_POOL;\n\n/**\n * Assign a unique nickname to a subagent based on its role.\n * Returns `Name (Role)` formatted string, e.g. `Einstein (Bug Hunter)`.\n *\n * @param role - The subagent's role id (e.g. 'bug-hunter', 'security-scanner')\n * @param used - Set of nickname keys already assigned in this fleet\n * (so no two subagents share the same base name)\n */\nexport function assignNickname(role: string, used: ReadonlySet<string>): string {\n // 1. Build preference list: role-specific → default fallback\n const preferences = [\n ...(DOMAIN_PREFERENCES[role] ?? []),\n ...(DOMAIN_PREFERENCES['default'] ?? []),\n ];\n\n // 2. Find the first unassigned nickname from preferences. Skip keys that are\n // not in the pool — preference lists can drift out of sync with the pool\n // (typos, removed names), and an unknown key must not crash assignment.\n for (const key of preferences) {\n const entry = NICKNAME_POOL[key as NicknameKey];\n if (entry && !used.has(key)) {\n return `${entry.name} (${formatRole(role)})`;\n }\n }\n\n // 3. Exhausted preferences — pick the first unused name round-robin style\n for (const entry of ALL_NICKNAMES) {\n const key = Object.entries(NICKNAME_POOL).find(([, v]) => v.name === entry.name)?.[0];\n if (key && !used.has(key)) {\n return `${entry.name} (${formatRole(role)})`;\n }\n }\n\n // 4. Pool exhausted — append counter to last resort\n const counter = used.size + 1;\n return `Scientist #${counter} (${formatRole(role)})`;\n}\n\n/** Format role id into human-readable title-case. */\nfunction formatRole(role: string): string {\n return role\n .split(/[-_]/)\n .map((w) => w.charAt(0).toUpperCase() + w.slice(1))\n .join(' ');\n}\n\n/**\n * Returns all available nickname keys. Useful for testing or reset logic.\n */\nexport function getAllNicknameKeys(): string[] {\n return Object.keys(NICKNAME_POOL);\n}","import { randomUUID } from 'node:crypto';\r\nimport { EventEmitter } from 'node:events';\r\nimport type { AgentBridge, BridgeMessage } from '../types/agent-bridge.js';\r\nimport type {\r\n CoordinatorStatus,\r\n MultiAgentConfig,\r\n MultiAgentCoordinator,\r\n SpawnResult,\r\n SubagentConfig,\r\n SubagentContext,\r\n SubagentError,\r\n SubagentErrorKind,\r\n SubagentRunContext,\r\n SubagentRunner,\r\n TaskResult,\r\n TaskSpec,\r\n} from '../types/multi-agent.js';\r\nimport { ProviderError } from '../types/provider.js';\r\nimport { BudgetExceededError, SubagentBudget } from './subagent-budget.js';\r\nimport { applyRosterBudget } from './fleet.js';\r\nimport { assignNickname } from './subagent-nicknames.js';\r\n\r\ntype SubagentStatus = 'running' | 'idle' | 'stopped' | 'error';\r\n\r\ninterface SubagentEntry {\r\n config: SubagentConfig;\r\n context: SubagentContext;\r\n status: SubagentStatus;\r\n currentTask?: string;\r\n abortController: AbortController;\r\n /** Lazily created on first dispatch — budget is per-task, not per-subagent. */\r\n activeBudget?: SubagentBudget;\r\n}\r\n\r\nexport interface MultiAgentCoordinatorOptions {\r\n /**\r\n * Callback that executes a task on behalf of a subagent. Required for\r\n * `assign()` to actually run anything — without it, tasks queue forever.\r\n * The coordinator provides per-subagent isolation (own budget, own signal,\r\n * own bridge) and enforces timeout + concurrency.\r\n */\r\n runner?: SubagentRunner;\r\n}\r\n\r\nexport class DefaultMultiAgentCoordinator extends EventEmitter implements MultiAgentCoordinator {\r\n readonly coordinatorId: string;\r\n readonly config: MultiAgentConfig;\r\n private runner?: SubagentRunner;\r\n private fleetBus?: import('./fleet-bus.js').FleetBus;\r\n\r\n private readonly subagents = new Map<string, SubagentEntry>();\r\n\r\n /**\r\n * Base nickname keys already handed out this run (e.g. `einstein`, `tesla`).\r\n * Prevents two workers sharing a name. Direct `coordinator.spawn()` callers\r\n * (parallel/eternal engine, SDD parallel run) don't go through\r\n * `Director.spawn()` where nicknames are normally assigned, so the\r\n * coordinator upgrades placeholder names (\"Executor\", \"slot-ab12cd\", role\r\n * names) to memorable ones here — that's what surfaces in the fleet monitor.\r\n */\r\n private readonly usedNicknames = new Set<string>();\r\n /** Maps subagentId → nickname key (e.g. 'einstein'). Used to free the slot on remove(). */\r\n private readonly subagentNicknames = new Map<string, string>();\r\n\r\n private pendingTasks: TaskSpec[] = [];\r\n private completedResults: TaskResult[] = [];\r\n /** Prevents completedResults from growing unbounded in long-running coordinators. */\r\n private static readonly MAX_COMPLETED_RESULTS = 10_000;\r\n private totalIterations = 0;\r\n private inFlight = 0;\r\n /**\r\n * Subagents currently being stopped. Set on entry to `stop()`, cleared\r\n * once `recordCompletion` lands the terminal TaskResult. Used by\r\n * `runDispatched` and `findIdleSubagent` to refuse mid-flight dispatch\r\n * to a subagent the caller has already asked to terminate — closes the\r\n * assign+terminate race where a fresh task could land on a worker that\r\n * was about to be killed.\r\n */\r\n private readonly terminating = new Set<string>();\r\n\r\n constructor(config: MultiAgentConfig, options: MultiAgentCoordinatorOptions = {}) {\r\n super();\r\n this.coordinatorId = config.coordinatorId;\r\n this.config = config;\r\n this.runner = options.runner;\r\n }\r\n\r\n /**\r\n * Replace the runner after construction. Used when the runner depends\r\n * on infrastructure (e.g. FleetBus) that isn't available until after\r\n * the coordinator's owning Director is built.\r\n */\r\n setRunner(runner: SubagentRunner): void {\r\n this.runner = runner;\r\n }\r\n\r\n /**\r\n * Wire a FleetBus for director-mode event emission. Call after the\r\n * FleetManager is constructed so the coordinator can emit lifecycle\r\n * events the TUI and monitoring tools subscribe to.\r\n */\r\n setFleetBus(fleet: import('./fleet-bus.js').FleetBus): void {\r\n this.fleetBus = fleet;\r\n }\r\n\r\n /**\r\n * Change the in-flight dispatch ceiling at runtime. Lowering does NOT\r\n * preempt running tasks — already-dispatched subagents finish their\r\n * current task; only future dispatches respect the new cap. Raising\r\n * immediately tries to fill the freed slots from the pending queue.\r\n */\r\n setMaxConcurrent(n: number): void {\r\n if (!Number.isFinite(n) || n < 1) {\r\n throw new Error(`maxConcurrent must be a finite integer >= 1, got ${n}`);\r\n }\r\n this.config.maxConcurrent = Math.floor(n);\r\n this.tryDispatchNext();\r\n }\r\n\r\n /**\r\n * Upgrade a placeholder/role-derived name to a memorable scientist nickname\r\n * (e.g. \"Einstein (Executor)\"). A name is treated as a placeholder when it is\r\n * empty, equals the role (case-insensitive), is a generic default\r\n * (\"subagent\"/\"adhoc\"/\"generic\"), or is an auto-generated `slot-…` id.\r\n * Explicit, human-chosen names — including nicknames already assigned by\r\n * `Director.spawn()` — are left untouched, so this never double-assigns.\r\n */\r\n private withNickname(subagent: SubagentConfig, subagentId: string): SubagentConfig {\r\n const role = subagent.role ?? 'subagent';\r\n const name = subagent.name?.trim() ?? '';\r\n const isPlaceholder =\r\n name === '' ||\r\n name.toLowerCase() === role.toLowerCase() ||\r\n name === 'subagent' ||\r\n name === 'adhoc' ||\r\n name === 'generic' ||\r\n /^slot-/.test(name);\r\n if (!isPlaceholder) return subagent;\r\n const nickname = assignNickname(role, this.usedNicknames);\r\n const baseKey = nickname.split(' ')[0]!.toLowerCase().replace(/[^a-z0-9-]/g, '-');\r\n this.usedNicknames.add(baseKey);\r\n this.subagentNicknames.set(subagentId, baseKey);\r\n return { ...subagent, name: nickname };\r\n }\r\n\r\n async spawn(subagent: SubagentConfig): Promise<SpawnResult> {\r\n const id = subagent.id || randomUUID();\r\n subagent = this.withNickname(subagent, id);\r\n // Duplicate-id guard. Previously a second spawn({id}) with the\r\n // same id silently overwrote the existing entry — orphaning the\r\n // first subagent's AbortController, Context, and any in-flight\r\n // task referencing it. Two spawns with the same id are almost\r\n // always a bug at the caller; refuse and let them surface it.\r\n if (this.subagents.has(id)) {\r\n throw new Error(`Subagent id \"${id}\" already exists — refusing to overwrite`);\r\n }\r\n const context: SubagentContext = {\r\n subagentId: id,\r\n tasks: [],\r\n // Wired later by the caller via setSubagentBridge() once the\r\n // bidirectional bridge is created. Readers must null-check / use\r\n // hasParentBridge() — the type now reflects this.\r\n parentBridge: null,\r\n doneCondition: this.config.doneCondition,\r\n maxConcurrent: this.config.maxConcurrent ?? 16,\r\n };\r\n\r\n this.subagents.set(id, {\r\n config: { ...subagent, id },\r\n context,\r\n status: 'idle',\r\n abortController: new AbortController(),\r\n });\r\n\r\n this.emit('subagent.started', { subagent: { ...subagent, id } });\r\n\r\n this.fleetBus?.emit({\r\n subagentId: id,\r\n ts: Date.now(),\r\n type: 'subagent.assigned',\r\n payload: {\r\n subagentId: id,\r\n name: subagent.name,\r\n provider: subagent.provider,\r\n model: subagent.model,\r\n },\r\n });\r\n\r\n this.emitCoordinatorStats();\r\n\r\n return { subagentId: id, agentId: id };\r\n }\r\n\r\n async assign(task: TaskSpec): Promise<void> {\r\n this.pendingTasks.push(task);\r\n this.tryDispatchNext();\r\n }\r\n\r\n async delegate(to: string, msg: BridgeMessage): Promise<void> {\r\n const subagent = this.subagents.get(to);\r\n if (!subagent) throw new Error(`Subagent \"${to}\" not found`);\r\n if (!subagent.context.parentBridge) {\r\n throw new Error(`Subagent \"${to}\" has no parentBridge — call setSubagentBridge() first`);\r\n }\r\n await subagent.context.parentBridge.send(msg);\r\n }\r\n\r\n /**\r\n * Wire up the communication bridge for a subagent. Call after spawn() once\r\n * the caller has created the bidirectional connection.\r\n */\r\n setSubagentBridge(subagentId: string, bridge: AgentBridge): void {\r\n const subagent = this.subagents.get(subagentId);\r\n if (!subagent) throw new Error(`Subagent \"${subagentId}\" not found`);\r\n subagent.context.parentBridge = bridge;\r\n }\r\n\r\n async stop(subagentId: string): Promise<void> {\r\n const subagent = this.subagents.get(subagentId);\r\n if (!subagent) return;\r\n\r\n // Mark terminating BEFORE the abort so a synchronous tryDispatchNext\r\n // observation in another callback path sees the intent and skips\r\n // this subagent. Cleared by recordCompletion once the runner's\r\n // catch block lands the terminal TaskResult.\r\n this.terminating.add(subagentId);\r\n\r\n // Abort any in-flight run, then sever the bridge so further messages fail\r\n // fast instead of silently queueing on a dead subagent.\r\n subagent.abortController.abort();\r\n subagent.status = 'stopped';\r\n subagent.currentTask = undefined;\r\n subagent.context.parentBridge = null;\r\n\r\n this.emit('subagent.stopped', { subagentId, reason: 'stopped by coordinator' });\r\n\r\n this.fleetBus?.emit({\r\n subagentId,\r\n ts: Date.now(),\r\n type: 'subagent.stopped',\r\n payload: { subagentId, reason: 'stopped by coordinator' },\r\n });\r\n\r\n this.emitCoordinatorStats();\r\n }\r\n\r\n async stopAll(): Promise<void> {\r\n // Clear the queue FIRST so no new tasks land on subagents while\r\n // we're tearing them down. Each dropped task gets a synthetic\r\n // `aborted_by_parent` completion so any caller awaiting it (e.g.\r\n // delegate tool's awaitTasks) resolves instead of hanging.\r\n //\r\n // Pending tasks never reached `inFlight`, so we cannot route them\r\n // through `recordCompletion` — its underflow guard would short-\r\n // circuit on the second pending task and emit a warning instead\r\n // of the completion event. The shared helper inline-emits.\r\n this.drainPendingAsAborted('Coordinator stopAll() drained the pending queue');\r\n // allSettled so one failure doesn't leave other subagents un-stopped.\r\n await Promise.allSettled([...this.subagents.keys()].map((id) => this.stop(id)));\r\n }\r\n\r\n /**\r\n * Get current coordinator stats for monitoring/debugging.\r\n */\r\n getStats(): {\r\n total: number;\r\n running: number;\r\n idle: number;\r\n stopped: number;\r\n inFlight: number;\r\n pending: number;\r\n completed: number;\r\n } {\r\n let running = 0;\r\n let idle = 0;\r\n let stopped = 0;\r\n for (const [, entry] of this.subagents) {\r\n if (entry.status === 'running') running++;\r\n else if (entry.status === 'idle') idle++;\r\n else stopped++;\r\n }\r\n return {\r\n total: this.subagents.size,\r\n running,\r\n idle,\r\n stopped,\r\n inFlight: this.inFlight,\r\n pending: this.pendingTasks.length,\r\n completed: this.completedResults.length,\r\n };\r\n }\r\n\r\n /** Emit a reactive coordinator.stats event on FleetBus so the TUI can subscribe. */\r\n private emitCoordinatorStats(): void {\r\n const stats = this.getStats();\r\n const subagentStatuses = Array.from(this.subagents.entries()).map(([id, s]) => ({\r\n subagentId: id,\r\n taskId: s.currentTask ?? '',\r\n status: s.status,\r\n assigned: s.context.parentBridge !== null,\r\n }));\r\n this.fleetBus?.emit({\r\n subagentId: this.coordinatorId,\r\n ts: Date.now(),\r\n type: 'coordinator.stats',\r\n payload: { ...stats, subagentStatuses },\r\n });\r\n }\r\n\r\n getStatus(): CoordinatorStatus {\r\n return {\r\n coordinatorId: this.coordinatorId,\r\n subagents: Array.from(this.subagents.entries()).map(([id, s]) => ({\r\n id,\r\n name: s.config.name,\r\n status: s.status,\r\n currentTask: s.currentTask,\r\n })),\r\n pendingTasks: this.pendingTasks.length,\r\n completedTasks: this.completedResults.length,\r\n totalIterations: this.totalIterations,\r\n done: this.isDone(),\r\n };\r\n }\r\n\r\n /** Expose snapshot of completed results — useful for callers awaiting all done. */\r\n results(): readonly TaskResult[] {\r\n return this.completedResults;\r\n }\r\n\r\n /**\r\n * Wait for one or more tasks to complete and return their results.\r\n * If a task is already done when called, returns immediately.\r\n * Resolves to an array in the same order as `taskIds`.\r\n */\r\n async awaitTasks(taskIds: string[]): Promise<TaskResult[]> {\r\n return Promise.all(\r\n taskIds.map((id) => {\r\n const cached = this.completedResults.find((r) => r.taskId === id);\r\n if (cached) return cached;\r\n // Fallback: poll until the task completes (up to timeoutMs).\r\n // The coordinator fires 'task.completed' on every result, so\r\n // we use a promise-based waiter tied to that event.\r\n return new Promise<TaskResult>((resolve, reject) => {\r\n const timeout = setTimeout(() => {\r\n this.off('task.completed', handler);\r\n reject(new Error(`awaitTasks timed out waiting for task \"${id}\"`));\r\n }, this.config.timeoutMs ?? 300_000);\r\n const handler = ({ result }: { task: TaskSpec; result: TaskResult }) => {\r\n if (result.taskId === id) {\r\n clearTimeout(timeout);\r\n this.off('task.completed', handler);\r\n resolve(result);\r\n }\r\n };\r\n this.on('task.completed', handler);\r\n });\r\n }),\r\n );\r\n }\r\n\r\n /**\r\n * Manual completion — for callers that drive subagents without a runner\r\n * (e.g. external orchestrators). When a runner is configured the coordinator\r\n * calls this itself.\r\n */\r\n completeTask(result: TaskResult): void {\r\n this.recordCompletion(result);\r\n }\r\n\r\n // --- internal dispatching ---------------------------------------------\r\n\r\n private tryDispatchNext(): void {\r\n while (this.canDispatch()) {\r\n const dispatchable = this.takeNextDispatchableTask();\r\n if (!dispatchable) {\r\n // No idle worker right now. If every spawned subagent is\r\n // stopped or mid-termination, the pending queue is dead —\r\n // a pending task can never start, so synthetic-complete it\r\n // as `aborted_by_parent`. Without this, an `assign()` after\r\n // `stop()` would hang forever waiting for `task.completed`.\r\n // We DO NOT drain when subagents are busy (status='running'):\r\n // those will free up and accept the work normally.\r\n if (this.pendingTasks.length > 0 && !this.hasLiveSubagent()) {\r\n this.drainPendingAsAborted(\r\n 'No live subagent available — all stopped or mid-termination',\r\n );\r\n }\r\n return;\r\n }\r\n const { subagentId, task } = dispatchable;\r\n // Attach a catch so a synchronous throw inside runDispatched (rare —\r\n // e.g. provider misconfiguration before the first await) becomes a\r\n // visible failed task instead of an unhandled rejection that leaves\r\n // `inFlight` permanently elevated.\r\n this.runDispatched(subagentId, task).catch((err) => {\r\n this.recordCompletion({\r\n subagentId,\r\n taskId: task.id,\r\n status: 'failed',\r\n error: classifySubagentError(err),\r\n iterations: 0,\r\n toolCalls: 0,\r\n durationMs: 0,\r\n });\r\n });\r\n }\r\n }\r\n\r\n private canDispatch(): boolean {\r\n const max = this.config.maxConcurrent ?? 16;\r\n return this.inFlight < max && this.pendingTasks.length > 0;\r\n }\r\n\r\n private takeNextDispatchableTask(): { subagentId: string; task: TaskSpec } | null {\r\n for (let i = 0; i < this.pendingTasks.length; i++) {\r\n const task = this.pendingTasks[i]!;\r\n const subagentId = task.subagentId\r\n ? this.isIdleSubagent(task.subagentId)\r\n ? task.subagentId\r\n : null\r\n : this.findIdleSubagent();\r\n if (!subagentId) continue;\r\n this.pendingTasks.splice(i, 1);\r\n return { subagentId, task };\r\n }\r\n return null;\r\n }\r\n\r\n private findIdleSubagent(): string | null {\r\n for (const [id, s] of this.subagents) {\r\n // Skip subagents that are mid-termination — `stop()` set the\r\n // `terminating` flag and aborted the controller, but the\r\n // status mutation happens synchronously after; checking both\r\n // is belt-and-suspenders against any race where status is\r\n // transiently still 'idle' while termination is in flight.\r\n if (s.status === 'idle' && !this.terminating.has(id)) return id;\r\n }\r\n return null;\r\n }\r\n\r\n private isIdleSubagent(id: string): boolean {\r\n const subagent = this.subagents.get(id);\r\n return !!subagent && subagent.status === 'idle' && !this.terminating.has(id);\r\n }\r\n\r\n /**\r\n * Returns true iff at least one spawned subagent could still\r\n * process a task. A \"live\" subagent is one that is not stopped\r\n * AND not mid-termination — `running` workers count because they\r\n * will eventually finish and become idle.\r\n *\r\n * When no subagent has ever been spawned, returns `true` so a\r\n * pre-spawn `assign()` simply queues (legacy behaviour). The\r\n * dead-end detection only fires after `stop()` has retired every\r\n * spawned worker.\r\n *\r\n * Used by `tryDispatchNext` to detect a dead-end pending queue.\r\n */\r\n private hasLiveSubagent(): boolean {\r\n if (this.subagents.size === 0) return true;\r\n for (const [id, s] of this.subagents) {\r\n if (s.status !== 'stopped' && !this.terminating.has(id)) return true;\r\n }\r\n return false;\r\n }\r\n\r\n /**\r\n * Drain every pending task with a synthetic `aborted_by_parent`\r\n * completion event. Same shape as the `stopAll()` drain — we go\r\n * around `recordCompletion` because pending tasks were never\r\n * counted in `inFlight` and routing them through would trip the\r\n * underflow guard on every task after the first.\r\n */\r\n private drainPendingAsAborted(message: string): void {\r\n const dropped = this.pendingTasks.splice(0, this.pendingTasks.length);\r\n for (const t of dropped) {\r\n const synthetic: TaskResult = {\r\n subagentId: t.subagentId ?? 'unassigned',\r\n taskId: t.id,\r\n status: 'stopped',\r\n error: {\r\n kind: 'aborted_by_parent',\r\n message,\r\n retryable: false,\r\n },\r\n iterations: 0,\r\n toolCalls: 0,\r\n durationMs: 0,\r\n };\r\n this.completedResults.push(synthetic);\r\n this.emit('task.completed', { task: t, result: synthetic });\r\n }\r\n }\r\n\r\n private async runDispatched(subagentId: string, task: TaskSpec): Promise<void> {\r\n const subagent = this.subagents.get(subagentId);\r\n if (!subagent) return;\r\n // Final race guard: if `stop(subagentId)` ran between dispatch\r\n // and us arriving here, refuse to start the task and surface it\r\n // as `aborted_by_parent` so any caller awaiting the task id\r\n // unblocks. Without this, the task would be marked 'running',\r\n // collide with the just-completed 'stopped' state, and leak\r\n // inFlight by 1 because no recordCompletion path covers it.\r\n if (this.terminating.has(subagentId) || subagent.status === 'stopped') {\r\n this.recordCompletion({\r\n subagentId,\r\n taskId: task.id,\r\n status: 'stopped',\r\n error: {\r\n kind: 'aborted_by_parent',\r\n message: 'Subagent was terminated before task could start',\r\n retryable: false,\r\n },\r\n iterations: 0,\r\n toolCalls: 0,\r\n durationMs: 0,\r\n });\r\n return;\r\n }\r\n\r\n subagent.status = 'running';\r\n subagent.currentTask = task.id;\r\n task.subagentId = subagentId;\r\n subagent.context.tasks.push(task);\r\n\r\n this.fleetBus?.emit({\r\n subagentId,\r\n taskId: task.id,\r\n ts: Date.now(),\r\n type: 'subagent.running',\r\n payload: { subagentId, taskId: task.id },\r\n });\r\n\r\n this.emit('task.assigned', { task, subagentId });\r\n this.emitCoordinatorStats();\r\n\r\n // Budget combines coordinator defaults with per-subagent and per-task overrides.\r\n // Precedence: task > subagent (raw, no roster fills) > coordinator default > roster default.\r\n // We intentionally call applyRosterBudget LATE — only as a final fallback after\r\n // the coordinator's defaultBudget has had a chance to apply. This prevents\r\n // GENERIC_SUBAGENT_BUDGET (5000 iter) from shadowing the coordinator's explicit default.\r\n const rawMaxIterations = subagent.config.maxIterations;\r\n const rawMaxToolCalls = subagent.config.maxToolCalls;\r\n const rawMaxTokens = subagent.config.maxTokens;\r\n const rawMaxCostUsd = subagent.config.maxCostUsd;\r\n const rawTimeoutMs = subagent.config.timeoutMs;\r\n const rawIdleTimeoutMs = subagent.config.idleTimeoutMs;\r\n const configWithRosterDefaults = applyRosterBudget(subagent.config);\r\n const budget = new SubagentBudget({\r\n maxIterations:\r\n rawMaxIterations ?? this.config.defaultBudget?.maxIterations ?? configWithRosterDefaults.maxIterations,\r\n maxToolCalls:\r\n rawMaxToolCalls ??\r\n this.config.defaultBudget?.maxToolCalls ??\r\n configWithRosterDefaults.maxToolCalls,\r\n maxTokens:\r\n rawMaxTokens ?? this.config.defaultBudget?.maxTokens ?? configWithRosterDefaults.maxTokens,\r\n maxCostUsd:\r\n rawMaxCostUsd ?? this.config.defaultBudget?.maxCostUsd ?? configWithRosterDefaults.maxCostUsd,\r\n // Wall-clock cap is opt-in (explicit config / defaultBudget only); the\r\n // roster no longer supplies one. Idle is the default reaper.\r\n timeoutMs:\r\n rawTimeoutMs ?? this.config.defaultBudget?.timeoutMs ?? configWithRosterDefaults.timeoutMs,\r\n idleTimeoutMs:\r\n rawIdleTimeoutMs ??\r\n this.config.defaultBudget?.idleTimeoutMs ??\r\n configWithRosterDefaults.idleTimeoutMs,\r\n });\r\n subagent.activeBudget = budget;\r\n\r\n if (!this.runner) {\r\n // No runner wired — caller drives execution via completeTask(). Status\r\n // reverts when the caller reports. We intentionally don't bump\r\n // `inFlight` here: `completeTask` → `recordCompletion` would then\r\n // decrement an inFlight that runDispatched never incremented, masking\r\n // the \"no runner\" state. With this guard, `isDone()`'s all_tasks_done\r\n // check still settles correctly once the caller reports.\r\n return;\r\n }\r\n\r\n // Only count inFlight when we actually own the execution lifecycle.\r\n this.inFlight++;\r\n\r\n const startTime = Date.now();\r\n const runCtx: SubagentRunContext = {\r\n subagentId,\r\n config: subagent.config,\r\n budget,\r\n signal: subagent.abortController.signal,\r\n bridge: subagent.context.parentBridge || null,\r\n };\r\n\r\n let result: TaskResult;\r\n\r\n budget.start();\r\n try {\r\n const outcome = await this.executeWithTimeout(this.runner, task, runCtx, budget);\r\n result = {\r\n subagentId,\r\n taskId: task.id,\r\n status: 'success',\r\n result: outcome.result,\r\n iterations: outcome.iterations,\r\n toolCalls: outcome.toolCalls,\r\n durationMs: Date.now() - startTime,\r\n };\r\n } catch (err) {\r\n // Order matters: a timeout calls abort() to signal cooperative runners,\r\n // which also flips `signal.aborted=true`. Inspect the error first so we\r\n // surface 'timeout' rather than masking it as 'stopped'.\r\n const status: TaskResult['status'] =\r\n err instanceof BudgetExceededError && (err.kind === 'timeout' || err.kind === 'idle_timeout')\r\n ? 'timeout'\r\n : subagent.abortController.signal.aborted\r\n ? 'stopped'\r\n : 'failed';\r\n const usage = budget.usage();\r\n result = {\r\n subagentId,\r\n taskId: task.id,\r\n status,\r\n error: classifySubagentError(err, {\r\n parentAborted: subagent.abortController.signal.aborted,\r\n }),\r\n iterations: usage.iterations,\r\n toolCalls: usage.toolCalls,\r\n durationMs: Date.now() - startTime,\r\n };\r\n }\r\n\r\n this.recordCompletion(result);\r\n }\r\n\r\n private async executeWithTimeout(\r\n runner: SubagentRunner,\r\n task: TaskSpec,\r\n ctx: SubagentRunContext,\r\n budget: SubagentBudget,\r\n ) {\r\n const initialTimeoutMs = budget.limits.timeoutMs;\r\n const idleLimitMs = budget.limits.idleTimeoutMs;\r\n if (initialTimeoutMs === undefined && idleLimitMs === undefined) {\r\n return runner(task, ctx);\r\n }\r\n\r\n // Re-armable watchdog. The default guard is IDLE-based: while the agent\r\n // keeps producing activity (iterations / tool calls / streamed progress),\r\n // `budget.idleMs()` stays below the window and we simply re-arm — an\r\n // actively-working subagent is never killed by the clock. Only a genuine\r\n // stall (no activity for `idleTimeoutMs`) reaps it. An explicit wall-clock\r\n // `timeoutMs` (rare, opt-in) keeps the original soft-warning behaviour: it\r\n // negotiates an extension via the Director's auto-extend listener and\r\n // re-arms rather than hard-killing a task solely for running long.\r\n const start = Date.now();\r\n let timer: ReturnType<typeof setTimeout> | null = null;\r\n\r\n const timeoutPromise = new Promise<never>((_, reject) => {\r\n const armFor = (ms: number) => {\r\n if (timer) clearTimeout(timer);\r\n timer = setTimeout(onTick, Math.max(0, ms));\r\n };\r\n // Re-arm for whichever deadline is sooner — the idle window (counted\r\n // from last activity) or the explicit wall-clock cap. Either being\r\n // unset drops out of the min, so single-limit configs behave exactly\r\n // as that limit alone.\r\n const scheduleNext = () => {\r\n const wallRemaining =\r\n initialTimeoutMs === undefined\r\n ? Number.POSITIVE_INFINITY\r\n : (budget.limits.timeoutMs ?? initialTimeoutMs) - (Date.now() - start);\r\n const idleRemaining =\r\n idleLimitMs === undefined\r\n ? Number.POSITIVE_INFINITY\r\n : (budget.limits.idleTimeoutMs ?? idleLimitMs) - budget.idleMs();\r\n // Floor at a small positive so a near-zero remainder can't busy-loop.\r\n armFor(Math.max(25, Math.min(wallRemaining, idleRemaining)));\r\n };\r\n\r\n const onTick = async () => {\r\n const elapsed = Date.now() - start;\r\n const wallLimit =\r\n initialTimeoutMs === undefined ? undefined : budget.limits.timeoutMs ?? initialTimeoutMs;\r\n const idleLimit =\r\n idleLimitMs === undefined ? undefined : budget.limits.idleTimeoutMs ?? idleLimitMs;\r\n const wallExceeded = wallLimit !== undefined && elapsed >= wallLimit;\r\n const idleExceeded = idleLimit !== undefined && budget.idleMs() >= idleLimit;\r\n\r\n // Idle stall with no wall-clock cap also due: a genuinely hung agent\r\n // (no activity for the whole window). Reap it directly — idle is not\r\n // negotiable; the point of the default is to free a stuck slot.\r\n if (idleExceeded && !wallExceeded) {\r\n this.subagents.get(ctx.subagentId)?.abortController.abort();\r\n reject(new BudgetExceededError('timeout', idleLimit!, budget.idleMs()));\r\n return;\r\n }\r\n // Neither deadline actually tripped — we woke early because activity\r\n // pushed the idle deadline out. Re-arm for the new soonest deadline.\r\n if (!wallExceeded) {\r\n scheduleNext();\r\n return;\r\n }\r\n\r\n // Wall-clock cap hit. This is opt-in and keeps the original\r\n // soft-warning behaviour: negotiate an extension rather than\r\n // hard-killing a task solely for running long.\r\n const limit = wallLimit!;\r\n // Without an onThreshold handler the original behaviour stands:\r\n // abort the signal and hard-reject. This preserves the contract\r\n // for direct SubagentBudget consumers that don't wire negotiation.\r\n if (!budget.onThreshold) {\r\n this.subagents.get(ctx.subagentId)?.abortController.abort();\r\n reject(new BudgetExceededError('timeout', limit, elapsed));\r\n return;\r\n }\r\n // With a handler, ask for an extension. The budget's\r\n // requestDecision returns 'stop' on no response (decision\r\n // fallback timer inside SubagentBudget), so this never hangs.\r\n try {\r\n const result = budget.onThreshold({\r\n kind: 'timeout',\r\n used: elapsed,\r\n limit,\r\n requestDecision: () =>\r\n new Promise((resolveDecision) => {\r\n budget._events?.emit('budget.threshold_reached', {\r\n kind: 'timeout',\r\n used: elapsed,\r\n limit,\r\n timeoutMs: 60_000,\r\n extend: (extra) => resolveDecision({ extend: extra }),\r\n deny: () => resolveDecision('stop'),\r\n });\r\n }),\r\n });\r\n const decision = typeof result === 'string' ? result : await result;\r\n if (decision === 'continue' || decision === 'throw' || decision === 'stop') {\r\n // Timeout denied / no-op — re-arm for another full wall window so\r\n // we ask again later. This makes wall-clock timeout a pure warning\r\n // event: the subagent keeps running until it naturally finishes or\r\n // the user stops it. No task is hard-killed solely for running long.\r\n armFor(Math.max(1_000, limit));\r\n return;\r\n }\r\n // 'extend' — patch budget and re-arm for the new remainder.\r\n if (decision.extend.timeoutMs !== undefined) {\r\n (budget.limits as Record<string, unknown>).timeoutMs = decision.extend.timeoutMs;\r\n scheduleNext();\r\n return;\r\n }\r\n // No timeoutMs in extend — fall through to reject.\r\n this.subagents.get(ctx.subagentId)?.abortController.abort();\r\n reject(new BudgetExceededError('timeout', limit, elapsed));\r\n } catch (err) {\r\n this.subagents.get(ctx.subagentId)?.abortController.abort();\r\n reject(\r\n err instanceof BudgetExceededError\r\n ? err\r\n : new BudgetExceededError('timeout', limit, elapsed),\r\n );\r\n }\r\n };\r\n // First arm: whichever of the idle window / wall-clock cap is sooner.\r\n scheduleNext();\r\n });\r\n\r\n try {\r\n return await Promise.race([runner(task, ctx), timeoutPromise]);\r\n } finally {\r\n if (timer) clearTimeout(timer);\r\n }\r\n }\r\n\r\n private recordCompletion(result: TaskResult): void {\r\n this.completedResults.push(result);\r\n // Trim oldest entries when the cap is exceeded — keep the most recent\r\n // results so /fleet and roll_up still have data to work with.\r\n if (this.completedResults.length > DefaultMultiAgentCoordinator.MAX_COMPLETED_RESULTS) {\r\n this.completedResults.splice(\r\n 0,\r\n this.completedResults.length - DefaultMultiAgentCoordinator.MAX_COMPLETED_RESULTS,\r\n );\r\n }\r\n this.totalIterations += result.iterations;\r\n if (this.inFlight > 0) {\r\n this.inFlight--;\r\n } else if (this.runner) {\r\n // Runner-driven path completed without an outstanding inFlight slot —\r\n // shouldn't happen unless completeTask was called externally.\r\n this.emit('warning', {\r\n type: 'inFlight_underflow',\r\n taskId: result.taskId,\r\n subagentId: result.subagentId,\r\n });\r\n return;\r\n }\r\n\r\n const subagent = this.subagents.get(result.subagentId);\r\n if (subagent && subagent.status !== 'stopped') {\r\n const failed = result.status === 'failed' || result.status === 'timeout';\r\n // Synchronously reset the worker to idle after either a clean\r\n // finish or a transient failure. The previous code parked the\r\n // subagent in 'error' and used a `queueMicrotask` to flip it\r\n // back to 'idle' — that opened a window where `assign()` +\r\n // `tryDispatchNext` could race the microtask, leaving the\r\n // worker stuck in 'running' state while actually idle. By\r\n // resetting now, no async gap can leak the state machine.\r\n subagent.status = 'idle';\r\n void failed; // kept for future telemetry hooks\r\n subagent.currentTask = undefined;\r\n // If the run aborted (timeout or explicit stop), the subagent's\r\n // signal is now permanently aborted — recycling the controller lets\r\n // the next dispatched task start with a fresh cancellation scope.\r\n if (subagent.abortController.signal.aborted) {\r\n subagent.abortController = new AbortController();\r\n }\r\n\r\n this.fleetBus?.emit({\r\n subagentId: result.subagentId,\r\n ts: Date.now(),\r\n type: 'subagent.idle',\r\n payload: { subagentId: result.subagentId },\r\n });\r\n }\r\n // Clear the terminating flag now that the worker has a terminal\r\n // TaskResult on record. Subsequent stop() calls re-add it; new\r\n // assign() calls can flow normally.\r\n this.terminating.delete(result.subagentId);\r\n\r\n this.emit('task.completed', {\r\n task: subagent?.context.tasks.find((t) => t.id === result.taskId) ?? { id: result.taskId },\r\n result,\r\n });\r\n\r\n this.fleetBus?.emit({\r\n subagentId: result.subagentId,\r\n taskId: result.taskId,\r\n ts: Date.now(),\r\n type: 'subagent.completed',\r\n payload: {\r\n subagentId: result.subagentId,\r\n taskId: result.taskId,\r\n status: result.status,\r\n iterations: result.iterations,\r\n toolCalls: result.toolCalls,\r\n durationMs: result.durationMs,\r\n },\r\n });\r\n\r\n this.tryDispatchNext();\r\n\r\n // Emit after tryDispatchNext so the stats reflect the post-dispatch\r\n // state (either a new running subagent, or idle if the queue is drained).\r\n this.emitCoordinatorStats();\r\n\r\n if (this.isDone()) {\r\n this.emit('done', {\r\n results: this.completedResults,\r\n totalIterations: this.totalIterations,\r\n });\r\n }\r\n }\r\n\r\n /**\r\n * Stop a subagent and remove it from the coordinator. Releases all\r\n * associated resources (AbortController, context, budget state).\r\n * The subagent entry is deleted so the id can be reused in a future spawn.\r\n */\r\n async remove(subagentId: string): Promise<void> {\r\n const subagent = this.subagents.get(subagentId);\r\n if (!subagent) return;\r\n\r\n // Gracefully stop first — same logic as stop() but don't block on it.\r\n if (subagent.status === 'running' || subagent.status === 'idle') {\r\n this.terminating.add(subagentId);\r\n subagent.abortController.abort();\r\n subagent.status = 'stopped';\r\n }\r\n\r\n // Release all resources associated with this subagent.\r\n this.subagents.delete(subagentId);\r\n this.terminating.delete(subagentId);\r\n // Free the nickname slot so the same name can be reused by a future spawn.\r\n const nicknameKey = this.subagentNicknames.get(subagentId);\r\n if (nicknameKey) {\r\n this.usedNicknames.delete(nicknameKey);\r\n this.subagentNicknames.delete(subagentId);\r\n }\r\n\r\n // Clean up any pending tasks assigned to this subagent — emit synthetic\r\n // 'stopped' completions so callers awaiting them via awaitTasks() unblock\r\n // instead of hanging forever. Without this, a task queued for a removed\r\n // subagent would leave its waiter permanently unresolved.\r\n const orphaned = this.pendingTasks.filter((t) => t.subagentId === subagentId);\r\n this.pendingTasks = this.pendingTasks.filter((t) => t.subagentId !== subagentId);\r\n for (const t of orphaned) {\r\n const synthetic: TaskResult = {\r\n subagentId,\r\n taskId: t.id,\r\n status: 'stopped',\r\n error: {\r\n kind: 'aborted_by_parent',\r\n message: `Subagent \"${subagentId}\" was removed while task \"${t.id}\" was pending`,\r\n retryable: false,\r\n },\r\n iterations: 0,\r\n toolCalls: 0,\r\n durationMs: 0,\r\n };\r\n this.recordCompletion(synthetic);\r\n }\r\n\r\n this.fleetBus?.emit({\r\n subagentId,\r\n ts: Date.now(),\r\n type: 'subagent.removed',\r\n payload: { subagentId },\r\n });\r\n\r\n this.emitCoordinatorStats();\r\n }\r\n\r\n private isDone(): boolean {\r\n if (this.config.doneCondition.type === 'all_tasks_done') {\r\n return this.pendingTasks.length === 0 && this.inFlight === 0;\r\n }\r\n if (\r\n this.config.doneCondition.maxIterations !== undefined &&\r\n this.totalIterations >= this.config.doneCondition.maxIterations\r\n ) {\r\n return true;\r\n }\r\n return false;\r\n }\r\n}\r\n\r\n/**\r\n * Map any raw exception thrown out of a subagent's runner into a\r\n * structured `SubagentError`. This is the single point where the\r\n * coordinator decides \"what kind of failure was that\" — so callers\r\n * (delegate tool output, /agents UI, retry policies) branch on\r\n * `kind` instead of substring-matching `error.message`.\r\n *\r\n * The classification order matters:\r\n * 1. Provider errors first (their `status` + `retryable` are\r\n * already structured, just translate to our enum).\r\n * 2. Budget errors next (BudgetExceededError carries a discrete\r\n * `kind` we can lift directly).\r\n * 3. Parent-abort if the subagent's signal was aborted and we\r\n * didn't recognize the error otherwise — distinguishes user\r\n * Ctrl+C from a tool throwing.\r\n * 4. Substring sniffing for stable error markers (\"agent\r\n * aborted\" from agent-subagent-runner, \"Bridge transport\"\r\n * from agent-bridge).\r\n * 5. Fallback to `unknown` so callers know we couldn't classify.\r\n *\r\n * The `cause` field is always populated when `err` is an Error so\r\n * diagnostics survive even when `kind === 'unknown'` — no info is\r\n * dropped, the classifier just refused to commit.\r\n *\r\n * Exported because tests and CLI surfaces want to assert on the\r\n * classification without instantiating a coordinator.\r\n */\r\nexport function classifySubagentError(\r\n err: unknown,\r\n hints: { parentAborted?: boolean } = {},\r\n): SubagentError {\r\n const cause = err instanceof Error\r\n ? { name: err.name, message: err.message, stack: err.stack }\r\n : undefined;\r\n\r\n if (err instanceof ProviderError) {\r\n const baseMessage = err.describe();\r\n return providerErrorToSubagentError(err, baseMessage, cause);\r\n }\r\n\r\n const baseMessage = err instanceof Error ? err.message : String(err);\r\n\r\n if (err instanceof BudgetExceededError) {\r\n const map: Record<BudgetExceededError['kind'], SubagentErrorKind> = {\r\n iterations: 'budget_iterations',\r\n tool_calls: 'budget_tool_calls',\r\n tokens: 'budget_tokens',\r\n cost: 'budget_cost',\r\n timeout: 'budget_timeout',\r\n idle_timeout: 'budget_timeout',\r\n };\r\n return {\r\n kind: map[err.kind],\r\n message: baseMessage,\r\n // Budgets are user-configured ceilings, not transient failures —\r\n // retrying with the same budget will hit the same ceiling. The\r\n // orchestrator must raise the budget or narrow the task first.\r\n retryable: false,\r\n cause,\r\n };\r\n }\r\n\r\n // Distinguish parent-aborted from real failures BEFORE substring\r\n // sniffing — if the parent signal is aborted, the most common\r\n // exception is \"agent aborted\" thrown by agent-subagent-runner.\r\n if (hints.parentAborted) {\r\n return {\r\n kind: 'aborted_by_parent',\r\n message: baseMessage,\r\n retryable: false,\r\n cause,\r\n };\r\n }\r\n\r\n // Stable markers — these strings live in our own code and are\r\n // checked here intentionally so callers can react without\r\n // exception-type imports.\r\n const lower = baseMessage.toLowerCase();\r\n if (/agent aborted$/i.test(baseMessage)) {\r\n return {\r\n kind: 'aborted_by_parent',\r\n message: baseMessage,\r\n retryable: false,\r\n cause,\r\n };\r\n }\r\n if (/agent exhausted iteration limit$/i.test(baseMessage)) {\r\n return { kind: 'budget_iterations', message: baseMessage, retryable: false, cause };\r\n }\r\n if (/empty response$/i.test(baseMessage)) {\r\n return { kind: 'empty_response', message: baseMessage, retryable: false, cause };\r\n }\r\n // The runner throws `Error('tool failed: <name>')` when an executed tool\r\n // returned `ok:false` and the agent ultimately ended without recovering\r\n // (or aborted). Surface as `tool_failed` so callers don't conflate a\r\n // failed tool with a thrown tool — both are useful but mean different\r\n // things at the LLM layer.\r\n if (/^tool failed: /i.test(baseMessage)) {\r\n return { kind: 'tool_failed', message: baseMessage, retryable: false, cause };\r\n }\r\n if (lower.includes('bridge transport') || /bridge.*(closed|disconnect)/i.test(baseMessage)) {\r\n return { kind: 'bridge_failed', message: baseMessage, retryable: false, cause };\r\n }\r\n if (/context length|max.*tokens?.*exceeded|prompt is too long/i.test(baseMessage)) {\r\n return { kind: 'context_overflow', message: baseMessage, retryable: false, cause };\r\n }\r\n\r\n // Final fallback — preserve cause so diagnostics aren't lost.\r\n return {\r\n kind: 'unknown',\r\n message: baseMessage,\r\n retryable: false,\r\n cause,\r\n };\r\n}\r\n\r\nfunction providerErrorToSubagentError(\r\n err: ProviderError,\r\n message: string,\r\n cause: SubagentError['cause'],\r\n): SubagentError {\r\n const status = err.status;\r\n // Read suggested retry-after from the provider body when present so\r\n // the orchestrator doesn't have to invent a backoff. Most providers\r\n // include retry-after as a header / body field which our provider\r\n // layer normalises into `body.message` — we cannot trust a numeric\r\n // field exists, so we leave backoffMs unset when unknown.\r\n if (status === 429 || err.body?.type === 'rate_limit_error') {\r\n return {\r\n kind: 'provider_rate_limit',\r\n message,\r\n retryable: true,\r\n // Conservative default: 5s. Provider-specific code can override\r\n // by emitting an error whose body carries an explicit hint.\r\n backoffMs: 5_000,\r\n cause,\r\n };\r\n }\r\n if (status === 401 || status === 403 || err.body?.type === 'authentication_error') {\r\n return { kind: 'provider_auth', message, retryable: false, cause };\r\n }\r\n if (status === 408 || status === 0) {\r\n return { kind: 'provider_timeout', message, retryable: true, cause };\r\n }\r\n if (status >= 500 && status < 600) {\r\n return {\r\n kind: 'provider_5xx',\r\n message,\r\n retryable: true,\r\n backoffMs: 3_000,\r\n cause,\r\n };\r\n }\r\n // Other provider errors (400 invalid request, 404 not found, etc.)\r\n // are not retryable as-is and don't have a dedicated kind — surface\r\n // as 'unknown' so the orchestrator treats them as terminal.\r\n return { kind: 'unknown', message, retryable: err.retryable, cause };\r\n}\r\n","import { randomUUID } from 'node:crypto';\nimport * as fsp from 'node:fs/promises';\nimport * as path from 'node:path';\nimport type { BrainArbiter } from './brain.js';\nimport { DirectorStateCheckpoint, type DirectorStateSnapshot } from '../storage/director-state.js';\nimport type { BridgeMessage } from '../types/agent-bridge.js';\nimport type { ModelMatrixEntry } from '../types/config.js';\nimport type {\n CoordinatorStatus,\n MultiAgentConfig,\n SubagentConfig,\n SubagentRunner,\n TaskResult,\n TaskSpec,\n} from '../types/multi-agent.js';\nimport type { SessionWriter } from '../types/session.js';\nimport type { Tool } from '../types/tool.js';\nimport { atomicWrite } from '../utils/atomic-write.js';\nimport { InMemoryAgentBridge } from './agent-bridge.js';\nimport {\n type CollabDebugReport,\n CollabSession,\n type CollabSessionOptions,\n} from './collab-debug.js';\nimport {\n DEFAULT_DIRECTOR_PREAMBLE,\n DEFAULT_SUBAGENT_BASELINE,\n composeDirectorPrompt,\n composeSubagentPrompt,\n rosterSummaryFromConfigs,\n} from './director-prompts.js';\nimport {\n makeAskResultTool,\n makeAskTool,\n makeAssignTool,\n makeAwaitTasksTool,\n makeCollabDebugTool,\n makeFleetEmitTool,\n makeFleetHealthTool,\n makeFleetSessionTool,\n makeFleetStatusTool,\n makeFleetUsageTool,\n makeRollUpTool,\n makeSpawnTool,\n makeTerminateAllTool,\n makeTerminateTool,\n makeWorkCompleteTool,\n} from './director-tools.js';\nimport { FleetBus, type FleetUsage, FleetUsageAggregator } from './fleet-bus.js';\nimport type { FleetManager } from './fleet-manager.js';\nimport type { ICoordinator } from './icoordinator.js';\nimport { InMemoryBridgeTransport } from './in-memory-transport.js';\nimport { LargeAnswerStore } from './large-answer-store.js';\nimport { resolveModelMatrix } from './model-matrix.js';\nimport { DefaultMultiAgentCoordinator } from './multi-agent-coordinator.js';\nimport { assignNickname } from './subagent-nicknames.js';\n\n/**\n * Director — high-level orchestrator that owns a `MultiAgentCoordinator`,\n * a `FleetBus`, and a `FleetUsageAggregator`. Exposes a small imperative\n * API (`spawn`, `assign`, `awaitTasks`, `terminate`, `status`, `usage`)\n * that's easy to test, and a `tools()` factory that wraps the same API\n * as agent-callable `Tool`s so an LLM can drive the orchestration.\n *\n * This class is intentionally *not* an `Agent`. It's a coordinator +\n * observability surface. To make it LLM-driven, construct an Agent\n * with `director.tools()` registered. That keeps the construction\n * symmetric with how other agents are built and avoids smuggling a\n * heavy LLM dependency into core just for the director path.\n */\nexport interface DirectorOptions {\n config: MultiAgentConfig;\n runner?: SubagentRunner;\n /** Optional Brain arbiter above the director for policy/decision escalation. */\n brain?: BrainArbiter;\n /**\n * When set, the director writes a `fleet.json` manifest to this path\n * recording every spawned subagent (id, provider, model, role, task\n * ids). Used by `wstack replay <runId>` to rehydrate a fleet. Pass an\n * absolute file path — the directory must already exist (the\n * director-session factory creates it when used together).\n */\n manifestPath?: string;\n /**\n * Optional roster used by `leaderSystemPrompt()` to render a roles\n * summary into the leader's preamble. Same shape as the roster passed\n * to `tools()` — typically the same value.\n */\n roster?: Record<string, SubagentConfig>;\n /**\n * Override the built-in fleet preamble (see `DEFAULT_DIRECTOR_PREAMBLE`).\n * Pass an empty string to suppress the preamble entirely.\n */\n directorPreamble?: string;\n /**\n * Override the built-in subagent baseline (see\n * `DEFAULT_SUBAGENT_BASELINE`). Pass an empty string to suppress.\n */\n subagentBaseline?: string;\n /**\n * Absolute path to a directory the fleet can use as a shared scratchpad\n * (read + write by every subagent). When set, the director creates it on\n * construction and `subagentSystemPrompt()` automatically injects a\n * \"Shared notes\" block telling subagents where to drop their findings.\n * This is the cheap fleet-coordination channel — agents don't need each\n * other's transcripts, just each other's conclusions.\n *\n * Convention: under a fleet run rooted at `<sessionsRoot>/<runId>/`,\n * pass `<sessionsRoot>/<runId>/shared/` here.\n */\n sharedScratchpadPath?: string;\n /**\n * Maximum number of spawns this director can perform across its\n * lifetime. Default: unlimited. Acts as a hard fleet-wide cost cap —\n * a runaway leader that keeps spawning workers gets cut off cleanly\n * instead of burning provider tokens until the user kills the\n * process. The N+1-th spawn call rejects with a `FleetSpawnBudgetError`.\n */\n maxSpawns?: number;\n /**\n * Maximum nesting depth for spawns. The director constructed by the\n * user is at depth `spawnDepth` (default 0); any subagent that itself\n * acts as a director would construct its own `Director` with\n * `spawnDepth: parent.spawnDepth + 1`. When `spawnDepth >= maxSpawnDepth`,\n * `spawn()` rejects. Default: 2 (root director can spawn workers; a\n * worker that becomes a sub-director cannot itself spawn further).\n * This stops infinite recursive director chains from a hostile or\n * confused prompt.\n */\n maxSpawnDepth?: number;\n /**\n * Current spawn-chain depth for this director instance. Defaults to 0.\n * A nested director should pass `parent.spawnDepth + 1`. Together with\n * `maxSpawnDepth` this bounds the chain.\n */\n spawnDepth?: number;\n /**\n * Absolute path to a director-state checkpoint file. When set, the\n * director writes an incremental snapshot of pending/running/completed\n * tasks + spawned subagents on every state mutation. Distinct from\n * `manifestPath`: the manifest is a final record written on shutdown,\n * the checkpoint is a live mirror useful for crash recovery and the\n * `wstack resume` \"you had N tasks in flight\" banner.\n */\n stateCheckpointPath?: string;\n /**\n * Session writer the director should forward task lifecycle events to\n * (`agent_spawned`, `task_created`, `task_completed`, `task_failed`).\n * When omitted these events stay in-memory only — useful for tests but\n * lossy in production. Production callers (the CLI) pass the same\n * writer the host Agent uses so all events land in a single JSONL.\n */\n sessionWriter?: SessionWriter;\n /**\n * Debounce window for periodic manifest writes triggered by spawn/\n * assign/complete events. Default: 2000ms. Pass 0 to disable periodic\n * writes (the manifest will then only be written on `shutdown()`).\n */\n manifestDebounceMs?: number;\n /**\n * Fleet-wide cost ceiling. When set, `spawn()` refuses any new subagent\n * that would push the fleet's total cost above this limit. The cap\n * is checked BEFORE the spawn is recorded — a refused spawn must not\n * leak partial state into the manifest or fleet bus. Let in-flight\n * tasks complete; refuse new spawns only. When omitted or Infinity,\n * no cost cap applies.\n *\n * Distinct from SubagentBudget.maxCostUsd (per-subagent spend) — this\n * field caps the *entire fleet* total.\n */\n directorBudget?: {\n /**\n * Maximum total USD the fleet may spend across all subagents.\n * Default: Infinity (no cap).\n */\n maxCostUsd?: number;\n };\n /**\n * Maximum auto-extensions per subagent per budget kind before the\n * director denies further extensions. A subagent hitting the same\n * soft limit repeatedly (e.g. 3× budget.threshold_reached for\n * tool_calls) is likely looping on a prompt/config issue, not\n * making legitimate progress. Default: 2. Set to Infinity to\n * disable the cap (use with caution — a misconfigured subagent\n * could burn unlimited budget).\n */\n maxBudgetExtensions?: number;\n /**\n * Debounce window for state-checkpoint writes. Default: 250ms.\n * Bursts of spawn/assign/complete events collapse into one disk\n * hit. Higher values reduce write amplification on fast machines;\n * lower values improve crash-recovery fidelity (less state lost\n * on sudden process exit).\n */\n checkpointDebounceMs?: number;\n /**\n * Sessions root directory for per-subagent JSONL transcripts.\n * When set, the director can read subagent transcripts directly for\n * `fleet_session` tool — no bridge round-trip needed. Path convention:\n * `<sessionsRoot>/<directorRunId>/<subagentId>.jsonl`.\n */\n sessionsRoot?: string;\n /**\n * Director run id — namespaced under `sessionsRoot` to locate per-subagent\n * JSONLs. Defaults to the director's own `id` when omitted.\n */\n directorRunId?: string;\n /**\n * Pre-built fleet manager. When provided the Director delegates all\n * fleet-level policy (spawn budgets, manifest assembly, checkpointing)\n * to this instance and takes ownership of the coordinator + bridge\n * layer only. This enables unit-testing fleet policy in isolation\n * and swapping implementations without changing the Director surface.\n *\n * When omitted the Director creates its own fleet infrastructure\n * (same behavior as before this field was added).\n */\n fleetManager?: FleetManager;\n /**\n * Optional LLM classifier for the smart dispatcher. When set, the\n * `spawn_subagent` tool can accept a free-form `description` field\n * and the director will automatically route to the best-matching\n * catalog agent using `dispatchAgent()`. When omitted, routing is\n * pure heuristic (no provider call) — sufficient for most tasks.\n *\n * Build from a `complete(prompt) => string` function using\n * `makeLLMClassifier(complete)` from the dispatcher module.\n */\n dispatchClassifier?: import('../coordination/dispatcher.js').DispatchClassifier;\n /**\n * Maximum context load (as a fraction of maxContext) the leader agent\n * is allowed to reach before a new spawn is rejected. Default: 0.85.\n * When the leader's context pressure exceeds this threshold, spawning\n * a new subagent is refused — the leader must compact first.\n * Only used when no `fleetManager` is provided (inline mode).\n * Set to 1.0 to disable this check.\n */\n maxLeaderContextLoad?: number;\n /**\n * Provider's max context window in tokens. Used with `maxLeaderContextLoad`\n * to compute the absolute token threshold. Default: 128_000.\n * Only used when no `fleetManager` is provided (inline mode).\n *\n * A function may be supplied when the leader can switch models at runtime;\n * spawn() reads it lazily so the threshold follows the active model.\n */\n maxContext?: number | (() => number | undefined);\n /**\n * Per-task model matrix (Config.modelMatrix). When set, a spawn whose\n * config has no explicit `model` is resolved against this matrix by role\n * (→ phase → `*`) before the subagent is built — so the spawned event,\n * manifest, and the agent itself all run the matched model. Explicit\n * per-spawn `model` overrides always win.\n *\n * Pass a **function** (not a snapshot) when the matrix can change at\n * runtime (the CLI passes `() => configStore.get().modelMatrix`) so a\n * mid-session `/setmodel` takes effect on the next spawn. A static record\n * is also accepted for tests and one-shot runs.\n */\n modelMatrix?: ModelMatrixSource;\n}\n\n/** Either a static matrix or a live getter (re-read on every spawn). */\nexport type ModelMatrixSource =\n | Record<string, ModelMatrixEntry>\n | (() => Record<string, ModelMatrixEntry> | undefined);\n\n/**\n * Thrown by `Director.spawn()` when a configured spawn cap (`maxSpawns`,\n * `maxSpawnDepth`) is hit. Distinct error class so callers — including\n * the `spawn_subagent` tool surface — can recognize the budget case and\n * report it cleanly instead of treating it like an unexpected failure.\n */\nexport class FleetSpawnBudgetError extends Error {\n readonly kind: 'max_spawns' | 'max_spawn_depth';\n readonly limit: number;\n readonly observed: number;\n constructor(\n kind: 'max_spawns' | 'max_spawn_depth',\n limit: number,\n observed: number,\n message?: string,\n ) {\n const defaultMsg =\n kind === 'max_spawns'\n ? `Director spawn budget exceeded: tried to spawn #${observed} but maxSpawns is ${limit}`\n : `Director spawn depth budget exceeded: this director is at depth ${observed} and maxSpawnDepth is ${limit}`;\n super(message ?? defaultMsg);\n this.name = 'FleetSpawnBudgetError';\n this.kind = kind;\n this.limit = limit;\n this.observed = observed;\n }\n}\n\n/**\n * Thrown by `Director.spawn()` when the fleet-wide cost cap is exceeded.\n * Distinct from `FleetSpawnBudgetError` (spawn count/depth) — this is a\n * dollar-denominated ceiling that tracks cumulative spend across all\n * subagents in the fleet.\n */\nexport class FleetCostCapError extends Error {\n readonly kind: 'max_cost_usd';\n readonly limit: number;\n readonly observed: number;\n constructor(limit: number, observed: number) {\n super(\n `Director cost cap exceeded: total fleet spend ${observed.toFixed(4)} exceeds maxCostUsd ${limit.toFixed(4)}`,\n );\n this.name = 'FleetCostCapError';\n this.kind = 'max_cost_usd';\n this.limit = limit;\n this.observed = observed;\n }\n}\n\n/**\n * Thrown by `Director.spawn()` when the leader agent's context pressure\n * exceeds the configured threshold. The leader must compact before a new\n * subagent can be spawned — the context window is too full to safely\n * orchestrate additional agents.\n */\nexport class FleetContextOverflowError extends Error {\n readonly kind: 'max_context_load';\n readonly limit: number;\n readonly observed: number;\n constructor(limit: number, observed: number) {\n super(\n `Leader context overflow: leader has ${observed} tokens in flight (limit: ${limit}). Compact the leader context before spawning more subagents.`,\n );\n this.name = 'FleetContextOverflowError';\n this.kind = 'max_context_load';\n this.limit = limit;\n this.observed = observed;\n }\n}\n\nexport class Director implements ICoordinator {\n /** Alias for the ICoordinator contract. `id` is retained for backward compatibility. */\n get coordinatorId(): string {\n return this.id;\n }\n readonly id: string;\n /**\n * The fleet event bus. Backed by `fleetManager?.fleet` when a FleetManager\n * is injected; otherwise own FleetBus instance (preserves existing behavior).\n */\n readonly fleet: FleetBus;\n /**\n * Usage rollup. Backed by `fleetManager?.usage` when a FleetManager is\n * injected; otherwise own FleetUsageAggregator.\n */\n readonly usage: FleetUsageAggregator;\n\n /**\n * Update the leader agent's current context pressure (full request tokens:\n * messages + systemPrompt + toolDefs). The director checks this before every\n * spawn — if the pressure exceeds `maxLeaderContextLoad * maxContext`,\n * spawning is refused with a `FleetContextOverflowError`.\n *\n * Call this after each leader agent iteration to keep the pressure current.\n * The compactor's `CompactReport.fullRequestTokensAfter` is a natural source.\n */\n setLeaderContextPressure(tokens: number): void {\n this.leaderContextPressure = tokens;\n // Mirror to FleetManager when available so the check is centralized.\n this.fleetManager?.setLeaderContextPressure(tokens);\n }\n\n /**\n * Read the leader agent's current context pressure.\n */\n getLeaderContextPressure(): number {\n return this.leaderContextPressure;\n }\n\n private resolveMaxContext(): number {\n const resolved = typeof this.maxContext === 'function' ? this.maxContext() : this.maxContext;\n return resolved && resolved > 0 ? resolved : 128_000;\n }\n /** Optional Brain arbiter for director-level policy decisions. */\n private readonly brain?: BrainArbiter;\n /**\n * Optional fleet-level policy container. When provided the Director\n * delegates spawn budgeting, manifest entries, and checkpointing to it\n * instead of managing those internally. All other behavior is unchanged.\n */\n readonly fleetManager: FleetManager | undefined;\n /**\n * Director-side bridge endpoint. Subagents are wired to the same\n * in-memory transport so the director can `ask()` them synchronously\n * and they can `send()` progress back. Exposed so external code (e.g.\n * the TUI) can subscribe to inbound messages.\n */\n readonly bridge: InMemoryAgentBridge;\n private readonly transport: InMemoryBridgeTransport;\n private readonly coordinator: DefaultMultiAgentCoordinator;\n /** Resolves with the matching `TaskResult` the first time the\n * coordinator emits `task.completed` for a given task id. Each entry\n * is created lazily on first poll/await and cleared once consumed. */\n private readonly taskWaiters = new Map<\n string,\n {\n promise: Promise<TaskResult>;\n resolve: (r: TaskResult) => void;\n }\n >();\n /** Cache of completed results in case the consumer asks AFTER the\n * coordinator already fired the event — `awaitTasks(['t-1'])` after\n * t-1 finished should resolve immediately, not hang. */\n private readonly completed = new Map<string, TaskResult>();\n /** Prevents the completed Map from growing unbounded in long-running directors. */\n private static readonly MAX_COMPLETED = 10_000;\n /** Per-subagent provider/model metadata, captured at spawn time so the\n * FleetUsageAggregator's metaLookup can surface readable rows. */\n private readonly subagentMeta = new Map<string, { provider?: string; model?: string }>();\n private readonly priceLookups = new Map<\n string,\n { input?: number; output?: number; cacheRead?: number; cacheWrite?: number }\n >();\n /** Bridge endpoints we created per subagent (so we can `stop()` them\n * on shutdown and free transport subscriptions). */\n private readonly subagentBridges = new Map<string, InMemoryAgentBridge>();\n /** Tracks per-spawn config + assigned task ids for manifest writing. */\n private readonly manifestEntries = new Map<\n string,\n {\n subagentId: string;\n name: string;\n role?: string;\n provider?: string;\n model?: string;\n taskIds: string[];\n }\n >();\n /** Tracks assigned nicknames so the same name is never reused in one fleet. */\n private readonly _usedNicknames = new Set<string>();\n private readonly manifestPath?: string;\n private readonly roster?: Record<string, SubagentConfig>;\n private readonly directorPreamble: string;\n private readonly subagentBaseline: string;\n /** Absolute path to the fleet's shared scratchpad directory, or null\n * when none was configured. Exposed as a readonly getter for callers\n * that need to surface the path to the user (e.g. the CLI logging\n * the location after `--director` boots). */\n readonly sharedScratchpadPath: string | null;\n /** Spawn cap (lifetime total). Infinity means unlimited. */\n readonly maxSpawns: number;\n /** Nesting cap. The N-th director in a chain has `spawnDepth = N-1`. */\n readonly maxSpawnDepth: number;\n /** This director's position in a director chain. Root director = 0. */\n readonly spawnDepth: number;\n /** Live spawn counter for `maxSpawns` enforcement. */\n private spawnCount = 0;\n /** Optional checkpoint mirror — writes the live task graph + roster to disk. */\n private readonly stateCheckpoint: DirectorStateCheckpoint | null;\n /** Optional session writer for emitting task_* / agent_* lifecycle events. */\n private readonly sessionWriter: SessionWriter | null;\n /** Debounce timer for periodic manifest writes. */\n private manifestTimer: NodeJS.Timeout | null = null;\n private readonly manifestDebounceMs: number;\n /** Fleet-wide cost cap (entire fleet total, distinct from SubagentBudget limits). Infinity means no cap. */\n private readonly maxFleetCostUsd: number;\n /** Max auto-extensions per subagent per budget kind before denying. */\n private readonly maxBudgetExtensions: number;\n /** Sessions root for direct subagent JSONL reads (fleet_session tool). */\n private readonly sessionsRoot?: string;\n /** Director run id for JSONL path resolution. */\n private readonly directorRunId: string;\n /** Resolves task descriptions back from `assign()` so completion events\n * can also carry a human-readable title. */\n private readonly taskDescriptions = new Map<string, string>();\n /** Snapshot of which subagent owns each task — drives state-checkpoint\n * status updates without re-walking the manifest. */\n private readonly taskOwners = new Map<string, string>();\n /** Cumulative auto-extension grants per subagent (all budget kinds). Lets\n * /fleet render \"⚡ extended ×N\" without replaying the event stream. */\n private readonly extendTotals = new Map<string, number>();\n /**\n * Handle to the coordinator-side `task.completed` listener so we can\n * unsubscribe in `shutdown()`. Without this, repeated Director\n * construction (e.g. tests, hot reloads) accumulates listeners on a\n * cached coordinator and slowly drifts the EventEmitter past its\n * default cap.\n */\n private taskCompletedListener:\n | ((payload: { task: TaskSpec; result: TaskResult }) => void)\n | null = null;\n /** Optional LLM classifier for smart dispatch. Passed from options. */\n readonly dispatchClassifier?: import('../coordination/dispatcher.js').DispatchClassifier;\n /** Leader agent's current context pressure (full request tokens). */\n private leaderContextPressure = 0;\n /** Maximum context load fraction before spawn is refused. */\n private readonly maxLeaderContextLoad: number;\n /** Provider's max context window in tokens, or a live resolver for runtime model switches. */\n private readonly maxContext: number | (() => number | undefined);\n /** Per-task model matrix (static record or live getter); resolved\n * per-spawn when no explicit model is set. */\n private readonly modelMatrix?: ModelMatrixSource;\n /**\n * When set by `workComplete()`, the director stops dispatching new tasks\n * and terminates all running subagents. Used when the director's LLM decides\n * the goal is satisfied and no further spawns are needed — prevents the\n * coordinator from keeping workers alive for tasks that will never arrive.\n */\n private workCompleteFlag = false;\n /** Pending /btw notes stashed by the leader agent (see setLeaderBtwNote). */\n private _leaderBtwNotes: string[] = [];\n /** Active collab sessions tracked by sessionId (see spawnCollab). */\n private readonly _activeCollabSessions = new Map<\n string,\n import('./collab-debug.js').CollabSession\n >();\n /** Prevents large `ask_subagent` answers from bloating the leader's context window. */\n readonly largeAnswerStore: LargeAnswerStore;\n\n constructor(opts: DirectorOptions) {\n this.id = opts.config.coordinatorId || randomUUID();\n this.brain = opts.brain;\n this.manifestPath = opts.manifestPath;\n this.roster = opts.roster;\n this.directorPreamble = opts.directorPreamble ?? DEFAULT_DIRECTOR_PREAMBLE;\n this.subagentBaseline = opts.subagentBaseline ?? DEFAULT_SUBAGENT_BASELINE;\n this.sharedScratchpadPath = opts.sharedScratchpadPath ?? null;\n this.maxSpawns = opts.maxSpawns ?? Number.POSITIVE_INFINITY;\n this.maxSpawnDepth = opts.maxSpawnDepth ?? 2;\n this.spawnDepth = opts.spawnDepth ?? 0;\n this.sessionWriter = opts.sessionWriter ?? null;\n this.manifestDebounceMs = opts.manifestDebounceMs ?? 2000;\n this.dispatchClassifier = opts.dispatchClassifier;\n this.maxFleetCostUsd = opts.directorBudget?.maxCostUsd ?? Number.POSITIVE_INFINITY;\n this.maxBudgetExtensions = opts.maxBudgetExtensions ?? 5;\n this.maxLeaderContextLoad = opts.maxLeaderContextLoad ?? 0.85;\n this.maxContext = opts.maxContext ?? 128_000;\n this.modelMatrix = opts.modelMatrix;\n this.sessionsRoot = opts.sessionsRoot;\n this.directorRunId = opts.directorRunId ?? this.id;\n this.stateCheckpoint = opts.stateCheckpointPath\n ? new DirectorStateCheckpoint(\n opts.stateCheckpointPath,\n {\n directorRunId: this.id,\n maxSpawns: opts.maxSpawns,\n spawnDepth: this.spawnDepth,\n maxSpawnDepth: this.maxSpawnDepth,\n directorBudget: opts.directorBudget,\n },\n opts.checkpointDebounceMs ?? 250,\n )\n : null;\n this.fleetManager = opts.fleetManager;\n if (this.sharedScratchpadPath) {\n // Create the directory eagerly so subagents that try to write\n // there on first iteration don't trip on ENOENT. Fire-and-forget,\n // but surface failures via process.emitWarning — the downstream\n // ENOENT a subagent hits is opaque without this signal.\n void fsp\n .mkdir(this.sharedScratchpadPath, { recursive: true })\n .catch((err) => this.logShutdownError('shared_scratchpad_mkdir', err));\n }\n this.transport = new InMemoryBridgeTransport();\n this.bridge = new InMemoryAgentBridge(\n { agentId: this.id, coordinatorId: this.id },\n this.transport,\n );\n // Delegate to FleetManager when injected; otherwise create own instances\n // (preserves existing behavior for callers that don't pass fleetManager).\n if (this.fleetManager) {\n this.fleet = this.fleetManager.fleet;\n this.usage = this.fleetManager.usage;\n } else {\n this.fleet = new FleetBus();\n this.usage = new FleetUsageAggregator(\n this.fleet,\n (_id, provider, model) => {\n if (provider && model) return this.priceLookups.get(`${provider}/${model}`);\n return undefined;\n },\n (id) => this.subagentMeta.get(id),\n );\n }\n this.coordinator = new DefaultMultiAgentCoordinator(\n { ...opts.config, coordinatorId: this.id },\n { runner: opts.runner },\n );\n this.coordinator.setFleetBus(this.fleet);\n this.fleetManager?.setCoordinator(this.coordinator);\n // Mirror coordinator completion events into the waiter table. This\n // lets `awaitTasks([...])` resolve on the *next* completion event\n // without polling — and the `completed` cache covers the case where\n // a caller asks after the fact.\n //\n // The listener is captured in a field (`taskCompletedListener`) so\n // `shutdown()` can `coordinator.off(...)` it cleanly — otherwise\n // repeated Director construction against a cached coordinator\n // (tests, hot reloads) leaks listeners and eventually trips\n // EventEmitter's max-listener warning.\n this.taskCompletedListener = (payload: { task: TaskSpec; result: TaskResult }) => {\n const r = payload.result;\n this.completed.set(r.taskId, r);\n // Trim oldest entries when the cap is exceeded — keep most recent results\n // so rollUp() and completedResults() still have data to return.\n if (this.completed.size > Director.MAX_COMPLETED) {\n const toDelete = this.completed.size - Director.MAX_COMPLETED;\n const keys = [...this.completed.keys()].slice(0, toDelete);\n for (const k of keys) this.completed.delete(k);\n }\n const waiter = this.taskWaiters.get(r.taskId);\n if (waiter) {\n waiter.resolve(r);\n this.taskWaiters.delete(r.taskId);\n }\n // Mirror into the on-disk checkpoint + session event stream so a\n // crashed director leaves a complete picture of which tasks landed.\n const title = this.taskDescriptions.get(r.taskId) ?? payload.task.description ?? r.taskId;\n const failed = r.status !== 'success';\n // Disk-side state-checkpoint and session JSONL both store `error`\n // as a string for historical reasons. The structured SubagentError\n // envelope carries `kind`, `message`, `retryable`, etc. — flatten\n // to a `kind: message` string here so old readers stay valid and\n // grep-friendly. The full envelope is still available live via\n // the EventBus / TaskResult to in-process consumers.\n const errorString = r.error ? `${r.error.kind}: ${r.error.message}` : undefined;\n this.stateCheckpoint?.recordTaskStatus(r.taskId, {\n status: failed ? (r.status as 'failed' | 'timeout' | 'stopped') : 'completed',\n completedAt: new Date().toISOString(),\n iterations: r.iterations,\n toolCalls: r.toolCalls,\n durationMs: r.durationMs,\n error: errorString,\n });\n this.stateCheckpoint?.setUsage(this.usage.snapshot());\n void this.appendSessionEvent(\n failed\n ? {\n type: 'task_failed',\n ts: new Date().toISOString(),\n taskId: r.taskId,\n title,\n error: errorString ?? r.status,\n }\n : {\n type: 'task_completed',\n ts: new Date().toISOString(),\n taskId: r.taskId,\n title,\n },\n );\n // Flush immediately on task completion — the result should be\n // visible in the manifest without waiting for the debounce window.\n // Use flushManifest() so any pending debounce timer is also cleared.\n if (this.fleetManager) {\n this.fleetManager.flushManifest();\n } else {\n this.scheduleManifest();\n }\n };\n this.coordinator.on('task.completed', this.taskCompletedListener);\n\n // Wire budget.threshold_reached events from the FleetBus into the\n // coordinator's task completion path. When a subagent hits a soft\n // limit, the runner emits this event; we intercept it here, resolve\n // the decision promise (via extend/deny), and let the normal\n // task.completed flow handle the rest.\n //\n // Extension guard: a subagent that hits the same soft limit\n // `maxBudgetExtensions` times without completing its task is looping\n // on a prompt/config issue, not running out of budget legitimately.\n // After the configured number of extends we deny and let the task\n // fail — the host agent should then split the work or narrow the\n // scope. We track this per subagent+kind combination.\n const extendCounts = new Map<string, number>();\n // Per-subagent progress heartbeat: counts tool executions so the timeout\n // kind can extend indefinitely WHILE the agent is doing work, yet still\n // deny a wedged agent that produces no new tool calls between grants.\n // Wall-clock time always advances, so timeout alone is never a reliable\n // \"stuck\" signal — tool activity is.\n const progressBySubagent = new Map<string, number>();\n const lastTimeoutProgress = new Map<string, number>();\n this.fleet.filter('tool.executed', (e) => {\n progressBySubagent.set(e.subagentId, (progressBySubagent.get(e.subagentId) ?? 0) + 1);\n });\n this.fleet.filter('budget.threshold_reached', (e) => {\n const payload = e.payload as {\n kind: 'timeout' | 'idle_timeout' | 'iterations' | 'tool_calls' | 'tokens' | 'cost';\n used: number;\n limit: number;\n timeoutMs: number;\n extend: (extra: Record<string, unknown>) => void;\n deny: () => void;\n };\n // -----------------------------------------------------------------------\n // Collab agents are NOT handled here. Their CollabSession owns the\n // budget.threshold_reached routing — it calls session.cancel() (never\n // payload.deny()) when the Director decides to stop, so the agent\n // finishes naturally. The Director's auto-extend/deny logic would\n // conflict with that decision and must not run for collab subagents.\n // -----------------------------------------------------------------------\n if (\n e.subagentId.startsWith('bug-hunter-') ||\n e.subagentId.startsWith('refactor-planner-') ||\n e.subagentId.startsWith('critic-')\n ) {\n // Skip — let the CollabSession's fleet handler deal with it.\n // The session calls session.cancel() on the FleetBus, which causes\n // the subagent to finish naturally without Director intervention.\n return;\n }\n // Timeout is governed by the heartbeat, not the extension cap. While the\n // subagent keeps executing tools it never dies on wall-clock time; once\n // it stops making progress between grants, it's genuinely stuck → deny.\n if (payload.kind === 'timeout') {\n const progress = progressBySubagent.get(e.subagentId) ?? 0;\n const lastProgress = lastTimeoutProgress.get(e.subagentId) ?? -1;\n if (progress <= lastProgress) {\n payload.deny();\n return;\n }\n lastTimeoutProgress.set(e.subagentId, progress);\n setImmediate(() => {\n const newLimit = Math.min(Math.ceil(payload.limit * 2), 24 * 60 * 60_000);\n this.recordExtension(e.subagentId, e.taskId, 'timeout', newLimit);\n payload.extend({ timeoutMs: newLimit });\n });\n return;\n }\n const guardKey = `${e.subagentId}:${payload.kind}`;\n const prior = extendCounts.get(guardKey) ?? 0;\n if (prior >= this.maxBudgetExtensions) {\n payload.deny();\n extendCounts.delete(guardKey);\n return;\n }\n if (payload.kind === 'cost' && this.maxFleetCostUsd < Number.POSITIVE_INFINITY) {\n const totalCost = this.usage.snapshot().total?.cost ?? 0;\n if (totalCost >= this.maxFleetCostUsd) {\n payload.deny();\n return;\n }\n }\n const grantExtension = () => {\n setImmediate(() => {\n const extra: Record<string, unknown> = {};\n const base = Math.max(payload.limit, payload.used);\n const grow = (ceiling: number) => Math.min(Math.ceil(base * 1.5), ceiling);\n let newLimit = base;\n switch (payload.kind) {\n case 'iterations':\n newLimit = grow(50_000);\n extra.maxIterations = newLimit;\n break;\n case 'tool_calls':\n newLimit = grow(100_000);\n extra.maxToolCalls = newLimit;\n break;\n case 'tokens':\n newLimit = grow(5_000_000);\n extra.maxTokens = newLimit;\n break;\n case 'cost':\n newLimit = Math.min(base * 1.5, 100);\n extra.maxCostUsd = newLimit;\n break;\n }\n extendCounts.set(guardKey, prior + 1);\n this.recordExtension(e.subagentId, e.taskId, payload.kind, newLimit);\n payload.extend(extra);\n });\n };\n if (this.brain) {\n void this.brain\n .decide({\n id: `director-budget-${e.subagentId}-${payload.kind}`,\n source: 'director',\n question: `Should the director extend the ${payload.kind} budget for subagent ${e.subagentId}?`,\n context: [\n e.taskId ? `Task id: ${e.taskId}` : undefined,\n `Used: ${payload.used}`,\n `Limit: ${payload.limit}`,\n `Prior extensions for this kind: ${prior}`,\n ]\n .filter(Boolean)\n .join('\\n'),\n risk: payload.kind === 'cost' ? 'high' : 'medium',\n fallback: 'continue',\n options: [\n {\n id: 'extend',\n label: 'Grant the director default budget extension',\n consequence: 'The subagent continues with a larger per-kind budget.',\n risk: payload.kind === 'cost' ? 'high' : 'medium',\n recommended: true,\n },\n {\n id: 'stop',\n label: 'Stop this subagent at the current budget limit',\n consequence: 'The current task will fail or stop due to budget pressure.',\n risk: 'low',\n },\n ],\n })\n .then((decision) => {\n if (decision.type === 'deny') {\n payload.deny();\n return;\n }\n if (decision.type === 'ask_human') {\n payload.deny();\n return;\n }\n if (decision.optionId === 'stop' || /\\bstop\\b/i.test(decision.text)) {\n payload.deny();\n return;\n }\n grantExtension();\n })\n .catch(() => payload.deny());\n return;\n }\n grantExtension();\n });\n // Large-answer store: prevents big `ask_subagent` responses from\n // bloating the leader's context window. Responses above 2K chars\n // are stored out-of-band; only a summary goes into ctx.messages.\n this.largeAnswerStore = new LargeAnswerStore(2000);\n }\n\n /**\n * Record a granted budget extension and broadcast it on the FleetBus so\n * the host can re-emit `subagent.budget_extended` for live UI badges.\n * Called from both the timeout heartbeat path and the per-kind grant path.\n */\n private recordExtension(\n subagentId: string,\n taskId: string | undefined,\n kind: string,\n newLimit: number,\n ): void {\n const total = (this.extendTotals.get(subagentId) ?? 0) + 1;\n this.extendTotals.set(subagentId, total);\n this.fleet.emit({\n subagentId,\n taskId,\n ts: Date.now(),\n type: 'budget.extended',\n payload: { kind, newLimit, totalExtensions: total },\n });\n }\n\n /** Cumulative auto-extension count for one subagent (0 when never extended). */\n extensionsFor(subagentId: string): number {\n return this.extendTotals.get(subagentId) ?? 0;\n }\n\n /**\n * Signal that the director's work is done. Once called:\n * - `spawn()` throws `FleetSpawnBudgetError('max_spawns', …)` — no new\n * subagents can be created\n * - Running subagents are NOT forcibly stopped — they finish naturally,\n * but no new tasks are dispatched to them\n *\n * This lets the director LLM say \"I'm satisfied with the results, stop\n * spawning and wind down\" — without killing in-flight work mid-execution.\n * Call `terminateAll()` separately if you need immediate teardown.\n *\n * Idempotent — calling twice is a no-op.\n */\n workComplete(): void {\n this.workCompleteFlag = true;\n this.fleet.emit({\n subagentId: this.id,\n ts: Date.now(),\n type: 'director.work_complete',\n payload: {},\n });\n }\n\n /** Returns true if `workComplete()` has been called on this director. */\n isWorkComplete(): boolean {\n return this.workCompleteFlag;\n }\n\n /**\n * Stashes a /btw note on the leader agent's context. The leader's agent loop\n * calls `consumeBtwNotes()` at each iteration boundary and folds pending notes\n * into the conversation as a visible block — no abort, no restart, just a\n * \"by the way\" nudge the model picks up on its next turn.\n *\n * This is the entry point for the host (CLI, TUI) to inject /btw notes\n * programmatically without going through the slash-command path.\n */\n setLeaderBtwNote(note: string): number {\n const trimmed = note.trim();\n if (!trimmed) return this._leaderBtwNotes.length;\n this._leaderBtwNotes = [...this._leaderBtwNotes, trimmed].slice(-20);\n return this._leaderBtwNotes.length;\n }\n\n /**\n * Read and clear all pending /btw notes the leader has stashed.\n * Returns them in FIFO order (empty array when none).\n *\n * Called by CollabSession when a budget threshold event fires so the\n * Director can inspect accumulated /btw notes before deciding whether\n * to cancel the collab session or let it continue.\n */\n getLeaderBtwNotes(): string[] {\n const notes = this._leaderBtwNotes;\n this._leaderBtwNotes = [];\n return notes;\n }\n\n /**\n * Peek at pending /btw notes without consuming them.\n * Useful for UI to show \"N pending notes\" without clearing them.\n */\n peekLeaderBtwNotes(): string[] {\n return [...this._leaderBtwNotes];\n }\n\n /**\n * Drain (read + clear) all /btw notes in one call.\n * Alias for getLeaderBtwNotes() — kept for symmetry with consumeBtwNotes()\n * in the agent's btw.ts. The Director calls this at the point where it\n * makes a cancellation decision, not on every budget event.\n */\n drainLeaderBtwNotes(): string[] {\n return this.getLeaderBtwNotes();\n }\n\n /**\n * Cancel an active collab session by its id.\n * Emits `director.cancel_collab` on the FleetBus so the session's agents\n * finish early with a 'cancelled' disposition.\n *\n * Returns silently if the session id is not tracked or already settled.\n * The CollabDebugReport will reflect 'cancelled' disposition when awaited.\n */\n cancelCollabSession(sessionId: string, reason = 'Director cancelled'): void {\n const session = this._activeCollabSessions.get(sessionId);\n if (!session || session.isCancelled()) return;\n session.cancel(reason);\n // Stop each collab agent via the coordinator so their run() aborts.\n // This is the critical difference from a natural finish: we call\n // abortController.abort() on each subagent's run signal, which\n // propagates into agent.run() → tool executor and kills the run\n // before the budget or natural iteration limit ends it.\n // The abort is cooperative — the agent finishes its current iteration\n // then sees the signal and exits with status 'aborted', so no context\n // is silently lost.\n for (const [_role, subagentId] of session.getSubagentIds()) {\n this.coordinator.stop(subagentId).catch(() => {\n // Subagent may have already completed naturally — that's fine.\n // The stop() call is best-effort cleanup, not a guarantee.\n });\n }\n }\n\n /**\n * Subscribe a callback to be notified whenever a collab session raises\n * an alert (warning level). The callback receives the full DirectorAlert\n * payload so the host (CLI, TUI) can display it to the user.\n * Returns an unsubscribe function.\n */\n onCollabAlert(handler: (alert: import('./collab-debug.js').DirectorAlert) => void): () => void {\n return this.fleet.filter('collab.warning', (e) => {\n handler(e.payload as import('./collab-debug.js').DirectorAlert);\n });\n }\n\n /**\n * Returns all active (not yet settled) collab session ids.\n * Useful for the TUI to render a \"N active sessions\" badge and for\n * the host to know what can be cancelled.\n */\n activeCollabSessions(): string[] {\n return Array.from(this._activeCollabSessions.keys());\n }\n\n /** Best-effort session-writer append. Swallows failures — the director\n * must not break a fleet run because the session JSONL handle closed. */\n private async appendSessionEvent(event: Parameters<SessionWriter['append']>[0]): Promise<void> {\n if (!this.sessionWriter) return;\n try {\n await this.sessionWriter.append(event);\n } catch {\n // ignore\n }\n }\n\n /** Debounced manifest writer. A burst of spawn/assign/complete events\n * collapses into one write. Set `manifestDebounceMs` to 0 to write\n * synchronously (no debounce); set to negative to disable entirely. */\n private scheduleManifest(): void {\n if (!this.manifestPath) return;\n if (this.manifestDebounceMs === 0) {\n // 0 means instant flush — write synchronously, no timer.\n void this.writeManifest().catch((err) =>\n this.logShutdownError('manifest_write_debounced', err),\n );\n return;\n }\n if (this.manifestDebounceMs < 0) return;\n this.manifestTimer = setTimeout(() => {\n this.manifestTimer = null;\n void this.writeManifest().catch((err) =>\n this.logShutdownError('manifest_write_debounced', err),\n );\n }, this.manifestDebounceMs);\n }\n\n /**\n * Spawn a subagent. Identical to the coordinator's `spawn()` but\n * captures provider/model metadata for the usage aggregator and\n * lets the FleetBus attach to the runner's EventBus when the task\n * actually runs (see `attachSubagentBus`).\n *\n * Caller-supplied `priceLookup` is optional but recommended — without\n * it the `cost` column in `usage.snapshot()` stays at 0.\n */\n async spawn(\n config: SubagentConfig,\n priceLookup?: { input?: number; output?: number; cacheRead?: number; cacheWrite?: number },\n ): Promise<string> {\n // workComplete() signal: once the director decides the work is done,\n // refuse to spawn new subagents so the fleet winds down naturally.\n if (this.workCompleteFlag) {\n throw new FleetSpawnBudgetError(\n 'max_spawns',\n this.maxSpawns,\n this.spawnCount + 1,\n 'workComplete() has been called — director closed further spawning',\n );\n }\n // Per-task model matrix: when the caller didn't pin a model, resolve one\n // from the matrix by role (→ phase → `*`). Done here, before the spawned\n // event + manifest + coordinator handoff, so the fleet UI and the agent\n // itself all reflect the matched model. Explicit per-spawn models win.\n if (!config.model && this.modelMatrix) {\n const matrix = typeof this.modelMatrix === 'function' ? this.modelMatrix() : this.modelMatrix;\n const entry = resolveModelMatrix(matrix, config.role);\n if (entry) {\n config.model = entry.model;\n if (entry.provider) config.provider = entry.provider;\n }\n }\n // Enforce safety caps BEFORE touching the coordinator — a refused\n // spawn must not leak partial state into the manifest or fleet bus.\n // Delegate to FleetManager when available; use inline checks otherwise.\n if (this.fleetManager) {\n const rejection = this.fleetManager.canSpawn(config);\n if (rejection) {\n if (rejection.kind === 'max_spawn_depth')\n throw new FleetSpawnBudgetError('max_spawn_depth', rejection.limit, rejection.observed);\n if (rejection.kind === 'max_spawns')\n throw new FleetSpawnBudgetError('max_spawns', rejection.limit, rejection.observed);\n if (rejection.kind === 'max_cost_usd')\n throw new FleetCostCapError(rejection.limit, rejection.observed);\n if (rejection.kind === 'max_context_load')\n throw new FleetContextOverflowError(rejection.limit, rejection.observed);\n }\n } else {\n if (this.spawnDepth >= this.maxSpawnDepth) {\n throw new FleetSpawnBudgetError('max_spawn_depth', this.maxSpawnDepth, this.spawnDepth);\n }\n if (this.spawnCount >= this.maxSpawns) {\n throw new FleetSpawnBudgetError('max_spawns', this.maxSpawns, this.spawnCount + 1);\n }\n if (this.maxFleetCostUsd < Number.POSITIVE_INFINITY) {\n const totalCost = this.usage.snapshot().total?.cost ?? 0;\n if (totalCost >= this.maxFleetCostUsd) {\n throw new FleetCostCapError(this.maxFleetCostUsd, totalCost);\n }\n }\n // Context pressure check: reject spawn if leader context is too full.\n // maxLeaderContextLoad === 1.0 disables this check.\n if (this.maxLeaderContextLoad < 1.0) {\n const maxContext = this.resolveMaxContext();\n const threshold = maxContext * this.maxLeaderContextLoad;\n if (this.leaderContextPressure >= threshold) {\n throw new FleetContextOverflowError(threshold, this.leaderContextPressure);\n }\n }\n }\n let result: { subagentId: string };\n // If the config came from the roster with the default \"role-as-name\" pattern,\n // OR the name is one of the synthetic defaults used by ad-hoc spawn paths,\n // upgrade to a memorable nickname before the coordinator sees it. This ensures\n // the manifest, fleet UI, and session logs all display human names like\n // \"Einstein (Bug Hunter)\" instead of \"adhoc\" or \"general\".\n const needsNickname =\n config.name === config.role ||\n !config.name ||\n config.name === 'subagent' ||\n config.name === 'adhoc';\n if (needsNickname) {\n const role = config.role ?? 'subagent';\n if (this.fleetManager) {\n // FleetManager owns the used-nicknames set — just assign the nickname.\n // recordSpawn is called after spawn regardless of needsNickname to ensure\n // the manifest is keyed by the real subagentId.\n this.fleetManager.assignNicknameAndRecord(config);\n } else {\n config.name = assignNickname(role, this._usedNicknames);\n this._usedNicknames.add(\n config.name\n .split(' ')[0]!\n .toLowerCase()\n .replace(/[^a-z0-9-]/g, '-'),\n );\n }\n }\n result = await this.coordinator.spawn(config);\n // Record with FleetManager when available; otherwise manage inline.\n if (this.fleetManager) {\n // Always record the spawn with the real subagentId so the manifest is keyed correctly.\n this.fleetManager.recordSpawn(result.subagentId, config, priceLookup);\n } else {\n this.spawnCount += 1;\n this.subagentMeta.set(result.subagentId, {\n provider: config.provider,\n model: config.model,\n });\n if (priceLookup && config.provider && config.model) {\n this.priceLookups.set(`${config.provider}/${config.model}`, priceLookup);\n }\n }\n // Auto-wire a bridge per spawn — same transport as the director, so\n // `director.ask(subagentId, …)` and the subagent's own `bridge.send()`\n // round-trip without the caller having to plumb anything. Runners\n // grab their bridge from `ctx.bridge` (already populated by the\n // coordinator from `subagent.context.parentBridge`).\n const subagentBridge = new InMemoryAgentBridge(\n { agentId: result.subagentId, coordinatorId: this.id },\n this.transport,\n );\n this.coordinator.setSubagentBridge(result.subagentId, subagentBridge);\n this.subagentBridges.set(result.subagentId, subagentBridge);\n // Emit subagent.spawned on the FleetBus so the TUI can track collab agents\n // (which bypass MultiAgentHost.spawn and go through director.spawn directly).\n this.fleet.emit({\n subagentId: result.subagentId,\n ts: Date.now(),\n type: 'subagent.spawned',\n payload: {\n subagentId: result.subagentId,\n taskId: '', // taskId will be set when assign() is called\n name: config.name,\n role: config.role,\n provider: config.provider,\n model: config.model,\n },\n });\n // Record manifest entry only when not using FleetManager (it manages its own).\n if (!this.fleetManager) {\n this.manifestEntries.set(result.subagentId, {\n subagentId: result.subagentId,\n name: config.name,\n role: config.role,\n provider: config.provider,\n model: config.model,\n taskIds: [],\n });\n const spawnedAt = new Date().toISOString();\n this.stateCheckpoint?.recordSpawn(\n {\n id: result.subagentId,\n name: config.name,\n role: config.role,\n provider: config.provider,\n model: config.model,\n spawnedAt,\n },\n this.spawnCount,\n );\n void this.appendSessionEvent({\n type: 'agent_spawned',\n ts: spawnedAt,\n agentId: result.subagentId,\n role: config.role ?? config.name,\n });\n this.scheduleManifest();\n }\n return result.subagentId;\n }\n\n /**\n * Synchronously ask a subagent something via the bridge. Sends a\n * `task` message addressed to the subagent and awaits a matching\n * reply (matched by message id). Subagent runners that handle these\n * requests subscribe to `ctx.bridge` and reply with a message whose\n * `id` equals the incoming request's id (see `InMemoryAgentBridge`'s\n * `request<T>` implementation).\n *\n * Returns the response payload directly (the bridge wrapper is\n * unwrapped for ergonomics). Times out after `timeoutMs` (default\n * matches the bridge's own default of 30s) — surface those rejections\n * to the caller as actionable errors instead of letting tools hang.\n */\n async ask<T = unknown>(subagentId: string, payload: unknown, timeoutMs?: number): Promise<T> {\n if (!this.subagentBridges.has(subagentId)) {\n throw new Error(\n `ask: unknown subagent \"${subagentId}\" (spawn() it first; current fleet: ${Array.from(this.subagentBridges.keys()).join(', ') || '(empty)'})`,\n );\n }\n const msg: BridgeMessage = {\n id: randomUUID(),\n type: 'task',\n from: this.id,\n to: subagentId,\n payload,\n timestamp: Date.now(),\n priority: 'normal',\n };\n const reply = await this.bridge.request<T>(msg, timeoutMs);\n return reply.payload;\n }\n\n /**\n * Read completed task results and format them as a structured text\n * block the director's LLM can paste into its own context. The\n * Director keeps every completed `TaskResult` in `completed` so this\n * is a pure read — no bridge round-trip, cheap to call.\n *\n * The returned string is intentionally markdown-flavored: headers per\n * subagent, a one-line meta row (iter / tools / ms), and the task's\n * result text. Pass `style: 'json'` for a programmatic shape instead\n * (useful when the director model is doing structured-output work).\n */\n rollUp(taskIds: string[], style: 'markdown' | 'json' = 'markdown'): string {\n const rows = taskIds.map((id) => this.completed.get(id)).filter((r): r is TaskResult => !!r);\n if (style === 'json') {\n return JSON.stringify(\n rows.map((r) => ({\n taskId: r.taskId,\n subagentId: r.subagentId,\n status: r.status,\n iterations: r.iterations,\n toolCalls: r.toolCalls,\n durationMs: r.durationMs,\n result: r.result,\n error: r.error,\n })),\n null,\n 2,\n );\n }\n if (rows.length === 0) {\n return '_No completed tasks for the requested ids — try waiting first._';\n }\n const lines: string[] = [];\n for (const r of rows) {\n const meta = this.subagentMeta.get(r.subagentId);\n const tag = meta?.provider && meta?.model ? ` · ${meta.provider}/${meta.model}` : '';\n lines.push(`### ${r.subagentId}${tag}`);\n lines.push(`_${r.status} — ${r.iterations} iter · ${r.toolCalls} tools · ${r.durationMs}ms_`);\n lines.push('');\n if (r.error) lines.push(`**Error:** ${r.error}`);\n else if (typeof r.result === 'string') lines.push(r.result);\n else if (r.result !== undefined)\n lines.push('```json\\n' + JSON.stringify(r.result, null, 2) + '\\n```');\n else lines.push('_(no output)_');\n lines.push('');\n }\n return lines.join('\\n').trimEnd();\n }\n\n /**\n * Write the fleet manifest to `manifestPath`. Returns the path written\n * or null when no path was configured. Captures every spawn + its\n * assigned tasks — paired with per-subagent JSONLs, this is enough to\n * replay an entire director run.\n */\n async writeManifest(): Promise<string | null> {\n if (!this.manifestPath) return null;\n const manifest = {\n directorRunId: this.id,\n writtenAt: new Date().toISOString(),\n children: Array.from(this.manifestEntries.values()).map((e) => ({\n ...e,\n // Surface final status from `completed` when available — manifest\n // becomes much more useful for replay when it carries the\n // success/failure state.\n results: e.taskIds.map((tid) => {\n const r = this.completed.get(tid);\n return r\n ? {\n taskId: tid,\n status: r.status,\n iterations: r.iterations,\n toolCalls: r.toolCalls,\n durationMs: r.durationMs,\n }\n : { taskId: tid, status: 'pending' as const };\n }),\n })),\n usage: this.usage.snapshot(),\n };\n await fsp.mkdir(path.dirname(this.manifestPath), { recursive: true });\n await atomicWrite(this.manifestPath, JSON.stringify(manifest, null, 2), { mode: 0o600 });\n return this.manifestPath;\n }\n\n /**\n * Tear down the director: stop every subagent, close every bridge\n * endpoint, and (when configured) write the final manifest. Idempotent\n * — calling shutdown twice is a no-op on the second invocation.\n */\n async shutdown(): Promise<void> {\n if (this.manifestTimer) {\n clearTimeout(this.manifestTimer);\n this.manifestTimer = null;\n }\n // Detach the coordinator-side task.completed listener so a Director\n // that lives shorter than its coordinator (rare but possible in\n // tests + delegate auto-promotion) doesn't leak the closure on\n // the EventEmitter for the coordinator's remaining lifetime.\n if (this.taskCompletedListener) {\n this.coordinator.off('task.completed', this.taskCompletedListener);\n this.taskCompletedListener = null;\n }\n await this.coordinator.stopAll();\n for (const b of this.subagentBridges.values()) {\n await b.stop().catch((err) => this.logShutdownError('subagent_bridge_stop', err));\n }\n this.subagentBridges.clear();\n await this.bridge.stop().catch((err) => this.logShutdownError('director_bridge_stop', err));\n if (this.manifestPath)\n await this.writeManifest().catch((err) => this.logShutdownError('manifest_write', err));\n if (this.stateCheckpoint) {\n this.stateCheckpoint.setUsage(this.usage.snapshot());\n await this.stateCheckpoint\n .flush()\n .catch((err) => this.logShutdownError('state_checkpoint_flush', err));\n // Release the lock so a subsequent --resume can claim this checkpoint.\n // Without this, the next director run sees a stale lock and refuses.\n await this.stateCheckpoint\n .releaseLock()\n .catch((err) => this.logShutdownError('state_checkpoint_lock_release', err));\n }\n }\n\n /**\n * Funnel for shutdown-phase errors. We can't throw — `shutdown()` is\n * called from process-exit paths where an uncaught throw would lose\n * the manifest write that comes after. But we MUST NOT silently\n * swallow either — a persistent bridge-close failure would otherwise\n * mask a real bug. `process.emitWarning` is the right tier:\n * surfaces on stderr by default, lets the host plug a warning\n * listener for structured collection, and never affects exit code.\n */\n private logShutdownError(phase: string, err: unknown): void {\n const detail = err instanceof Error ? err.message : String(err);\n process.emitWarning(\n `Director shutdown phase \"${phase}\" failed: ${detail}`,\n 'DirectorShutdownWarning',\n );\n }\n\n /**\n * Hand a task to the coordinator. Returns the assigned task id so\n * callers can wait on it via `awaitTasks([id])`. The coordinator's\n * concurrency limit applies — the task may queue before running.\n */\n async assign(task: TaskSpec): Promise<string> {\n const taskWithId: TaskSpec = task.id ? task : { ...task, id: randomUUID() };\n // When workComplete() has been called, drain the pending queue as aborted\n // rather than dispatching new work. The director has decided the goal is\n // satisfied — queued tasks never get a chance to run, so synthesize their\n // completion now so any caller awaiting them unblocks immediately.\n if (this.workCompleteFlag) {\n const synthetic: TaskResult = {\n subagentId: taskWithId.subagentId ?? 'unassigned',\n taskId: taskWithId.id,\n status: 'stopped',\n error: {\n kind: 'aborted_by_parent',\n message: 'Director called workComplete() — no further tasks will run',\n retryable: false,\n },\n iterations: 0,\n toolCalls: 0,\n durationMs: 0,\n };\n this.completed.set(taskWithId.id, synthetic);\n const waiter = this.taskWaiters.get(taskWithId.id);\n if (waiter) {\n waiter.resolve(synthetic);\n this.taskWaiters.delete(taskWithId.id);\n }\n return taskWithId.id;\n }\n if (task.subagentId) {\n // Update manifest entry — delegate to FleetManager when available.\n if (this.fleetManager) {\n this.fleetManager.addTaskToSubagent(task.subagentId, taskWithId.id);\n } else {\n const entry = this.manifestEntries.get(task.subagentId);\n if (entry) entry.taskIds.push(taskWithId.id);\n }\n }\n await this.coordinator.assign(taskWithId);\n // Snapshot task metadata for completion-event titles + state checkpoint\n // bookkeeping. Done AFTER coordinator.assign() so we don't checkpoint a\n // task the coordinator rejected.\n this.taskDescriptions.set(taskWithId.id, taskWithId.description);\n if (taskWithId.subagentId) this.taskOwners.set(taskWithId.id, taskWithId.subagentId);\n const assignedAt = new Date().toISOString();\n this.stateCheckpoint?.recordTaskAssigned({\n taskId: taskWithId.id,\n subagentId: taskWithId.subagentId,\n description: taskWithId.description,\n status: 'running',\n assignedAt,\n });\n void this.appendSessionEvent({\n type: 'task_created',\n ts: assignedAt,\n taskId: taskWithId.id,\n title: taskWithId.description,\n });\n this.scheduleManifest();\n return taskWithId.id;\n }\n\n /**\n * Block until every task id resolves. Returns results in the same\n * order as the input. If any task hasn't completed by the time this\n * is called, the promise hangs until it does — pair with a timeout\n * at the caller if that's a concern. Resolves immediately for ids\n * whose results were already cached.\n */\n awaitTasks(taskIds: string[]): Promise<TaskResult[]> {\n return Promise.all(\n taskIds.map((id) => {\n const cached = this.completed.get(id);\n if (cached) return cached;\n const existing = this.taskWaiters.get(id);\n if (existing) return existing.promise;\n let resolve!: (r: TaskResult) => void;\n const promise = new Promise<TaskResult>((res) => {\n resolve = res;\n });\n this.taskWaiters.set(id, { promise, resolve });\n return promise;\n }),\n );\n }\n\n async terminate(subagentId: string): Promise<void> {\n await this.coordinator.stop(subagentId);\n }\n\n async terminateAll(): Promise<void> {\n await this.coordinator.stopAll();\n }\n\n async remove(subagentId: string): Promise<void> {\n await this.coordinator.remove(subagentId);\n\n // Clean up the bridge so it stops consuming resources.\n const bridge = this.subagentBridges.get(subagentId);\n if (bridge) {\n await bridge.stop();\n this.subagentBridges.delete(subagentId);\n }\n\n // Clean up the aggregator so terminated subagent data doesn't accumulate.\n this.usage.removeSubagent(subagentId);\n\n // Delegate nickname cleanup to FleetManager when available; otherwise handle\n // it directly here. This frees the slot so the same name can be reused.\n if (this.fleetManager) {\n this.fleetManager.removeSubagent(subagentId);\n } else {\n const entry = this.manifestEntries.get(subagentId);\n if (entry?.name) {\n const nicknameKey = entry.name\n .split(' ')[0]!\n .toLowerCase()\n .replace(/[^a-z0-9-]/g, '-');\n this._usedNicknames.delete(nicknameKey);\n }\n }\n\n // Remove all local state entries for this subagent.\n this.manifestEntries.delete(subagentId);\n this.taskOwners.delete(subagentId);\n this.taskDescriptions.delete(subagentId);\n }\n\n status(): CoordinatorStatus {\n const base = this.coordinator.getStatus();\n // Enrich each row with its cumulative auto-extension count so /fleet can\n // render \"⚡×N\" without a separate lookup.\n return {\n ...base,\n subagents: base.subagents.map((s) => ({\n ...s,\n extensions: this.extendTotals.get(s.id) ?? 0,\n })),\n };\n }\n\n /**\n * Subscribe to coordinator events. Currently only `task.completed` is\n * exposed (the others are internal lifecycle). Returns an unsubscribe\n * function. External callers (e.g. the CLI's `MultiAgentHost`) use this\n * to drive their own pending/results tracking without poking the\n * coordinator directly.\n */\n on(\n event: 'task.completed',\n handler: (payload: { task: TaskSpec; result: TaskResult }) => void,\n ): () => void {\n // EventEmitter.on returns `this`; wrap so callers get a stable\n // unsubscribe closure (matches the rest of our event API).\n this.coordinator.on(event, handler);\n return () => {\n this.coordinator.off(event, handler);\n };\n }\n\n /**\n * Snapshot of every task that has resolved (success, failed, timeout,\n * stopped) since the director started. Returned in completion order\n * via the internal map's iteration order. Used by `/fleet status` to\n * paint the completed table without reaching into private state.\n */\n completedResults(): TaskResult[] {\n return Array.from(this.completed.values());\n }\n\n /**\n * Inject a previously-saved checkpoint snapshot. Call this right after\n * constructing a Director during a `--resume` run so the in-memory state\n * (subagents, tasks, waiters) reflects the pre-crash reality instead of\n * starting from a blank slate. The director then resumes from there —\n * completing any in-flight tasks and ignoring tasks that already reached\n * a terminal state in the prior run.\n */\n setCheckpointState(snapshot: DirectorStateSnapshot): void {\n this.stateCheckpoint?.resume(snapshot);\n }\n\n /**\n * Read a subagent's JSONL transcript directly from disk (no bridge\n * round-trip needed). Returns the last assistant text, stop reason,\n * tool-use count, and line count — or null if the file is unavailable.\n * Requires `sessionsRoot` to be set on construction.\n */\n async readSession(\n subagentId: string,\n tail?: number,\n ): Promise<{\n lastAssistantText?: string;\n lastStopReason?: string;\n toolUsesObserved: number;\n events: number;\n path?: string;\n } | null> {\n if (!this.sessionsRoot) return null;\n const filePath = path.join(this.sessionsRoot, this.directorRunId, `${subagentId}.jsonl`);\n let raw: string;\n try {\n raw = await fsp.readFile(filePath, 'utf8');\n } catch {\n return null;\n }\n const lines = raw.split('\\n').filter((l) => l.trim());\n const targetLines = tail ? lines.slice(-tail) : lines;\n let lastAssistantText: string | undefined;\n let lastStopReason: string | undefined;\n let toolUses = 0;\n for (const line of targetLines) {\n try {\n const ev = JSON.parse(line) as { type?: string; text?: string; stopReason?: string };\n if (ev.type === 'assistant' && typeof ev.text === 'string') {\n lastAssistantText = ev.text;\n } else if (ev.type === 'stop' && ev.stopReason) {\n lastStopReason = ev.stopReason;\n } else if (ev.type === 'tool_use') {\n toolUses++;\n }\n } catch {\n // skip malformed lines\n }\n }\n return {\n lastAssistantText,\n lastStopReason,\n toolUsesObserved: toolUses,\n events: targetLines.length,\n path: filePath,\n };\n }\n\n snapshot(): FleetUsage {\n return this.usage.snapshot();\n }\n\n /**\n * Look up provider/model metadata for a spawned subagent. Returns\n * undefined when the subagent id is unknown (not yet spawned, or\n * already torn down). Callers — notably the TUI fleet panel — use\n * this to render human-readable provider/model tags next to each\n * subagent row without reaching into private state.\n */\n getSubagentMeta(id: string): { provider?: string; model?: string; name?: string } | undefined {\n const usage = this.subagentMeta.get(id);\n const manifest = this.manifestEntries.get(id);\n if (!usage && !manifest) return undefined;\n return {\n provider: usage?.provider ?? manifest?.provider,\n model: usage?.model ?? manifest?.model,\n name: manifest?.name,\n };\n }\n\n /**\n * Compose the leader/director-agent system prompt: fleet preamble +\n * (optional) roster summary + user base prompt. Pass the result to your\n * leader Agent's `ctx.systemPrompt` when constructing it.\n *\n * `basePrompt` defaults to `config.leaderSystemPrompt` so callers can\n * use the no-arg form when the multi-agent config already carries it.\n */\n leaderSystemPrompt(basePrompt?: string): string {\n return composeDirectorPrompt({\n basePrompt: basePrompt ?? this.coordinator.config.leaderSystemPrompt,\n directorPreamble: this.directorPreamble,\n rosterSummary: this.roster ? rosterSummaryFromConfigs(this.roster) : undefined,\n });\n }\n\n /**\n * Compose a subagent's system prompt for a given `SubagentConfig`:\n * baseline + role + task + per-spawn override. Returned by value — does\n * not mutate the config. Factories (the user-supplied `AgentFactory`)\n * should call this when building each subagent's Agent so the bridge\n * contract, role context, and override are all surfaced.\n *\n * When `taskBrief` is omitted the Task section is dropped. Pass the\n * actual task description here to reinforce it in the system prompt\n * (the runner already passes it as user input — duplicating in the\n * system prompt is optional but improves anchoring on small models).\n */\n subagentSystemPrompt(config: SubagentConfig, taskBrief?: string): string {\n return composeSubagentPrompt({\n baseline: this.subagentBaseline,\n role: config.prompt,\n task: taskBrief,\n sharedScratchpad: this.sharedScratchpadPath ?? undefined,\n override: config.systemPromptOverride,\n });\n }\n\n /**\n * Build the tool set the LLM-driven director uses to orchestrate.\n * Returns an array of `Tool` definitions; register these on the\n * director's `Agent` to expose `spawn_subagent`, `assign_task`, etc.\n * Each tool's `execute()` delegates straight to the matching method\n * above.\n *\n * Tools all carry `permission: 'auto'` — the *user* has already\n * approved running the director when they kicked off the run, so\n * gating individual orchestration calls behind a confirm prompt\n * would just be noise. The actual subagent tools they spawn are\n * still permission-checked normally.\n */\n tools(roster?: Record<string, SubagentConfig>): Tool[] {\n // Use stored roster as default — allows `director.tools()` to be\n // called without args when the roster was passed at construction.\n const effectiveRoster = roster ?? this.roster;\n const t: Tool[] = [\n makeSpawnTool(this, effectiveRoster),\n makeAssignTool(this),\n makeAwaitTasksTool(this),\n makeAskTool(this),\n makeAskResultTool(this),\n makeRollUpTool(this),\n makeTerminateTool(this),\n makeTerminateAllTool(this),\n makeFleetStatusTool(this),\n makeFleetUsageTool(this),\n makeFleetSessionTool(this),\n makeFleetHealthTool(this),\n makeCollabDebugTool(this),\n makeFleetEmitTool(this),\n makeWorkCompleteTool(this),\n ];\n return t;\n }\n\n /**\n * Attempt to acquire the checkpoint lock. Must be called before\n * resuming — if another director process is alive, this returns\n * false and the caller should not proceed with the resume.\n */\n async acquireCheckpointLock(): Promise<boolean> {\n return this.stateCheckpoint ? this.stateCheckpoint.acquireLock() : true;\n }\n\n /**\n * Start a collaborative debugging session: BugHunter, RefactorPlanner,\n * and Critic run in parallel on the same target files, with findings\n * flowing through the FleetBus (bug.found → refactor.plan →\n * critic.evaluation). Returns a structured CollabDebugReport when all\n * three agents complete or the session times out.\n */\n async spawnCollab(options: CollabSessionOptions): Promise<CollabDebugReport> {\n const session = new CollabSession(this, this.fleet, {\n ...options,\n onBudgetWarning: (alert) => {\n // Delegate to the host-provided handler if set; 'ignore' by default.\n // Collab agents are excluded from the Director's\n // budget.threshold_reached handler, so the session's own wireFleetBus()\n // budget handler (progress-based timeout logic, session.cancel()) runs\n // instead of the Director's auto-extend/deny logic.\n return options.onBudgetWarning?.(alert) ?? 'ignore';\n },\n });\n // Track so cancelCollabSession(sessionId) works and Director knows what's active\n this._activeCollabSessions.set(session.sessionId, session);\n session.on('session.done', () => this._activeCollabSessions.delete(session.sessionId));\n session.on('session.error', () => this._activeCollabSessions.delete(session.sessionId));\n return session.start();\n }\n\n /**\n * Resume from a prior checkpoint snapshot (loaded via\n * `loadDirectorState()`). Re-attach to the fleet mid-flight so\n * subsequent spawn/assign calls update the checkpoint normally.\n */\n resumeFromCheckpoint(snapshot: DirectorStateSnapshot): void {\n this.stateCheckpoint?.resume(snapshot);\n }\n}\n","import * as fsp from 'node:fs/promises';\r\nimport * as path from 'node:path';\r\nimport { randomUUID } from 'node:crypto';\r\nimport type { SubagentConfig, TaskResult } from '../types/multi-agent.js';\r\nimport type { JSONSchema, Tool } from '../types/tool.js';\r\nimport type { Director } from './director.js';\r\nimport { applyRosterBudget } from './fleet.js';\r\n\r\n/**\r\n * Opaque host interface so this factory doesn't have to depend on the\r\n * CLI's `MultiAgentHost`. Any caller that exposes the same three\r\n * methods can wire `delegate` — including test doubles.\r\n */\r\nexport interface DelegateHost {\r\n /** True if a Director is already attached and running. */\r\n isDirectorMode(): boolean;\r\n /** Build (or return the cached) Director when director mode is on. */\r\n ensureDirector(): Promise<Director | null>;\r\n /**\r\n * Force-promote a non-director session into director mode at runtime.\r\n * Returns the Director, or null when promotion is impossible (e.g. a\r\n * non-director coordinator has already spawned subagents in the\r\n * legacy code path).\r\n */\r\n promoteToDirector(): Promise<Director | null>;\r\n /**\r\n * Optional: when promotion fails, return the human-readable reason.\r\n * Used to render an actionable error to the calling model instead of\r\n * the prior opaque \"Director could not be activated\" message.\r\n * Implementations may return null when they don't track the reason.\r\n */\r\n getPromotionBlockReason?(): string | null;\r\n}\r\n\r\nexport interface CreateDelegateToolOptions {\r\n host: DelegateHost;\r\n /**\r\n * Roster used to resolve `role` strings into full `SubagentConfig`s.\r\n * Typically `FLEET_ROSTER`. When omitted, `delegate({ role })` calls\r\n * fail and only the explicit `name + provider + model` path works.\r\n */\r\n roster?: Record<string, SubagentConfig>;\r\n /**\r\n * Default await timeout in milliseconds. `delegate` blocks until the\r\n * subagent's task resolves; without a cap, a stuck worker would hang\r\n * the host indefinitely. Set generously (default: 4 hours) so the\r\n * orchestrator can run multi-step refactors / monorepo audits\r\n * without being killed for being slow — the orchestrator must\r\n * decide per-call when a task needs to be cut short.\r\n */\r\n defaultTimeoutMs?: number;\r\n /**\r\n * Absolute directory under which per-subagent JSONL transcripts live —\r\n * matches `MultiAgentHostOptions.sessionsRoot`. When set, the delegate\r\n * tool reads the subagent's transcript on timeout / budget-exhaustion\r\n * to extract partial output, so the host LLM gets *something* useful\r\n * back instead of just an error.\r\n */\r\n sessionsRoot?: string;\r\n /**\r\n * The directorRunId used to namespace transcripts (typically the host\r\n * session id). Combined with `sessionsRoot` to locate per-subagent\r\n * JSONLs at `<sessionsRoot>/<runId>/<subagentId>.jsonl`.\r\n */\r\n directorRunId?: string;\r\n /**\r\n * Buffer subtracted from the caller's `timeoutMs` before passing it\r\n * to the subagent. Gives the host a window to detect a subagent that\r\n * has gone silent and surface a partial result rather than a generic\r\n * timeout. Default: 60_000 ms (raised from 30s to give subagents\r\n * more headroom before the host kills them).\r\n */\r\n subagentTimeoutBufferMs?: number;\r\n}\r\n\r\n/**\r\n * `delegate` — the only multi-agent tool a regular (non-director) agent\r\n * ever needs. It bundles spawn + assign + await into a single call and\r\n * transparently auto-promotes the host into director mode on first use.\r\n *\r\n * The model never has to ask \"are we in director mode?\" — it just calls\r\n * `delegate({ role, task })` and gets back a `TaskResult`. The cost of\r\n * that ergonomic packaging is that `delegate` cannot be used for\r\n * parallel work as-is; the model must fire multiple `delegate` calls in\r\n * parallel through the provider's parallel-tool-call surface, or escalate\r\n * to the explicit `spawn_subagent` + `assign_task` + `await_tasks` flow\r\n * when it wants fan-out it controls itself.\r\n */\r\nexport function createDelegateTool(opts: CreateDelegateToolOptions): Tool {\r\n // Conservative default for the LLM's mental model.\r\n // The actual subagent budgets come from FLEET_ROSTER_BUDGETS (x10 higher)\r\n // and are applied in instantiateRosterConfig. This value only appears\r\n // in the schema to guide the LLM's delegation decisions — it does NOT\r\n // override the roster budget unless the caller explicitly passes it.\r\n const defaultTimeoutMs = opts.defaultTimeoutMs ?? 30 * 60 * 1000;\r\n const rosterIds = opts.roster ? Object.keys(opts.roster) : [];\r\n\r\n const inputSchema: JSONSchema = {\r\n type: 'object',\r\n properties: {\r\n task: {\r\n type: 'string',\r\n description:\r\n 'What the subagent should do — natural language, complete sentence(s). The subagent has its own tool slice, its own LLM call, and returns when its task is done.',\r\n },\r\n role: {\r\n type: 'string',\r\n description:\r\n rosterIds.length > 0\r\n ? `Roster role (preferred). One of: ${rosterIds.join(', ')}. Picks a pre-tuned config (prompt, budgets, tools) for that role.`\r\n : 'No roster is configured — pass `name` instead.',\r\n enum: rosterIds.length > 0 ? rosterIds : undefined,\r\n },\r\n name: {\r\n type: 'string',\r\n description:\r\n 'Display name for free-form subagents (not using a roster role). The subagent gets a large default budget (3h, 5000 iter, 15000 tool calls). Required when `role` is omitted.',\r\n },\r\n provider: {\r\n type: 'string',\r\n description:\r\n 'Provider id (e.g. \"anthropic\", \"openai\"). Defaults to the host provider when omitted.',\r\n },\r\n model: {\r\n type: 'string',\r\n description: 'Model id within the provider. Defaults to the host model when omitted.',\r\n },\r\n systemPromptOverride: {\r\n type: 'string',\r\n description: 'Optional extra prompt text appended to the role baseline.',\r\n },\r\n timeoutMs: {\r\n type: 'number',\r\n minimum: 1,\r\n description: `Wall-clock budget for this delegate in milliseconds. No hard cap — set as high as the task realistically needs (a monorepo audit can take hours, a single-file lint takes seconds). Default ${Math.round(defaultTimeoutMs / 1000 / 60)} minutes.`,\r\n },\r\n maxIterations: {\r\n type: 'number',\r\n minimum: 1,\r\n description:\r\n 'Maximum LLM iterations the subagent may take. Unset = use the role/coordinator default. Raise this for tasks with many tool-think-tool cycles (deep code analysis, multi-file refactors).',\r\n },\r\n maxToolCalls: {\r\n type: 'number',\r\n minimum: 1,\r\n description:\r\n 'Maximum number of tool invocations the subagent may make. Unset = use the role/coordinator default. Raise this for tasks that touch many files (large grep + read + report).',\r\n },\r\n idleTimeoutMs: {\r\n type: 'number',\r\n minimum: 1,\r\n description:\r\n 'Idle timeout in ms: reap the subagent after this long with no activity. Resets on every iteration/tool call. Unset = use the role/coordinator default.',\r\n },\r\n maxTokens: {\r\n type: 'number',\r\n minimum: 1,\r\n description:\r\n 'Maximum total tokens (input + output) the subagent may use. Unset = use the role/coordinator default.',\r\n },\r\n maxCostUsd: {\r\n type: 'number',\r\n minimum: 0,\r\n description:\r\n 'Maximum estimated USD cost the subagent may incur. Unset = use the role/coordinator default.',\r\n },\r\n },\r\n required: ['task'],\r\n };\r\n\r\n return {\r\n name: 'delegate',\r\n description:\r\n \"Hand a discrete piece of work to a dedicated subagent and wait for its result. The subagent has its own context, its own LLM call, and its own budget — use this when a task is self-contained, would otherwise blow up your context, or benefits from a specialized role (bug-hunter, security-scanner, refactor-planner, audit-log). For free-form coding tasks (not tied to a pre-defined role), pass `name` + `task` — the subagent runs as a general-purpose coding agent with a large default budget. YOU decide how big the budget is: pass `timeoutMs`, `maxIterations`, and `maxToolCalls` sized to the actual work. There is no hidden cap forcing a 3-minute / 80-iteration limit — if a monorepo audit needs 2 hours and 500 tool calls, ask for that. Call multiple delegates in parallel through the provider's parallel-tool-call surface to fan work out across roles.\",\r\n usageHint:\r\n \"Set `task` to a complete instruction. Either pick `role` from the roster (audit-log, bug-hunter, refactor-planner, security-scanner) or pass `name` to run a free-form coding agent. For non-trivial work, also pass `timeoutMs`, `maxIterations`, and `maxToolCalls`. Returns the subagent's `TaskResult` — including the textual `result`, iteration count, tool count, and duration. Auto-promotes the host into director mode on first call.\",\r\n permission: 'auto',\r\n mutating: false,\r\n inputSchema,\r\n async execute(input: unknown) {\r\n const i = (input ?? {}) as {\r\n task?: string;\r\n role?: string;\r\n name?: string;\r\n provider?: string;\r\n model?: string;\r\n systemPromptOverride?: string;\r\n timeoutMs?: number;\r\n maxIterations?: number;\r\n maxToolCalls?: number;\r\n idleTimeoutMs?: number;\r\n maxTokens?: number;\r\n maxCostUsd?: number;\r\n };\r\n\r\n if (typeof i.task !== 'string' || !i.task.trim()) {\r\n return { ok: false, error: '`task` is required.' };\r\n }\r\n\r\n try {\r\n let director = await opts.host.ensureDirector();\r\n if (!director) {\r\n director = await opts.host.promoteToDirector();\r\n }\r\n if (!director) {\r\n const reason = opts.host.getPromotionBlockReason?.();\r\n return {\r\n ok: false,\r\n error:\r\n reason ??\r\n 'Director could not be activated — multi-agent host already running in legacy non-director mode. Restart with `--director` for fleet support.',\r\n };\r\n }\r\n\r\n const timeoutMs = i.timeoutMs ?? defaultTimeoutMs;\r\n\r\n let cfg: SubagentConfig;\r\n if (i.role) {\r\n const base = opts.roster?.[i.role];\r\n if (!base) {\r\n return {\r\n ok: false,\r\n error: `Unknown role \"${i.role}\". Available: ${rosterIds.join(', ') || '(no roster configured)'}.`,\r\n };\r\n }\r\n cfg = instantiateRosterConfig(i.role, base);\r\n if (i.systemPromptOverride) cfg.systemPromptOverride = i.systemPromptOverride;\r\n if (i.provider) cfg.provider = i.provider;\r\n if (i.model) cfg.model = i.model;\r\n } else {\r\n if (!i.name) {\r\n return {\r\n ok: false,\r\n error: 'Either `role` (from the roster) or `name` is required.',\r\n };\r\n }\r\n cfg = {\r\n name: i.name,\r\n provider: i.provider,\r\n model: i.model,\r\n systemPromptOverride: i.systemPromptOverride,\r\n };\r\n // Apply generic budget so free-form subagents get the x10\r\n // budget even without a roster role.\r\n cfg = applyRosterBudget({ ...cfg, name: i.name });\r\n }\r\n\r\n if (typeof i.maxIterations === 'number') {\r\n cfg.maxIterations = i.maxIterations;\r\n }\r\n if (typeof i.maxToolCalls === 'number') {\r\n cfg.maxToolCalls = i.maxToolCalls;\r\n }\r\n if (typeof i.idleTimeoutMs === 'number') {\r\n cfg.idleTimeoutMs = i.idleTimeoutMs;\r\n }\r\n if (typeof i.maxTokens === 'number') {\r\n cfg.maxTokens = i.maxTokens;\r\n }\r\n if (typeof i.maxCostUsd === 'number') {\r\n cfg.maxCostUsd = i.maxCostUsd;\r\n }\r\n\r\n const SUBAGENT_TIMEOUT_BUFFER_MS = opts.subagentTimeoutBufferMs ?? 60_000;\r\n // Only FILL IN a budget timeout when the config has none — never\r\n // clamp a generous roster/generic budget DOWN to the host's await\r\n // window. The old `cfg.timeoutMs > desiredSubTimeout` clamp is what\r\n // capped 10h roster agents at ~4 minutes. The host await below is\r\n // heartbeat-based, so the subagent's own (auto-extending) budget is\r\n // the real ceiling.\r\n if (!cfg.timeoutMs) {\r\n cfg.timeoutMs = Math.max(30_000, timeoutMs - SUBAGENT_TIMEOUT_BUFFER_MS);\r\n }\r\n\r\n const subagentId = await director.spawn(cfg);\r\n const taskId = await director.assign({\r\n id: `${randomUUID()}`,\r\n description: i.task,\r\n subagentId,\r\n });\r\n // Heartbeat-aware host await: `timeoutMs` is treated as a SILENCE\r\n // tolerance, not a hard wall-clock cap. The deadline resets every\r\n // time the subagent emits a tool/iteration event, so a subagent\r\n // that keeps making progress is never killed for being slow —\r\n // only a genuinely stalled one (no events for `timeoutMs`) trips\r\n // the host timeout. Mirrors the budget's heartbeat auto-extend.\r\n const dir = director;\r\n const result = await new Promise<TaskResult | { __timeout: true }>((resolve) => {\r\n let settled = false;\r\n let timer: ReturnType<typeof setTimeout> | undefined;\r\n const finish = (value: TaskResult | { __timeout: true }) => {\r\n if (settled) return;\r\n settled = true;\r\n if (timer) clearTimeout(timer);\r\n offTool();\r\n offIter();\r\n offProgress();\r\n resolve(value);\r\n };\r\n const arm = () => {\r\n if (timer) clearTimeout(timer);\r\n timer = setTimeout(() => finish({ __timeout: true }), timeoutMs);\r\n };\r\n const bump = (e: { subagentId: string }) => {\r\n if (e.subagentId === subagentId) arm();\r\n };\r\n const offTool = dir.fleet.filter('tool.executed', bump);\r\n const offIter = dir.fleet.filter('iteration.started', bump);\r\n // tool.progress fires for streamed bash output, fetch byte progress,\r\n // and other long-duration tools — these are forward motion events\r\n // that should reset the idle timer just like iteration.started does.\r\n const offProgress = dir.fleet.filter('tool.progress', bump);\r\n arm();\r\n dir\r\n .awaitTasks([taskId])\r\n .then((r) => finish(r[0] ?? { __timeout: true }))\r\n .catch(() => finish({ __timeout: true }));\r\n });\r\n\r\n if ('__timeout' in result) {\r\n const partial = await readSubagentPartial(opts, subagentId);\r\n return {\r\n ok: false,\r\n stopReason: 'host_timeout',\r\n error: `Subagent did not finish within ${timeoutMs}ms.`,\r\n hint: 'Reduce scope of the next delegate, raise timeoutMs, or use spawn_subagent + await_tasks for long-running work.',\r\n subagentId,\r\n taskId,\r\n partial,\r\n };\r\n }\r\n\r\n const baseStopReason: StopReason =\r\n result.status === 'success'\r\n ? 'end_turn'\r\n : result.status === 'timeout'\r\n ? 'subagent_timeout'\r\n : result.status === 'stopped'\r\n ? 'aborted'\r\n : 'budget_exhausted';\r\n const partial =\r\n result.status === 'success' ? undefined : await readSubagentPartial(opts, subagentId);\r\n\r\n const errorKind = result.error?.kind;\r\n const retryable = result.error?.retryable;\r\n const backoffMs = result.error?.backoffMs;\r\n\r\n // Build a short summary for the chat history so the user sees\r\n // what the subagent accomplished without digging into the full result.\r\n const summary = buildDelegateSummary(i.role, result);\r\n\r\n return {\r\n ok: result.status === 'success',\r\n status: result.status,\r\n stopReason: baseStopReason,\r\n errorKind,\r\n retryable,\r\n backoffMs,\r\n subagentId: result.subagentId,\r\n taskId: result.taskId,\r\n result: result.result,\r\n error: result.error,\r\n iterations: result.iterations,\r\n toolCalls: result.toolCalls,\r\n durationMs: result.durationMs,\r\n ...(partial ? { partial } : {}),\r\n ...(hintForKind(errorKind, retryable, backoffMs, partial)\r\n ? { hint: hintForKind(errorKind, retryable, backoffMs, partial) }\r\n : {}),\r\n // Summary is included so callers (TUI, CLI renderer) can surface\r\n // it as a chat history line — the LLM also sees it for continuity.\r\n summary,\r\n };\r\n } catch (err) {\r\n return {\r\n ok: false,\r\n stopReason: 'error' as const,\r\n error: err instanceof Error ? err.message : String(err),\r\n };\r\n }\r\n },\r\n };\r\n}\r\n\r\nfunction instantiateRosterConfig(role: string, base: SubagentConfig): SubagentConfig {\r\n // Apply the x10 roster budget so subagents get far more running time\r\n // and iterations than the LLM is told about in the schema.\r\n // The LLM sees a conservative 30-min default; the subagent actually\r\n // gets 7.5–10 hours depending on role.\r\n const withBudget = applyRosterBudget({ ...base, role });\r\n return {\r\n ...withBudget,\r\n // Give each spawn a fresh id so parallel or repeated delegates\r\n // can use the same role safely.\r\n id: `${role}-${randomUUID().slice(0, 8)}`,\r\n };\r\n}\r\n\r\ntype StopReason =\r\n | 'end_turn'\r\n | 'budget_exhausted'\r\n | 'subagent_timeout'\r\n | 'host_timeout'\r\n | 'aborted'\r\n | 'error';\r\n\r\n/**\r\n * Per-kind orchestrator hint. Returned alongside the structured error\r\n * so the calling model has a concrete next step instead of \"task\r\n * failed, good luck\". Returns undefined for success / unknown kinds —\r\n * the caller checks for presence before including in output.\r\n */\r\nexport function hintForKind(\r\n kind: string | undefined,\r\n retryable: boolean | undefined,\r\n backoffMs: number | undefined,\r\n partial?: { lastAssistantText?: string },\r\n): string | undefined {\r\n if (!kind) return undefined;\r\n switch (kind) {\r\n case 'provider_rate_limit':\r\n return `Provider rate-limited. Retry safe after ${backoffMs ?? 5000}ms backoff. Consider a smaller model or fewer parallel delegates.`;\r\n case 'provider_5xx':\r\n return `Provider server error. Retry safe after ${backoffMs ?? 3000}ms backoff — usually transient.`;\r\n case 'provider_timeout':\r\n return 'Provider network timeout. Retry safe; reduce input size if it persists.';\r\n case 'provider_auth':\r\n return 'Provider rejected credentials. Cannot retry — fix the API key / config and re-invoke.';\r\n case 'context_overflow':\r\n return 'Subagent context exceeded the model limit. Narrow the task, use a larger-context model, or split into multiple delegates.';\r\n case 'budget_iterations':\r\n case 'budget_tool_calls':\r\n case 'budget_tokens':\r\n case 'budget_cost': {\r\n const base = 'Subagent exhausted its budget. The coordinator may auto-extend; otherwise raise the matching `max*` field (e.g. maxToolCalls: 600) on the next delegate, or split the task.';\r\n if (partial?.lastAssistantText) {\r\n return `${base}\\n\\nPartial output produced before budget hit:\\n${partial.lastAssistantText}`;\r\n }\r\n return base;\r\n }\r\n case 'budget_timeout': {\r\n const base = 'Subagent hit its wall-clock budget. Raise `timeoutMs` on the next delegate or split the task.';\r\n if (partial?.lastAssistantText) {\r\n return `${base}\\n\\nPartial output produced before timeout:\\n${partial.lastAssistantText}`;\r\n }\r\n return base;\r\n }\r\n case 'aborted_by_parent':\r\n return 'Subagent was aborted (user Ctrl+C, parent unwound, or sibling failure cascade). Not retryable until the abort condition is resolved.';\r\n case 'empty_response':\r\n return 'Subagent ended its turn with no text and no tool calls. Almost always a prompt / config issue — clarify the task or check the model.';\r\n case 'tool_failed': {\r\n const base = 'A tool inside the subagent returned ok:false. Retry with corrected inputs.';\r\n if (partial?.lastAssistantText) {\r\n return `${base}\\n\\nAgent reasoning before failure:\\n${partial.lastAssistantText}`;\r\n }\r\n return base;\r\n }\r\n case 'bridge_failed':\r\n return 'Parent-child bridge transport failed. This is rare — restart the session and retry.';\r\n default:\r\n return retryable\r\n ? 'Failure classified as retryable. Try again with the same input.'\r\n : undefined;\r\n }\r\n}\r\n\r\n/**\r\n * Compact summary of what a subagent did — shown in chat history so\r\n * the user immediately sees the outcome without parsing the full result.\r\n */\r\nfunction buildDelegateSummary(\r\n role: string | undefined,\r\n result: TaskResult,\r\n): string {\r\n const roleLabel = role ?? 'subagent';\r\n const ms = result.durationMs;\r\n const duration = ms < 60_000\r\n ? `${Math.round(ms / 1000)}s`\r\n : ms < 3_600_000\r\n ? `${Math.round(ms / 60_000)}m`\r\n : `${(ms / 3_600_000).toFixed(1)}h`;\r\n\r\n if (result.status === 'success') {\r\n const preview = typeof result.result === 'string'\r\n ? result.result.trim().slice(0, 120).replace(/\\n+/g, ' ')\r\n : null;\r\n const tail = preview ? ` — ${preview}` : '';\r\n return `[${roleLabel}] done in ${duration} (${result.iterations} iter, ${result.toolCalls} tools)${tail}`;\r\n }\r\n\r\n const errLabel = result.error?.kind ?? result.status;\r\n return `[${roleLabel}] ${result.status} after ${duration} (${result.iterations} iter, ${result.toolCalls} tools) — ${errLabel}`;\r\n}\r\n\r\n/**\r\n * Parse the per-subagent JSONL at `<sessionsRoot>/<runId>/<subagentId>.jsonl`\r\n * and pull out the last few useful pieces — the most recent assistant\r\n * text response, the stop reason, and a count of tool calls. Used by\r\n * `delegate` when the subagent timed out or exhausted budget without\r\n * returning a clean `finalText`, so the host LLM still sees what work\r\n * actually happened.\r\n */\r\nasync function readSubagentPartial(\r\n opts: CreateDelegateToolOptions,\r\n subagentId: string,\r\n): Promise<\r\n | {\r\n lastAssistantText?: string;\r\n lastStopReason?: string;\r\n toolUsesObserved: number;\r\n events: number;\r\n }\r\n | undefined\r\n> {\r\n if (!opts.sessionsRoot) return undefined;\r\n // Locate the JSONL. When `directorRunId` is provided we know the\r\n // exact path; otherwise scan the sessionsRoot for any subdir\r\n // containing this subagent id.\r\n const candidates: string[] = [];\r\n if (opts.directorRunId) {\r\n candidates.push(path.join(opts.sessionsRoot, opts.directorRunId, `${subagentId}.jsonl`));\r\n } else {\r\n try {\r\n const entries = await fsp.readdir(opts.sessionsRoot, { withFileTypes: true });\r\n for (const entry of entries) {\r\n if (entry.isDirectory()) {\r\n candidates.push(path.join(opts.sessionsRoot, entry.name, `${subagentId}.jsonl`));\r\n }\r\n }\r\n } catch {\r\n return undefined;\r\n }\r\n }\r\n for (const file of candidates) {\r\n let raw: string;\r\n try {\r\n raw = await fsp.readFile(file, 'utf8');\r\n } catch {\r\n continue;\r\n }\r\n const lines = raw.split('\\n').filter((l) => l.trim());\r\n let lastAssistantText: string | undefined;\r\n let lastStopReason: string | undefined;\r\n let toolUses = 0;\r\n for (const line of lines) {\r\n try {\r\n const ev = JSON.parse(line) as {\r\n type: string;\r\n content?: unknown;\r\n stopReason?: string;\r\n name?: string;\r\n };\r\n if (ev.type === 'tool_use') toolUses += 1;\r\n if (ev.type === 'llm_response') {\r\n if (typeof ev.stopReason === 'string') lastStopReason = ev.stopReason;\r\n if (Array.isArray(ev.content)) {\r\n const txt = (ev.content as Array<{ type?: string; text?: string }>)\r\n .filter((b) => b.type === 'text')\r\n .map((b) => b.text ?? '')\r\n .join('\\n')\r\n .trim();\r\n if (txt) lastAssistantText = txt;\r\n }\r\n }\r\n } catch {\r\n }\r\n }\r\n return {\r\n lastAssistantText,\r\n lastStopReason,\r\n toolUsesObserved: toolUses,\r\n events: lines.length,\r\n };\r\n }\r\n return undefined;\r\n}\r\n","import type { Agent, AgentInput, RunResult } from '../core/agent.js';\nimport type { EventBus } from '../kernel/events.js';\nimport type {\n SubagentConfig,\n SubagentRunContext,\n SubagentRunOutcome,\n SubagentRunner,\n TaskSpec,\n} from '../types/multi-agent.js';\nimport {\n BudgetExceededError,\n BudgetThresholdSignal,\n} from './subagent-budget.js';\nimport type { FleetBus } from './fleet-bus.js';\n\n/**\n * Caller-supplied factory that builds an isolated `Agent` for a subagent.\n * The factory MUST construct a fresh `Context` per call — sharing context\n * between subagents defeats isolation. Each Agent should also use either\n * its own `EventBus` or a forwarded view, so per-subagent metrics can be\n * attributed correctly.\n */\nexport type AgentFactory = (config: SubagentConfig) => Promise<AgentFactoryResult>;\n\nexport interface AgentFactoryResult {\n agent: Agent;\n /** Event bus the factory wired to this agent — required for budget hookup. */\n events: EventBus;\n /**\n * Optional cleanup hook invoked in the runner's `finally` block once\n * the task ends (success, failure, abort — same exit path). Factories\n * that own resources scoped to a single task (per-subagent JSONL\n * writers, transient providers, throwaway containers) implement this\n * to close them deterministically instead of relying on GC. Errors\n * thrown here are swallowed so a flaky cleanup can't mask the task's\n * real result.\n */\n dispose?: () => Promise<void> | void;\n}\n\nexport interface AgentRunnerOptions {\n factory: AgentFactory;\n /**\n * Format a TaskSpec into the user input the agent will receive. Defaults\n * to `task.description ?? ''`. Override when subagents expect structured\n * input (e.g. JSON contracts, role-prefixed prompts).\n */\n formatTaskInput?: (task: TaskSpec, config: SubagentConfig) => AgentInput;\n /**\n * When set, the runner attaches the subagent's EventBus to this FleetBus\n * on task start and detaches it when the task finishes. This is the\n * injection seam that lets the TUI fleet panel observe subagent activity\n * live — without it, FleetBus stays empty.\n */\n fleetBus?: FleetBus;\n}\n\n/**\n * Builds a `SubagentRunner` that drives a real `Agent` per task while honoring\n * the coordinator's budget and abort signal. This is the production adapter —\n * the coordinator's `runner` option in CLI/TUI assemblies points here.\n *\n * Lifecycle per task:\n * 1. factory(config) → fresh Agent + EventBus.\n * 2. Subscribe to events to feed the budget (tool calls, token usage).\n * 3. Call agent.run(input, { signal }) — the coordinator's signal cancels.\n * 4. Map RunResult.status onto a `SubagentRunOutcome` or throw on failure.\n * 5. Unsubscribe and let the factory's resources be GC'd.\n *\n * The budget is checked synchronously from event handlers — a runaway agent\n * that crosses its tool-call limit triggers `BudgetExceededError`, which the\n * coordinator surfaces as `status: 'failed'` on the task result.\n */\nexport function makeAgentSubagentRunner(opts: AgentRunnerOptions): SubagentRunner {\n const format = opts.formatTaskInput ?? defaultFormatTaskInput;\n\n return async (task: TaskSpec, ctx: SubagentRunContext): Promise<SubagentRunOutcome> => {\n const factoryResult = await opts.factory(ctx.config);\n const { agent, events } = factoryResult;\n\n // Attach subagent EventBus to FleetBus so the TUI fleet panel (and any\n // other FleetBus subscriber) can observe this subagent live. Detach on\n // task finish — each task is a fresh Agent + EventBus, so we never\n // want a stale bus lingering after the run.\n const detachFleet = opts.fleetBus?.attach(ctx.subagentId, events, task.id);\n\n // Hook budget into the agent's event stream. We capture errors thrown by\n // recordToolCall/recordUsage so the budget can short-circuit the run by\n // aborting the controller — the agent then unwinds cooperatively.\n const aborter = new AbortController();\n // Inject the EventBus into the budget so it can emit budget.threshold_reached\n // events when a soft limit is hit and the handler wants to ask the coordinator.\n ctx.budget._events = events;\n // Wire the threshold-negotiation handler. Without this the soft-limit\n // path is dead code: every budget overrun becomes a hard\n // BudgetExceededError and the subagent dies on its first 120-iteration\n // tick instead of asking the Director for headroom. The Director's\n // FleetBus listener (director.ts) auto-grants +50% up to a per-kind\n // ceiling and per-subagent extension count — wiring this is the\n // missing link that activates that flow.\n ctx.budget.onThreshold = ({ requestDecision }) => requestDecision();\n let budgetError: Error | null = null;\n\n /**\n * Common error handler for all budget-triggered events. Distinguishes:\n * - BudgetExceededError → hard stop, set budgetError + abort\n * - BudgetThresholdSignal → soft stop: await the coordinator's\n * decision. If 'stop', abort. If 'extend', the signal handler\n * has already patched the budget so we can continue without\n * actually aborting the agent.\n */\n const onBudgetError = (err: unknown): void => {\n if (err instanceof BudgetThresholdSignal) {\n // Await the coordinator's verdict before deciding whether to abort.\n err.decision\n .then((decision) => {\n if (decision === 'stop') {\n budgetError = new BudgetExceededError(err.kind, err.limit, err.used);\n aborter.abort();\n }\n // If 'extend': the budget limits were already patched by the\n // BudgetThresholdSignal handler (checkLimit → onThreshold →\n // coordinator extend → budget patched). Do NOT abort.\n // The tool call that triggered the signal will be retried.\n })\n .catch(() => {\n // If the decision promise rejects, treat as hard stop.\n budgetError = new BudgetExceededError(err.kind, err.limit, err.used);\n aborter.abort();\n });\n return;\n }\n // Hard stop (BudgetExceededError or other)\n aborter.abort();\n budgetError =\n err instanceof BudgetExceededError\n ? err\n : new BudgetExceededError(\n 'tool_calls',\n 0,\n 0,\n );\n // Attach the real error detail so the task result surfaces\n // something actionable instead of a generic budget message.\n if (budgetError !== err && err instanceof Error) {\n budgetError.message += ` (caused by: ${err.message})`;\n }\n };\n\n // Track the name of the most recent tool that returned ok:false so\n // we can lift it into the SubagentError when the agent ends without\n // recovering. Cleared on every successful tool execution so a tool\n // that later succeeded doesn't taint the final report.\n let lastToolFailed: string | null = null;\n\n const unsub: Array<() => void> = [];\n unsub.push(\n events.on('tool.executed', (e) => {\n // Count tool calls on the PAIRED 'tool.executed' event rather\n // than 'tool.started'. A tool can fire start then crash before\n // emitting executed (process killed, signal aborted mid-exec);\n // counting only the paired event keeps the budget tally honest\n // and matches what the model actually saw in its turn.\n try {\n ctx.budget.recordToolCall();\n } catch (eb) {\n onBudgetError(eb);\n }\n // Track ok:false so we can fail the subagent if it ends without\n // recovering. Successful runs clear it — the model may try a\n // tool, get an error, and self-heal on the next iteration; that\n // path should still report success.\n if (e.ok === false) {\n lastToolFailed = e.name;\n } else if (e.ok === true) {\n lastToolFailed = null;\n }\n }),\n events.on('provider.response', (e) => {\n try {\n ctx.budget.recordUsage(e.usage);\n } catch (e2) {\n void onBudgetError(e2);\n }\n }),\n events.on('iteration.started', () => {\n try {\n ctx.budget.recordIteration();\n } catch (e) {\n void onBudgetError(e);\n }\n // Emit a periodic progress snapshot every SUMMARY_INTERVAL\n // iterations so the leader can surface \"AGENT#2 ● L25 · 47 tools\"\n // in the main chat history without needing the FleetPanel open.\n const u = ctx.budget.usage();\n const since = u.iterations - lastSummaryAtIteration;\n if (since >= SUMMARY_INTERVAL) {\n lastSummaryAtIteration = u.iterations;\n events.emit('subagent.iteration_summary', {\n subagentId: ctx.subagentId,\n iteration: u.iterations,\n toolCalls: u.toolCalls,\n costUsd: u.costUsd,\n currentTool: currentToolName,\n partialText: streamingTextAcc.trim() || undefined,\n });\n }\n }),\n // D3: cooperative timeout enforcement DURING a long tool call.\n // The iteration-loop checkTimeout() only fires between agent\n // iterations — a single `bash sleep 3600` call would otherwise\n // park inside one tool execution while the timeout silently\n // passes, relying solely on the coordinator's hard Promise.race\n // to interrupt. Tools that emit `tool.progress` (bash chunks,\n // fetch byte progress, spawn-stream stdout) give us a heartbeat\n // we can hang the check on. When the budget trips here:\n // 1. onBudgetError sets budgetError + aborter.abort()\n // 2. aborter signal propagates to agent.run → tool executor\n // 3. tool's own signal listener kills the child process\n // Cheap: O(1) per progress event, and the budget short-circuits\n // when timeoutMs is unset (most subagents have one set anyway).\n events.on('tool.progress', () => {\n // Streamed progress (bash chunks, fetch bytes, spawn stdout) is forward\n // motion — reset the idle clock so a long-but-working tool is never\n // mistaken for a stall, THEN check whether a genuine timeout tripped.\n ctx.budget.markActivity();\n try {\n ctx.budget.checkTimeout();\n } catch (e) {\n void onBudgetError(e);\n }\n }),\n );\n\n // Track current tool name + streaming text for the periodic summary.\n let currentToolName: string | undefined;\n let streamingTextAcc = '';\n let lastSummaryAtIteration = 0;\n const SUMMARY_INTERVAL = 25;\n\n unsub.push(\n events.on('tool.started', (e) => {\n currentToolName = e.name;\n }),\n events.on('provider.text_delta', (e) => {\n // Streamed assistant text is forward motion too — keep the idle\n // clock fresh while the model is actively generating.\n ctx.budget.markActivity();\n // Accumulate last ~200 chars for the partial text snapshot.\n streamingTextAcc = (streamingTextAcc + e.text).slice(-200);\n }),\n );\n\n // Forward the coordinator signal so stop() from outside also aborts.\n const onParentAbort = () => aborter.abort();\n ctx.signal.addEventListener('abort', onParentAbort);\n\n let result: RunResult;\n try {\n result = await agent.run(format(task, ctx.config), { signal: aborter.signal });\n } finally {\n detachFleet?.();\n ctx.signal.removeEventListener('abort', onParentAbort);\n for (const u of unsub) u();\n // Per-task resource cleanup. Closes JSONL writers, throwaway\n // providers, etc. that the factory wired up. Swallowed errors —\n // a flaky cleanup must not mask the real task result. The\n // caller can re-emit via observability if needed.\n if (factoryResult.dispose) {\n try {\n await factoryResult.dispose();\n } catch {\n // intentional swallow — see comment above\n }\n }\n }\n\n // A budget violation is the signal — surface it so the coordinator can\n // tag the task with the right failure kind ('failed' for budget; the\n // coordinator separately recognises 'timeout' from BudgetExceededError).\n if (budgetError) {\n // BudgetThresholdSignal: the soft limit was hit but the coordinator\n // hasn't resolved the extension decision yet. If the decision was\n // 'extend', the coordinator patched limits and the agent finished\n // normally — no error to surface. If 'stop', budgetError becomes\n // a BudgetExceededError thrown below.\n // instanceof check on Error subtypes requires 'any' intersection\n // on the union — use a property guard instead.\n if ('decision' in budgetError) {\n const decision = await (budgetError as BudgetThresholdSignal).decision;\n if (decision === 'stop') {\n budgetError = new BudgetExceededError(\n (budgetError as BudgetThresholdSignal).kind,\n (budgetError as BudgetThresholdSignal).limit,\n (budgetError as BudgetThresholdSignal).used,\n );\n } else {\n budgetError = null;\n }\n }\n if (budgetError) throw budgetError;\n }\n\n if (result.status === 'failed') {\n throw result.error instanceof Error\n ? result.error\n : new Error(String(result.error ?? 'agent failed'));\n }\n // 'aborted' and 'max_iterations' aren't successes — let the coordinator\n // classify them. When the parent signal was aborted, coordinator marks\n // the task 'stopped' (matched against subagent.abortController.aborted).\n if (result.status === 'aborted') {\n throw new Error('agent aborted');\n }\n if (result.status === 'max_iterations') {\n throw new Error('agent exhausted iteration limit');\n }\n\n const usage = ctx.budget.usage();\n // Empty-response guard. A \"successful\" run with no text AND no tool\n // calls is almost always a prompt / config issue, not a real\n // success — the agent burned an iteration to say nothing. Surface\n // it as a classified failure so callers can show \"✗ empty_response\"\n // instead of a confusing green ✓ with no output. We only trip on\n // the (no-text AND no-tools) intersection because text-less runs\n // with tool calls are legit (e.g. \"run npm test then end_turn\").\n const finalText = (result.finalText ?? '').trim();\n if (finalText.length === 0 && usage.toolCalls === 0) {\n throw new Error('empty response');\n }\n // Unrecovered-tool-failure guard. If the last executed tool came\n // back ok:false AND the agent ended its turn with no closing text,\n // the agent never acknowledged or recovered from the failure — the\n // task is effectively broken. A model that handles a tool error\n // emits SOME text on the next iteration (\"the read failed, trying\n // an alternate path…\") which clears `lastToolFailed`; the only way\n // both signals can be live at end-of-run is if the model gave up\n // silently. Surface as `tool_failed` so callers see the actual\n // failure mode instead of a clean ✓ with no output.\n if (finalText.length === 0 && lastToolFailed !== null) {\n throw new Error(`tool failed: ${lastToolFailed}`);\n }\n return {\n result: result.finalText,\n iterations: result.iterations,\n toolCalls: usage.toolCalls,\n };\n };\n}\n\nfunction defaultFormatTaskInput(task: TaskSpec): AgentInput {\n return task.description ?? '';\n}\n","import type { ContentBlock, ToolResultBlock, ToolUseBlock } from '../types/blocks.js';\nimport type { Message } from '../types/messages.js';\n\nexport interface MessageRepairReport {\n changed: boolean;\n removedToolUses: string[];\n removedToolResults: string[];\n removedMessages: number;\n}\n\nexport interface MessageRepairResult {\n messages: Message[];\n report: MessageRepairReport;\n}\n\n/**\n * Repair provider-level tool-call adjacency invariants.\n *\n * Anthropic requires every assistant `tool_use` block to have a matching\n * `tool_result` block in the immediately following user message. Manual\n * context surgery (summary/prune) can cut through the middle of such an\n * exchange. This function removes only the now-orphaned protocol blocks,\n * preserving surrounding text/images/thinking blocks where possible.\n */\nexport function repairToolUseAdjacency(messages: Message[]): MessageRepairResult {\n const removedToolUses: string[] = [];\n const removedToolResults: string[] = [];\n let removedMessages = 0;\n let changed = false;\n const out: Message[] = [];\n\n for (let i = 0; i < messages.length; i++) {\n const original = messages[i]!;\n let msg = original;\n\n if (hasToolUse(msg)) {\n const nextIds = toolResultIds(messages[i + 1]);\n const filtered = mapContent(msg, (blocks) => {\n const next: ContentBlock[] = [];\n for (const block of blocks) {\n if (block.type === 'tool_use' && !nextIds.has(block.id)) {\n removedToolUses.push(block.id);\n changed = true;\n continue;\n }\n next.push(block);\n }\n return next;\n });\n msg = filtered ?? msg;\n }\n\n if (hasToolResult(msg)) {\n const allowed = toolUseIds(out[out.length - 1]);\n const filtered = mapContent(msg, (blocks) => {\n const next: ContentBlock[] = [];\n for (const block of blocks) {\n if (block.type === 'tool_result' && !allowed.has(block.tool_use_id)) {\n removedToolResults.push(block.tool_use_id);\n changed = true;\n continue;\n }\n next.push(block);\n }\n return next;\n });\n msg = filtered ?? msg;\n }\n\n if (isEmptyMessage(msg)) {\n removedMessages++;\n changed = true;\n continue;\n }\n out.push(msg);\n }\n\n return {\n messages: changed ? out : messages,\n report: { changed, removedToolUses, removedToolResults, removedMessages },\n };\n}\n\nfunction hasToolUse(msg: Message | undefined): boolean {\n return contentBlocks(msg).some((b): b is ToolUseBlock => b.type === 'tool_use');\n}\n\nfunction hasToolResult(msg: Message | undefined): boolean {\n return contentBlocks(msg).some((b): b is ToolResultBlock => b.type === 'tool_result');\n}\n\nfunction toolUseIds(msg: Message | undefined): Set<string> {\n const ids = new Set<string>();\n if (!msg || msg.role !== 'assistant') return ids;\n for (const block of contentBlocks(msg)) {\n if (block.type === 'tool_use') ids.add(block.id);\n }\n return ids;\n}\n\nfunction toolResultIds(msg: Message | undefined): Set<string> {\n const ids = new Set<string>();\n if (!msg || msg.role !== 'user') return ids;\n for (const block of contentBlocks(msg)) {\n if (block.type === 'tool_result') ids.add(block.tool_use_id);\n }\n return ids;\n}\n\nfunction contentBlocks(msg: Message | undefined): ContentBlock[] {\n return msg && Array.isArray(msg.content) ? msg.content : [];\n}\n\nfunction mapContent(\n msg: Message,\n fn: (blocks: ContentBlock[]) => ContentBlock[],\n): Message | null {\n if (!Array.isArray(msg.content)) return msg;\n const next = fn(msg.content);\n if (next.length === msg.content.length && next.every((b, idx) => b === msg.content[idx])) {\n return msg;\n }\n return { ...msg, content: next };\n}\n\nfunction isEmptyMessage(msg: Message): boolean {\n if (typeof msg.content === 'string') return msg.content.trim().length === 0;\n return msg.content.length === 0;\n}\n","import { randomBytes } from 'node:crypto';\nimport * as fsp from 'node:fs/promises';\nimport * as path from 'node:path';\nimport type { EventBus } from '../kernel/events.js';\nimport type { ContentBlock } from '../types/blocks.js';\nimport type { Message } from '../types/messages.js';\nimport type { SecretScrubber } from '../types/secret-scrubber.js';\nimport type {\n ResumedSession,\n SessionData,\n SessionEvent,\n SessionMetadata,\n SessionStore,\n SessionSummary,\n SessionWriter,\n} from '../types/session.js';\nimport { atomicWrite, ensureDir } from '../utils/atomic-write.js';\nimport { repairToolUseAdjacency } from '../utils/message-invariants.js';\n\nexport interface SessionStoreOptions {\n dir: string;\n /** Optional EventBus for emitting session diagnostics. */\n events?: EventBus;\n /**\n * Optional secret scrubber. When set, `user_input` and `llm_response` event\n * content is scrubbed before being persisted to the JSONL log and the\n * summary sidecar — so a secret a user pastes or the model echoes does not\n * sit in cleartext on disk (and does not ride along in history cloud-sync).\n * Tool output is already scrubbed upstream by the executor; this closes the\n * conversation-turn gap (finding F-06).\n */\n secretScrubber?: SecretScrubber;\n}\n\nexport class DefaultSessionStore implements SessionStore {\n private readonly dir: string;\n private readonly events?: EventBus;\n private readonly secretScrubber?: SecretScrubber;\n\n constructor(opts: SessionStoreOptions) {\n this.dir = opts.dir;\n this.events = opts.events;\n this.secretScrubber = opts.secretScrubber;\n }\n\n /** Join session ID to its absolute path within the store directory. */\n private sessionPath(id: string, ext: '.jsonl' | '.summary.json'): string {\n return path.join(this.dir, `${id}${ext}`);\n }\n\n private async ensureShardDir(_id: string): Promise<string> {\n await ensureDir(this.dir);\n return this.dir;\n }\n\n async create(meta: Omit<SessionMetadata, 'startedAt'>): Promise<SessionWriter> {\n const startedAt = new Date().toISOString();\n const id = meta.id ?? `${startedAt.replace(/[:.]/g, '-')}-${randomBytes(2).toString('hex')}`;\n const shardDir = await this.ensureShardDir(id);\n const file = path.join(shardDir, `${id}.jsonl`);\n let handle: fsp.FileHandle;\n try {\n handle = await fsp.open(file, 'a', 0o600);\n } catch (err) {\n throw new Error(\n `Failed to open session file: ${err instanceof Error ? err.message : String(err)}`,\n { cause: err },\n );\n }\n try {\n return new FileSessionWriter(id, handle, startedAt, meta, this.events, {\n dir: shardDir,\n filePath: file,\n secretScrubber: this.secretScrubber,\n });\n } catch (err) {\n await handle.close().catch(() => {});\n throw err;\n }\n }\n\n async resume(id: string): Promise<ResumedSession> {\n const file = this.sessionPath(id, '.jsonl');\n const data = await this.load(id);\n let handle: fsp.FileHandle;\n try {\n handle = await fsp.open(file, 'a', 0o600);\n } catch (err) {\n throw new Error(\n `Failed to open session \"${id}\" for append: ${err instanceof Error ? err.message : String(err)}`,\n { cause: err },\n );\n }\n try {\n const writer = new FileSessionWriter(\n id,\n handle,\n new Date().toISOString(),\n {\n id,\n model: data.metadata.model,\n provider: data.metadata.provider,\n },\n this.events,\n { resumed: true, dir: this.dir, filePath: file, secretScrubber: this.secretScrubber },\n );\n return { writer, data };\n } catch (err) {\n await handle.close().catch(() => {});\n throw err;\n }\n }\n\n async load(id: string): Promise<SessionData> {\n const file = this.sessionPath(id, '.jsonl');\n const raw = await fsp.readFile(file, 'utf8');\n const lines = raw.split('\\n').filter((l) => l.trim());\n const events: SessionEvent[] = [];\n for (const line of lines) {\n try {\n const parsed: unknown = JSON.parse(line);\n if (\n parsed !== null &&\n typeof parsed === 'object' &&\n typeof (parsed as { type?: unknown }).type === 'string' &&\n typeof (parsed as { ts?: unknown }).ts === 'string'\n ) {\n events.push(parsed as SessionEvent);\n }\n } catch {\n // skip malformed JSON\n }\n }\n const meta = this.metaFromEvents(id, events);\n const { messages, usage } = this.replay(events, id);\n return { metadata: meta, events, messages, usage };\n }\n\n async list(limit = 20): Promise<SessionSummary[]> {\n try {\n await ensureDir(this.dir);\n const ids = await this.collectSessionIds(this.dir);\n const sessions = await Promise.all(ids.map((id) => this.summaryFor(id).catch(() => null)));\n const out = sessions.filter((s): s is SessionSummary => s !== null);\n out.sort((a, b) => {\n if (a.startedAt < b.startedAt) return 1;\n if (a.startedAt > b.startedAt) return -1;\n return a.id.localeCompare(b.id);\n });\n return out.slice(0, limit);\n } catch {\n return [];\n }\n }\n\n /** Recursively collect all session IDs from shard subdirectories. */\n private async collectSessionIds(dir: string): Promise<string[]> {\n const ids: string[] = [];\n const entries = await fsp.readdir(dir, { withFileTypes: true });\n for (const entry of entries) {\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n ids.push(...(await this.collectSessionIds(full)));\n } else if (entry.isFile() && entry.name.endsWith('.jsonl')) {\n ids.push(entry.name.replace(/\\.jsonl$/, ''));\n }\n }\n return ids;\n }\n\n private async summaryFor(id: string): Promise<SessionSummary> {\n const manifest = this.sessionPath(id, '.summary.json');\n try {\n const raw = await fsp.readFile(manifest, 'utf8');\n return JSON.parse(raw) as SessionSummary;\n } catch {\n const full = this.sessionPath(id, '.jsonl');\n const stat = await fsp.stat(full);\n const summary = await this.summarize(id, stat.mtime.toISOString());\n await atomicWrite(manifest, JSON.stringify(summary), { mode: 0o600 }).catch((err) => {\n console.warn(\n `[session-store] Failed to write manifest for \"${id}\":`,\n err instanceof Error ? err.message : String(err),\n );\n });\n return summary;\n }\n }\n\n async delete(id: string): Promise<void> {\n await fsp.unlink(this.sessionPath(id, '.jsonl'));\n await fsp.unlink(this.sessionPath(id, '.summary.json')).catch(() => undefined);\n }\n\n async clearHistory(id: string): Promise<void> {\n await this.ensureShardDir(id);\n const file = this.sessionPath(id, '.jsonl');\n const meta = this.sessionPath(id, '.summary.json');\n const record = `${JSON.stringify({\n type: 'session_start',\n ts: new Date().toISOString(),\n id,\n model: 'unknown',\n provider: 'unknown',\n })}\\n`;\n await fsp.writeFile(file, record, 'utf8');\n await fsp.unlink(meta).catch(() => undefined);\n }\n\n private async summarize(id: string, mtime: string): Promise<SessionSummary> {\n try {\n const data = await this.load(id);\n const firstUser = data.events.find((e) => e.type === 'user_input');\n const title =\n firstUser && firstUser.type === 'user_input'\n ? userInputTitle(firstUser.content)\n : '(empty session)';\n return {\n id,\n title,\n startedAt: data.metadata.startedAt,\n model: data.metadata.model ?? 'unknown',\n provider: data.metadata.provider ?? 'unknown',\n tokenTotal: data.usage.input + data.usage.output,\n };\n } catch {\n return {\n id,\n title: '(damaged)',\n startedAt: mtime,\n model: 'unknown',\n provider: 'unknown',\n tokenTotal: 0,\n };\n }\n }\n\n private metaFromEvents(id: string, events: SessionEvent[]): SessionMetadata {\n const start = events.find((e) => e.type === 'session_start');\n const end = events.find((e) => e.type === 'session_end');\n return {\n id,\n startedAt: start?.ts ?? new Date(0).toISOString(),\n endedAt: end?.ts,\n model: start?.model,\n provider: start?.provider,\n pendingToolUses: end?.pendingToolUses,\n };\n }\n\n private replay(\n events: SessionEvent[],\n sessionId = 'unknown',\n ): { messages: Message[]; usage: SessionData['usage'] } {\n const messages: Message[] = [];\n let usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };\n const openToolUses = new Set<string>();\n for (const e of events) {\n if (e.type === 'user_input') {\n openToolUses.clear();\n messages.push({ role: 'user', content: e.content });\n } else if (e.type === 'llm_response') {\n messages.push({ role: 'assistant', content: e.content });\n for (const b of e.content) {\n if (b.type === 'tool_use') openToolUses.add(b.id);\n }\n usage = {\n input: usage.input + (e.usage.input ?? 0),\n output: usage.output + (e.usage.output ?? 0),\n cacheRead: (usage.cacheRead ?? 0) + (e.usage.cacheRead ?? 0),\n cacheWrite: (usage.cacheWrite ?? 0) + (e.usage.cacheWrite ?? 0),\n };\n } else if (e.type === 'tool_result') {\n if (!openToolUses.has(e.id)) {\n this.events?.emit('session.damaged', {\n sessionId,\n detail: `Orphan tool_result \"${e.id}\" has no matching tool_use`,\n });\n continue;\n }\n openToolUses.delete(e.id);\n const content: ContentBlock[] = [\n {\n type: 'tool_result',\n tool_use_id: e.id,\n content: typeof e.content === 'string' ? e.content : JSON.stringify(e.content),\n is_error: e.isError,\n },\n ];\n const last = messages[messages.length - 1];\n if (last && last.role === 'user') {\n if (Array.isArray(last.content)) {\n last.content.push(...content);\n } else if (typeof last.content === 'string') {\n last.content = [{ type: 'text', text: last.content }, ...content];\n } else {\n messages.push({ role: 'user', content });\n }\n } else {\n messages.push({ role: 'user', content });\n }\n }\n }\n if (openToolUses.size > 0) {\n this.events?.emit('session.damaged', {\n sessionId,\n detail: `${openToolUses.size} tool_use blocks without matching results - replay repaired`,\n });\n }\n const repaired = repairToolUseAdjacency(messages);\n if (repaired.report.changed) {\n this.events?.emit('session.damaged', {\n sessionId,\n detail:\n `Repaired replay adjacency: removed ${repaired.report.removedToolUses.length} tool_use, ` +\n `${repaired.report.removedToolResults.length} tool_result, ` +\n `${repaired.report.removedMessages} empty messages`,\n });\n }\n return { messages: repaired.messages, usage };\n }\n}\n\nclass FileSessionWriter implements SessionWriter {\n private closed = false;\n private closing = false;\n private manifestFile: string;\n private summary: SessionSummary;\n private tokenIn = 0;\n private tokenOut = 0;\n private readonly filePath: string;\n get transcriptPath(): string | undefined {\n return this.filePath || undefined;\n }\n private initDone = false;\n private readonly resumed: boolean;\n private appendFailCount = 0;\n private lastAppendWarnAt = 0;\n private readonly secretScrubber?: SecretScrubber;\n\n /**\n * Scrub secrets out of conversation-turn events before they are observed\n * for the summary, written to the JSONL log, or surfaced on resume. Only\n * `user_input` / `llm_response` carry free-form user/model text; other event\n * types either have no secret-bearing content or are already scrubbed\n * upstream (tool results). Returns the event unchanged when no scrubber is\n * configured.\n */\n private scrubEvent(event: SessionEvent): SessionEvent {\n const s = this.secretScrubber;\n if (!s) return event;\n if (event.type === 'user_input') {\n return {\n ...event,\n content:\n typeof event.content === 'string' ? s.scrub(event.content) : s.scrubObject(event.content),\n };\n }\n if (event.type === 'llm_response') {\n return { ...event, content: s.scrubObject(event.content) };\n }\n return event;\n }\n\n private pendingFileSnapshots: Array<{\n path: string;\n action: 'created' | 'modified' | 'deleted';\n before: string | null;\n after: string | null;\n }> = [];\n /** Tracks open tool_use IDs during the current run to serialize on close for resume. */\n private openToolUses = new Set<string>();\n\n recordFileChange(input: {\n path: string;\n action: 'created' | 'modified' | 'deleted';\n before: string | null;\n after: string | null;\n }): void {\n this.pendingFileSnapshots.push(input);\n }\n\n constructor(\n public readonly id: string,\n private handle: fsp.FileHandle,\n private readonly startedAt: string,\n private readonly meta: Omit<SessionMetadata, 'startedAt'>,\n private readonly events?: EventBus,\n opts: {\n resumed?: boolean;\n dir?: string;\n filePath?: string;\n secretScrubber?: SecretScrubber;\n } = {},\n ) {\n this.resumed = opts.resumed ?? false;\n this.manifestFile = opts.dir ? path.join(opts.dir, `${id}.summary.json`) : '';\n this.filePath = opts.filePath ?? '';\n this.secretScrubber = opts.secretScrubber;\n this.summary = {\n id,\n title: '(empty session)',\n startedAt,\n model: meta.model ?? 'unknown',\n provider: meta.provider ?? 'unknown',\n tokenTotal: 0,\n };\n }\n\n get pendingToolUses(): string[] {\n return Array.from(this.openToolUses);\n }\n\n private async writeSessionStartLazy(): Promise<void> {\n const record = `${JSON.stringify({\n type: this.resumed ? 'session_resumed' : 'session_start',\n ts: this.startedAt,\n id: this.id,\n model: this.meta.model ?? 'unknown',\n provider: this.meta.provider ?? 'unknown',\n })}\\n`;\n try {\n if (this.filePath) {\n await fsp.writeFile(this.filePath, record, { flag: 'a', mode: 0o600 });\n }\n } catch {\n // best-effort\n }\n }\n\n async append(event: SessionEvent): Promise<void> {\n if (this.closed) return;\n if (!this.initDone) {\n this.initDone = true;\n await this.writeSessionStartLazy();\n }\n // Scrub before observing (the summary title is derived from user_input\n // content) and before writing, so neither the JSONL nor the sidecar holds\n // a cleartext secret.\n const scrubbed = this.scrubEvent(event);\n this.observeForSummary(scrubbed);\n try {\n await this.handle.appendFile(`${JSON.stringify(scrubbed)}\\n`, 'utf8');\n } catch (err) {\n this.appendFailCount++;\n const now = Date.now();\n if (now - this.lastAppendWarnAt > 5000) {\n const suppressed = this.appendFailCount - 1;\n const tail = suppressed > 0 ? ` (+${suppressed} suppressed)` : '';\n console.warn(\n '[session] append failed:',\n err instanceof Error ? err.message : String(err),\n tail,\n );\n this.lastAppendWarnAt = now;\n this.appendFailCount = 0;\n }\n }\n }\n\n private observeForSummary(event: SessionEvent): void {\n // Track open tool uses so we can serialize them on close for resume.\n if (event.type === 'tool_use') {\n this.openToolUses.add(event.id);\n } else if (event.type === 'tool_result') {\n this.openToolUses.delete(event.id);\n }\n if (event.type === 'user_input' && this.summary.title === '(empty session)') {\n this.summary = { ...this.summary, title: userInputTitle(event.content) };\n } else if (event.type === 'llm_response') {\n this.tokenIn += event.usage.input;\n this.tokenOut += event.usage.output;\n this.summary = { ...this.summary, tokenTotal: this.tokenIn + this.tokenOut };\n } else if (event.type === 'session_end') {\n const total = event.usage.input + event.usage.output;\n if (total > 0) this.summary = { ...this.summary, tokenTotal: total };\n }\n }\n\n async close(): Promise<void> {\n if (this.closing) return;\n this.closing = true;\n this.closed = true;\n if (this.manifestFile) {\n try {\n await atomicWrite(this.manifestFile, JSON.stringify(this.summary), { mode: 0o600 });\n } catch {\n // manifest write is best-effort\n }\n }\n try {\n await this.handle.close();\n } catch {\n // ignore\n }\n }\n\n async writeCheckpoint(promptIndex: number, promptPreview: string): Promise<void> {\n const fileCount = this.pendingFileSnapshots.length;\n if (fileCount > 0) {\n await this.writeFileSnapshot(promptIndex, [...this.pendingFileSnapshots]);\n this.pendingFileSnapshots = [];\n }\n await this.append({\n type: 'checkpoint',\n ts: new Date().toISOString(),\n promptIndex,\n promptPreview,\n });\n this.events?.emit('checkpoint.written', {\n promptIndex,\n promptPreview,\n ts: new Date().toISOString(),\n fileCount,\n });\n }\n\n async writeFileSnapshot(\n promptIndex: number,\n files: import('../types/session.js').FileSnapshot[],\n ): Promise<void> {\n await this.append({\n type: 'file_snapshot',\n ts: new Date().toISOString(),\n promptIndex,\n files,\n });\n }\n\n async truncateToCheckpoint(targetPromptIndex: number): Promise<number> {\n if (!this.filePath) return 0;\n const raw = await fsp.readFile(this.filePath, 'utf8');\n const lines = raw.split('\\n');\n const kept: string[] = [];\n let removedCount = 0;\n\n let targetCheckpointLine = -1;\n let afterTarget = false;\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!;\n if (!line.trim()) continue;\n\n let event: { type?: string; promptIndex?: number };\n try {\n event = JSON.parse(line);\n } catch {\n kept.push(line);\n continue;\n }\n\n if (event.type === 'checkpoint') {\n if ((event as { promptIndex: number }).promptIndex === targetPromptIndex) {\n targetCheckpointLine = kept.length;\n afterTarget = true;\n } else if ((event as { promptIndex: number }).promptIndex > targetPromptIndex) {\n afterTarget = true;\n }\n }\n\n if (event.promptIndex !== undefined && event.promptIndex > targetPromptIndex) {\n removedCount++;\n } else if (event.promptIndex === undefined) {\n if (!afterTarget || targetCheckpointLine === -1) {\n kept.push(line);\n } else {\n removedCount++;\n }\n } else {\n kept.push(line);\n }\n }\n\n const truncated = kept.join('\\n');\n // Windows EPERM fix: close the append-mode handle, write via temp file\n // and rename, then reopen. This is needed because rename() fails on\n // Windows when the target has an open file handle.\n const tmpPath = `${this.filePath}.rewind.tmp`;\n await fsp.writeFile(tmpPath, truncated + '\\n', 'utf8');\n try {\n await this.handle.close();\n await fsp.rename(tmpPath, this.filePath);\n // Re-open in append mode for continued use of this file.\n this.handle = await fsp.open(this.filePath, 'a', 0o600);\n } catch (err) {\n await fsp.unlink(tmpPath).catch(() => undefined);\n throw err;\n }\n\n await this.append({\n type: 'rewound',\n ts: new Date().toISOString(),\n toPromptIndex: targetPromptIndex,\n revertedFiles: [],\n });\n\n this.events?.emit('session.rewound', {\n toPromptIndex: targetPromptIndex,\n revertedFiles: [],\n removedEvents: removedCount,\n });\n\n return removedCount;\n }\n\n async clearSession(): Promise<void> {\n if (!this.filePath) return;\n const record = `${JSON.stringify({\n type: 'session_start',\n ts: new Date().toISOString(),\n id: this.id,\n model: this.meta.model ?? 'unknown',\n provider: this.meta.provider ?? 'unknown',\n })}\\n`;\n await fsp.writeFile(this.filePath, record, 'utf8');\n }\n\n /**\n * Idea #1 — write an in-flight marker. The agent loop should call\n * this at the start of each long-running operation; a matching\n * `clearInFlightMarker` follows on clean exit. A stale marker\n * (no end) is what `SessionRecovery.detectStale` looks for.\n */\n async writeInFlightMarker(context: string): Promise<void> {\n if (!context || context.length > 500) {\n throw new Error('In-flight context must be 1..500 chars');\n }\n await this.append({\n type: 'in_flight_start',\n ts: new Date().toISOString(),\n context,\n });\n this.events?.emit('in_flight.started', { context, ts: new Date().toISOString() });\n }\n\n /**\n * Idea #1 — close the in-flight marker. Idempotent in spirit\n * (you can call it after a successful iteration even if you\n * didn't open one this round) — but the session log records\n * every call so postmortem tooling can see \"the agent finished\n * cleanly X times, then died without finishing Y\".\n */\n async clearInFlightMarker(reason: 'clean' | 'aborted' | 'recovered'): Promise<void> {\n await this.append({\n type: 'in_flight_end',\n ts: new Date().toISOString(),\n reason,\n });\n this.events?.emit('in_flight.ended', { reason, ts: new Date().toISOString() });\n }\n}\n\nfunction userInputTitle(content: string | ContentBlock[]): string {\n const text =\n typeof content === 'string'\n ? content\n : content\n .filter((b): b is { type: 'text'; text: string } => b.type === 'text')\n .map((b) => b.text)\n .join(' ');\n return (text || '(non-text input)').slice(0, 60);\n}\n","import * as path from 'node:path';\nimport { DefaultSessionStore } from '../storage/session-store.js';\nimport type { SessionStore, SessionWriter } from '../types/session.js';\n\n/**\n * Per-subagent session factory.\n *\n * Director runs produce many parallel transcripts — one per spawned\n * subagent — and we want them all rooted under the same director-run\n * directory so a future `wstack replay <runId>` can rehydrate the whole\n * fleet from a single tree.\n *\n * The factory builds (or accepts) a `SessionStore` whose `dir` points at\n * `<sessionsRoot>/<directorRunId>/`, and returns a small `create()`\n * function that the orchestration layer calls per-spawn. Each call\n * yields a fresh `SessionWriter` whose JSONL file lives in that\n * directory, named by either the caller-supplied `subagentId` (preferred,\n * so the file name is human-readable) or a derived id.\n *\n * **Why a thin factory instead of plumbing options through every spawn\n * site?** Because the director is the only caller that needs this\n * isolation pattern, and shoving `sessionStore` options into\n * `SubagentConfig` would leak storage details into a config shape that\n * agents and the coordinator have no business knowing about.\n */\nexport interface DirectorSessionFactoryOptions {\n /**\n * Either a parent directory where `<directorRunId>/` will be created,\n * or a pre-built `SessionStore` whose `dir` already points at the\n * director run directory. Tests pass an in-memory store for isolation;\n * production code passes the path under `~/.wrongstack/sessions/`.\n */\n store?: SessionStore;\n sessionsRoot?: string;\n /**\n * Director run id — namespaces all subagent JSONLs under one folder.\n * Defaults to a timestamped id; supplied explicitly when resuming a\n * prior fleet manifest.\n */\n directorRunId?: string;\n}\n\nexport interface DirectorSessionFactory {\n /** Absolute directory where this director run's transcripts live. */\n readonly dir: string;\n /** The director run id used to namespace the directory. */\n readonly directorRunId: string;\n /**\n * Create a fresh `SessionWriter` for the named subagent. Each\n * subagent gets its own JSONL file. The writer's `id` matches the\n * supplied `subagentId` so disk paths line up with in-memory ids.\n */\n createSubagentSession(args: {\n subagentId: string;\n provider?: string;\n model?: string;\n title?: string;\n }): Promise<SessionWriter>;\n}\n\n/**\n * Build a `DirectorSessionFactory`. Pass either a pre-configured\n * `SessionStore` (tests) or a `sessionsRoot` path (production). When\n * neither is supplied the factory throws — there's no sane default for\n * \"where do these JSONLs live\".\n */\nexport function makeDirectorSessionFactory(\n opts: DirectorSessionFactoryOptions,\n): DirectorSessionFactory {\n const runId = opts.directorRunId ?? `${new Date().toISOString().replace(/[:.]/g, '-')}-director`;\n\n let store: SessionStore;\n let dir: string;\n if (opts.store) {\n // The caller wired its own store — we trust them on where the\n // files land. We can't introspect a `SessionStore`'s directory\n // without a typed accessor, so we report the run id and let the\n // caller record the path separately if needed.\n store = opts.store;\n dir = opts.sessionsRoot ? path.join(opts.sessionsRoot, runId) : '(caller-managed)';\n } else if (opts.sessionsRoot) {\n dir = path.join(opts.sessionsRoot, runId);\n store = new DefaultSessionStore({ dir });\n } else {\n throw new Error('makeDirectorSessionFactory requires either `store` or `sessionsRoot`');\n }\n\n return {\n dir,\n directorRunId: runId,\n async createSubagentSession({ subagentId, provider, model, title }) {\n // Per-subagent JSONL — DefaultSessionStore generates the file name\n // from the metadata `id`, so we pass `subagentId` directly to\n // keep disk artifacts human-readable.\n return store.create({\n id: subagentId,\n title: title ?? subagentId,\n provider: provider ?? 'unknown',\n model: model ?? 'unknown',\n });\n },\n };\n}\n","/**\n * Default auto-extend policy for subagent budgets.\n *\n * The budget's soft-limit path (`SubagentBudget` → `budget.threshold_reached`)\n * only negotiates an extension when SOMETHING listens on the EventBus. Under a\n * `Director`, that listener is the director's own auto-extend handler. On the\n * plain coordinator path (e.g. a bare `/spawn` with no director) nothing\n * listens, so the budget falls back to a hard stop and the subagent dies the\n * moment it crosses a soft limit.\n *\n * `attachAutoExtend` is the additive fix: wire it to a subagent's EventBus and\n * budget overruns are auto-granted headroom instead of killing the run. It is\n * heartbeat-aware for the timeout kind — wall-clock time always advances, so a\n * naive \"extend timeout forever\" would let a wedged agent run indefinitely.\n * Instead, a timeout extension is granted only when the agent has executed a\n * new tool call or started a new iteration since the last timeout extension.\n * No progress since last time ⇒ the agent is genuinely stuck ⇒ deny and let it\n * fail. The non-timeout kinds (iterations/tool_calls/tokens/cost) extend up to\n * a per-kind cap, then deny — those ceilings are the real runaway guard.\n */\nimport type { EventBus } from '../kernel/events.js';\n\nexport interface AutoExtendCeiling {\n maxIterations?: number;\n maxToolCalls?: number;\n maxTokens?: number;\n maxCostUsd?: number;\n timeoutMs?: number;\n}\n\nexport interface AutoExtendPolicy {\n /** Multiplier applied to the tripped limit when extending. Default 0.5 (+50%). */\n factor?: number;\n /**\n * Max extensions per NON-timeout kind before denying. Timeout is governed by\n * the heartbeat check, not this cap, so it can extend indefinitely while the\n * agent makes progress. Default 8.\n */\n maxExtensionsPerKind?: number;\n /** Absolute ceilings — an extension never pushes a limit past these. */\n ceiling?: AutoExtendCeiling;\n}\n\nconst DEFAULT_CEILING: Required<AutoExtendCeiling> = {\n maxIterations: 50_000,\n maxToolCalls: 100_000,\n maxTokens: 5_000_000,\n maxCostUsd: 100,\n timeoutMs: 24 * 60 * 60 * 1000,\n};\n\nconst FIELD_BY_KIND = {\n iterations: 'maxIterations',\n tool_calls: 'maxToolCalls',\n tokens: 'maxTokens',\n cost: 'maxCostUsd',\n timeout: 'timeoutMs',\n idle_timeout: 'timeoutMs',\n} as const;\n\n/**\n * Attach an auto-extend policy to a subagent's EventBus. Returns an unsubscribe\n * function that detaches all listeners — call it when the subagent task ends.\n */\nexport function attachAutoExtend(events: EventBus, policy: AutoExtendPolicy = {}): () => void {\n const factor = policy.factor ?? 0.5;\n const maxPerKind = policy.maxExtensionsPerKind ?? 8;\n const ceiling = { ...DEFAULT_CEILING, ...policy.ceiling };\n\n const extendCounts = new Map<string, number>();\n // Monotonic progress counter: tool executions + iteration starts. Used to\n // decide whether a timeout extension is warranted (progress) or the agent is\n // wedged (no progress since the last timeout grant).\n let progress = 0;\n let lastTimeoutProgress = -1;\n\n const unsubs: Array<() => void> = [\n events.on('tool.executed', () => {\n progress++;\n }),\n events.on('iteration.started', () => {\n progress++;\n }),\n events.on('budget.threshold_reached', (e) => {\n const { kind, limit, extend, deny } = e;\n\n if (kind === 'timeout' || kind === 'idle_timeout') {\n if (progress > lastTimeoutProgress) {\n lastTimeoutProgress = progress;\n const next = Math.min(Math.ceil(limit * (1 + factor)), ceiling.timeoutMs);\n extend({ timeoutMs: next });\n } else {\n // No new work since the last timeout extension — the agent is stuck.\n deny();\n }\n return;\n }\n\n const count = extendCounts.get(kind) ?? 0;\n if (count >= maxPerKind) {\n deny();\n return;\n }\n extendCounts.set(kind, count + 1);\n const field = FIELD_BY_KIND[kind];\n const cap = ceiling[field];\n const next = Math.min(Math.ceil(limit * (1 + factor)), cap);\n extend({ [field]: next });\n }),\n ];\n\n return () => {\n for (const u of unsubs) u();\n };\n}\n","import { FleetBus } from './fleet-bus.js';\n\n/**\n * A no-op FleetBus that discards all events. Used when no real fleet\n * bus is available (non-director mode) so the runner's `fleetBus`\n * field is always valid and the `attach()` call is always safe.\n *\n * One singleton instance is sufficient — it has no state to reset.\n */\nexport const NULL_FLEET_BUS = new FleetBus();\n","import * as fsp from 'node:fs/promises';\r\nimport * as path from 'node:path';\r\nimport { randomUUID } from 'node:crypto';\r\nimport { atomicWrite } from '../utils/atomic-write.js';\r\nimport { assignNickname } from './subagent-nicknames.js';\r\nimport type { SubagentConfig } from '../types/multi-agent.js';\r\nimport type { SessionWriter } from '../types/session.js';\r\nimport { DirectorStateCheckpoint } from '../storage/director-state.js';\r\nimport { FleetBus, FleetUsageAggregator } from './fleet-bus.js';\r\nimport type { FleetUsage } from './fleet-bus.js';\r\nimport type { IFleetManager } from './ifleet-manager.js';\r\nimport type { DefaultMultiAgentCoordinator } from './multi-agent-coordinator.js';\r\n\r\n/** Options for constructing a FleetManager. */\r\nexport interface FleetManagerOptions {\r\n manifestPath?: string;\r\n sessionsRoot?: string;\r\n directorRunId?: string;\r\n maxSpawns?: number;\r\n maxSpawnDepth?: number;\r\n spawnDepth?: number;\r\n stateCheckpointPath?: string;\r\n sessionWriter?: SessionWriter;\r\n manifestDebounceMs?: number;\r\n checkpointDebounceMs?: number;\r\n directorBudget?: { maxCostUsd?: number };\r\n /**\r\n * Maximum context load (as a fraction of maxContext) the leader agent\r\n * is allowed to reach before a new spawn is rejected. Default: 0.85.\r\n * When the leader's context pressure exceeds this threshold, spawning\r\n * a new subagent is refused — the leader must compact first.\r\n * Set to 1.0 to disable this check.\r\n */\r\n maxLeaderContextLoad?: number;\r\n /**\r\n * Provider's max context window in tokens. Used with `maxLeaderContextLoad`\r\n * to compute the absolute token threshold. Default: 128_000.\r\n *\r\n * A function may be supplied when the leader can switch models at runtime;\r\n * canSpawn() reads it lazily so the spawn threshold follows the active model.\r\n */\r\n maxContext?: number | (() => number | undefined);\r\n}\r\n\r\n/**\r\n * Fleet-level policy container extracted from `Director`. Owns:\r\n * - FleetBus + FleetUsageAggregator\r\n * - Spawn caps and counters\r\n * - Manifest entries and debounced writing\r\n * - State checkpointing\r\n *\r\n * This lets the `Director` focus on orchestration (spawn/assign/await/ask)\r\n * while fleet-level decisions live in one place. The class implements\r\n * `IFleetManager` so it remains swappable in future.\r\n *\r\n * @example\r\n * ```typescript\r\n * const fm = new FleetManager({ manifestPath: '/tmp/fleet.json' });\r\n * const err = fm.canSpawn({ name: 'worker' });\r\n * if (!err) fm.recordSpawn('sub-1', { name: 'worker' });\r\n * await fm.writeManifest();\r\n * ```\r\n */\r\nexport class FleetManager implements IFleetManager {\r\n /** The fleet-wide event bus. */\r\n readonly fleet: FleetBus;\r\n /** Usage rollup across all subagents. */\r\n readonly usage: FleetUsageAggregator;\r\n\r\n private readonly manifestPath?: string;\r\n private readonly directorRunId: string;\r\n /** Spawn cap (lifetime total). Infinity means unlimited. */\r\n readonly maxSpawns: number;\r\n /** Nesting cap. */\r\n readonly maxSpawnDepth: number;\r\n /** This director's depth in a director chain. Root = 0. */\r\n readonly spawnDepth: number;\r\n /** Live spawn counter. */\r\n private spawnCount = 0;\r\n private readonly stateCheckpoint: DirectorStateCheckpoint | null;\r\n private readonly sessionWriter: SessionWriter | null;\r\n private manifestTimer: NodeJS.Timeout | null = null;\r\n private readonly manifestDebounceMs: number;\r\n /** Fleet-wide cost cap. Infinity = no cap. Distinct from SubagentBudget limits,\r\n * which track per-subagent spend — this field caps the entire fleet total. */\r\n private readonly maxFleetCostUsd: number;\r\n private readonly manifestEntries = new Map<\r\n string,\r\n { subagentId: string; name: string; role?: string; provider?: string; model?: string; taskIds: string[] }\r\n >();\r\n /** Pending tasks with their descriptions — populated by `addPendingTask`\r\n * and cleared by `removePendingTask`. Replaces the host-side `pending`\r\n * Map so task descriptions live in one place (FleetManager). */\r\n private readonly pendingTasks = new Map<string, { subagentId: string; description: string }>();\r\n private readonly subagentMeta = new Map<string, { provider?: string; model?: string }>();\r\n private readonly priceLookups = new Map<string, { input?: number; output?: number; cacheRead?: number; cacheWrite?: number }>();\r\n /** Tracks which nickname keys are already assigned — prevents collisions. */\r\n private readonly _usedNicknames = new Set<string>();\r\n /** The coordinator (wired via setCoordinator by Director after construction). */\r\n private coordinator: DefaultMultiAgentCoordinator | null = null;\r\n /** Leader agent's current context pressure (full request tokens). */\r\n private leaderContextPressure = 0;\r\n /** Maximum context load fraction before spawn is refused. */\r\n private readonly maxLeaderContextLoad: number;\r\n /** Provider's max context window in tokens, or a live resolver for runtime model switches. */\r\n private readonly maxContext: number | (() => number | undefined);\r\n\r\n constructor(opts: FleetManagerOptions = {}) {\r\n this.manifestPath = opts.manifestPath;\r\n this.directorRunId = opts.directorRunId ?? randomUUID();\r\n this.maxSpawns = opts.maxSpawns ?? Number.POSITIVE_INFINITY;\r\n this.maxSpawnDepth = opts.maxSpawnDepth ?? 2;\r\n this.spawnDepth = opts.spawnDepth ?? 0;\r\n this.sessionWriter = opts.sessionWriter ?? null;\r\n this.manifestDebounceMs = opts.manifestDebounceMs ?? 2000;\r\n this.maxFleetCostUsd = opts.directorBudget?.maxCostUsd ?? Number.POSITIVE_INFINITY;\r\n this.maxLeaderContextLoad = opts.maxLeaderContextLoad ?? 0.85;\r\n this.maxContext = opts.maxContext ?? 128_000;\r\n this.stateCheckpoint = opts.stateCheckpointPath\r\n ? new DirectorStateCheckpoint(\r\n opts.stateCheckpointPath,\r\n {\r\n directorRunId: this.directorRunId,\r\n maxSpawns: opts.maxSpawns,\r\n spawnDepth: this.spawnDepth,\r\n maxSpawnDepth: this.maxSpawnDepth,\r\n directorBudget: opts.directorBudget,\r\n },\r\n opts.checkpointDebounceMs ?? 250,\r\n )\r\n : null;\r\n\r\n this.fleet = new FleetBus();\r\n this.usage = new FleetUsageAggregator(\r\n this.fleet,\r\n (_id, provider, model) => {\r\n if (provider && model) return this.priceLookups.get(`${provider}/${model}`);\r\n return undefined;\r\n },\r\n (id) => this.subagentMeta.get(id),\r\n );\r\n }\r\n\r\n // -----------------------------------------------------------------------\r\n // IFleetManager surface\r\n // -----------------------------------------------------------------------\r\n\r\n get fleetBus(): FleetBus {\r\n return this.fleet;\r\n }\r\n\r\n /**\r\n * Wire the coordinator after Director construction. The coordinator\r\n * is not available when FleetManager is constructed standalone.\r\n * Once set, `getFleetStats()` delegates to `coordinator.getStats()`.\r\n */\r\n setCoordinator(coordinator: DefaultMultiAgentCoordinator): void {\r\n this.coordinator = coordinator;\r\n }\r\n\r\n snapshot(): FleetUsage {\r\n return this.usage.snapshot();\r\n }\r\n\r\n getSubagentMeta(id: string): { provider?: string; model?: string; name?: string } | undefined {\r\n const meta = this.subagentMeta.get(id);\r\n const manifest = this.manifestEntries.get(id);\r\n if (!meta && !manifest) return undefined;\r\n return {\r\n provider: meta?.provider ?? manifest?.provider,\r\n model: meta?.model ?? manifest?.model,\r\n name: manifest?.name,\r\n };\r\n }\r\n\r\n /**\r\n * Returns null if the spawn is allowed, or an object describing\r\n * which cap was exceeded. Does NOT throw — the caller decides\r\n * how to surface the rejection.\r\n */\r\n canSpawn(_config: SubagentConfig): { kind: 'max_spawns' | 'max_spawn_depth' | 'max_cost_usd' | 'max_context_load'; limit: number; observed: number } | null {\r\n if (this.spawnDepth >= this.maxSpawnDepth) {\r\n return { kind: 'max_spawn_depth', limit: this.maxSpawnDepth, observed: this.spawnDepth };\r\n }\r\n if (this.spawnCount >= this.maxSpawns) {\r\n return { kind: 'max_spawns', limit: this.maxSpawns, observed: this.spawnCount + 1 };\r\n }\r\n if (this.maxFleetCostUsd < Number.POSITIVE_INFINITY) {\r\n const totalCost = this.usage.snapshot().total?.cost ?? 0;\r\n if (totalCost >= this.maxFleetCostUsd) {\r\n return { kind: 'max_cost_usd', limit: this.maxFleetCostUsd, observed: totalCost };\r\n }\r\n }\r\n // Context pressure check: reject spawn if leader context is too full.\r\n // maxLeaderContextLoad === 1.0 disables this check.\r\n if (this.maxLeaderContextLoad < 1.0) {\r\n const maxContext = this.resolveMaxContext();\r\n const threshold = maxContext * this.maxLeaderContextLoad;\r\n if (this.leaderContextPressure >= threshold) {\r\n return {\r\n kind: 'max_context_load',\r\n limit: threshold,\r\n observed: this.leaderContextPressure,\r\n };\r\n }\r\n }\r\n return null;\r\n }\r\n\r\n setLeaderContextPressure(tokens: number): void {\r\n this.leaderContextPressure = tokens;\r\n }\r\n\r\n private resolveMaxContext(): number {\r\n const resolved =\r\n typeof this.maxContext === 'function' ? this.maxContext() : this.maxContext;\r\n return resolved && resolved > 0 ? resolved : 128_000;\r\n }\r\n\r\n /**\r\n * Assign a memorable nickname (e.g. \"Einstein (Bug Hunter)\") to the config,\r\n * record it so the same name is never reused, then record the spawn.\r\n *\r\n * Call this INSTEAD of `recordSpawn` when you want automatic nicknames.\r\n * The nickname is written back to `config.name` BEFORE the coordinator\r\n * sees the config, so the manifest, logs, and fleet UI all show it.\r\n *\r\n * NOTE: This method ONLY assigns the nickname and marks it used.\r\n * The caller MUST call `recordSpawn(subagentId, config, priceLookup)` AFTER\r\n * `coordinator.spawn()` returns with the real subagentId. This is because\r\n * the subagentId is not known until after the coordinator creates the subagent.\r\n */\r\n assignNicknameAndRecord(\r\n config: SubagentConfig,\r\n ): string {\r\n const role = config.role ?? 'subagent';\r\n const nickname = assignNickname(role, this._usedNicknames);\r\n // Extract the base key (e.g. \"einstein\") from the pool to mark it used.\r\n const baseKey = nickname.split(' ')[0]!.toLowerCase().replace(/[^a-z0-9-]/g, '-');\r\n this._usedNicknames.add(baseKey);\r\n // Write the full nickname back into config so the coordinator\r\n // and manifest both see the human name.\r\n config.name = nickname;\r\n return nickname;\r\n }\r\n\r\n /**\r\n * Returns the set of already-assigned nickname keys — useful for debugging\r\n * and testing.\r\n */\r\n get usedNicknames(): ReadonlySet<string> {\r\n return this._usedNicknames;\r\n }\r\n\r\n /**\r\n * Records a spawn: increments counter, stores metadata, updates state checkpoint,\r\n * and schedules a debounced manifest write. Call AFTER the coordinator\r\n * has successfully spawned the subagent.\r\n *\r\n * @param subagentId The subagent's id (from coordinator.spawn result)\r\n * @param config The SubagentConfig that was used\r\n * @param priceLookup Optional per-subagent pricing data\r\n */\r\n recordSpawn(\r\n subagentId: string,\r\n config: SubagentConfig,\r\n priceLookup?: { input?: number; output?: number; cacheRead?: number; cacheWrite?: number },\r\n ): void {\r\n this.spawnCount += 1;\r\n this.subagentMeta.set(subagentId, {\r\n provider: config.provider,\r\n model: config.model,\r\n });\r\n if (priceLookup && config.provider && config.model) {\r\n this.priceLookups.set(`${config.provider}/${config.model}`, priceLookup);\r\n }\r\n this.manifestEntries.set(subagentId, {\r\n subagentId,\r\n name: config.name,\r\n role: config.role,\r\n provider: config.provider,\r\n model: config.model,\r\n taskIds: [],\r\n });\r\n // State checkpoint: persist the spawn even before any task is assigned\r\n this.stateCheckpoint?.recordSpawn({\r\n id: subagentId,\r\n name: config.name,\r\n role: config.role,\r\n provider: config.provider,\r\n model: config.model,\r\n spawnedAt: new Date().toISOString(),\r\n }, this.spawnCount);\r\n void this.appendSessionEvent({\r\n type: 'agent_spawned',\r\n ts: new Date().toISOString(),\r\n agentId: subagentId,\r\n role: config.role ?? config.name,\r\n });\r\n this.scheduleManifest();\r\n }\r\n\r\n async writeManifest(): Promise<string | null> {\r\n if (!this.manifestPath) return null;\r\n const manifest = {\r\n version: 1,\r\n directorRunId: this.directorRunId,\r\n generatedAt: new Date().toISOString(),\r\n children: Array.from(this.manifestEntries.values()).map((entry) => ({\r\n id: entry.subagentId,\r\n name: entry.name,\r\n role: entry.role,\r\n provider: entry.provider,\r\n model: entry.model,\r\n taskIds: entry.taskIds,\r\n })),\r\n usage: this.usage.snapshot(),\r\n };\r\n await fsp.mkdir(path.dirname(this.manifestPath), { recursive: true });\r\n await atomicWrite(this.manifestPath, JSON.stringify(manifest, null, 2), { mode: 0o600 });\r\n return this.manifestPath;\r\n }\r\n\r\n /**\r\n * Attach task ids to an already-spawned subagent. Called by\r\n * `Director.assign()` after the coordinator assigns a task.\r\n */\r\n addTaskToSubagent(subagentId: string, taskId: string): void {\r\n const entry = this.manifestEntries.get(subagentId);\r\n if (entry) entry.taskIds.push(taskId);\r\n }\r\n\r\n /**\r\n * Debounced manifest write. Call after any state mutation\r\n * (spawn, assign, complete) so a burst collapses into one write.\r\n * When `manifestDebounceMs` is 0, writes are synchronous (no debounce).\r\n */\r\n scheduleManifest(): void {\r\n if (!this.manifestPath) return;\r\n if (this.manifestDebounceMs === 0) {\r\n // 0 means instant flush — write synchronously, no timer.\r\n void this.writeManifest().catch((err) => {\r\n const detail = err instanceof Error ? err.message : String(err);\r\n process.emitWarning(\r\n `FleetManager manifest write failed: ${detail}`,\r\n 'FleetManagerWarning',\r\n );\r\n });\r\n return;\r\n }\r\n if (this.manifestDebounceMs < 0) return;\r\n if (this.manifestTimer) return;\r\n this.manifestTimer = setTimeout(() => {\r\n this.manifestTimer = null;\r\n void this.writeManifest().catch((err) => {\r\n // Surface via process.emitWarning so a persistent manifest-write\r\n // failure doesn't get silently swallowed (e.g. ENOSPC on the\r\n // sessions dir would otherwise leave fleet state un-persisted with\r\n // no signal until shutdown).\r\n const detail = err instanceof Error ? err.message : String(err);\r\n process.emitWarning(\r\n `FleetManager manifest write failed: ${detail}`,\r\n 'FleetManagerWarning',\r\n );\r\n });\r\n }, this.manifestDebounceMs);\r\n }\r\n\r\n /**\r\n * Bypass the debounce timer and write the manifest immediately.\r\n * Clears any pending debounce timer before writing.\r\n */\r\n async flushManifest(): Promise<void> {\r\n if (!this.manifestPath) return;\r\n if (this.manifestTimer) {\r\n clearTimeout(this.manifestTimer);\r\n this.manifestTimer = null;\r\n }\r\n await this.writeManifest().catch((err) => {\r\n const detail = err instanceof Error ? err.message : String(err);\r\n process.emitWarning(\r\n `FleetManager manifest write failed: ${detail}`,\r\n 'FleetManagerWarning',\r\n );\r\n });\r\n }\r\n\r\n /** Best-effort session event writer. Swallows failures. */\r\n private async appendSessionEvent(event: Parameters<SessionWriter['append']>[0]): Promise<void> {\r\n if (!this.sessionWriter) return;\r\n try {\r\n await this.sessionWriter.append(event);\r\n } catch {\r\n // ignore\r\n }\r\n }\r\n\r\n // -----------------------------------------------------------------------\r\n // Pending task management — eliminates host-side state duplication\r\n // -----------------------------------------------------------------------\r\n\r\n addPendingTask(taskId: string, subagentId: string, description: string): void {\r\n this.pendingTasks.set(taskId, { subagentId, description });\r\n }\r\n\r\n removePendingTask(taskId: string): void {\r\n this.pendingTasks.delete(taskId);\r\n }\r\n\r\n getFleetStats(): {\r\n total: number;\r\n running: number;\r\n idle: number;\r\n stopped: number;\r\n inFlight: number;\r\n pending: number;\r\n completed: number;\r\n subagentStatuses: { subagentId: string; taskId: string; status: string; assigned: boolean }[];\r\n } {\r\n if (!this.coordinator) {\r\n return {\r\n total: 0, running: 0, idle: 0, stopped: 0,\r\n inFlight: 0, pending: 0, completed: 0,\r\n subagentStatuses: [],\r\n };\r\n }\r\n const stats = this.coordinator.getStats();\r\n const subagentStatuses: { subagentId: string; taskId: string; status: string; assigned: boolean }[] = [];\r\n for (const [subagentId, s] of this.coordinator['subagents']) {\r\n subagentStatuses.push({\r\n subagentId,\r\n taskId: s.currentTask ?? '',\r\n status: s.status,\r\n assigned: s.context.parentBridge !== null,\r\n });\r\n }\r\n return { ...stats, subagentStatuses };\r\n }\r\n\r\n getFleetStatus(): {\r\n pending: { taskId: string; description: string; subagentId: string }[];\r\n live: { subagentId: string; status: string; task?: string }[];\r\n } {\r\n const pending = Array.from(this.pendingTasks.entries()).map(([taskId, v]) => ({\r\n taskId,\r\n description: v.description,\r\n subagentId: v.subagentId,\r\n }));\r\n // live is populated by MultiAgentHost from the coordinator — fleet\r\n // manager has no direct visibility into subagent status\r\n return { pending, live: [] };\r\n }\r\n\r\n /**\r\n * Clean up all fleet-manager state associated with a removed subagent:\r\n * - Frees the nickname slot so the same name can be reused\r\n * - Removes any pending tasks for this subagent\r\n */\r\n removeSubagent(subagentId: string): void {\r\n // Free the nickname slot so the same name can be reused.\r\n const entry = this.manifestEntries.get(subagentId);\r\n if (entry?.name) {\r\n const nicknameKey = entry.name.split(' ')[0]!.toLowerCase().replace(/[^a-z0-9-]/g, '-');\r\n this._usedNicknames.delete(nicknameKey);\r\n }\r\n // Remove any pending tasks assigned to this subagent.\r\n for (const [taskId, task] of this.pendingTasks) {\r\n if (task.subagentId === subagentId) {\r\n this.pendingTasks.delete(taskId);\r\n }\r\n }\r\n }\r\n\r\n /** Release all resources: clear the manifest debounce timer and dispose the usage aggregator. */\r\n dispose(): void {\r\n if (this.manifestTimer) {\r\n clearTimeout(this.manifestTimer);\r\n this.manifestTimer = null;\r\n }\r\n this.usage.dispose();\r\n }\r\n}"]}
|