@wrongstack/core 0.1.10 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/dist/{agent-bridge-6KPqsFx6.d.ts → agent-bridge-C3DUGjSb.d.ts} +1 -1
  2. package/dist/{compactor-B4mQZXf2.d.ts → compactor-BUU6Zm_3.d.ts} +1 -1
  3. package/dist/{config-BU9f_5yH.d.ts → config-CKLYPkCi.d.ts} +1 -1
  4. package/dist/{context-BmM2xGUZ.d.ts → context-IovtuTf8.d.ts} +10 -0
  5. package/dist/coordination/index.d.ts +211 -13
  6. package/dist/coordination/index.js +964 -67
  7. package/dist/coordination/index.js.map +1 -1
  8. package/dist/defaults/index.d.ts +33 -18
  9. package/dist/defaults/index.js +1273 -42
  10. package/dist/defaults/index.js.map +1 -1
  11. package/dist/{events-BMNaEFZl.d.ts → events-CNB9PALO.d.ts} +99 -1
  12. package/dist/execution/index.d.ts +12 -12
  13. package/dist/extension/index.d.ts +9 -0
  14. package/dist/extension/index.js +234 -0
  15. package/dist/extension/index.js.map +1 -0
  16. package/dist/index-BDb0cAMP.d.ts +806 -0
  17. package/dist/index.d.ts +112 -29
  18. package/dist/index.js +2036 -490
  19. package/dist/index.js.map +1 -1
  20. package/dist/infrastructure/index.d.ts +6 -6
  21. package/dist/kernel/index.d.ts +12 -9
  22. package/dist/kernel/index.js +73 -7
  23. package/dist/kernel/index.js.map +1 -1
  24. package/dist/{mcp-servers-Dzgg4x1w.d.ts → mcp-servers-DR35ojJZ.d.ts} +3 -3
  25. package/dist/models/index.d.ts +2 -2
  26. package/dist/models/index.js +24 -1
  27. package/dist/models/index.js.map +1 -1
  28. package/dist/{multi-agent-fmkRHtof.d.ts → multi-agent-B9a6sflH.d.ts} +71 -3
  29. package/dist/observability/index.d.ts +2 -2
  30. package/dist/{path-resolver-DBjaoXFq.d.ts → path-resolver-Cl_q0u-R.d.ts} +2 -2
  31. package/dist/provider-runner-BXuADQqQ.d.ts +36 -0
  32. package/dist/sdd/index.d.ts +3 -3
  33. package/dist/{secret-scrubber-CicHLN4G.d.ts → secret-scrubber-CgG2tV2B.d.ts} +1 -1
  34. package/dist/{secret-scrubber-DF88luOe.d.ts → secret-scrubber-Cuy5afaQ.d.ts} +1 -1
  35. package/dist/security/index.d.ts +20 -4
  36. package/dist/security/index.js +37 -2
  37. package/dist/security/index.js.map +1 -1
  38. package/dist/{selector-BbJqiEP4.d.ts → selector-wT2fv9Fg.d.ts} +1 -1
  39. package/dist/{session-reader-Drq8RvJu.d.ts → session-reader-CcPi4BQ8.d.ts} +1 -1
  40. package/dist/{skill-DhfSizKv.d.ts → skill-C_7znCIC.d.ts} +2 -2
  41. package/dist/storage/index.d.ts +164 -6
  42. package/dist/storage/index.js +297 -2
  43. package/dist/storage/index.js.map +1 -1
  44. package/dist/{renderer-rk_1Swwc.d.ts → system-prompt-Dk1qm8ey.d.ts} +30 -2
  45. package/dist/{tool-executor-CpuJPYm9.d.ts → tool-executor-DKu4A6nB.d.ts} +5 -5
  46. package/dist/types/index.d.ts +16 -16
  47. package/dist/types/index.js +24 -1
  48. package/dist/types/index.js.map +1 -1
  49. package/dist/utils/index.d.ts +1 -1
  50. package/dist/utils/index.js +24 -1
  51. package/dist/utils/index.js.map +1 -1
  52. package/package.json +5 -1
  53. package/dist/plugin-DJk6LL8B.d.ts +0 -434
  54. package/dist/system-prompt-BC_8ypCG.d.ts +0 -23
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/coordination/in-memory-transport.ts","../../src/coordination/agent-bridge.ts","../../src/coordination/director-prompts.ts","../../src/coordination/fleet-bus.ts","../../src/coordination/subagent-budget.ts","../../src/coordination/multi-agent-coordinator.ts","../../src/coordination/director.ts","../../src/coordination/agent-subagent-runner.ts","../../src/utils/atomic-write.ts","../../src/storage/session-store.ts","../../src/coordination/director-session.ts","../../src/coordination/fleet.ts"],"names":["handlers","randomUUID","fsp","path","fs","randomBytes","stat","path4"],"mappings":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AAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA,oDAAA,CAAA;AAAA,EAoCR,aAAA,EAAe,EAAA;AAAA,EACf,YAAA,EAAc,GAAA;AAAA,EACd,SAAA,EAAW;AACb;AAMO,IAAM,sBAAA,GAAyC;AAAA,EACpD,EAAA,EAAI,kBAAA;AAAA,EACJ,IAAA,EAAM,kBAAA;AAAA,EACN,IAAA,EAAM,kBAAA;AAAA,EACN,MAAA,EAAQ,CAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA,qEAAA,CAAA;AAAA,EA4CR,aAAA,EAAe,EAAA;AAAA,EACf,YAAA,EAAc,GAAA;AAAA,EACd,SAAA,EAAW;AACb;AAGO,IAAM,YAAA,GAA+C;AAAA,EAC1D,WAAA,EAAa,eAAA;AAAA,EACb,YAAA,EAAc,gBAAA;AAAA,EACd,kBAAA,EAAoB,sBAAA;AAAA,EACpB,kBAAA,EAAoB;AACtB;AAGO,IAAM,gBAAA,GAAmB,MAAA,CAAO,MAAA,CAAO,YAAY","file":"index.js","sourcesContent":["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\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.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 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 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 }\n this.pendingRequests.clear();\n this.inflightGuards.clear();\n this.subscriptions.clear();\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 * 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`;\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","import type { EventBus } from '../kernel/events.js';\n\n/**\n * Single fleet-wide event with subagent attribution. Whatever a child\n * agent emits on its own EventBus gets re-published here, prefixed with\n * `subagentId` so a single subscriber can multiplex across the fleet.\n *\n * The director uses `FleetBus.filter('tool.executed', …)` to see every\n * tool call across the fleet; the TUI uses\n * `FleetBus.subscribe(id, handler)` to render a per-subagent panel.\n */\nexport interface FleetEvent {\n subagentId: string;\n taskId?: string;\n ts: number;\n type: string;\n payload: unknown;\n}\n\nexport type FleetHandler = (event: FleetEvent) => void;\n\n/**\n * Fan-in for per-subagent EventBuses. Each subagent's bus is plugged in\n * via `attach()`; the FleetBus re-emits every event with subagent\n * attribution. Detachment is automatic via the returned disposer — call\n * it when a subagent terminates so we don't leak listeners.\n *\n * The bus exposes two subscription modes: by `subagentId` (everything\n * from one child) and by `type` (one event-type across the fleet). They\n * compose — if you need a per-subagent + per-type slice, subscribe by\n * type and filter on `event.subagentId` in your handler.\n */\nexport class FleetBus {\n private readonly byId = new Map<string, Set<FleetHandler>>();\n private readonly byType = new Map<string, Set<FleetHandler>>();\n private readonly any = new Set<FleetHandler>();\n\n /**\n * Hook a subagent's EventBus into the fleet. EventBus is strongly\n * typed and doesn't expose an `onAny` hook, so we subscribe to the\n * canonical set of event types a subagent emits during a run. New\n * event types added to the kernel must be added here too — but the\n * cost is a tiny single line per type, and the explicit list keeps\n * the wire format clear.\n *\n * Returns a disposer that detaches every subscription; call on\n * subagent teardown so the listeners don't outlive the run.\n */\n attach(subagentId: string, bus: EventBus, taskId?: string): () => void {\n const FORWARDED_TYPES = [\n 'tool.started',\n 'tool.executed',\n 'tool.progress',\n 'tool.confirm_needed',\n 'iteration.started',\n 'iteration.completed',\n 'provider.text_delta',\n 'provider.response',\n 'provider.retry',\n 'provider.error',\n 'session.started',\n 'session.ended',\n 'session.damaged',\n 'compaction.fired',\n 'compaction.failed',\n 'token.threshold',\n ] as const;\n const offs: Array<() => void> = [];\n for (const t of FORWARDED_TYPES) {\n offs.push(\n bus.on(t, (payload: unknown) => {\n this.emit({ subagentId, taskId, ts: Date.now(), type: t, payload });\n }),\n );\n }\n return () => {\n for (const off of offs) off();\n };\n }\n\n /** Subscribe to every event from one subagent. */\n subscribe(subagentId: string, handler: FleetHandler): () => void {\n let set = this.byId.get(subagentId);\n if (!set) {\n set = new Set();\n this.byId.set(subagentId, set);\n }\n set.add(handler);\n return () => {\n set!.delete(handler);\n };\n }\n\n /** Subscribe to one event type across all subagents. */\n filter(type: string, handler: FleetHandler): () => void {\n let set = this.byType.get(type);\n if (!set) {\n set = new Set();\n this.byType.set(type, set);\n }\n set.add(handler);\n return () => {\n set!.delete(handler);\n };\n }\n\n /** Subscribe to literally everything. The fleet roll-up uses this. */\n onAny(handler: FleetHandler): () => void {\n this.any.add(handler);\n return () => {\n this.any.delete(handler);\n };\n }\n\n emit(event: FleetEvent): void {\n // Each fan-out is best-effort — a misbehaving handler must not\n // bring down the bus or other handlers. Errors are swallowed\n // (matching the rest of the project's listener-error policy).\n const byId = this.byId.get(event.subagentId);\n if (byId)\n for (const h of byId) {\n try {\n h(event);\n } catch {\n /* ignore */\n }\n }\n const byType = this.byType.get(event.type);\n if (byType)\n for (const h of byType) {\n try {\n h(event);\n } catch {\n /* ignore */\n }\n }\n for (const h of this.any) {\n try {\n h(event);\n } catch {\n /* ignore */\n }\n }\n }\n}\n\n/**\n * Roll-up of token usage + cost across an entire director run. The\n * director's `fleet_status` tool returns this so the model can reason\n * about budget in its next turn (\"the researcher already burned $0.40,\n * lean on summaries for the next task\").\n */\nexport interface FleetUsage {\n total: {\n input: number;\n output: number;\n cacheRead: number;\n cacheWrite: number;\n cost: number;\n };\n perSubagent: Record<string, SubagentUsageSnapshot>;\n}\n\nexport interface SubagentUsageSnapshot {\n subagentId: string;\n provider?: string;\n model?: string;\n input: number;\n output: number;\n cacheRead: number;\n cacheWrite: number;\n cost: number;\n toolCalls: number;\n iterations: number;\n startedAt: number;\n lastEventAt: number;\n}\n\n/**\n * Aggregates provider.response + tool.executed events from the FleetBus\n * into a live `FleetUsage` snapshot. Costs are computed by the caller\n * via a `priceLookup(subagentId)` so we don't bake provider-pricing\n * coupling into core; the CLI/tests supply a function that resolves\n * each subagent's per-token rates from the models registry.\n */\nexport class FleetUsageAggregator {\n private readonly perSubagent = new Map<string, SubagentUsageSnapshot>();\n private readonly total = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };\n\n constructor(\n private readonly bus: FleetBus,\n private readonly priceLookup?: (\n subagentId: string,\n ) => { input?: number; output?: number; cacheRead?: number; cacheWrite?: number } | undefined,\n private readonly metaLookup?: (\n subagentId: string,\n ) => { provider?: string; model?: string } | undefined,\n ) {\n bus.filter('provider.response', (e) => this.onProviderResponse(e));\n bus.filter('tool.executed', (e) => this.onToolExecuted(e));\n bus.filter('iteration.started', (e) => this.onIterationStarted(e));\n }\n\n /** Live snapshot — safe to call from a tool's execute() body. */\n snapshot(): FleetUsage {\n return {\n total: { ...this.total },\n perSubagent: Object.fromEntries(\n Array.from(this.perSubagent.entries()).map(([k, v]) => [k, { ...v }]),\n ),\n };\n }\n\n private ensure(subagentId: string): SubagentUsageSnapshot {\n let snap = this.perSubagent.get(subagentId);\n if (!snap) {\n const meta = this.metaLookup?.(subagentId);\n snap = {\n subagentId,\n provider: meta?.provider,\n model: meta?.model,\n input: 0,\n output: 0,\n cacheRead: 0,\n cacheWrite: 0,\n cost: 0,\n toolCalls: 0,\n iterations: 0,\n startedAt: Date.now(),\n lastEventAt: Date.now(),\n };\n this.perSubagent.set(subagentId, snap);\n }\n return snap;\n }\n\n private onProviderResponse(e: FleetEvent): void {\n const snap = this.ensure(e.subagentId);\n const p = e.payload as {\n usage?: { input?: number; output?: number; cacheRead?: number; cacheWrite?: number };\n };\n const usage = p?.usage;\n if (!usage) return;\n snap.input += usage.input ?? 0;\n snap.output += usage.output ?? 0;\n snap.cacheRead += usage.cacheRead ?? 0;\n snap.cacheWrite += usage.cacheWrite ?? 0;\n this.total.input += usage.input ?? 0;\n this.total.output += usage.output ?? 0;\n this.total.cacheRead += usage.cacheRead ?? 0;\n this.total.cacheWrite += usage.cacheWrite ?? 0;\n const price = this.priceLookup?.(e.subagentId);\n if (price) {\n const delta =\n ((usage.input ?? 0) / 1_000_000) * (price.input ?? 0) +\n ((usage.output ?? 0) / 1_000_000) * (price.output ?? 0) +\n ((usage.cacheRead ?? 0) / 1_000_000) * (price.cacheRead ?? 0) +\n ((usage.cacheWrite ?? 0) / 1_000_000) * (price.cacheWrite ?? 0);\n snap.cost += delta;\n this.total.cost += delta;\n }\n snap.lastEventAt = e.ts;\n }\n\n private onToolExecuted(e: FleetEvent): void {\n const snap = this.ensure(e.subagentId);\n snap.toolCalls += 1;\n snap.lastEventAt = e.ts;\n }\n\n private onIterationStarted(e: FleetEvent): void {\n const snap = this.ensure(e.subagentId);\n snap.iterations += 1;\n snap.lastEventAt = e.ts;\n }\n}\n","import type { Usage } from '../types/provider.js';\n\nexport type BudgetKind = 'tool_calls' | 'iterations' | 'tokens' | '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 /** Wall-clock timeout from start() to checkTimeout(). */\n timeoutMs?: number;\n}\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 * 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: `record*` methods throw `BudgetExceededError` synchronously the\n * moment a limit is crossed. The caller (runner/coordinator) catches this and\n * marks the task as 'failed' with the budget kind, so the operator can see\n * exactly which ceiling tripped.\n *\n * Timeout note: `checkTimeout()` is a cooperative guard called by the\n * runner on each iteration loop. The coordinator additionally enforces a\n * hard wall-clock deadline via `Promise.race` in `executeWithTimeout`.\n * Both mechanisms throw `BudgetExceededError` ('timeout') — the runner's\n * check is best-effort (catches cases where the runner loop doesn't call it)\n * and the coordinator's race is the authoritative cutoff. The two are\n * intentionally independent; they converge on the same error type so\n * `runDispatched` handles both identically.\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 constructor(limits: BudgetLimits = {}) {\n this.limits = Object.freeze({ ...limits });\n }\n\n start(): void {\n this.startTime = Date.now();\n }\n\n recordIteration(): void {\n this.iterations++;\n if (this.limits.maxIterations !== undefined && this.iterations > this.limits.maxIterations) {\n throw new BudgetExceededError('iterations', this.limits.maxIterations, this.iterations);\n }\n }\n\n recordToolCall(): void {\n this.toolCalls++;\n if (this.limits.maxToolCalls !== undefined && this.toolCalls > this.limits.maxToolCalls) {\n throw new BudgetExceededError('tool_calls', this.limits.maxToolCalls, this.toolCalls);\n }\n }\n\n recordUsage(usage: Usage, costUsd = 0): void {\n this.tokenInput += usage.input;\n this.tokenOutput += usage.output;\n this.costUsd += costUsd;\n\n const totalTokens = this.tokenInput + this.tokenOutput;\n if (this.limits.maxTokens !== undefined && totalTokens > this.limits.maxTokens) {\n throw new BudgetExceededError('tokens', this.limits.maxTokens, totalTokens);\n }\n if (this.limits.maxCostUsd !== undefined && this.costUsd > this.limits.maxCostUsd) {\n throw new BudgetExceededError('cost', this.limits.maxCostUsd, this.costUsd);\n }\n }\n\n /**\n * Throws if the wall-clock budget is exhausted. Call this from the iteration\n * loop so a hung tool can't keep a subagent running past its deadline.\n */\n checkTimeout(): void {\n if (this.startTime === null || this.limits.timeoutMs === undefined) return;\n const elapsed = Date.now() - this.startTime;\n if (elapsed > this.limits.timeoutMs) {\n throw new BudgetExceededError('timeout', this.limits.timeoutMs, elapsed);\n }\n }\n\n /** Returns true if a timeout has occurred without throwing. Useful for races. */\n isTimedOut(): boolean {\n if (this.startTime === null || this.limits.timeoutMs === undefined) return false;\n return Date.now() - this.startTime > this.limits.timeoutMs;\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","import { randomUUID } from 'node:crypto';\nimport { EventEmitter } from 'node:events';\nimport type { AgentBridge, BridgeMessage } from '../types/agent-bridge.js';\nimport type {\n CoordinatorStatus,\n MultiAgentConfig,\n MultiAgentCoordinator,\n SpawnResult,\n SubagentConfig,\n SubagentContext,\n SubagentRunContext,\n SubagentRunner,\n TaskResult,\n TaskSpec,\n} from '../types/multi-agent.js';\nimport { BudgetExceededError, SubagentBudget } from './subagent-budget.js';\n\ntype SubagentStatus = 'running' | 'idle' | 'stopped' | 'error';\n\ninterface SubagentEntry {\n config: SubagentConfig;\n context: SubagentContext;\n status: SubagentStatus;\n currentTask?: string;\n abortController: AbortController;\n /** Lazily created on first dispatch — budget is per-task, not per-subagent. */\n activeBudget?: SubagentBudget;\n}\n\nexport interface MultiAgentCoordinatorOptions {\n /**\n * Callback that executes a task on behalf of a subagent. Required for\n * `assign()` to actually run anything — without it, tasks queue forever.\n * The coordinator provides per-subagent isolation (own budget, own signal,\n * own bridge) and enforces timeout + concurrency.\n */\n runner?: SubagentRunner;\n}\n\nexport class DefaultMultiAgentCoordinator extends EventEmitter implements MultiAgentCoordinator {\n readonly coordinatorId: string;\n readonly config: MultiAgentConfig;\n private readonly runner?: SubagentRunner;\n\n private readonly subagents = new Map<string, SubagentEntry>();\n\n private pendingTasks: TaskSpec[] = [];\n private completedResults: TaskResult[] = [];\n private totalIterations = 0;\n private inFlight = 0;\n\n constructor(config: MultiAgentConfig, options: MultiAgentCoordinatorOptions = {}) {\n super();\n this.coordinatorId = config.coordinatorId;\n this.config = config;\n this.runner = options.runner;\n }\n\n async spawn(subagent: SubagentConfig): Promise<SpawnResult> {\n const id = subagent.id || randomUUID();\n const context: SubagentContext = {\n subagentId: id,\n tasks: [],\n // Wired later by the caller via setSubagentBridge() once the\n // bidirectional bridge is created. Readers must null-check / use\n // hasParentBridge() — the type now reflects this.\n parentBridge: null,\n doneCondition: this.config.doneCondition,\n maxConcurrent: this.config.maxConcurrent ?? 4,\n };\n\n this.subagents.set(id, {\n config: { ...subagent, id },\n context,\n status: 'idle',\n abortController: new AbortController(),\n });\n\n this.emit('subagent.started', { subagent: { ...subagent, id } });\n\n return { subagentId: id, agentId: id };\n }\n\n async assign(task: TaskSpec): Promise<void> {\n this.pendingTasks.push(task);\n this.tryDispatchNext();\n }\n\n async delegate(to: string, msg: BridgeMessage): Promise<void> {\n const subagent = this.subagents.get(to);\n if (!subagent) throw new Error(`Subagent \"${to}\" not found`);\n if (!subagent.context.parentBridge) {\n throw new Error(`Subagent \"${to}\" has no parentBridge — call setSubagentBridge() first`);\n }\n await subagent.context.parentBridge.send(msg);\n }\n\n /**\n * Wire up the communication bridge for a subagent. Call after spawn() once\n * the caller has created the bidirectional connection.\n */\n setSubagentBridge(subagentId: string, bridge: AgentBridge): void {\n const subagent = this.subagents.get(subagentId);\n if (!subagent) throw new Error(`Subagent \"${subagentId}\" not found`);\n subagent.context.parentBridge = bridge;\n }\n\n async stop(subagentId: string): Promise<void> {\n const subagent = this.subagents.get(subagentId);\n if (!subagent) return;\n\n // Abort any in-flight run, then sever the bridge so further messages fail\n // fast instead of silently queueing on a dead subagent.\n subagent.abortController.abort();\n subagent.status = 'stopped';\n subagent.currentTask = undefined;\n subagent.context.parentBridge = null;\n\n this.emit('subagent.stopped', { subagentId, reason: 'stopped by coordinator' });\n }\n\n async stopAll(): Promise<void> {\n // allSettled so one failure doesn't leave other subagents un-stopped.\n await Promise.allSettled([...this.subagents.keys()].map((id) => this.stop(id)));\n }\n\n getStatus(): CoordinatorStatus {\n return {\n coordinatorId: this.coordinatorId,\n subagents: Array.from(this.subagents.entries()).map(([id, s]) => ({\n id,\n name: s.config.name,\n status: s.status,\n currentTask: s.currentTask,\n })),\n pendingTasks: this.pendingTasks.length,\n completedTasks: this.completedResults.length,\n totalIterations: this.totalIterations,\n done: this.isDone(),\n };\n }\n\n /** Expose snapshot of completed results — useful for callers awaiting all done. */\n results(): readonly TaskResult[] {\n return this.completedResults;\n }\n\n /**\n * Manual completion — for callers that drive subagents without a runner\n * (e.g. external orchestrators). When a runner is configured the coordinator\n * calls this itself.\n */\n completeTask(result: TaskResult): void {\n this.recordCompletion(result);\n }\n\n // --- internal dispatching ---------------------------------------------\n\n private tryDispatchNext(): void {\n while (this.canDispatch()) {\n const subagentId = this.findIdleSubagent();\n if (!subagentId) return;\n const task = this.pendingTasks.shift();\n if (!task) return;\n // Attach a catch so a synchronous throw inside runDispatched (rare —\n // e.g. provider misconfiguration before the first await) becomes a\n // visible failed task instead of an unhandled rejection that leaves\n // `inFlight` permanently elevated.\n this.runDispatched(subagentId, task).catch((err) => {\n this.recordCompletion({\n subagentId,\n taskId: task.id,\n status: 'failed',\n error: err instanceof Error ? err.message : String(err),\n iterations: 0,\n toolCalls: 0,\n durationMs: 0,\n });\n });\n }\n }\n\n private canDispatch(): boolean {\n const max = this.config.maxConcurrent ?? 4;\n return this.inFlight < max && this.pendingTasks.length > 0;\n }\n\n private findIdleSubagent(): string | null {\n for (const [id, s] of this.subagents) {\n if (s.status === 'idle') return id;\n }\n return null;\n }\n\n private async runDispatched(subagentId: string, task: TaskSpec): Promise<void> {\n const subagent = this.subagents.get(subagentId);\n if (!subagent) return;\n\n subagent.status = 'running';\n subagent.currentTask = task.id;\n task.subagentId = subagentId;\n subagent.context.tasks.push(task);\n\n this.emit('task.assigned', { task, subagentId });\n\n // Budget combines coordinator defaults with per-subagent and per-task overrides.\n // Precedence: task > subagent > coordinator default.\n const budget = new SubagentBudget({\n maxIterations: subagent.config.maxIterations ?? this.config.defaultBudget?.maxIterations,\n maxToolCalls:\n task.maxToolCalls ??\n subagent.config.maxToolCalls ??\n this.config.defaultBudget?.maxToolCalls,\n maxTokens: subagent.config.maxTokens ?? this.config.defaultBudget?.maxTokens,\n maxCostUsd: subagent.config.maxCostUsd ?? this.config.defaultBudget?.maxCostUsd,\n timeoutMs:\n task.timeoutMs ?? subagent.config.timeoutMs ?? this.config.defaultBudget?.timeoutMs,\n });\n subagent.activeBudget = budget;\n\n if (!this.runner) {\n // No runner wired — caller drives execution via completeTask(). Status\n // reverts when the caller reports. We intentionally don't bump\n // `inFlight` here: `completeTask` → `recordCompletion` would then\n // decrement an inFlight that runDispatched never incremented, masking\n // the \"no runner\" state. With this guard, `isDone()`'s all_tasks_done\n // check still settles correctly once the caller reports.\n return;\n }\n\n // Only count inFlight when we actually own the execution lifecycle.\n this.inFlight++;\n\n const startTime = Date.now();\n const runCtx: SubagentRunContext = {\n subagentId,\n config: subagent.config,\n budget,\n signal: subagent.abortController.signal,\n bridge: subagent.context.parentBridge || null,\n };\n\n let result: TaskResult;\n\n budget.start();\n try {\n const outcome = await this.executeWithTimeout(this.runner, task, runCtx, budget);\n result = {\n subagentId,\n taskId: task.id,\n status: 'success',\n result: outcome.result,\n iterations: outcome.iterations,\n toolCalls: outcome.toolCalls,\n durationMs: Date.now() - startTime,\n };\n } catch (err) {\n // Order matters: a timeout calls abort() to signal cooperative runners,\n // which also flips `signal.aborted=true`. Inspect the error first so we\n // surface 'timeout' rather than masking it as 'stopped'.\n const status: TaskResult['status'] =\n err instanceof BudgetExceededError && err.kind === 'timeout'\n ? 'timeout'\n : subagent.abortController.signal.aborted\n ? 'stopped'\n : 'failed';\n const usage = budget.usage();\n result = {\n subagentId,\n taskId: task.id,\n status,\n error: err instanceof Error ? err.message : String(err),\n iterations: usage.iterations,\n toolCalls: usage.toolCalls,\n durationMs: Date.now() - startTime,\n };\n }\n\n this.recordCompletion(result);\n }\n\n private async executeWithTimeout(\n runner: SubagentRunner,\n task: TaskSpec,\n ctx: SubagentRunContext,\n budget: SubagentBudget,\n ) {\n const timeoutMs = budget.limits.timeoutMs;\n if (timeoutMs === undefined) return runner(task, ctx);\n\n let timer: ReturnType<typeof setTimeout> | null = null;\n const timeoutPromise = new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n // Abort the subagent's signal so cooperative runners can clean up.\n this.subagents.get(ctx.subagentId)?.abortController.abort();\n reject(new BudgetExceededError('timeout', timeoutMs, Date.now()));\n }, timeoutMs);\n });\n\n try {\n return await Promise.race([runner(task, ctx), timeoutPromise]);\n } finally {\n if (timer) clearTimeout(timer);\n }\n }\n\n private recordCompletion(result: TaskResult): void {\n this.completedResults.push(result);\n this.totalIterations += result.iterations;\n if (this.inFlight > 0) {\n this.inFlight--;\n } else if (this.runner) {\n // Runner-driven path completed without an outstanding inFlight slot —\n // shouldn't happen unless completeTask was called externally.\n this.emit('warning', {\n type: 'inFlight_underflow',\n taskId: result.taskId,\n subagentId: result.subagentId,\n });\n return;\n }\n\n const subagent = this.subagents.get(result.subagentId);\n if (subagent && subagent.status !== 'stopped') {\n const failed = result.status === 'failed' || result.status === 'timeout';\n subagent.status = failed ? 'error' : 'idle';\n subagent.currentTask = undefined;\n // If the run aborted (timeout or explicit stop), the subagent's\n // signal is now permanently aborted — recycling the controller lets\n // the next dispatched task start with a fresh cancellation scope.\n if (subagent.abortController.signal.aborted) {\n subagent.abortController = new AbortController();\n }\n // Reset error state on next assignment so a transient failure doesn't\n // permanently sideline the subagent.\n if (subagent.status === 'error') {\n queueMicrotask(() => {\n if (subagent.status === 'error') subagent.status = 'idle';\n this.tryDispatchNext();\n });\n }\n }\n\n this.emit('task.completed', {\n task: subagent?.context.tasks.find((t) => t.id === result.taskId) ?? { id: result.taskId },\n result,\n });\n\n this.tryDispatchNext();\n\n if (this.isDone()) {\n this.emit('done', {\n results: this.completedResults,\n totalIterations: this.totalIterations,\n });\n }\n }\n\n private isDone(): boolean {\n if (this.config.doneCondition.type === 'all_tasks_done') {\n return this.pendingTasks.length === 0 && this.inFlight === 0;\n }\n if (\n this.config.doneCondition.maxIterations !== undefined &&\n this.totalIterations >= this.config.doneCondition.maxIterations\n ) {\n return true;\n }\n return false;\n }\n}\n","import { randomUUID } from 'node:crypto';\nimport * as fsp from 'node:fs/promises';\nimport * as path from 'node:path';\nimport type { BridgeMessage } from '../types/agent-bridge.js';\nimport type {\n CoordinatorStatus,\n MultiAgentConfig,\n SubagentConfig,\n SubagentRunner,\n TaskResult,\n TaskSpec,\n} from '../types/multi-agent.js';\nimport type { JSONSchema, Tool } from '../types/tool.js';\nimport { InMemoryAgentBridge } from './agent-bridge.js';\nimport {\n DEFAULT_DIRECTOR_PREAMBLE,\n DEFAULT_SUBAGENT_BASELINE,\n composeDirectorPrompt,\n composeSubagentPrompt,\n rosterSummaryFromConfigs,\n} from './director-prompts.js';\nimport { FleetBus, type FleetUsage, FleetUsageAggregator } from './fleet-bus.js';\nimport { InMemoryBridgeTransport } from './in-memory-transport.js';\nimport { DefaultMultiAgentCoordinator } from './multi-agent-coordinator.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 `DirectorBudgetError`.\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\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 DirectorBudgetError extends Error {\n readonly kind: 'max_spawns' | 'max_spawn_depth';\n readonly limit: number;\n readonly observed: number;\n constructor(kind: 'max_spawns' | 'max_spawn_depth', limit: number, observed: number) {\n super(\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 );\n this.name = 'DirectorBudgetError';\n this.kind = kind;\n this.limit = limit;\n this.observed = observed;\n }\n}\n\nexport class Director {\n readonly id: string;\n readonly fleet: FleetBus;\n readonly usage: FleetUsageAggregator;\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 /** 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 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\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 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 // any failure surfaces later when an agent actually writes.\n void fsp.mkdir(this.sharedScratchpadPath, { recursive: true }).catch(() => undefined);\n }\n this.transport = new InMemoryBridgeTransport();\n this.bridge = new InMemoryAgentBridge(\n { agentId: this.id, coordinatorId: this.id },\n this.transport,\n );\n this.fleet = new FleetBus();\n this.usage = new FleetUsageAggregator(\n this.fleet,\n (id) => this.priceLookups.get(id),\n (id) => this.subagentMeta.get(id),\n );\n this.coordinator = new DefaultMultiAgentCoordinator(\n { ...opts.config, coordinatorId: this.id },\n { runner: opts.runner },\n );\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 this.coordinator.on('task.completed', (payload: { task: TaskSpec; result: TaskResult }) => {\n const r = payload.result;\n this.completed.set(r.taskId, r);\n const waiter = this.taskWaiters.get(r.taskId);\n if (waiter) {\n waiter.resolve(r);\n this.taskWaiters.delete(r.taskId);\n }\n });\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 // Enforce safety caps BEFORE touching the coordinator — a refused\n // spawn must not leak partial state into the manifest or fleet bus.\n if (this.spawnDepth >= this.maxSpawnDepth) {\n throw new DirectorBudgetError('max_spawn_depth', this.maxSpawnDepth, this.spawnDepth);\n }\n if (this.spawnCount >= this.maxSpawns) {\n throw new DirectorBudgetError('max_spawns', this.maxSpawns, this.spawnCount + 1);\n }\n this.spawnCount += 1;\n const result = await this.coordinator.spawn(config);\n this.subagentMeta.set(result.subagentId, {\n provider: config.provider,\n model: config.model,\n });\n if (priceLookup) this.priceLookups.set(result.subagentId, priceLookup);\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 // Record for manifest. Task ids attach as they're assigned via\n // `assign()` below.\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 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 fsp.writeFile(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 await this.coordinator.stopAll();\n for (const b of this.subagentBridges.values()) {\n await b.stop().catch(() => undefined);\n }\n this.subagentBridges.clear();\n await this.bridge.stop().catch(() => undefined);\n if (this.manifestPath) await this.writeManifest().catch(() => undefined);\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 if (task.subagentId) {\n const entry = this.manifestEntries.get(task.subagentId);\n if (entry) entry.taskIds.push(taskWithId.id);\n }\n await this.coordinator.assign(taskWithId);\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 status(): CoordinatorStatus {\n return this.coordinator.getStatus();\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 snapshot(): FleetUsage {\n return this.usage.snapshot();\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 const t: Tool[] = [\n makeSpawnTool(this, roster),\n makeAssignTool(this),\n makeAwaitTasksTool(this),\n makeAskTool(this),\n makeRollUpTool(this),\n makeTerminateTool(this),\n makeFleetStatusTool(this),\n makeFleetUsageTool(this),\n ];\n return t;\n }\n}\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\nfunction makeSpawnTool(director: Director, roster?: Record<string, SubagentConfig>): Tool {\n const inputSchema: JSONSchema = {\n type: 'object',\n properties: {\n role: {\n type: 'string',\n description:\n 'Roster role id (preferred). When set, the spawn uses the matching config from the roster and ignores other fields.',\n },\n name: {\n type: 'string',\n description: 'Display name for the subagent. Required when not using roster.',\n },\n provider: {\n type: 'string',\n description:\n 'Provider id (e.g. \"anthropic\", \"openai\"). Defaults to the leader provider when omitted.',\n },\n model: {\n type: 'string',\n description: 'Model id within the provider. Defaults to the leader model when omitted.',\n },\n systemPromptOverride: {\n type: 'string',\n description: 'Extra prompt text appended after the role-base prompt.',\n },\n maxIterations: { type: 'number' },\n maxToolCalls: { type: 'number' },\n maxCostUsd: { type: 'number' },\n },\n required: [],\n };\n return {\n name: 'spawn_subagent',\n description:\n 'Create a new subagent under this director. Returns the subagent id. Use this when you need a worker with a specific provider, model, or role to handle a piece of the plan.',\n usageHint:\n 'Either pass `role` (matches the roster) OR pass `name` + optional `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 base: SubagentConfig | undefined = role && roster ? roster[role] : undefined;\n if (role && !base) {\n return {\n error: `unknown role \"${role}\". roster has: ${roster ? Object.keys(roster).join(', ') : '(empty)'}`,\n };\n }\n const cfg: SubagentConfig = {\n ...(base ?? { 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')\n 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 try {\n const subagentId = await director.spawn(cfg);\n return { subagentId, provider: cfg.provider, model: cfg.model, name: cfg.name };\n } catch (err) {\n // Surface DirectorBudgetError (and any other spawn failure) as a\n // structured `{ error, kind }` payload so the leader model can\n // read the cap and replan — throwing would tear down the whole\n // tool call and give the model no signal to recover from.\n if (err instanceof DirectorBudgetError) {\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 makeAssignTool(director: Director): Tool {\n const inputSchema: JSONSchema = {\n type: 'object',\n properties: {\n subagentId: { type: 'string', description: 'Target subagent id. Required.' },\n description: {\n type: 'string',\n description: 'The task in natural language — what you want this subagent to do.',\n },\n maxToolCalls: { type: 'number', description: 'Optional per-task tool-call budget override.' },\n timeoutMs: { type: 'number', description: 'Optional per-task timeout in ms.' },\n },\n required: ['subagentId', 'description'],\n };\n return {\n name: 'assign_task',\n description:\n 'Hand a task to a previously spawned subagent. Returns the task id — pass it to `await_tasks` to block on completion.',\n permission: 'auto',\n mutating: false,\n inputSchema,\n async execute(input: unknown) {\n const i = input as {\n subagentId: string;\n description: string;\n maxToolCalls?: number;\n timeoutMs?: number;\n };\n const task: TaskSpec = {\n id: randomUUID(),\n description: i.description,\n subagentId: i.subagentId,\n maxToolCalls: i.maxToolCalls,\n timeoutMs: i.timeoutMs,\n };\n const taskId = await director.assign(task);\n return { taskId, subagentId: i.subagentId };\n },\n };\n}\n\nfunction makeAwaitTasksTool(director: Director): Tool {\n const inputSchema: JSONSchema = {\n type: 'object',\n properties: {\n taskIds: {\n type: 'array',\n items: { type: 'string' },\n description:\n 'One or more task ids returned by `assign_task`. The call blocks until every id resolves.',\n },\n },\n required: ['taskIds'],\n };\n return {\n name: 'await_tasks',\n description:\n 'Block until every named task completes. Returns the array of TaskResult — use this to gather subagent output before deciding the next step.',\n permission: 'auto',\n mutating: false,\n inputSchema,\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\nfunction makeAskTool(director: Director): Tool {\n const inputSchema: JSONSchema = {\n type: 'object',\n properties: {\n subagentId: {\n type: 'string',\n description: 'Subagent to ask. Must be a previously spawned id.',\n },\n question: {\n type: 'string',\n description: 'The question or instruction. Sent as the bridge message payload.',\n },\n timeoutMs: { type: 'number', description: 'Optional timeout in ms (default 30s).' },\n },\n required: ['subagentId', 'question'],\n };\n return {\n name: 'ask_subagent',\n description:\n 'Synchronously ask a subagent a question. Blocks until the subagent replies via the bridge (or the timeout fires). Use this when you need a one-shot answer without spawning a fresh task.',\n permission: 'auto',\n mutating: false,\n inputSchema,\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 return { ok: true, answer };\n } catch (err) {\n return { ok: false, error: err instanceof Error ? err.message : String(err) };\n }\n },\n };\n}\n\nfunction makeRollUpTool(director: Director): Tool {\n const inputSchema: JSONSchema = {\n type: 'object',\n properties: {\n taskIds: {\n type: 'array',\n items: { type: 'string' },\n description:\n 'Completed task ids to aggregate. Pass the ids returned by previous `assign_task` calls.',\n },\n style: {\n type: 'string',\n enum: ['markdown', 'json'],\n description:\n 'Output flavor — markdown (default) for in-prompt summarization, json for structured downstream processing.',\n },\n },\n required: ['taskIds'],\n };\n return {\n name: 'roll_up',\n description:\n \"Aggregate completed task results into a single formatted summary. Use this after `await_tasks` to fold subagent outputs back into the director's context before deciding the next step.\",\n permission: 'auto',\n mutating: false,\n inputSchema,\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\nfunction makeTerminateTool(director: Director): Tool {\n const inputSchema: JSONSchema = {\n type: 'object',\n properties: {\n subagentId: { type: 'string', description: 'Subagent to abort.' },\n },\n required: ['subagentId'],\n };\n return {\n name: 'terminate_subagent',\n description:\n 'Forcibly abort a subagent. Use sparingly — prefer waiting on the natural budget to expire. The current task (if any) ends with status \"stopped\".',\n permission: 'auto',\n mutating: true,\n inputSchema,\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\nfunction makeFleetStatusTool(director: Director): Tool {\n return {\n name: 'fleet_status',\n description:\n \"Snapshot of the fleet — every subagent's current status, pending vs. completed task counts, and the running total iteration count. Cheap; call freely.\",\n permission: 'auto',\n mutating: false,\n inputSchema: { type: 'object', properties: {}, required: [] },\n async execute() {\n return director.status();\n },\n };\n}\n\nfunction makeFleetUsageTool(director: Director): Tool {\n return {\n name: 'fleet_usage',\n description:\n 'Token + cost breakdown across the fleet, per-subagent and totals. Use this to reason about which workers to assign costly tasks to or when to wrap up to stay within budget.',\n permission: 'auto',\n mutating: false,\n inputSchema: { type: 'object', properties: {}, required: [] },\n async execute() {\n return director.snapshot();\n },\n };\n}\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 { BudgetExceededError } from './subagent-budget.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\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\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 { agent, events } = await opts.factory(ctx.config);\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 let budgetError: BudgetExceededError | null = null;\n\n const onBudgetError = (err: unknown) => {\n // Any error from a budget operation (BudgetExceededError, TypeError from\n // a malformed event payload, etc.) must abort the run. EventBus.emit()\n // swallows listener throws, so we can't re-throw — set budgetError and\n // abort the controller so the agent unwinds cooperatively.\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 const unsub: Array<() => void> = [];\n unsub.push(\n events.on('tool.started', () => {\n try {\n ctx.budget.recordToolCall();\n } catch (e) {\n onBudgetError(e);\n }\n }),\n events.on('provider.response', (e) => {\n try {\n ctx.budget.recordUsage(e.usage);\n } catch (e2) {\n onBudgetError(e2);\n }\n }),\n events.on('iteration.started', () => {\n try {\n ctx.budget.recordIteration();\n ctx.budget.checkTimeout();\n } catch (e) {\n onBudgetError(e);\n }\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 ctx.signal.removeEventListener('abort', onParentAbort);\n for (const u of unsub) u();\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) throw budgetError;\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 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 { 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 fs.rename(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","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 {\n ResumedSession,\n SessionData,\n SessionEvent,\n SessionMetadata,\n SessionStore,\n SessionSummary,\n SessionWriter,\n} from '../types/session.js';\nimport { ensureDir } from '../utils/atomic-write.js';\n\nexport interface SessionStoreOptions {\n dir: string;\n /** Optional EventBus for emitting session diagnostics. */\n events?: EventBus;\n}\n\nexport class DefaultSessionStore implements SessionStore {\n private readonly dir: string;\n private readonly events?: EventBus;\n\n constructor(opts: SessionStoreOptions) {\n this.dir = opts.dir;\n this.events = opts.events;\n }\n\n async create(meta: Omit<SessionMetadata, 'startedAt'>): Promise<SessionWriter> {\n await ensureDir(this.dir);\n const startedAt = new Date().toISOString();\n const id = meta.id ?? `${startedAt.replace(/[:.]/g, '-')}-${randomBytes(2).toString('hex')}`;\n const file = path.join(this.dir, `${id}.jsonl`);\n let handle: fsp.FileHandle;\n try {\n handle = await fsp.open(file, 'a', 0o600);\n } catch (err) {\n // Preserve cause + errno so callers can branch on EACCES vs EMFILE\n // vs ENOSPC etc. instead of substring-matching the error message.\n throw new Error(\n `Failed to open session file: ${err instanceof Error ? err.message : String(err)}`,\n {\n cause: err,\n },\n );\n }\n try {\n return new FileSessionWriter(id, handle, startedAt, meta, { dir: this.dir, filePath: file });\n } catch (err) {\n await handle.close().catch(() => {});\n throw err;\n }\n }\n\n async resume(id: string): Promise<ResumedSession> {\n const data = await this.load(id);\n const file = path.join(this.dir, `${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 \"${id}\" for append: ${err instanceof Error ? err.message : String(err)}`,\n { cause: err },\n );\n }\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 { resumed: true, dir: this.dir, filePath: file },\n );\n return { writer, data };\n }\n\n async load(id: string): Promise<SessionData> {\n const file = path.join(this.dir, `${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 // Session JSONL is on-disk user-writable state; downstream replay\n // trusts `e.type` / `e.ts` etc. and would TypeError on a malformed\n // shape. Validate the discriminator + timestamp before pushing.\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 // else: skip — a hand-edited file with a partial object should not\n // crash replay, just lose that one event.\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 files = await fsp.readdir(this.dir);\n const ids = files.filter((f) => f.endsWith('.jsonl')).map((f) => f.replace(/\\.jsonl$/, ''));\n // Read all manifests in parallel; fall back to full load only for\n // sessions that haven't been closed cleanly (or predate the manifest).\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 // Equal timestamps — use id as tiebreaker for stable sort\n return a.id.localeCompare(b.id);\n });\n return out.slice(0, limit);\n } catch {\n return [];\n }\n }\n\n private async summaryFor(id: string): Promise<SessionSummary> {\n const manifest = path.join(this.dir, `${id}.summary.json`);\n try {\n const raw = await fsp.readFile(manifest, 'utf8');\n return JSON.parse(raw) as SessionSummary;\n } catch {\n // Manifest missing/corrupt — fall back to a full parse and backfill\n // the manifest so the next `list()` hits the fast path.\n const full = path.join(this.dir, `${id}.jsonl`);\n const stat = await fsp.stat(full);\n const summary = await this.summarize(id, stat.mtime.toISOString());\n await fsp\n .writeFile(manifest, JSON.stringify(summary), { mode: 0o600 })\n .catch((err) => {\n // Best-effort manifest write — list() falls back to full parse\n // on next invocation, so surface the error for diagnostics but\n // don't fail the listing.\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(path.join(this.dir, `${id}.jsonl`));\n await fsp.unlink(path.join(this.dir, `${id}.summary.json`)).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 };\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 // Orphan tool_result: tool_use was never seen. Skip to avoid\n // corrupting the replayed message sequence.\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 // Convert string content to blocks and append\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 truncated`,\n });\n // Return what we could replay instead of throwing — a damaged session\n // should not block the entire session-listing or resume path.\n return { messages, usage };\n }\n return { messages, usage };\n }\n}\n\nclass FileSessionWriter implements SessionWriter {\n private closed = false;\n private manifestFile: string;\n private summary: SessionSummary;\n private tokenIn = 0;\n private tokenOut = 0;\n private readonly filePath: string;\n private initDone = false;\n private readonly resumed: boolean;\n private appendFailCount = 0;\n private lastAppendWarnAt = 0;\n\n constructor(\n public readonly id: string,\n private readonly handle: fsp.FileHandle,\n private readonly startedAt: string,\n private readonly meta: Omit<SessionMetadata, 'startedAt'>,\n opts: { resumed?: boolean; dir?: string; filePath?: string } = {},\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.summary = {\n id,\n title: '(empty session)',\n startedAt,\n model: meta.model ?? 'unknown',\n provider: meta.provider ?? 'unknown',\n tokenTotal: 0,\n };\n // Session start is written lazily on first append to avoid sync I/O\n // in constructor and eliminate reliance on FileHandle.fd private property.\n }\n\n private async writeSessionStart(): Promise<void> {\n if (this.initDone || this.closed) return;\n this.initDone = true;\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 // Use fs.promises.writeFile directly to avoid FileHandle.fd private access\n await fsp.writeFile(this.filePath, record, { flag: 'a', mode: 0o600 });\n }\n } catch {\n // best-effort; session will still be usable without the start event logged\n }\n }\n\n async append(event: SessionEvent): Promise<void> {\n if (this.closed) return;\n if (!this.initDone) {\n await this.writeSessionStart();\n }\n this.observeForSummary(event);\n try {\n await this.handle.appendFile(`${JSON.stringify(event)}\\n`, 'utf8');\n } catch (err) {\n // A persistent failure (full disk, broken pipe) would otherwise log\n // once per appended event — which for a chatty agent run is a lot.\n // Debounce to one log per 5 s and surface the suppressed count.\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 /**\n * Watch events as they're appended and keep the summary state hot, so\n * `close()` can flush a `<id>.summary.json` manifest without re-reading\n * the JSONL. `list()` reads only manifests, turning a per-session full\n * parse into a single stat+read.\n */\n private observeForSummary(event: SessionEvent): void {\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 // session_end usage is the canonical total — prefer it if non-zero.\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.closed) return;\n this.closed = true;\n if (this.manifestFile) {\n try {\n await fsp.writeFile(this.manifestFile, JSON.stringify(this.summary), { mode: 0o600 });\n } catch {\n // manifest write is best-effort; list() falls back to full load.\n }\n }\n try {\n await this.handle.close();\n } catch {\n // ignore\n }\n }\n}\n\nfunction userInputTitle(content: string | ContentBlock[]): string {\n if (typeof content === 'string') return content.slice(0, 60);\n const text = 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 * Pre-built subagent role configurations for the WrongStack fleet.\n * These can be passed to `MultiAgentHost.spawn()` or used as templates\n * for the director's roster.\n */\nimport type { SubagentConfig } from '../types/multi-agent.js';\n\n/**\n * Audit Log Agent — analyzes session logs, event streams, and traces.\n * Use for: post-mortems, trend analysis, operational insights.\n */\nexport const AUDIT_LOG_AGENT: SubagentConfig = {\n id: 'audit-log',\n name: 'Audit Log',\n role: 'audit-log',\n prompt: `You are the Audit Log agent. Your job is to analyze structured JSONL\nsession logs and produce actionable markdown reports.\n\nScope:\n- Parse session logs (iteration counts, tool calls, errors, usage)\n- Detect repeated failure patterns across multiple runs\n- Identify tool usage anomalies (over-use, failures, unexpected chains)\n- Track token consumption trends\n- Generate structured audit reports with severity ratings\n\nInput format you accept:\n{ \"task\": \"analyze | report | trends\", \"sessionPath\": \"<path>\", \"focus\": \"errors | tools | usage | all\" }\n\nOutput: Markdown audit report with sections:\n- ## Summary (totals, error rate)\n- ## Top Errors (count + context)\n- ## Tool Usage (table with calls, failures, avg duration)\n- ## Anomalies (pattern → severity)\n\nWorking rules:\n- Never fabricate numbers — read the actual logs first\n- Always include file:line references for errors\n- If sessionPath is missing, ask the director to provide it\n- Report confidence level: high (>90% accuracy), medium, low`,\n\n maxIterations: 50,\n maxToolCalls: 200,\n timeoutMs: 120_000,\n};\n\n/**\n * Bug Hunter Agent — systematic bug and code smell detection.\n * Use for: pre-refactoring health checks, code review, regression prevention.\n */\nexport const BUG_HUNTER_AGENT: SubagentConfig = {\n id: 'bug-hunter',\n name: 'Bug Hunter',\n role: 'bug-hunter',\n prompt: `You are the Bug Hunter agent. Your job is to systematically scan\nsource code for bugs, anti-patterns, and code smells using pattern matching\nand heuristics. Output a prioritized hit list with file:line references.\n\nScope:\n- Detect common bug patterns (uncaught errors, resource leaks, race conditions)\n- Identify anti-patterns (callback hell, God objects, circular deps)\n- Find TypeScript-specific issues (unsafe any, missing null checks, branded types)\n- Flag security-sensitive constructs (eval, innerHTML, hardcoded secrets)\n- Rank findings: critical > high > medium > low\n\nInput format you accept:\n{ \"task\": \"scan | hunt | check\", \"paths\": [\"src/**/*.ts\"], \"focus\": \"bugs | patterns | security | all\", \"severityThreshold\": \"medium\" }\n\nOutput: Markdown bug hunt report:\n- ## Critical (must fix first)\n- ## High (should fix)\n- ## Medium\n- ## Low (consider)\nEach entry: **[TYPE]** \\`file:line\\` — description + suggested fix\n\nBug pattern reference you know:\n| Pattern | Regex hint | Severity |\n|---------|------------|----------|\n| Uncaught promise | /\\.then\\\\(.*\\\\)/ without catch | high |\n| Event leak | on\\\\( without off/removeListener | high |\n| Hardcoded secret | [a-zA-Z0-9/_-]{20,} in config files | critical |\n| unsafe any | : any\\\\b or <any> | medium |\n| innerHTML | innerHTML\\\\s*= | high |\n\nWorking rules:\n- Never scan node_modules — it's noise\n- Always include file:line for every finding\n- If >30% of findings are false positives, note the confidence level\n- Ask director for clarification if paths are ambiguous`,\n\n maxIterations: 80,\n maxToolCalls: 300,\n timeoutMs: 180_000,\n};\n\n/**\n * Refactor Planner Agent — structured refactoring planning.\n * Use for: large rewrites, technical debt reduction, architecture improvements.\n */\nexport const REFACTOR_PLANNER_AGENT: SubagentConfig = {\n id: 'refactor-planner',\n name: 'Refactor Planner',\n role: 'refactor-planner',\n prompt: `You are the Refactor Planner agent. Your job is to analyze code\nstructure and produce a concrete, phased refactoring plan with risk\nassessment, dependency ordering, and rollback strategy.\n\nScope:\n- Map module-level dependencies (import graph)\n- Identify coupling hotspots (high fan-in/out modules)\n- Assess refactoring risk by complexity and test coverage\n- Generate phased plans with checkpoint milestones\n- Produce diff-friendly task lists (one task = one concern)\n\nInput format you accept:\n{ \"task\": \"plan | assess | roadmap\", \"target\": \"src/core\", \"constraint\": \"no-breaking-changes | minimal-downtime | full-rewrite\", \"focus\": \"architecture | performance | maintainability\" }\n\nOutput: Markdown refactor plan:\n- ## Phase 1: Low Risk / High Payoff (do first)\n Table: | # | Task | Module | Risk | Est. Time |\n- ## Phase 2: Medium Risk\n- ## Phase 3: High Risk (requires full regression)\n- ## Dependency Graph (abbreviated ASCII)\n- ## Rollback Strategy\n- ## Exit Criteria (checkbox list)\n\nRisk scoring criteria:\n| Factor | Low | Medium | High |\n|--------|-----|--------|------|\n| Cyclomatic complexity | <10 | 10-20 | >20 |\n| Test coverage | >80% | 50-80% | <50% |\n| Fan-out (imports) | <5 | 5-15 | >15 |\n\nWorking rules:\n- Always include rollback strategy — every refactor can fail\n- Merge tasks that take <1h into a single phase\n- Respect team constraints (reviewer availability, parallelization)\n- Never plan without analyzing the actual code first`,\n\n maxIterations: 60,\n maxToolCalls: 250,\n timeoutMs: 150_000,\n};\n\n/**\n * Security Scanner Agent — vulnerability and secret detection.\n * Use for: CI checks, pre-release audits, dependency vulnerability scanning.\n */\nexport const SECURITY_SCANNER_AGENT: SubagentConfig = {\n id: 'security-scanner',\n name: 'Security Scanner',\n role: 'security-scanner',\n prompt: `You are the Security Scanner agent. Your job is to scan code,\nconfigs, and dependencies for security issues from hardcoded secrets to\nsupply chain risks.\n\nScope:\n- Detect hardcoded secrets: API keys, tokens, passwords, private keys\n- Find injection vectors: eval, innerHTML, SQL concat, shell injection\n- Identify insecure patterns: weak crypto, hardcoded IVs, disabled TLS\n- Scan dependencies for known CVEs (via npm/pnpm audit)\n- Flag supply chain risks: postinstall hooks, unverified scripts, .npmrc\n\nInput format you accept:\n{ \"task\": \"scan | audit | secrets | dependencies\", \"paths\": [\"src\", \"config\"], \"depth\": \"quick | normal | deep\" }\n\nOutput: Markdown security report:\n- ## CRITICAL: Secrets Found (with code snippets)\n- ## HIGH: Injection Vectors\n- ## MEDIUM: Insecure Patterns\n- ## Dependency Issues (CVE list)\n- ## Summary table (severity → count)\n- ## Remediation Checklist (with checkboxes)\n\nSecret patterns you detect:\n| Pattern | Example | Severity |\n|---------|---------|----------|\n| AWS Access Key | AKIAIOSFODNN7EXAMPLE | critical |\n| AWS Secret Key | [a-zA-Z0-9/+=]{40} base64 | critical |\n| GitHub Token | ghp_[a-zA-Z0-9]{36} | critical |\n| Private Key PEM | -----BEGIN.*PRIVATE KEY----- | critical |\n| JWT | eyJ[a-zA-Z0-9_-]+ | high |\n\nInjection patterns:\n| Construct | Safe alternative |\n|-----------|-----------------|\n| eval(str) | new Function() or parse |\n| innerHTML = x | textContent or sanitize |\n| exec(\\`cmd \\${x}\\`) | execFile with args array |\n\nWorking rules:\n- Never scan node_modules — use npm audit instead\n- Always provide remediation steps, not just findings\n- Verify regex-based secrets before flagging (false positive risk)\n- When in doubt, flag as medium rather than ignoring potential issues`,\n\n maxIterations: 70,\n maxToolCalls: 280,\n timeoutMs: 160_000,\n};\n\n/** All pre-built agents in a map for easy lookup by role. */\nexport const FLEET_ROSTER: Record<string, SubagentConfig> = {\n 'audit-log': AUDIT_LOG_AGENT,\n 'bug-hunter': BUG_HUNTER_AGENT,\n 'refactor-planner': REFACTOR_PLANNER_AGENT,\n 'security-scanner': SECURITY_SCANNER_AGENT,\n};\n\n/** Quick-access list for spawning all at once. */\nexport const ALL_FLEET_AGENTS = Object.values(FLEET_ROSTER);\n"]}
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/coordination/director-prompts.ts","../../src/coordination/fleet-bus.ts","../../src/types/errors.ts","../../src/types/provider.ts","../../src/coordination/subagent-budget.ts","../../src/coordination/multi-agent-coordinator.ts","../../src/coordination/director.ts","../../src/coordination/delegate-tool.ts","../../src/coordination/agent-subagent-runner.ts","../../src/storage/session-store.ts","../../src/coordination/director-session.ts","../../src/coordination/fleet.ts"],"names":["path","fs","stat","handlers","randomUUID","fsp2","path2","partial","path3","fsp3","randomBytes","path5"],"mappings":";;;;;;AASA,eAAsB,WAAA,CACpB,UAAA,EACA,OAAA,EACA,IAAA,GAA2B,EAAC,EACb;AACf,EAAA,MAAM,GAAA,GAAWA,cAAQ,UAAU,CAAA;AACnC,EAAA,MAASC,IAAA,CAAA,KAAA,CAAM,GAAA,EAAK,EAAE,SAAA,EAAW,MAAM,CAAA;AACvC,EAAA,MAAM,GAAA,GAAWD,KAAA,CAAA,IAAA,CAAK,GAAA,EAAK,CAAA,CAAA,EAASA,eAAS,UAAU,CAAC,CAAA,CAAA,EAAI,WAAA,CAAY,CAAC,CAAA,CAAE,QAAA,CAAS,KAAK,CAAC,CAAA,IAAA,CAAM,CAAA;AAIhG,EAAA,IAAI;AACF,IAAA,IAAI,OA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AA,GAAyC;AAAA,EACpD,EAAA,EAAI,kBAAA;AAAA,EACJ,IAAA,EAAM,kBAAA;AAAA,EACN,IAAA,EAAM,kBAAA;AAAA,EACN,MAAA,EAAQ,CAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA,qEAAA;AAAA;AA6CV;AAGO,IAAM,YAAA,GAA+C;AAAA,EAC1D,WAAA,EAAa,eAAA;AAAA,EACb,YAAA,EAAc,gBAAA;AAAA,EACd,kBAAA,EAAoB,sBAAA;AAAA,EACpB,kBAAA,EAAoB;AACtB;AAGO,IAAM,gBAAA,GAAmB,MAAA,CAAO,MAAA,CAAO,YAAY","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 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 * 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 */\nexport class DirectorStateCheckpoint {\n private snapshot: DirectorStateSnapshot;\n private readonly filePath: 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 },\n debounceMs = 250,\n ) {\n this.filePath = filePath;\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 subagents: [],\n tasks: [],\n };\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 }\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\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.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 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 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 }\n this.pendingRequests.clear();\n this.inflightGuards.clear();\n this.subscriptions.clear();\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 * 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`;\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","import type { EventBus } from '../kernel/events.js';\n\n/**\n * Single fleet-wide event with subagent attribution. Whatever a child\n * agent emits on its own EventBus gets re-published here, prefixed with\n * `subagentId` so a single subscriber can multiplex across the fleet.\n *\n * The director uses `FleetBus.filter('tool.executed', …)` to see every\n * tool call across the fleet; the TUI uses\n * `FleetBus.subscribe(id, handler)` to render a per-subagent panel.\n */\nexport interface FleetEvent {\n subagentId: string;\n taskId?: string;\n ts: number;\n type: string;\n payload: unknown;\n}\n\nexport type FleetHandler = (event: FleetEvent) => void;\n\n/**\n * Fan-in for per-subagent EventBuses. Each subagent's bus is plugged in\n * via `attach()`; the FleetBus re-emits every event with subagent\n * attribution. Detachment is automatic via the returned disposer — call\n * it when a subagent terminates so we don't leak listeners.\n *\n * The bus exposes two subscription modes: by `subagentId` (everything\n * from one child) and by `type` (one event-type across the fleet). They\n * compose — if you need a per-subagent + per-type slice, subscribe by\n * type and filter on `event.subagentId` in your handler.\n */\nexport class FleetBus {\n private readonly byId = new Map<string, Set<FleetHandler>>();\n private readonly byType = new Map<string, Set<FleetHandler>>();\n private readonly any = new Set<FleetHandler>();\n\n /**\n * Hook a subagent's EventBus into the fleet. EventBus is strongly\n * typed and doesn't expose an `onAny` hook, so we subscribe to the\n * canonical set of event types a subagent emits during a run. New\n * event types added to the kernel must be added here too — but the\n * cost is a tiny single line per type, and the explicit list keeps\n * the wire format clear.\n *\n * Returns a disposer that detaches every subscription; call on\n * subagent teardown so the listeners don't outlive the run.\n */\n attach(subagentId: string, bus: EventBus, taskId?: string): () => void {\n const FORWARDED_TYPES = [\n 'tool.started',\n 'tool.executed',\n 'tool.progress',\n 'tool.confirm_needed',\n 'iteration.started',\n 'iteration.completed',\n 'provider.text_delta',\n // Subagent extended-thinking output. Forwarded so the FleetPanel /\n // /fleet log can surface \"the planner is thinking…\" instead of a\n // silent gap between iteration.started and the first text_delta.\n 'provider.thinking_delta',\n 'provider.response',\n 'provider.retry',\n 'provider.error',\n 'session.started',\n 'session.ended',\n 'session.damaged',\n 'compaction.fired',\n 'compaction.failed',\n 'token.threshold',\n ] as const;\n const offs: Array<() => void> = [];\n for (const t of FORWARDED_TYPES) {\n offs.push(\n bus.on(t, (payload: unknown) => {\n this.emit({ subagentId, taskId, ts: Date.now(), type: t, payload });\n }),\n );\n }\n return () => {\n for (const off of offs) off();\n };\n }\n\n /** Subscribe to every event from one subagent. */\n subscribe(subagentId: string, handler: FleetHandler): () => void {\n let set = this.byId.get(subagentId);\n if (!set) {\n set = new Set();\n this.byId.set(subagentId, set);\n }\n set.add(handler);\n return () => {\n set!.delete(handler);\n };\n }\n\n /** Subscribe to one event type across all subagents. */\n filter(type: string, handler: FleetHandler): () => void {\n let set = this.byType.get(type);\n if (!set) {\n set = new Set();\n this.byType.set(type, set);\n }\n set.add(handler);\n return () => {\n set!.delete(handler);\n };\n }\n\n /** Subscribe to literally everything. The fleet roll-up uses this. */\n onAny(handler: FleetHandler): () => void {\n this.any.add(handler);\n return () => {\n this.any.delete(handler);\n };\n }\n\n emit(event: FleetEvent): void {\n // Each fan-out is best-effort — a misbehaving handler must not\n // bring down the bus or other handlers. Errors are swallowed\n // (matching the rest of the project's listener-error policy).\n const byId = this.byId.get(event.subagentId);\n if (byId)\n for (const h of byId) {\n try {\n h(event);\n } catch {\n /* ignore */\n }\n }\n const byType = this.byType.get(event.type);\n if (byType)\n for (const h of byType) {\n try {\n h(event);\n } catch {\n /* ignore */\n }\n }\n for (const h of this.any) {\n try {\n h(event);\n } catch {\n /* ignore */\n }\n }\n }\n}\n\n/**\n * Roll-up of token usage + cost across an entire director run. The\n * director's `fleet_status` tool returns this so the model can reason\n * about budget in its next turn (\"the researcher already burned $0.40,\n * lean on summaries for the next task\").\n */\nexport interface FleetUsage {\n total: {\n input: number;\n output: number;\n cacheRead: number;\n cacheWrite: number;\n cost: number;\n };\n perSubagent: Record<string, SubagentUsageSnapshot>;\n}\n\nexport interface SubagentUsageSnapshot {\n subagentId: string;\n provider?: string;\n model?: string;\n input: number;\n output: number;\n cacheRead: number;\n cacheWrite: number;\n cost: number;\n toolCalls: number;\n iterations: number;\n startedAt: number;\n lastEventAt: number;\n}\n\n/**\n * Aggregates provider.response + tool.executed events from the FleetBus\n * into a live `FleetUsage` snapshot. Costs are computed by the caller\n * via a `priceLookup(subagentId)` so we don't bake provider-pricing\n * coupling into core; the CLI/tests supply a function that resolves\n * each subagent's per-token rates from the models registry.\n */\nexport class FleetUsageAggregator {\n private readonly perSubagent = new Map<string, SubagentUsageSnapshot>();\n private readonly total = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };\n\n constructor(\n private readonly bus: FleetBus,\n private readonly priceLookup?: (\n subagentId: string,\n ) => { input?: number; output?: number; cacheRead?: number; cacheWrite?: number } | undefined,\n private readonly metaLookup?: (\n subagentId: string,\n ) => { provider?: string; model?: string } | undefined,\n ) {\n bus.filter('provider.response', (e) => this.onProviderResponse(e));\n bus.filter('tool.executed', (e) => this.onToolExecuted(e));\n bus.filter('iteration.started', (e) => this.onIterationStarted(e));\n }\n\n /** Live snapshot — safe to call from a tool's execute() body. */\n snapshot(): FleetUsage {\n return {\n total: { ...this.total },\n perSubagent: Object.fromEntries(\n Array.from(this.perSubagent.entries()).map(([k, v]) => [k, { ...v }]),\n ),\n };\n }\n\n private ensure(subagentId: string): SubagentUsageSnapshot {\n let snap = this.perSubagent.get(subagentId);\n if (!snap) {\n const meta = this.metaLookup?.(subagentId);\n snap = {\n subagentId,\n provider: meta?.provider,\n model: meta?.model,\n input: 0,\n output: 0,\n cacheRead: 0,\n cacheWrite: 0,\n cost: 0,\n toolCalls: 0,\n iterations: 0,\n startedAt: Date.now(),\n lastEventAt: Date.now(),\n };\n this.perSubagent.set(subagentId, snap);\n }\n return snap;\n }\n\n private onProviderResponse(e: FleetEvent): void {\n const snap = this.ensure(e.subagentId);\n const p = e.payload as {\n usage?: { input?: number; output?: number; cacheRead?: number; cacheWrite?: number };\n };\n const usage = p?.usage;\n if (!usage) return;\n snap.input += usage.input ?? 0;\n snap.output += usage.output ?? 0;\n snap.cacheRead += usage.cacheRead ?? 0;\n snap.cacheWrite += usage.cacheWrite ?? 0;\n this.total.input += usage.input ?? 0;\n this.total.output += usage.output ?? 0;\n this.total.cacheRead += usage.cacheRead ?? 0;\n this.total.cacheWrite += usage.cacheWrite ?? 0;\n const price = this.priceLookup?.(e.subagentId);\n if (price) {\n const delta =\n ((usage.input ?? 0) / 1_000_000) * (price.input ?? 0) +\n ((usage.output ?? 0) / 1_000_000) * (price.output ?? 0) +\n ((usage.cacheRead ?? 0) / 1_000_000) * (price.cacheRead ?? 0) +\n ((usage.cacheWrite ?? 0) / 1_000_000) * (price.cacheWrite ?? 0);\n snap.cost += delta;\n this.total.cost += delta;\n }\n snap.lastEventAt = e.ts;\n }\n\n private onToolExecuted(e: FleetEvent): void {\n const snap = this.ensure(e.subagentId);\n snap.toolCalls += 1;\n snap.lastEventAt = e.ts;\n }\n\n private onIterationStarted(e: FleetEvent): void {\n const snap = this.ensure(e.subagentId);\n snap.iterations += 1;\n snap.lastEventAt = e.ts;\n }\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\nexport type ErrorCode =\n // Provider\n | 'PROVIDER_RATE_LIMITED'\n | 'PROVIDER_AUTH_FAILED'\n | 'PROVIDER_OVERLOADED'\n | 'PROVIDER_INVALID_REQUEST'\n | 'PROVIDER_SERVER_ERROR'\n | 'PROVIDER_NETWORK_ERROR'\n | 'PROVIDER_CONTEXT_OVERFLOW'\n // Tool\n | 'TOOL_NOT_FOUND'\n | 'TOOL_PERMISSION_DENIED'\n | 'TOOL_EXECUTION_FAILED'\n | 'TOOL_TIMEOUT'\n | 'TOOL_INPUT_INVALID'\n // Config\n | 'CONFIG_INVALID'\n | 'CONFIG_NOT_FOUND'\n | 'CONFIG_PARSE_FAILED'\n | 'CONFIG_MIGRATION_NEEDED'\n // Plugin\n | 'PLUGIN_LOAD_FAILED'\n | 'PLUGIN_API_MISMATCH'\n | 'PLUGIN_MISSING_DEPENDENCY'\n // Agent\n | 'AGENT_ITERATION_LIMIT'\n | 'AGENT_CONTEXT_OVERFLOW'\n | 'AGENT_ABORTED'\n | 'AGENT_RUN_FAILED'\n // Session\n | 'SESSION_NOT_FOUND'\n | 'SESSION_CORRUPTED'\n | 'SESSION_WRITE_FAILED'\n // Container / Registry\n | 'CONTAINER_TOKEN_ALREADY_BOUND'\n | 'CONTAINER_TOKEN_NOT_BOUND'\n | 'REGISTRY_DUPLICATE'\n | 'REGISTRY_NOT_FOUND'\n // General\n | 'UNKNOWN';\n\nexport type ErrorSubsystem =\n | 'provider'\n | 'tool'\n | 'config'\n | 'plugin'\n | 'agent'\n | 'session'\n | 'container'\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 === '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 === 'AGENT_ABORTED' ? 'warning' : 'error',\n recoverable: opts.recoverable ?? opts.code === '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'> = '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' ? '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 === 'SESSION_WRITE_FAILED' ? 'error' : 'warning',\n recoverable: opts.code !== '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// ── 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","import type { ContentBlock, TextBlock } from './blocks.js';\nimport type { ErrorCode } from './errors.js';\nimport { WrongStackError } 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 'PROVIDER_NETWORK_ERROR';\n if (type === 'rate_limit_error' || status === 429) return 'PROVIDER_RATE_LIMITED';\n if (type === 'authentication_error' || status === 401) return 'PROVIDER_AUTH_FAILED';\n if (type === 'overloaded_error' || status === 529) return 'PROVIDER_OVERLOADED';\n if (type === 'invalid_request_error' || status === 400) return 'PROVIDER_INVALID_REQUEST';\n if (status === 408) return 'PROVIDER_NETWORK_ERROR';\n if (status >= 500) return 'PROVIDER_SERVER_ERROR';\n return 'PROVIDER_INVALID_REQUEST';\n}\n","import type { Usage } from '../types/provider.js';\n\nexport type BudgetKind = 'tool_calls' | 'iterations' | 'tokens' | '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 /** Wall-clock timeout from start() to checkTimeout(). */\n timeoutMs?: number;\n}\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 * 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: `record*` methods throw `BudgetExceededError` synchronously the\n * moment a limit is crossed. The caller (runner/coordinator) catches this and\n * marks the task as 'failed' with the budget kind, so the operator can see\n * exactly which ceiling tripped.\n *\n * Timeout note: `checkTimeout()` is a cooperative guard called by the\n * runner on each iteration loop. The coordinator additionally enforces a\n * hard wall-clock deadline via `Promise.race` in `executeWithTimeout`.\n * Both mechanisms throw `BudgetExceededError` ('timeout') — the runner's\n * check is best-effort (catches cases where the runner loop doesn't call it)\n * and the coordinator's race is the authoritative cutoff. The two are\n * intentionally independent; they converge on the same error type so\n * `runDispatched` handles both identically.\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 constructor(limits: BudgetLimits = {}) {\n this.limits = Object.freeze({ ...limits });\n }\n\n start(): void {\n this.startTime = Date.now();\n }\n\n recordIteration(): void {\n this.iterations++;\n if (this.limits.maxIterations !== undefined && this.iterations > this.limits.maxIterations) {\n throw new BudgetExceededError('iterations', this.limits.maxIterations, this.iterations);\n }\n }\n\n recordToolCall(): void {\n this.toolCalls++;\n if (this.limits.maxToolCalls !== undefined && this.toolCalls > this.limits.maxToolCalls) {\n throw new BudgetExceededError('tool_calls', this.limits.maxToolCalls, this.toolCalls);\n }\n }\n\n recordUsage(usage: Usage, costUsd = 0): void {\n this.tokenInput += usage.input;\n this.tokenOutput += usage.output;\n this.costUsd += costUsd;\n\n const totalTokens = this.tokenInput + this.tokenOutput;\n if (this.limits.maxTokens !== undefined && totalTokens > this.limits.maxTokens) {\n throw new BudgetExceededError('tokens', this.limits.maxTokens, totalTokens);\n }\n if (this.limits.maxCostUsd !== undefined && this.costUsd > this.limits.maxCostUsd) {\n throw new BudgetExceededError('cost', this.limits.maxCostUsd, this.costUsd);\n }\n }\n\n /**\n * Throws if the wall-clock budget is exhausted. Call this from the iteration\n * loop so a hung tool can't keep a subagent running past its deadline.\n */\n checkTimeout(): void {\n if (this.startTime === null || this.limits.timeoutMs === undefined) return;\n const elapsed = Date.now() - this.startTime;\n if (elapsed > this.limits.timeoutMs) {\n throw new BudgetExceededError('timeout', this.limits.timeoutMs, elapsed);\n }\n }\n\n /** Returns true if a timeout has occurred without throwing. Useful for races. */\n isTimedOut(): boolean {\n if (this.startTime === null || this.limits.timeoutMs === undefined) return false;\n return Date.now() - this.startTime > this.limits.timeoutMs;\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","import { randomUUID } from 'node:crypto';\nimport { EventEmitter } from 'node:events';\nimport type { AgentBridge, BridgeMessage } from '../types/agent-bridge.js';\nimport type {\n CoordinatorStatus,\n MultiAgentConfig,\n MultiAgentCoordinator,\n SpawnResult,\n SubagentConfig,\n SubagentContext,\n SubagentError,\n SubagentErrorKind,\n SubagentRunContext,\n SubagentRunner,\n TaskResult,\n TaskSpec,\n} from '../types/multi-agent.js';\nimport { ProviderError } from '../types/provider.js';\nimport { BudgetExceededError, SubagentBudget } from './subagent-budget.js';\n\ntype SubagentStatus = 'running' | 'idle' | 'stopped' | 'error';\n\ninterface SubagentEntry {\n config: SubagentConfig;\n context: SubagentContext;\n status: SubagentStatus;\n currentTask?: string;\n abortController: AbortController;\n /** Lazily created on first dispatch — budget is per-task, not per-subagent. */\n activeBudget?: SubagentBudget;\n}\n\nexport interface MultiAgentCoordinatorOptions {\n /**\n * Callback that executes a task on behalf of a subagent. Required for\n * `assign()` to actually run anything — without it, tasks queue forever.\n * The coordinator provides per-subagent isolation (own budget, own signal,\n * own bridge) and enforces timeout + concurrency.\n */\n runner?: SubagentRunner;\n}\n\nexport class DefaultMultiAgentCoordinator extends EventEmitter implements MultiAgentCoordinator {\n readonly coordinatorId: string;\n readonly config: MultiAgentConfig;\n private runner?: SubagentRunner;\n\n private readonly subagents = new Map<string, SubagentEntry>();\n\n private pendingTasks: TaskSpec[] = [];\n private completedResults: TaskResult[] = [];\n private totalIterations = 0;\n private inFlight = 0;\n /**\n * Subagents currently being stopped. Set on entry to `stop()`, cleared\n * once `recordCompletion` lands the terminal TaskResult. Used by\n * `runDispatched` and `findIdleSubagent` to refuse mid-flight dispatch\n * to a subagent the caller has already asked to terminate — closes the\n * assign+terminate race where a fresh task could land on a worker that\n * was about to be killed.\n */\n private readonly terminating = new Set<string>();\n\n constructor(config: MultiAgentConfig, options: MultiAgentCoordinatorOptions = {}) {\n super();\n this.coordinatorId = config.coordinatorId;\n this.config = config;\n this.runner = options.runner;\n }\n\n /**\n * Replace the runner after construction. Used when the runner depends\n * on infrastructure (e.g. FleetBus) that isn't available until after\n * the coordinator's owning Director is built.\n */\n setRunner(runner: SubagentRunner): void {\n this.runner = runner;\n }\n\n async spawn(subagent: SubagentConfig): Promise<SpawnResult> {\n const id = subagent.id || randomUUID();\n // Duplicate-id guard. Previously a second spawn({id}) with the\n // same id silently overwrote the existing entry — orphaning the\n // first subagent's AbortController, Context, and any in-flight\n // task referencing it. Two spawns with the same id are almost\n // always a bug at the caller; refuse and let them surface it.\n if (this.subagents.has(id)) {\n throw new Error(`Subagent id \"${id}\" already exists — refusing to overwrite`);\n }\n const context: SubagentContext = {\n subagentId: id,\n tasks: [],\n // Wired later by the caller via setSubagentBridge() once the\n // bidirectional bridge is created. Readers must null-check / use\n // hasParentBridge() — the type now reflects this.\n parentBridge: null,\n doneCondition: this.config.doneCondition,\n maxConcurrent: this.config.maxConcurrent ?? 4,\n };\n\n this.subagents.set(id, {\n config: { ...subagent, id },\n context,\n status: 'idle',\n abortController: new AbortController(),\n });\n\n this.emit('subagent.started', { subagent: { ...subagent, id } });\n\n return { subagentId: id, agentId: id };\n }\n\n async assign(task: TaskSpec): Promise<void> {\n this.pendingTasks.push(task);\n this.tryDispatchNext();\n }\n\n async delegate(to: string, msg: BridgeMessage): Promise<void> {\n const subagent = this.subagents.get(to);\n if (!subagent) throw new Error(`Subagent \"${to}\" not found`);\n if (!subagent.context.parentBridge) {\n throw new Error(`Subagent \"${to}\" has no parentBridge — call setSubagentBridge() first`);\n }\n await subagent.context.parentBridge.send(msg);\n }\n\n /**\n * Wire up the communication bridge for a subagent. Call after spawn() once\n * the caller has created the bidirectional connection.\n */\n setSubagentBridge(subagentId: string, bridge: AgentBridge): void {\n const subagent = this.subagents.get(subagentId);\n if (!subagent) throw new Error(`Subagent \"${subagentId}\" not found`);\n subagent.context.parentBridge = bridge;\n }\n\n async stop(subagentId: string): Promise<void> {\n const subagent = this.subagents.get(subagentId);\n if (!subagent) return;\n\n // Mark terminating BEFORE the abort so a synchronous tryDispatchNext\n // observation in another callback path sees the intent and skips\n // this subagent. Cleared by recordCompletion once the runner's\n // catch block lands the terminal TaskResult.\n this.terminating.add(subagentId);\n\n // Abort any in-flight run, then sever the bridge so further messages fail\n // fast instead of silently queueing on a dead subagent.\n subagent.abortController.abort();\n subagent.status = 'stopped';\n subagent.currentTask = undefined;\n subagent.context.parentBridge = null;\n\n this.emit('subagent.stopped', { subagentId, reason: 'stopped by coordinator' });\n }\n\n async stopAll(): Promise<void> {\n // Clear the queue FIRST so no new tasks land on subagents while\n // we're tearing them down. Each dropped task gets a synthetic\n // `aborted_by_parent` completion so any caller awaiting it (e.g.\n // delegate tool's awaitTasks) resolves instead of hanging.\n //\n // Pending tasks never reached `inFlight`, so we cannot route them\n // through `recordCompletion` — its underflow guard would short-\n // circuit on the second pending task and emit a warning instead\n // of the completion event. The shared helper inline-emits.\n this.drainPendingAsAborted('Coordinator stopAll() drained the pending queue');\n // allSettled so one failure doesn't leave other subagents un-stopped.\n await Promise.allSettled([...this.subagents.keys()].map((id) => this.stop(id)));\n }\n\n getStatus(): CoordinatorStatus {\n return {\n coordinatorId: this.coordinatorId,\n subagents: Array.from(this.subagents.entries()).map(([id, s]) => ({\n id,\n name: s.config.name,\n status: s.status,\n currentTask: s.currentTask,\n })),\n pendingTasks: this.pendingTasks.length,\n completedTasks: this.completedResults.length,\n totalIterations: this.totalIterations,\n done: this.isDone(),\n };\n }\n\n /** Expose snapshot of completed results — useful for callers awaiting all done. */\n results(): readonly TaskResult[] {\n return this.completedResults;\n }\n\n /**\n * Manual completion — for callers that drive subagents without a runner\n * (e.g. external orchestrators). When a runner is configured the coordinator\n * calls this itself.\n */\n completeTask(result: TaskResult): void {\n this.recordCompletion(result);\n }\n\n // --- internal dispatching ---------------------------------------------\n\n private tryDispatchNext(): void {\n while (this.canDispatch()) {\n const subagentId = this.findIdleSubagent();\n if (!subagentId) {\n // No idle worker right now. If every spawned subagent is\n // stopped or mid-termination, the pending queue is dead —\n // a pending task can never start, so synthetic-complete it\n // as `aborted_by_parent`. Without this, an `assign()` after\n // `stop()` would hang forever waiting for `task.completed`.\n // We DO NOT drain when subagents are busy (status='running'):\n // those will free up and accept the work normally.\n if (this.pendingTasks.length > 0 && !this.hasLiveSubagent()) {\n this.drainPendingAsAborted(\n 'No live subagent available — all stopped or mid-termination',\n );\n }\n return;\n }\n const task = this.pendingTasks.shift();\n if (!task) return;\n // Attach a catch so a synchronous throw inside runDispatched (rare —\n // e.g. provider misconfiguration before the first await) becomes a\n // visible failed task instead of an unhandled rejection that leaves\n // `inFlight` permanently elevated.\n this.runDispatched(subagentId, task).catch((err) => {\n this.recordCompletion({\n subagentId,\n taskId: task.id,\n status: 'failed',\n error: classifySubagentError(err),\n iterations: 0,\n toolCalls: 0,\n durationMs: 0,\n });\n });\n }\n }\n\n private canDispatch(): boolean {\n const max = this.config.maxConcurrent ?? 4;\n return this.inFlight < max && this.pendingTasks.length > 0;\n }\n\n private findIdleSubagent(): string | null {\n for (const [id, s] of this.subagents) {\n // Skip subagents that are mid-termination — `stop()` set the\n // `terminating` flag and aborted the controller, but the\n // status mutation happens synchronously after; checking both\n // is belt-and-suspenders against any race where status is\n // transiently still 'idle' while termination is in flight.\n if (s.status === 'idle' && !this.terminating.has(id)) return id;\n }\n return null;\n }\n\n /**\n * Returns true iff at least one spawned subagent could still\n * process a task. A \"live\" subagent is one that is not stopped\n * AND not mid-termination — `running` workers count because they\n * will eventually finish and become idle.\n *\n * When no subagent has ever been spawned, returns `true` so a\n * pre-spawn `assign()` simply queues (legacy behaviour). The\n * dead-end detection only fires after `stop()` has retired every\n * spawned worker.\n *\n * Used by `tryDispatchNext` to detect a dead-end pending queue.\n */\n private hasLiveSubagent(): boolean {\n if (this.subagents.size === 0) return true;\n for (const [id, s] of this.subagents) {\n if (s.status !== 'stopped' && !this.terminating.has(id)) return true;\n }\n return false;\n }\n\n /**\n * Drain every pending task with a synthetic `aborted_by_parent`\n * completion event. Same shape as the `stopAll()` drain — we go\n * around `recordCompletion` because pending tasks were never\n * counted in `inFlight` and routing them through would trip the\n * underflow guard on every task after the first.\n */\n private drainPendingAsAborted(message: string): void {\n const dropped = this.pendingTasks.splice(0, this.pendingTasks.length);\n for (const t of dropped) {\n const synthetic: TaskResult = {\n subagentId: t.subagentId ?? 'unassigned',\n taskId: t.id,\n status: 'stopped',\n error: {\n kind: 'aborted_by_parent',\n message,\n retryable: false,\n },\n iterations: 0,\n toolCalls: 0,\n durationMs: 0,\n };\n this.completedResults.push(synthetic);\n this.emit('task.completed', { task: t, result: synthetic });\n }\n }\n\n private async runDispatched(subagentId: string, task: TaskSpec): Promise<void> {\n const subagent = this.subagents.get(subagentId);\n if (!subagent) return;\n // Final race guard: if `stop(subagentId)` ran between dispatch\n // and us arriving here, refuse to start the task and surface it\n // as `aborted_by_parent` so any caller awaiting the task id\n // unblocks. Without this, the task would be marked 'running',\n // collide with the just-completed 'stopped' state, and leak\n // inFlight by 1 because no recordCompletion path covers it.\n if (this.terminating.has(subagentId) || subagent.status === 'stopped') {\n this.recordCompletion({\n subagentId,\n taskId: task.id,\n status: 'stopped',\n error: {\n kind: 'aborted_by_parent',\n message: 'Subagent was terminated before task could start',\n retryable: false,\n },\n iterations: 0,\n toolCalls: 0,\n durationMs: 0,\n });\n return;\n }\n\n subagent.status = 'running';\n subagent.currentTask = task.id;\n task.subagentId = subagentId;\n subagent.context.tasks.push(task);\n\n this.emit('task.assigned', { task, subagentId });\n\n // Budget combines coordinator defaults with per-subagent and per-task overrides.\n // Precedence: task > subagent > coordinator default.\n const budget = new SubagentBudget({\n maxIterations: subagent.config.maxIterations ?? this.config.defaultBudget?.maxIterations,\n maxToolCalls:\n task.maxToolCalls ??\n subagent.config.maxToolCalls ??\n this.config.defaultBudget?.maxToolCalls,\n maxTokens: subagent.config.maxTokens ?? this.config.defaultBudget?.maxTokens,\n maxCostUsd: subagent.config.maxCostUsd ?? this.config.defaultBudget?.maxCostUsd,\n timeoutMs:\n task.timeoutMs ?? subagent.config.timeoutMs ?? this.config.defaultBudget?.timeoutMs,\n });\n subagent.activeBudget = budget;\n\n if (!this.runner) {\n // No runner wired — caller drives execution via completeTask(). Status\n // reverts when the caller reports. We intentionally don't bump\n // `inFlight` here: `completeTask` → `recordCompletion` would then\n // decrement an inFlight that runDispatched never incremented, masking\n // the \"no runner\" state. With this guard, `isDone()`'s all_tasks_done\n // check still settles correctly once the caller reports.\n return;\n }\n\n // Only count inFlight when we actually own the execution lifecycle.\n this.inFlight++;\n\n const startTime = Date.now();\n const runCtx: SubagentRunContext = {\n subagentId,\n config: subagent.config,\n budget,\n signal: subagent.abortController.signal,\n bridge: subagent.context.parentBridge || null,\n };\n\n let result: TaskResult;\n\n budget.start();\n try {\n const outcome = await this.executeWithTimeout(this.runner, task, runCtx, budget);\n result = {\n subagentId,\n taskId: task.id,\n status: 'success',\n result: outcome.result,\n iterations: outcome.iterations,\n toolCalls: outcome.toolCalls,\n durationMs: Date.now() - startTime,\n };\n } catch (err) {\n // Order matters: a timeout calls abort() to signal cooperative runners,\n // which also flips `signal.aborted=true`. Inspect the error first so we\n // surface 'timeout' rather than masking it as 'stopped'.\n const status: TaskResult['status'] =\n err instanceof BudgetExceededError && err.kind === 'timeout'\n ? 'timeout'\n : subagent.abortController.signal.aborted\n ? 'stopped'\n : 'failed';\n const usage = budget.usage();\n result = {\n subagentId,\n taskId: task.id,\n status,\n error: classifySubagentError(err, {\n parentAborted: subagent.abortController.signal.aborted,\n }),\n iterations: usage.iterations,\n toolCalls: usage.toolCalls,\n durationMs: Date.now() - startTime,\n };\n }\n\n this.recordCompletion(result);\n }\n\n private async executeWithTimeout(\n runner: SubagentRunner,\n task: TaskSpec,\n ctx: SubagentRunContext,\n budget: SubagentBudget,\n ) {\n const timeoutMs = budget.limits.timeoutMs;\n if (timeoutMs === undefined) return runner(task, ctx);\n\n let timer: ReturnType<typeof setTimeout> | null = null;\n const timeoutPromise = new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n // Abort the subagent's signal so cooperative runners can clean up.\n this.subagents.get(ctx.subagentId)?.abortController.abort();\n reject(new BudgetExceededError('timeout', timeoutMs, Date.now()));\n }, timeoutMs);\n });\n\n try {\n return await Promise.race([runner(task, ctx), timeoutPromise]);\n } finally {\n if (timer) clearTimeout(timer);\n }\n }\n\n private recordCompletion(result: TaskResult): void {\n this.completedResults.push(result);\n this.totalIterations += result.iterations;\n if (this.inFlight > 0) {\n this.inFlight--;\n } else if (this.runner) {\n // Runner-driven path completed without an outstanding inFlight slot —\n // shouldn't happen unless completeTask was called externally.\n this.emit('warning', {\n type: 'inFlight_underflow',\n taskId: result.taskId,\n subagentId: result.subagentId,\n });\n return;\n }\n\n const subagent = this.subagents.get(result.subagentId);\n if (subagent && subagent.status !== 'stopped') {\n const failed = result.status === 'failed' || result.status === 'timeout';\n // Synchronously reset the worker to idle after either a clean\n // finish or a transient failure. The previous code parked the\n // subagent in 'error' and used a `queueMicrotask` to flip it\n // back to 'idle' — that opened a window where `assign()` +\n // `tryDispatchNext` could race the microtask, leaving the\n // worker stuck in 'running' state while actually idle. By\n // resetting now, no async gap can leak the state machine.\n subagent.status = 'idle';\n void failed; // kept for future telemetry hooks\n subagent.currentTask = undefined;\n // If the run aborted (timeout or explicit stop), the subagent's\n // signal is now permanently aborted — recycling the controller lets\n // the next dispatched task start with a fresh cancellation scope.\n if (subagent.abortController.signal.aborted) {\n subagent.abortController = new AbortController();\n }\n }\n // Clear the terminating flag now that the worker has a terminal\n // TaskResult on record. Subsequent stop() calls re-add it; new\n // assign() calls can flow normally.\n this.terminating.delete(result.subagentId);\n\n this.emit('task.completed', {\n task: subagent?.context.tasks.find((t) => t.id === result.taskId) ?? { id: result.taskId },\n result,\n });\n\n this.tryDispatchNext();\n\n if (this.isDone()) {\n this.emit('done', {\n results: this.completedResults,\n totalIterations: this.totalIterations,\n });\n }\n }\n\n private isDone(): boolean {\n if (this.config.doneCondition.type === 'all_tasks_done') {\n return this.pendingTasks.length === 0 && this.inFlight === 0;\n }\n if (\n this.config.doneCondition.maxIterations !== undefined &&\n this.totalIterations >= this.config.doneCondition.maxIterations\n ) {\n return true;\n }\n return false;\n }\n}\n\n/**\n * Map any raw exception thrown out of a subagent's runner into a\n * structured `SubagentError`. This is the single point where the\n * coordinator decides \"what kind of failure was that\" — so callers\n * (delegate tool output, /agents UI, retry policies) branch on\n * `kind` instead of substring-matching `error.message`.\n *\n * The classification order matters:\n * 1. Provider errors first (their `status` + `retryable` are\n * already structured, just translate to our enum).\n * 2. Budget errors next (BudgetExceededError carries a discrete\n * `kind` we can lift directly).\n * 3. Parent-abort if the subagent's signal was aborted and we\n * didn't recognize the error otherwise — distinguishes user\n * Ctrl+C from a tool throwing.\n * 4. Substring sniffing for stable error markers (\"agent\n * aborted\" from agent-subagent-runner, \"Bridge transport\"\n * from agent-bridge).\n * 5. Fallback to `unknown` so callers know we couldn't classify.\n *\n * The `cause` field is always populated when `err` is an Error so\n * diagnostics survive even when `kind === 'unknown'` — no info is\n * dropped, the classifier just refused to commit.\n *\n * Exported because tests and CLI surfaces want to assert on the\n * classification without instantiating a coordinator.\n */\nexport function classifySubagentError(\n err: unknown,\n hints: { parentAborted?: boolean } = {},\n): SubagentError {\n const cause = err instanceof Error\n ? { name: err.name, message: err.message, stack: err.stack }\n : undefined;\n const baseMessage = err instanceof Error ? err.message : String(err);\n\n if (err instanceof ProviderError) {\n return providerErrorToSubagentError(err, baseMessage, cause);\n }\n\n if (err instanceof BudgetExceededError) {\n const map: Record<BudgetExceededError['kind'], SubagentErrorKind> = {\n iterations: 'budget_iterations',\n tool_calls: 'budget_tool_calls',\n tokens: 'budget_tokens',\n cost: 'budget_cost',\n timeout: 'budget_timeout',\n };\n return {\n kind: map[err.kind],\n message: baseMessage,\n // Budgets are user-configured ceilings, not transient failures —\n // retrying with the same budget will hit the same ceiling. The\n // orchestrator must raise the budget or narrow the task first.\n retryable: false,\n cause,\n };\n }\n\n // Distinguish parent-aborted from real failures BEFORE substring\n // sniffing — if the parent signal is aborted, the most common\n // exception is \"agent aborted\" thrown by agent-subagent-runner.\n if (hints.parentAborted) {\n return {\n kind: 'aborted_by_parent',\n message: baseMessage,\n retryable: false,\n cause,\n };\n }\n\n // Stable markers — these strings live in our own code and are\n // checked here intentionally so callers can react without\n // exception-type imports.\n const lower = baseMessage.toLowerCase();\n if (/agent aborted$/i.test(baseMessage)) {\n return {\n kind: 'aborted_by_parent',\n message: baseMessage,\n retryable: false,\n cause,\n };\n }\n if (/agent exhausted iteration limit$/i.test(baseMessage)) {\n return { kind: 'budget_iterations', message: baseMessage, retryable: false, cause };\n }\n if (/empty response$/i.test(baseMessage)) {\n return { kind: 'empty_response', message: baseMessage, retryable: false, cause };\n }\n // The runner throws `Error('tool failed: <name>')` when an executed tool\n // returned `ok:false` and the agent ultimately ended without recovering\n // (or aborted). Surface as `tool_failed` so callers don't conflate a\n // failed tool with a thrown tool — both are useful but mean different\n // things at the LLM layer.\n if (/^tool failed: /i.test(baseMessage)) {\n return { kind: 'tool_failed', message: baseMessage, retryable: false, cause };\n }\n if (lower.includes('bridge transport') || /bridge.*(closed|disconnect)/i.test(baseMessage)) {\n return { kind: 'bridge_failed', message: baseMessage, retryable: false, cause };\n }\n if (/context length|max.*tokens?.*exceeded|prompt is too long/i.test(baseMessage)) {\n return { kind: 'context_overflow', message: baseMessage, retryable: false, cause };\n }\n\n // Final fallback — preserve cause so diagnostics aren't lost.\n return {\n kind: 'unknown',\n message: baseMessage,\n retryable: false,\n cause,\n };\n}\n\nfunction providerErrorToSubagentError(\n err: ProviderError,\n message: string,\n cause: SubagentError['cause'],\n): SubagentError {\n const status = err.status;\n // Read suggested retry-after from the provider body when present so\n // the orchestrator doesn't have to invent a backoff. Most providers\n // include retry-after as a header / body field which our provider\n // layer normalises into `body.message` — we cannot trust a numeric\n // field exists, so we leave backoffMs unset when unknown.\n if (status === 429 || err.body?.type === 'rate_limit_error') {\n return {\n kind: 'provider_rate_limit',\n message,\n retryable: true,\n // Conservative default: 5s. Provider-specific code can override\n // by emitting an error whose body carries an explicit hint.\n backoffMs: 5_000,\n cause,\n };\n }\n if (status === 401 || status === 403 || err.body?.type === 'authentication_error') {\n return { kind: 'provider_auth', message, retryable: false, cause };\n }\n if (status === 408 || status === 0) {\n return { kind: 'provider_timeout', message, retryable: true, cause };\n }\n if (status >= 500 && status < 600) {\n return {\n kind: 'provider_5xx',\n message,\n retryable: true,\n backoffMs: 3_000,\n cause,\n };\n }\n // Other provider errors (400 invalid request, 404 not found, etc.)\n // are not retryable as-is and don't have a dedicated kind — surface\n // as 'unknown' so the orchestrator treats them as terminal.\n return { kind: 'unknown', message, retryable: err.retryable, cause };\n}\n","import { randomUUID } from 'node:crypto';\nimport * as fsp from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { DirectorStateCheckpoint } from '../storage/director-state.js';\nimport type { BridgeMessage } from '../types/agent-bridge.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 { JSONSchema, Tool } from '../types/tool.js';\nimport { InMemoryAgentBridge } from './agent-bridge.js';\nimport {\n DEFAULT_DIRECTOR_PREAMBLE,\n DEFAULT_SUBAGENT_BASELINE,\n composeDirectorPrompt,\n composeSubagentPrompt,\n rosterSummaryFromConfigs,\n} from './director-prompts.js';\nimport { FleetBus, type FleetUsage, FleetUsageAggregator } from './fleet-bus.js';\nimport { InMemoryBridgeTransport } from './in-memory-transport.js';\nimport { DefaultMultiAgentCoordinator } from './multi-agent-coordinator.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 `DirectorBudgetError`.\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\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 DirectorBudgetError extends Error {\n readonly kind: 'max_spawns' | 'max_spawn_depth';\n readonly limit: number;\n readonly observed: number;\n constructor(kind: 'max_spawns' | 'max_spawn_depth', limit: number, observed: number) {\n super(\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 );\n this.name = 'DirectorBudgetError';\n this.kind = kind;\n this.limit = limit;\n this.observed = observed;\n }\n}\n\nexport class Director {\n readonly id: string;\n readonly fleet: FleetBus;\n readonly usage: FleetUsageAggregator;\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 /** 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 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 /** 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 /**\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: ((payload: { task: TaskSpec; result: TaskResult }) => void) | null = null;\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.stateCheckpoint = opts.stateCheckpointPath\n ? new DirectorStateCheckpoint(opts.stateCheckpointPath, {\n directorRunId: this.id,\n maxSpawns: opts.maxSpawns,\n spawnDepth: this.spawnDepth,\n maxSpawnDepth: this.maxSpawnDepth,\n })\n : null;\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 // any failure surfaces later when an agent actually writes.\n void fsp.mkdir(this.sharedScratchpadPath, { recursive: true }).catch(() => undefined);\n }\n this.transport = new InMemoryBridgeTransport();\n this.bridge = new InMemoryAgentBridge(\n { agentId: this.id, coordinatorId: this.id },\n this.transport,\n );\n this.fleet = new FleetBus();\n this.usage = new FleetUsageAggregator(\n this.fleet,\n (id) => this.priceLookups.get(id),\n (id) => this.subagentMeta.get(id),\n );\n this.coordinator = new DefaultMultiAgentCoordinator(\n { ...opts.config, coordinatorId: this.id },\n { runner: opts.runner },\n );\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 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\n ? `${r.error.kind}: ${r.error.message}`\n : 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 this.scheduleManifest();\n };\n this.coordinator.on('task.completed', this.taskCompletedListener);\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 disable. */\n private scheduleManifest(): void {\n if (!this.manifestPath || this.manifestDebounceMs <= 0) return;\n if (this.manifestTimer) return;\n this.manifestTimer = setTimeout(() => {\n this.manifestTimer = null;\n void this.writeManifest().catch(() => undefined);\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 // Enforce safety caps BEFORE touching the coordinator — a refused\n // spawn must not leak partial state into the manifest or fleet bus.\n if (this.spawnDepth >= this.maxSpawnDepth) {\n throw new DirectorBudgetError('max_spawn_depth', this.maxSpawnDepth, this.spawnDepth);\n }\n if (this.spawnCount >= this.maxSpawns) {\n throw new DirectorBudgetError('max_spawns', this.maxSpawns, this.spawnCount + 1);\n }\n this.spawnCount += 1;\n const result = await this.coordinator.spawn(config);\n this.subagentMeta.set(result.subagentId, {\n provider: config.provider,\n model: config.model,\n });\n if (priceLookup) this.priceLookups.set(result.subagentId, priceLookup);\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 // Record for manifest. Task ids attach as they're assigned via\n // `assign()` below.\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 // Live state checkpoint + session event so crash recovery and the\n // resume banner both see this spawn even before any task is assigned.\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 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 fsp.writeFile(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 }\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 if (task.subagentId) {\n const entry = this.manifestEntries.get(task.subagentId);\n if (entry) entry.taskIds.push(taskWithId.id);\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 status(): CoordinatorStatus {\n return this.coordinator.getStatus();\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 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 const t: Tool[] = [\n makeSpawnTool(this, roster),\n makeAssignTool(this),\n makeAwaitTasksTool(this),\n makeAskTool(this),\n makeRollUpTool(this),\n makeTerminateTool(this),\n makeFleetStatusTool(this),\n makeFleetUsageTool(this),\n ];\n return t;\n }\n}\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\nfunction makeSpawnTool(director: Director, roster?: Record<string, SubagentConfig>): Tool {\n const inputSchema: JSONSchema = {\n type: 'object',\n properties: {\n role: {\n type: 'string',\n description:\n 'Roster role id (preferred). When set, the spawn uses the matching config from the roster and ignores other fields.',\n },\n name: {\n type: 'string',\n description: 'Display name for the subagent. Required when not using roster.',\n },\n provider: {\n type: 'string',\n description:\n 'Provider id (e.g. \"anthropic\", \"openai\"). Defaults to the leader provider when omitted.',\n },\n model: {\n type: 'string',\n description: 'Model id within the provider. Defaults to the leader model when omitted.',\n },\n systemPromptOverride: {\n type: 'string',\n description: 'Extra prompt text appended after the role-base prompt.',\n },\n maxIterations: { type: 'number' },\n maxToolCalls: { type: 'number' },\n maxCostUsd: { type: 'number' },\n },\n required: [],\n };\n return {\n name: 'spawn_subagent',\n description:\n 'Create a new subagent under this director. Returns the subagent id. Use this when you need a worker with a specific provider, model, or role to handle a piece of the plan.',\n usageHint:\n 'Either pass `role` (matches the roster) OR pass `name` + optional `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 base: SubagentConfig | undefined = role && roster ? roster[role] : undefined;\n if (role && !base) {\n return {\n error: `unknown role \"${role}\". roster has: ${roster ? Object.keys(roster).join(', ') : '(empty)'}`,\n };\n }\n const cfg: SubagentConfig = {\n ...(base ?? { 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')\n 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 try {\n const subagentId = await director.spawn(cfg);\n return { subagentId, provider: cfg.provider, model: cfg.model, name: cfg.name };\n } catch (err) {\n // Surface DirectorBudgetError (and any other spawn failure) as a\n // structured `{ error, kind }` payload so the leader model can\n // read the cap and replan — throwing would tear down the whole\n // tool call and give the model no signal to recover from.\n if (err instanceof DirectorBudgetError) {\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 makeAssignTool(director: Director): Tool {\n const inputSchema: JSONSchema = {\n type: 'object',\n properties: {\n subagentId: { type: 'string', description: 'Target subagent id. Required.' },\n description: {\n type: 'string',\n description: 'The task in natural language — what you want this subagent to do.',\n },\n maxToolCalls: { type: 'number', description: 'Optional per-task tool-call budget override.' },\n timeoutMs: { type: 'number', description: 'Optional per-task timeout in ms.' },\n },\n required: ['subagentId', 'description'],\n };\n return {\n name: 'assign_task',\n description:\n 'Hand a task to a previously spawned subagent. Returns the task id — pass it to `await_tasks` to block on completion.',\n permission: 'auto',\n mutating: false,\n inputSchema,\n async execute(input: unknown) {\n const i = input as {\n subagentId: string;\n description: string;\n maxToolCalls?: number;\n timeoutMs?: number;\n };\n const task: TaskSpec = {\n id: randomUUID(),\n description: i.description,\n subagentId: i.subagentId,\n maxToolCalls: i.maxToolCalls,\n timeoutMs: i.timeoutMs,\n };\n const taskId = await director.assign(task);\n return { taskId, subagentId: i.subagentId };\n },\n };\n}\n\nfunction makeAwaitTasksTool(director: Director): Tool {\n const inputSchema: JSONSchema = {\n type: 'object',\n properties: {\n taskIds: {\n type: 'array',\n items: { type: 'string' },\n description:\n 'One or more task ids returned by `assign_task`. The call blocks until every id resolves.',\n },\n },\n required: ['taskIds'],\n };\n return {\n name: 'await_tasks',\n description:\n 'Block until every named task completes. Returns the array of TaskResult — use this to gather subagent output before deciding the next step.',\n permission: 'auto',\n mutating: false,\n inputSchema,\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\nfunction makeAskTool(director: Director): Tool {\n const inputSchema: JSONSchema = {\n type: 'object',\n properties: {\n subagentId: {\n type: 'string',\n description: 'Subagent to ask. Must be a previously spawned id.',\n },\n question: {\n type: 'string',\n description: 'The question or instruction. Sent as the bridge message payload.',\n },\n timeoutMs: { type: 'number', description: 'Optional timeout in ms (default 30s).' },\n },\n required: ['subagentId', 'question'],\n };\n return {\n name: 'ask_subagent',\n description:\n 'Synchronously ask a subagent a question. Blocks until the subagent replies via the bridge (or the timeout fires). Use this when you need a one-shot answer without spawning a fresh task.',\n permission: 'auto',\n mutating: false,\n inputSchema,\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 return { ok: true, answer };\n } catch (err) {\n return { ok: false, error: err instanceof Error ? err.message : String(err) };\n }\n },\n };\n}\n\nfunction makeRollUpTool(director: Director): Tool {\n const inputSchema: JSONSchema = {\n type: 'object',\n properties: {\n taskIds: {\n type: 'array',\n items: { type: 'string' },\n description:\n 'Completed task ids to aggregate. Pass the ids returned by previous `assign_task` calls.',\n },\n style: {\n type: 'string',\n enum: ['markdown', 'json'],\n description:\n 'Output flavor — markdown (default) for in-prompt summarization, json for structured downstream processing.',\n },\n },\n required: ['taskIds'],\n };\n return {\n name: 'roll_up',\n description:\n \"Aggregate completed task results into a single formatted summary. Use this after `await_tasks` to fold subagent outputs back into the director's context before deciding the next step.\",\n permission: 'auto',\n mutating: false,\n inputSchema,\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\nfunction makeTerminateTool(director: Director): Tool {\n const inputSchema: JSONSchema = {\n type: 'object',\n properties: {\n subagentId: { type: 'string', description: 'Subagent to abort.' },\n },\n required: ['subagentId'],\n };\n return {\n name: 'terminate_subagent',\n description:\n 'Forcibly abort a subagent. Use sparingly — prefer waiting on the natural budget to expire. The current task (if any) ends with status \"stopped\".',\n permission: 'auto',\n mutating: true,\n inputSchema,\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\nfunction makeFleetStatusTool(director: Director): Tool {\n return {\n name: 'fleet_status',\n description:\n \"Snapshot of the fleet — every subagent's current status, pending vs. completed task counts, and the running total iteration count. Cheap; call freely.\",\n permission: 'auto',\n mutating: false,\n inputSchema: { type: 'object', properties: {}, required: [] },\n async execute() {\n return director.status();\n },\n };\n}\n\nfunction makeFleetUsageTool(director: Director): Tool {\n return {\n name: 'fleet_usage',\n description:\n 'Token + cost breakdown across the fleet, per-subagent and totals. Use this to reason about which workers to assign costly tasks to or when to wrap up to stay within budget.',\n permission: 'auto',\n mutating: false,\n inputSchema: { type: 'object', properties: {}, required: [] },\n async execute() {\n return director.snapshot();\n },\n };\n}\n","import * as fsp from 'node:fs/promises';\nimport * as path from 'node:path';\nimport type { SubagentConfig, TaskResult } from '../types/multi-agent.js';\nimport type { JSONSchema, Tool } from '../types/tool.js';\nimport type { Director } from './director.js';\n\n/**\n * Opaque host interface so this factory doesn't have to depend on the\n * CLI's `MultiAgentHost`. Any caller that exposes the same three\n * methods can wire `delegate` — including test doubles.\n */\nexport interface DelegateHost {\n /** True if a Director is already attached and running. */\n isDirectorMode(): boolean;\n /** Build (or return the cached) Director when director mode is on. */\n ensureDirector(): Promise<Director | null>;\n /**\n * Force-promote a non-director session into director mode at runtime.\n * Returns the Director, or null when promotion is impossible (e.g. a\n * non-director coordinator has already spawned subagents in the\n * legacy code path).\n */\n promoteToDirector(): Promise<Director | null>;\n /**\n * Optional: when promotion fails, return the human-readable reason.\n * Used to render an actionable error to the calling model instead of\n * the prior opaque \"Director could not be activated\" message.\n * Implementations may return null when they don't track the reason.\n */\n getPromotionBlockReason?(): string | null;\n}\n\nexport interface CreateDelegateToolOptions {\n host: DelegateHost;\n /**\n * Roster used to resolve `role` strings into full `SubagentConfig`s.\n * Typically `FLEET_ROSTER`. When omitted, `delegate({ role })` calls\n * fail and only the explicit `name + provider + model` path works.\n */\n roster?: Record<string, SubagentConfig>;\n /**\n * Default await timeout in milliseconds. `delegate` blocks until the\n * subagent's task resolves; without a cap, a stuck worker would hang\n * the host indefinitely. Set generously (default: 4 hours) so the\n * orchestrator can run multi-step refactors / monorepo audits\n * without being killed for being slow — the orchestrator must\n * decide per-call when a task needs to be cut short.\n */\n defaultTimeoutMs?: number;\n /**\n * Absolute directory under which per-subagent JSONL transcripts live —\n * matches `MultiAgentHostOptions.sessionsRoot`. When set, the delegate\n * tool reads the subagent's transcript on timeout / budget-exhaustion\n * to extract partial output, so the host LLM gets *something* useful\n * back instead of just an error.\n */\n sessionsRoot?: string;\n /**\n * The directorRunId used to namespace transcripts (typically the host\n * session id). Combined with `sessionsRoot` to locate per-subagent\n * JSONLs at `<sessionsRoot>/<runId>/<subagentId>.jsonl`.\n */\n directorRunId?: string;\n}\n\n/**\n * `delegate` — the only multi-agent tool a regular (non-director) agent\n * ever needs. It bundles spawn + assign + await into a single call and\n * transparently auto-promotes the host into director mode on first use.\n *\n * The model never has to ask \"are we in director mode?\" — it just calls\n * `delegate({ role, task })` and gets back a `TaskResult`. The cost of\n * that ergonomic packaging is that `delegate` cannot be used for\n * parallel work as-is; the model must fire multiple `delegate` calls in\n * parallel through the provider's parallel-tool-call surface, or escalate\n * to the explicit `spawn_subagent` + `assign_task` + `await_tasks` flow\n * when it wants fan-out it controls itself.\n */\nexport function createDelegateTool(opts: CreateDelegateToolOptions): Tool {\n // 4 hours by default. The previous 5-minute default killed any\n // non-trivial fan-out (monorepo audits, multi-file refactors) and\n // forced the orchestrator to constantly pass an explicit timeoutMs.\n // The right model here: the orchestrator should pick a tight value\n // only when it knows the work is small; otherwise let it run.\n const defaultTimeoutMs = opts.defaultTimeoutMs ?? 4 * 60 * 60 * 1000;\n const rosterIds = opts.roster ? Object.keys(opts.roster) : [];\n\n const inputSchema: JSONSchema = {\n type: 'object',\n properties: {\n task: {\n type: 'string',\n description:\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.',\n },\n role: {\n type: 'string',\n description:\n rosterIds.length > 0\n ? `Roster role (preferred). One of: ${rosterIds.join(', ')}. Picks a pre-tuned config (prompt, budgets, tools) for that role.`\n : 'No roster is configured — pass `name` instead.',\n enum: rosterIds.length > 0 ? rosterIds : undefined,\n },\n name: {\n type: 'string',\n description:\n 'Display name for the subagent when not using a roster role. Required when `role` is omitted.',\n },\n provider: {\n type: 'string',\n description:\n 'Provider id (e.g. \"anthropic\", \"openai\"). Defaults to the host provider when omitted.',\n },\n model: {\n type: 'string',\n description: 'Model id within the provider. Defaults to the host model when omitted.',\n },\n systemPromptOverride: {\n type: 'string',\n description: 'Optional extra prompt text appended to the role baseline.',\n },\n timeoutMs: {\n type: 'number',\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.`,\n },\n maxIterations: {\n type: 'number',\n description:\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).',\n },\n maxToolCalls: {\n type: 'number',\n description:\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).',\n },\n },\n required: ['task'],\n };\n\n return {\n name: 'delegate',\n description:\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). 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.\",\n usageHint:\n \"Set `task` to a complete instruction. Either pick `role` from the roster or pass `name` + `provider` + `model`. For non-trivial work, also pass `timeoutMs` (the wall-clock budget you actually need), `maxIterations`, and `maxToolCalls` — defaults are intentionally generous (4 hours) but the right values depend on scope. 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.\",\n permission: 'auto',\n mutating: false,\n inputSchema,\n async execute(input: unknown) {\n const i = (input ?? {}) as {\n task?: string;\n role?: string;\n name?: string;\n provider?: string;\n model?: string;\n systemPromptOverride?: string;\n timeoutMs?: number;\n maxIterations?: number;\n maxToolCalls?: number;\n };\n\n if (typeof i.task !== 'string' || !i.task.trim()) {\n return { ok: false, error: '`task` is required.' };\n }\n\n let director = await opts.host.ensureDirector();\n if (!director) {\n director = await opts.host.promoteToDirector();\n }\n if (!director) {\n // Prefer the host's structured reason (set by promoteToDirector\n // when it refuses) so the calling model can see \"3 subagents\n // running, wait or /fleet kill\" instead of a one-size-fits-all\n // \"could not activate\" string. Fall back to the legacy message\n // for hosts that don't implement the optional reason hook.\n const reason = opts.host.getPromotionBlockReason?.();\n return {\n ok: false,\n error:\n reason ??\n 'Director could not be activated — multi-agent host already running in legacy non-director mode. Restart with `--director` for fleet support.',\n };\n }\n\n const timeoutMs = i.timeoutMs ?? defaultTimeoutMs;\n\n // Resolve config: prefer roster role when provided, fall back to\n // explicit name/provider/model. The two forms are intentionally\n // exclusive to keep the surface narrow.\n let cfg: SubagentConfig;\n if (i.role) {\n const base = opts.roster?.[i.role];\n if (!base) {\n return {\n ok: false,\n error: `Unknown role \"${i.role}\". Available: ${rosterIds.join(', ') || '(no roster configured)'}.`,\n };\n }\n cfg = { ...base };\n if (i.systemPromptOverride) cfg.systemPromptOverride = i.systemPromptOverride;\n if (i.provider) cfg.provider = i.provider;\n if (i.model) cfg.model = i.model;\n } else {\n if (!i.name) {\n return {\n ok: false,\n error: 'Either `role` (from the roster) or `name` is required.',\n };\n }\n cfg = {\n name: i.name,\n provider: i.provider,\n model: i.model,\n systemPromptOverride: i.systemPromptOverride,\n };\n }\n\n // Caller-supplied iteration / tool-call budgets win over both the\n // role default and the coordinator default. This is how the\n // orchestrator dials a long-running audit up to \"as much as it\n // needs\" without us having to second-guess the right number\n // anywhere lower in the stack.\n if (typeof i.maxIterations === 'number' && i.maxIterations > 0) {\n cfg.maxIterations = i.maxIterations;\n }\n if (typeof i.maxToolCalls === 'number' && i.maxToolCalls > 0) {\n cfg.maxToolCalls = i.maxToolCalls;\n }\n\n // Timeout coordination (Fix 2). The subagent's internal `timeoutMs`\n // is its OWN budget cap; the delegate's `timeoutMs` is the host's\n // patience. If the host's patience runs out before the subagent's\n // budget does, the host sees a `__timeout` with no result — but\n // the subagent keeps running, burning compute the host can never\n // observe. Force the subagent's internal cap to land ~30s BEFORE\n // the host's timeout so the subagent always finishes (or\n // exhausts) within the host's window and surfaces a real\n // outcome instead of a silent loss.\n const SUBAGENT_TIMEOUT_BUFFER_MS = 30_000;\n const desiredSubTimeout = Math.max(30_000, timeoutMs - SUBAGENT_TIMEOUT_BUFFER_MS);\n if (!cfg.timeoutMs || cfg.timeoutMs > desiredSubTimeout) {\n cfg.timeoutMs = desiredSubTimeout;\n }\n\n try {\n const subagentId = await director.spawn(cfg);\n const taskId = await director.assign({\n id: '',\n description: i.task,\n subagentId,\n });\n const result = await Promise.race<TaskResult | { __timeout: true }>([\n director.awaitTasks([taskId]).then((r) => r[0] as TaskResult),\n new Promise<{ __timeout: true }>((resolve) =>\n setTimeout(() => resolve({ __timeout: true }), timeoutMs),\n ),\n ]);\n\n if ('__timeout' in result) {\n // Host gave up waiting. Subagent may still be running but the\n // budget coordination above should have already capped it ~30s\n // before this point. Try to extract whatever the subagent\n // produced so far from its JSONL transcript.\n const partial = await readSubagentPartial(opts, subagentId);\n return {\n ok: false,\n stopReason: 'host_timeout',\n error: `Subagent did not finish within ${timeoutMs}ms.`,\n hint: 'Reduce scope of the next delegate, raise timeoutMs, or use spawn_subagent + await_tasks for long-running work.',\n subagentId,\n taskId,\n partial,\n };\n }\n\n // Task completed — but \"completed\" can mean success, budget\n // exhaustion (failed/timeout), or stop. Distinguish them so\n // the host LLM can react differently:\n // - 'success' → end_turn, finalText reflects the actual answer\n // - 'failed'/'timeout' with iterations >= maxIterations → budget\n // - 'stopped' → user/director aborted\n // For non-success, also pull partial output from JSONL because\n // the runner throws on max_iterations and `result.result` ends\n // up empty.\n const baseStopReason: StopReason =\n result.status === 'success'\n ? 'end_turn'\n : result.status === 'timeout'\n ? 'subagent_timeout'\n : result.status === 'stopped'\n ? 'aborted'\n : 'budget_exhausted';\n const partial =\n result.status === 'success' ? undefined : await readSubagentPartial(opts, subagentId);\n\n // Lift the classified error envelope into top-level fields so a\n // model reading this output can branch on `errorKind` / `retryable`\n // without parsing a nested object. The original `error` envelope\n // is preserved verbatim for callers that want the full record\n // (including the `cause` stack for diagnostics).\n const errorKind = result.error?.kind;\n const retryable = result.error?.retryable;\n const backoffMs = result.error?.backoffMs;\n return {\n ok: result.status === 'success',\n status: result.status,\n stopReason: baseStopReason,\n errorKind,\n retryable,\n backoffMs,\n subagentId: result.subagentId,\n taskId: result.taskId,\n result: result.result,\n error: result.error,\n iterations: result.iterations,\n toolCalls: result.toolCalls,\n durationMs: result.durationMs,\n ...(partial ? { partial } : {}),\n ...(hintForKind(errorKind, retryable, backoffMs)\n ? { hint: hintForKind(errorKind, retryable, backoffMs) }\n : {}),\n };\n } catch (err) {\n return {\n ok: false,\n stopReason: 'error' as const,\n error: err instanceof Error ? err.message : String(err),\n };\n }\n },\n };\n}\n\ntype StopReason =\n | 'end_turn'\n | 'budget_exhausted'\n | 'subagent_timeout'\n | 'host_timeout'\n | 'aborted'\n | 'error';\n\n/**\n * Per-kind orchestrator hint. Returned alongside the structured error\n * so the calling model has a concrete next step instead of \"task\n * failed, good luck\". Returns undefined for success / unknown kinds —\n * the caller checks for presence before including in output.\n */\nfunction hintForKind(\n kind: string | undefined,\n retryable: boolean | undefined,\n backoffMs: number | undefined,\n): string | undefined {\n if (!kind) return undefined;\n switch (kind) {\n case 'provider_rate_limit':\n return `Provider rate-limited. Retry safe after ${backoffMs ?? 5000}ms backoff. Consider a smaller model or fewer parallel delegates.`;\n case 'provider_5xx':\n return `Provider server error. Retry safe after ${backoffMs ?? 3000}ms backoff — usually transient.`;\n case 'provider_timeout':\n return 'Provider network timeout. Retry safe; reduce input size if it persists.';\n case 'provider_auth':\n return 'Provider rejected credentials. Cannot retry — fix the API key / config and re-invoke.';\n case 'context_overflow':\n return 'Subagent context exceeded the model limit. Narrow the task, use a larger-context model, or split into multiple delegates.';\n case 'budget_iterations':\n case 'budget_tool_calls':\n case 'budget_tokens':\n case 'budget_cost':\n return 'Subagent exhausted its budget. Raise the matching `max*` field on the next delegate or narrow task scope.';\n case 'budget_timeout':\n return 'Subagent hit its wall-clock budget. Raise `timeoutMs` on the next delegate or split the task.';\n case 'aborted_by_parent':\n return 'Subagent was aborted (user Ctrl+C, parent unwound, or sibling failure cascade). Not retryable until the abort condition is resolved.';\n case 'empty_response':\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.';\n case 'tool_failed':\n return 'A tool inside the subagent returned ok:false. Inspect `partial.lastAssistantText` for the agent reasoning, then retry with corrected inputs.';\n case 'bridge_failed':\n return 'Parent-child bridge transport failed. This is rare — restart the session and retry.';\n default:\n return retryable\n ? 'Failure classified as retryable. Try again with the same input.'\n : undefined;\n }\n}\n\n/**\n * Parse the per-subagent JSONL at `<sessionsRoot>/<runId>/<subagentId>.jsonl`\n * and pull out the last few useful pieces — the most recent assistant\n * text response, the stop reason, and a count of tool calls. Used by\n * `delegate` when the subagent timed out or exhausted budget without\n * returning a clean `finalText`, so the host LLM still sees what work\n * actually happened.\n */\nasync function readSubagentPartial(\n opts: CreateDelegateToolOptions,\n subagentId: string,\n): Promise<\n | {\n lastAssistantText?: string;\n lastStopReason?: string;\n toolUsesObserved: number;\n events: number;\n }\n | undefined\n> {\n if (!opts.sessionsRoot) return undefined;\n // Locate the JSONL. When `directorRunId` is provided we know the\n // exact path; otherwise scan the sessionsRoot for any subdir\n // containing this subagent id.\n const candidates: string[] = [];\n if (opts.directorRunId) {\n candidates.push(path.join(opts.sessionsRoot, opts.directorRunId, `${subagentId}.jsonl`));\n } else {\n try {\n const runDirs = await fsp.readdir(opts.sessionsRoot);\n for (const r of runDirs) {\n candidates.push(path.join(opts.sessionsRoot, r, `${subagentId}.jsonl`));\n }\n } catch {\n return undefined;\n }\n }\n for (const file of candidates) {\n let raw: string;\n try {\n raw = await fsp.readFile(file, 'utf8');\n } catch {\n continue;\n }\n const lines = raw.split('\\n').filter((l) => l.trim());\n let lastAssistantText: string | undefined;\n let lastStopReason: string | undefined;\n let toolUses = 0;\n for (const line of lines) {\n try {\n const ev = JSON.parse(line) as {\n type: string;\n content?: unknown;\n stopReason?: string;\n name?: string;\n };\n if (ev.type === 'tool_use') toolUses += 1;\n if (ev.type === 'llm_response') {\n if (typeof ev.stopReason === 'string') lastStopReason = ev.stopReason;\n if (Array.isArray(ev.content)) {\n const txt = (ev.content as Array<{ type?: string; text?: string }>)\n .filter((b) => b.type === 'text')\n .map((b) => b.text ?? '')\n .join('\\n')\n .trim();\n if (txt) lastAssistantText = txt;\n }\n }\n } catch {\n // skip\n }\n }\n return {\n lastAssistantText,\n lastStopReason,\n toolUsesObserved: toolUses,\n events: lines.length,\n };\n }\n return undefined;\n}\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 { BudgetExceededError } 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 let budgetError: BudgetExceededError | null = null;\n\n const onBudgetError = (err: unknown) => {\n // Any error from a budget operation (BudgetExceededError, TypeError from\n // a malformed event payload, etc.) must abort the run. EventBus.emit()\n // swallows listener throws, so we can't re-throw — set budgetError and\n // abort the controller so the agent unwinds cooperatively.\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 onBudgetError(e2);\n }\n }),\n events.on('iteration.started', () => {\n try {\n ctx.budget.recordIteration();\n ctx.budget.checkTimeout();\n } catch (e) {\n onBudgetError(e);\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 try {\n ctx.budget.checkTimeout();\n } catch (e) {\n onBudgetError(e);\n }\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) throw budgetError;\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 { 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 {\n ResumedSession,\n SessionData,\n SessionEvent,\n SessionMetadata,\n SessionStore,\n SessionSummary,\n SessionWriter,\n} from '../types/session.js';\nimport { ensureDir } from '../utils/atomic-write.js';\n\nexport interface SessionStoreOptions {\n dir: string;\n /** Optional EventBus for emitting session diagnostics. */\n events?: EventBus;\n}\n\nexport class DefaultSessionStore implements SessionStore {\n private readonly dir: string;\n private readonly events?: EventBus;\n\n constructor(opts: SessionStoreOptions) {\n this.dir = opts.dir;\n this.events = opts.events;\n }\n\n async create(meta: Omit<SessionMetadata, 'startedAt'>): Promise<SessionWriter> {\n await ensureDir(this.dir);\n const startedAt = new Date().toISOString();\n const id = meta.id ?? `${startedAt.replace(/[:.]/g, '-')}-${randomBytes(2).toString('hex')}`;\n const file = path.join(this.dir, `${id}.jsonl`);\n let handle: fsp.FileHandle;\n try {\n handle = await fsp.open(file, 'a', 0o600);\n } catch (err) {\n // Preserve cause + errno so callers can branch on EACCES vs EMFILE\n // vs ENOSPC etc. instead of substring-matching the error message.\n throw new Error(\n `Failed to open session file: ${err instanceof Error ? err.message : String(err)}`,\n {\n cause: err,\n },\n );\n }\n try {\n return new FileSessionWriter(id, handle, startedAt, meta, { dir: this.dir, filePath: file });\n } catch (err) {\n await handle.close().catch(() => {});\n throw err;\n }\n }\n\n async resume(id: string): Promise<ResumedSession> {\n const data = await this.load(id);\n const file = path.join(this.dir, `${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 \"${id}\" for append: ${err instanceof Error ? err.message : String(err)}`,\n { cause: err },\n );\n }\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 { resumed: true, dir: this.dir, filePath: file },\n );\n return { writer, data };\n }\n\n async load(id: string): Promise<SessionData> {\n const file = path.join(this.dir, `${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 // Session JSONL is on-disk user-writable state; downstream replay\n // trusts `e.type` / `e.ts` etc. and would TypeError on a malformed\n // shape. Validate the discriminator + timestamp before pushing.\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 // else: skip — a hand-edited file with a partial object should not\n // crash replay, just lose that one event.\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 files = await fsp.readdir(this.dir);\n const ids = files.filter((f) => f.endsWith('.jsonl')).map((f) => f.replace(/\\.jsonl$/, ''));\n // Read all manifests in parallel; fall back to full load only for\n // sessions that haven't been closed cleanly (or predate the manifest).\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 // Equal timestamps — use id as tiebreaker for stable sort\n return a.id.localeCompare(b.id);\n });\n return out.slice(0, limit);\n } catch {\n return [];\n }\n }\n\n private async summaryFor(id: string): Promise<SessionSummary> {\n const manifest = path.join(this.dir, `${id}.summary.json`);\n try {\n const raw = await fsp.readFile(manifest, 'utf8');\n return JSON.parse(raw) as SessionSummary;\n } catch {\n // Manifest missing/corrupt — fall back to a full parse and backfill\n // the manifest so the next `list()` hits the fast path.\n const full = path.join(this.dir, `${id}.jsonl`);\n const stat = await fsp.stat(full);\n const summary = await this.summarize(id, stat.mtime.toISOString());\n await fsp\n .writeFile(manifest, JSON.stringify(summary), { mode: 0o600 })\n .catch((err) => {\n // Best-effort manifest write — list() falls back to full parse\n // on next invocation, so surface the error for diagnostics but\n // don't fail the listing.\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(path.join(this.dir, `${id}.jsonl`));\n await fsp.unlink(path.join(this.dir, `${id}.summary.json`)).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 };\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 // Orphan tool_result: tool_use was never seen. Skip to avoid\n // corrupting the replayed message sequence.\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 // Convert string content to blocks and append\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 truncated`,\n });\n // Return what we could replay instead of throwing — a damaged session\n // should not block the entire session-listing or resume path.\n return { messages, usage };\n }\n return { messages, usage };\n }\n}\n\nclass FileSessionWriter implements SessionWriter {\n private closed = false;\n private manifestFile: string;\n private summary: SessionSummary;\n private tokenIn = 0;\n private tokenOut = 0;\n private readonly filePath: string;\n /** Public accessor for the JSONL path — required by SessionWriter so\n * observability surfaces (`/fleet log`, FleetPanel) can locate the\n * transcript without recomputing the path from session metadata. */\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\n constructor(\n public readonly id: string,\n private readonly handle: fsp.FileHandle,\n private readonly startedAt: string,\n private readonly meta: Omit<SessionMetadata, 'startedAt'>,\n opts: { resumed?: boolean; dir?: string; filePath?: string } = {},\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.summary = {\n id,\n title: '(empty session)',\n startedAt,\n model: meta.model ?? 'unknown',\n provider: meta.provider ?? 'unknown',\n tokenTotal: 0,\n };\n // Session start is written lazily on first append to avoid sync I/O\n // in constructor and eliminate reliance on FileHandle.fd private property.\n }\n\n private async writeSessionStart(): Promise<void> {\n if (this.initDone || this.closed) return;\n this.initDone = true;\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 // Use fs.promises.writeFile directly to avoid FileHandle.fd private access\n await fsp.writeFile(this.filePath, record, { flag: 'a', mode: 0o600 });\n }\n } catch {\n // best-effort; session will still be usable without the start event logged\n }\n }\n\n async append(event: SessionEvent): Promise<void> {\n if (this.closed) return;\n if (!this.initDone) {\n await this.writeSessionStart();\n }\n this.observeForSummary(event);\n try {\n await this.handle.appendFile(`${JSON.stringify(event)}\\n`, 'utf8');\n } catch (err) {\n // A persistent failure (full disk, broken pipe) would otherwise log\n // once per appended event — which for a chatty agent run is a lot.\n // Debounce to one log per 5 s and surface the suppressed count.\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 /**\n * Watch events as they're appended and keep the summary state hot, so\n * `close()` can flush a `<id>.summary.json` manifest without re-reading\n * the JSONL. `list()` reads only manifests, turning a per-session full\n * parse into a single stat+read.\n */\n private observeForSummary(event: SessionEvent): void {\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 // session_end usage is the canonical total — prefer it if non-zero.\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.closed) return;\n this.closed = true;\n if (this.manifestFile) {\n try {\n await fsp.writeFile(this.manifestFile, JSON.stringify(this.summary), { mode: 0o600 });\n } catch {\n // manifest write is best-effort; list() falls back to full load.\n }\n }\n try {\n await this.handle.close();\n } catch {\n // ignore\n }\n }\n}\n\nfunction userInputTitle(content: string | ContentBlock[]): string {\n if (typeof content === 'string') return content.slice(0, 60);\n const text = 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 * Pre-built subagent role configurations for the WrongStack fleet.\n * These can be passed to `MultiAgentHost.spawn()` or used as templates\n * for the director's roster.\n */\nimport type { SubagentConfig } from '../types/multi-agent.js';\n\n/**\n * Audit Log Agent — analyzes session logs, event streams, and traces.\n * Use for: post-mortems, trend analysis, operational insights.\n */\nexport const AUDIT_LOG_AGENT: SubagentConfig = {\n id: 'audit-log',\n name: 'Audit Log',\n role: 'audit-log',\n prompt: `You are the Audit Log agent. Your job is to analyze structured JSONL\nsession logs and produce actionable markdown reports.\n\nScope:\n- Parse session logs (iteration counts, tool calls, errors, usage)\n- Detect repeated failure patterns across multiple runs\n- Identify tool usage anomalies (over-use, failures, unexpected chains)\n- Track token consumption trends\n- Generate structured audit reports with severity ratings\n\nInput format you accept:\n{ \"task\": \"analyze | report | trends\", \"sessionPath\": \"<path>\", \"focus\": \"errors | tools | usage | all\" }\n\nOutput: Markdown audit report with sections:\n- ## Summary (totals, error rate)\n- ## Top Errors (count + context)\n- ## Tool Usage (table with calls, failures, avg duration)\n- ## Anomalies (pattern → severity)\n\nWorking rules:\n- Never fabricate numbers — read the actual logs first\n- Always include file:line references for errors\n- If sessionPath is missing, ask the director to provide it\n- Report confidence level: high (>90% accuracy), medium, low`,\n\n // No hardcoded budgets — the orchestrator (delegate tool or\n // spawn_subagent) decides per-task how much room a subagent gets.\n // A monorepo audit needs hours; a single-file lint check needs\n // seconds. Pinning a number here forces the orchestrator to fight\n // the role's default instead of just asking for what it needs.\n};\n\n/**\n * Bug Hunter Agent — systematic bug and code smell detection.\n * Use for: pre-refactoring health checks, code review, regression prevention.\n */\nexport const BUG_HUNTER_AGENT: SubagentConfig = {\n id: 'bug-hunter',\n name: 'Bug Hunter',\n role: 'bug-hunter',\n prompt: `You are the Bug Hunter agent. Your job is to systematically scan\nsource code for bugs, anti-patterns, and code smells using pattern matching\nand heuristics. Output a prioritized hit list with file:line references.\n\nScope:\n- Detect common bug patterns (uncaught errors, resource leaks, race conditions)\n- Identify anti-patterns (callback hell, God objects, circular deps)\n- Find TypeScript-specific issues (unsafe any, missing null checks, branded types)\n- Flag security-sensitive constructs (eval, innerHTML, hardcoded secrets)\n- Rank findings: critical > high > medium > low\n\nInput format you accept:\n{ \"task\": \"scan | hunt | check\", \"paths\": [\"src/**/*.ts\"], \"focus\": \"bugs | patterns | security | all\", \"severityThreshold\": \"medium\" }\n\nOutput: Markdown bug hunt report:\n- ## Critical (must fix first)\n- ## High (should fix)\n- ## Medium\n- ## Low (consider)\nEach entry: **[TYPE]** \\`file:line\\` — description + suggested fix\n\nBug pattern reference you know:\n| Pattern | Regex hint | Severity |\n|---------|------------|----------|\n| Uncaught promise | /\\.then\\\\(.*\\\\)/ without catch | high |\n| Event leak | on\\\\( without off/removeListener | high |\n| Hardcoded secret | [a-zA-Z0-9/_-]{20,} in config files | critical |\n| unsafe any | : any\\\\b or <any> | medium |\n| innerHTML | innerHTML\\\\s*= | high |\n\nWorking rules:\n- Never scan node_modules — it's noise\n- Always include file:line for every finding\n- If >30% of findings are false positives, note the confidence level\n- Ask director for clarification if paths are ambiguous`,\n\n // Budgets are set by the orchestrator per task — see fleet.ts header.\n};\n\n/**\n * Refactor Planner Agent — structured refactoring planning.\n * Use for: large rewrites, technical debt reduction, architecture improvements.\n */\nexport const REFACTOR_PLANNER_AGENT: SubagentConfig = {\n id: 'refactor-planner',\n name: 'Refactor Planner',\n role: 'refactor-planner',\n prompt: `You are the Refactor Planner agent. Your job is to analyze code\nstructure and produce a concrete, phased refactoring plan with risk\nassessment, dependency ordering, and rollback strategy.\n\nScope:\n- Map module-level dependencies (import graph)\n- Identify coupling hotspots (high fan-in/out modules)\n- Assess refactoring risk by complexity and test coverage\n- Generate phased plans with checkpoint milestones\n- Produce diff-friendly task lists (one task = one concern)\n\nInput format you accept:\n{ \"task\": \"plan | assess | roadmap\", \"target\": \"src/core\", \"constraint\": \"no-breaking-changes | minimal-downtime | full-rewrite\", \"focus\": \"architecture | performance | maintainability\" }\n\nOutput: Markdown refactor plan:\n- ## Phase 1: Low Risk / High Payoff (do first)\n Table: | # | Task | Module | Risk | Est. Time |\n- ## Phase 2: Medium Risk\n- ## Phase 3: High Risk (requires full regression)\n- ## Dependency Graph (abbreviated ASCII)\n- ## Rollback Strategy\n- ## Exit Criteria (checkbox list)\n\nRisk scoring criteria:\n| Factor | Low | Medium | High |\n|--------|-----|--------|------|\n| Cyclomatic complexity | <10 | 10-20 | >20 |\n| Test coverage | >80% | 50-80% | <50% |\n| Fan-out (imports) | <5 | 5-15 | >15 |\n\nWorking rules:\n- Always include rollback strategy — every refactor can fail\n- Merge tasks that take <1h into a single phase\n- Respect team constraints (reviewer availability, parallelization)\n- Never plan without analyzing the actual code first`,\n\n // Budgets are set by the orchestrator per task — see fleet.ts header.\n};\n\n/**\n * Security Scanner Agent — vulnerability and secret detection.\n * Use for: CI checks, pre-release audits, dependency vulnerability scanning.\n */\nexport const SECURITY_SCANNER_AGENT: SubagentConfig = {\n id: 'security-scanner',\n name: 'Security Scanner',\n role: 'security-scanner',\n prompt: `You are the Security Scanner agent. Your job is to scan code,\nconfigs, and dependencies for security issues from hardcoded secrets to\nsupply chain risks.\n\nScope:\n- Detect hardcoded secrets: API keys, tokens, passwords, private keys\n- Find injection vectors: eval, innerHTML, SQL concat, shell injection\n- Identify insecure patterns: weak crypto, hardcoded IVs, disabled TLS\n- Scan dependencies for known CVEs (via npm/pnpm audit)\n- Flag supply chain risks: postinstall hooks, unverified scripts, .npmrc\n\nInput format you accept:\n{ \"task\": \"scan | audit | secrets | dependencies\", \"paths\": [\"src\", \"config\"], \"depth\": \"quick | normal | deep\" }\n\nOutput: Markdown security report:\n- ## CRITICAL: Secrets Found (with code snippets)\n- ## HIGH: Injection Vectors\n- ## MEDIUM: Insecure Patterns\n- ## Dependency Issues (CVE list)\n- ## Summary table (severity → count)\n- ## Remediation Checklist (with checkboxes)\n\nSecret patterns you detect:\n| Pattern | Example | Severity |\n|---------|---------|----------|\n| AWS Access Key | AKIAIOSFODNN7EXAMPLE | critical |\n| AWS Secret Key | [a-zA-Z0-9/+=]{40} base64 | critical |\n| GitHub Token | ghp_[a-zA-Z0-9]{36} | critical |\n| Private Key PEM | -----BEGIN.*PRIVATE KEY----- | critical |\n| JWT | eyJ[a-zA-Z0-9_-]+ | high |\n\nInjection patterns:\n| Construct | Safe alternative |\n|-----------|-----------------|\n| eval(str) | new Function() or parse |\n| innerHTML = x | textContent or sanitize |\n| exec(\\`cmd \\${x}\\`) | execFile with args array |\n\nWorking rules:\n- Never scan node_modules — use npm audit instead\n- Always provide remediation steps, not just findings\n- Verify regex-based secrets before flagging (false positive risk)\n- When in doubt, flag as medium rather than ignoring potential issues`,\n\n // Budgets are set by the orchestrator per task — see fleet.ts header.\n};\n\n/** All pre-built agents in a map for easy lookup by role. */\nexport const FLEET_ROSTER: Record<string, SubagentConfig> = {\n 'audit-log': AUDIT_LOG_AGENT,\n 'bug-hunter': BUG_HUNTER_AGENT,\n 'refactor-planner': REFACTOR_PLANNER_AGENT,\n 'security-scanner': SECURITY_SCANNER_AGENT,\n};\n\n/** Quick-access list for spawning all at once. */\nexport const ALL_FLEET_AGENTS = Object.values(FLEET_ROSTER);\n"]}