@wrongstack/core 0.54.1 → 0.63.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{agent-bridge-Dnhw4tnM.d.ts → agent-bridge-B5rxWrg3.d.ts} +1 -1
- package/dist/{agent-subagent-runner-By7jruZ_.d.ts → agent-subagent-runner-Zc3f37Sg.d.ts} +3 -3
- package/dist/{compactor-Duhsf0ge.d.ts → compactor-0vjZ8KTk.d.ts} +1 -1
- package/dist/{config-bht0txXS.d.ts → config-BdDuaZmB.d.ts} +112 -2
- package/dist/{context-DtPKqKYV.d.ts → context-iFMEO2rN.d.ts} +8 -8
- package/dist/coordination/index.d.ts +12 -12
- package/dist/defaults/index.d.ts +21 -21
- package/dist/defaults/index.js +254 -92
- package/dist/defaults/index.js.map +1 -1
- package/dist/{events-CbHTS4ZZ.d.ts → events-k8CHjcrN.d.ts} +20 -1
- package/dist/execution/index.d.ts +14 -14
- package/dist/execution/index.js +70 -10
- package/dist/execution/index.js.map +1 -1
- package/dist/extension/index.d.ts +7 -7
- package/dist/{goal-store-DwcTDDiX.d.ts → goal-store-iHltMi5n.d.ts} +1 -1
- package/dist/{index-CI271MjL.d.ts → index-Bc6BiP5q.d.ts} +77 -6
- package/dist/{index-ge5F2dnc.d.ts → index-CWdW_CJt.d.ts} +10 -8
- package/dist/index.d.ts +56 -32
- package/dist/index.js +520 -85
- package/dist/index.js.map +1 -1
- package/dist/infrastructure/index.d.ts +6 -6
- package/dist/infrastructure/index.js +1 -1
- package/dist/infrastructure/index.js.map +1 -1
- package/dist/kernel/index.d.ts +9 -9
- package/dist/kernel/index.js +3 -1
- package/dist/kernel/index.js.map +1 -1
- package/dist/{mcp-servers-DE6gzBry.d.ts → mcp-servers-CwqQDMYy.d.ts} +3 -3
- package/dist/models/index.d.ts +2 -2
- package/dist/{multi-agent-BmC_xiog.d.ts → multi-agent-SASYOrWA.d.ts} +2 -2
- package/dist/{multi-agent-coordinator-CjNX4uBD.d.ts → multi-agent-coordinator-CNUJYq7U.d.ts} +2 -2
- package/dist/{null-fleet-bus-BNiSlTna.d.ts → null-fleet-bus-DRoJ0uOY.d.ts} +7 -7
- package/dist/observability/index.d.ts +2 -2
- package/dist/{path-resolver-Bax85amb.d.ts → path-resolver-C5sPVne8.d.ts} +2 -2
- package/dist/{permission-Drm7LpPo.d.ts → permission-Ld-i5ugf.d.ts} +13 -1
- package/dist/{permission-policy-CU6sqWxF.d.ts → permission-policy-CL-mPufp.d.ts} +14 -7
- package/dist/{plan-templates-CLRcurWN.d.ts → plan-templates-ThBHOjaM.d.ts} +4 -4
- package/dist/{provider-runner-BikCxGCx.d.ts → provider-runner-DJQa211J.d.ts} +3 -3
- package/dist/{retry-policy-Chtlvr5b.d.ts → retry-policy-BfBScewS.d.ts} +1 -1
- package/dist/sdd/index.d.ts +9 -9
- package/dist/sdd/index.js +1 -1
- package/dist/sdd/index.js.map +1 -1
- package/dist/security/index.d.ts +3 -3
- package/dist/security/index.js +115 -13
- package/dist/security/index.js.map +1 -1
- package/dist/{selector-BvSPdJj6.d.ts → selector-DxhW7ML3.d.ts} +1 -1
- package/dist/{session-reader-BGhzMir4.d.ts → session-reader-q2ThszgG.d.ts} +1 -1
- package/dist/storage/index.d.ts +6 -6
- package/dist/{system-prompt-dtzV_mLm.d.ts → system-prompt-7LHyBbIf.d.ts} +32 -2
- package/dist/{tool-executor-CgU0yWpB.d.ts → tool-executor-CIjpGaRA.d.ts} +5 -4
- package/dist/types/index.d.ts +14 -14
- package/dist/types/index.js +62 -6
- package/dist/types/index.js.map +1 -1
- package/dist/utils/index.d.ts +2 -2
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/token-estimate.ts","../../src/utils/message-invariants.ts","../../src/execution/compactor.ts","../../src/types/blocks.ts","../../src/execution/intelligent-compactor.ts","../../src/models/llm-selector.ts","../../src/execution/selective-compactor.ts","../../src/types/errors.ts","../../src/execution/auto-compaction-middleware.ts","../../src/security/capabilities.ts","../../src/utils/json-schema-validate.ts","../../src/utils/tool-output-serializer.ts","../../src/execution/tool-executor.ts","../../src/utils/regex-guard.ts","../../src/execution/autonomous-runner.ts","../../src/utils/atomic-write.ts","../../src/storage/goal-store.ts","../../src/execution/eternal-autonomy.ts","../../src/coordination/subagent-budget.ts","../../src/coordination/agent-subagent-runner.ts","../../src/coordination/agents/types.ts","../../src/coordination/agents/phase1-discovery.ts","../../src/coordination/agents/phase2-planning.ts","../../src/coordination/agents/phase3-build.ts","../../src/coordination/agents/phase4-verify.ts","../../src/coordination/agents/phase5-review.ts","../../src/coordination/agents/phase6-domain.ts","../../src/coordination/agents/phase7-knowledge.ts","../../src/coordination/agents/phase8-delivery.ts","../../src/coordination/agents/phase9-meta.ts","../../src/coordination/agents/index.ts","../../src/coordination/dispatcher.ts","../../src/types/provider.ts","../../src/coordination/fleet.ts","../../src/coordination/subagent-nicknames.ts","../../src/coordination/multi-agent-coordinator.ts","../../src/execution/parallel-eternal-engine.ts","../../src/execution/autonomy-prompt-contributor.ts","../../src/execution/goal-preamble.ts","../../src/execution/regex-patterns.ts","../../src/execution/retry-policy.ts","../../src/execution/error-handler.ts","../../src/execution/skill-loader.ts"],"names":["hasToolUse","repair","afterTokens","afterFull","path","stat","resolve","path2","fsp","unlink","first","decision","kind","baseMessage","sleep","GOAL_COMPLETE_MARKER","randomUUID","execFile","promisify","execFileP","fs2","path3"],"mappings":";;;;;;;;;AAoBA,IAAM,kBAAA,GAAqB,CAAC,IAAA,EAAc,aAAA,GAAgB,GAAA,KACxD,IAAA,CAAK,GAAA,CAAI,CAAA,EAAG,IAAA,CAAK,IAAA,CAAK,IAAA,CAAK,MAAA,GAAS,aAAa,CAAC,CAAA;AAoBpD,IAAM,cAAA,uBAAqB,GAAA,EAAoB;AAE/C,IAAM,uBAAA,GAA0B,GAAA;AAEhC,SAAS,iBAAA,CAAkB,KAAa,OAAA,EAA+B;AACrE,EAAA,MAAM,QAAA,GA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AA,GACjB,KAAK,KAAA,CAAM,CAAA,EAAG,mBAAmB,CAAC,CAAA,CAAE,IAAA,EAAK,GACxC,KAAK,IAAA,EAAK,CAAE,MAAM,IAAI,CAAA,CAAE,CAAC,CAAA,IAAK,EAAA;AAGrC,EAAA,MAAM,QAAkB,EAAC;AACzB,EAAA,MAAM,WAAA,GAAc,qCAAA,CAAsC,IAAA,CAAK,IAAI,CAAA;AACnE,EAAA,IAAI,WAAA,EAAa;AACf,IAAA,MAAM,QAAQ,WAAA,CAAY,CAAC,EACxB,OAAA,CAAQ,OAAA,EAAS,GAAG,CAAA,CACpB,KAAA,CAAM,GAAG,CAAA,CACT,GAAA,CAAI,CAAC,CAAA,KAAM,CAAA,CAAE,MAAM,CAAA,CACnB,OAAO,OAAO,CAAA;AACjB,IAAA,KAAA,CAAM,IAAA,CAAK,GAAG,KAAK,CAAA;AAAA,EACrB;AAEA,EAAA,OAAO,EAAE,SAAS,KAAA,EAAM;AAC1B","file":"index.js","sourcesContent":["/**\n * Shared token estimation with JSON.stringify caching.\n * Avoids repeated stringification of tool input objects.\n *\n * ## Calibration\n *\n * `estimateRequestTokens` uses a fixed 3.5 chars/token heuristic — a\n * conservative overestimate that prevents underestimation but reduces\n * accuracy. After each API call, call `recordActualUsage()` with the\n * real `usage.input` from the provider response. The module maintains a\n * rolling average of `actual / estimated` ratio (EWM, α=0.3) and\n * applies it to subsequent calls via `estimateRequestTokensCalibrated`.\n *\n * Calibration is per-module (shared across all callers), which is\n * sufficient: the chars/token ratio is a property of the tokenizer,\n * not the model. Uncalibrated calls (before any samples, or when\n * `recordActualUsage` is not called) fall back to the uncalibrated\n * estimate so nothing breaks.\n */\n\nconst RoughTokenEstimate = (text: string, charsPerToken = 3.5): number =>\n Math.max(1, Math.ceil(text.length / charsPerToken));\n\n/** Calibration state: actual/estimated ratio via exponential weighted moving average. */\nconst _cal = {\n ratio: 1.0, // current calibration multiplier (actual / estimated)\n count: 0, // number of samples recorded\n prevEst: 0, // estimated tokens from the most recent estimateRequestTokens call\n /** EWM α — higher = faster adaptation, more volatile */\n alpha: 0.3,\n};\n\nconst MIN_SAMPLES_FOR_CALIBRATION = 3;\n\n/**\n * Cache of computed estimates keyed by the stringified input — not the\n * input object itself. Previously the cache was keyed by the input object\n * via WeakMap, but JSON.stringify() produces a new object reference each\n * call so the cache never hit. Now we use a Map with string keys so that\n * repeated stringifications of the same structure share a single entry.\n */\nconst ESTIMATE_CACHE = new Map<string, number>();\n\nconst ESTIMATE_CACHE_MAX_SIZE = 10_000;\n\nfunction getCachedEstimate(key: string, compute: () => number): number {\n const existing = ESTIMATE_CACHE.get(key);\n if (existing !== undefined) return existing;\n if (ESTIMATE_CACHE.size >= ESTIMATE_CACHE_MAX_SIZE) {\n // Evict oldest quarter when at capacity — simple LRU-ish policy.\n const keys = [...ESTIMATE_CACHE.keys()];\n for (let i = 0; i < Math.floor(ESTIMATE_CACHE_MAX_SIZE / 4); i++) {\n ESTIMATE_CACHE.delete(keys[i]!);\n }\n }\n const estimate = compute();\n ESTIMATE_CACHE.set(key, estimate);\n return estimate;\n}\n\n/**\n * Estimate tokens for a tool_use block input.\n * Caches the stringified result keyed by the stable string representation\n * to avoid repeated JSON.stringify calls during context window checks.\n */\nexport function estimateToolInputTokens(input: unknown): number {\n if (typeof input === 'string') return RoughTokenEstimate(input);\n if (input === null || typeof input !== 'object') {\n return RoughTokenEstimate(String(input));\n }\n const key = JSON.stringify(input);\n return getCachedEstimate(key, () => RoughTokenEstimate(key));\n}\n\n/**\n * Estimate tokens for a tool_result content.\n */\nexport function estimateToolResultTokens(content: string | unknown): number {\n if (typeof content === 'string') return RoughTokenEstimate(content);\n const key = JSON.stringify(content);\n return getCachedEstimate(key, () => RoughTokenEstimate(key));\n}\n\n/**\n * Estimate tokens for a text block.\n */\nexport function estimateTextTokens(text: string): number {\n return RoughTokenEstimate(text);\n}\n\n/**\n * Rough estimate of tokens in a tool definition (name + description + schema).\n * Accounts for the JSON-serialized inputSchema which is sent to the API\n * but NOT included in roughEstimate(content).\n */\nexport function estimateToolDefTokens(tool: { name: string; description?: string; inputSchema: unknown }): number {\n return RoughTokenEstimate(tool.name) +\n RoughTokenEstimate(tool.description ?? '') +\n RoughTokenEstimate(JSON.stringify(tool.inputSchema));\n}\n\n/**\n * Estimate the total API request token count: system prompt + tool definitions\n * + conversation messages. Use this for context-window bar calculations\n * instead of roughEstimate (which only counts messages).\n *\n * The overhead ratio (overhead / messages) varies by conversation length:\n * - Short conversations (< 10 messages): ~30-50% overhead (large system+tools)\n * - Medium (10-50 messages): ~15-30%\n * - Long (> 50 messages): ~5-15%\n *\n * Returns { messages, systemPrompt, tools, total } for debugging display.\n */\nexport interface RequestTokenBreakdown {\n messages: number;\n systemPrompt: number;\n tools: number;\n total: number;\n}\n\nexport function estimateRequestTokens(\n messages: unknown,\n systemPrompt: unknown,\n tools: { name: string; description?: string; inputSchema: unknown }[],\n): RequestTokenBreakdown {\n // Messages: apply the same logic as roughEstimate\n let messagesTokens = 0;\n if (typeof messages === 'string') {\n messagesTokens = RoughTokenEstimate(messages);\n } else if (Array.isArray(messages)) {\n for (const m of messages) {\n if (typeof m === 'object' && m !== null && 'content' in m) {\n const content = (m as { content: unknown }).content;\n if (typeof content === 'string') {\n messagesTokens += RoughTokenEstimate(content);\n } else if (Array.isArray(content)) {\n for (const b of content) {\n if (typeof b === 'object' && b !== null) {\n if ((b as { type?: string }).type === 'text') {\n messagesTokens += RoughTokenEstimate((b as { text: string }).text);\n } else {\n messagesTokens += RoughTokenEstimate(JSON.stringify(b));\n }\n }\n }\n }\n }\n }\n }\n\n // System prompt\n let systemTokens = 0;\n if (typeof systemPrompt === 'string') {\n systemTokens = RoughTokenEstimate(systemPrompt);\n } else if (Array.isArray(systemPrompt)) {\n for (const b of systemPrompt) {\n if (typeof b === 'object' && b !== null && (b as { type?: string }).type === 'text') {\n systemTokens += RoughTokenEstimate((b as { text: string }).text);\n }\n }\n }\n\n // Tool definitions\n let toolsTokens = 0;\n for (const t of tools) {\n toolsTokens += estimateToolDefTokens(t);\n }\n\n const total = messagesTokens + systemTokens + toolsTokens;\n\n // Record the raw estimate for calibration: the next recordActualUsage()\n // call will pair this against the actual API usage so the rolling ratio\n // stays in sync with the real chars/token ratio of the content.\n _cal.prevEst = total;\n\n return {\n messages: messagesTokens,\n systemPrompt: systemTokens,\n tools: toolsTokens,\n total,\n };\n}\n\n/**\n * Record the actual API input token count after a provider call so\n * `estimateRequestTokensCalibrated` can self-correct on subsequent calls.\n *\n * Prefer passing `estimatedInputTokens` explicitly (the calibrated pre-flight\n * estimate from the middleware) — this avoids race conditions when other code\n * also calls `estimateRequestTokens` between the pre-flight and this call\n * (e.g. audit logging in agent.ts).\n *\n * When `estimatedInputTokens` is omitted, falls back to `_cal.prevEst`\n * for backward compatibility with callers that don't have the pre-flight value.\n */\nexport function recordActualUsage(actualInputTokens: number, estimatedInputTokens?: number): void {\n if (actualInputTokens <= 0) return;\n const est = estimatedInputTokens ?? _cal.prevEst;\n if (est <= 0) return;\n\n const sampleRatio = actualInputTokens / est;\n if (_cal.count === 0) {\n _cal.ratio = sampleRatio;\n } else {\n // EWM: new = α * sample + (1-α) * old → α=0.3 = fast initial converge\n _cal.ratio = _cal.alpha * sampleRatio + (1 - _cal.alpha) * _cal.ratio;\n }\n // Sanity bound: keep the rolling ratio within [0.5, 1.5] so a sequence\n // of bad samples can't blow up the calibration for everyone.\n _cal.ratio = Math.min(1.5, Math.max(0.5, _cal.ratio));\n _cal.count++;\n}\n\n/**\n * Returns the current calibration state. Exposed for debugging and\n * tests — not needed by normal callers.\n */\nexport function getCalibrationState(): { ratio: number; count: number; calibrated: boolean } {\n return {\n ratio: _cal.ratio,\n count: _cal.count,\n calibrated: _cal.count >= MIN_SAMPLES_FOR_CALIBRATION,\n };\n}\n\n/**\n * Like `estimateRequestTokens` but applies the rolling calibration factor\n * so context pressure readings converge on reality within a few iterations.\n *\n * Before any `recordActualUsage` samples are collected, returns the same\n * result as `estimateRequestTokens` (ratio = 1.0, no distortion).\n * After `MIN_SAMPLES_FOR_CALIBRATION` samples, applies the calibrated\n * multiplier capped to the range [0.5, 1.5] as a sanity bound.\n */\nexport function estimateRequestTokensCalibrated(\n messages: unknown,\n systemPrompt: unknown,\n tools: { name: string; description?: string; inputSchema: unknown }[],\n): RequestTokenBreakdown {\n const result = estimateRequestTokens(messages, systemPrompt, tools);\n\n if (_cal.count >= MIN_SAMPLES_FOR_CALIBRATION) {\n const safeRatio = Math.min(1.5, Math.max(0.5, _cal.ratio));\n return {\n messages: Math.round(result.messages * safeRatio),\n systemPrompt: Math.round(result.systemPrompt * safeRatio),\n tools: Math.round(result.tools * safeRatio),\n total: Math.round(result.total * safeRatio),\n };\n }\n\n return result;\n}\n\n/**\n * Resets calibration state. Primarily for tests that run in the same\n * process and need a clean slate between suites.\n */\nexport function resetCalibration(): void {\n _cal.ratio = 1.0;\n _cal.count = 0;\n _cal.prevEst = 0;\n}\n","import type { ContentBlock, ToolResultBlock, ToolUseBlock } from '../types/blocks.js';\nimport type { Message } from '../types/messages.js';\n\nexport interface MessageRepairReport {\n changed: boolean;\n removedToolUses: string[];\n removedToolResults: string[];\n removedMessages: number;\n}\n\nexport interface MessageRepairResult {\n messages: Message[];\n report: MessageRepairReport;\n}\n\n/**\n * Repair provider-level tool-call adjacency invariants.\n *\n * Anthropic requires every assistant `tool_use` block to have a matching\n * `tool_result` block in the immediately following user message. Manual\n * context surgery (summary/prune) can cut through the middle of such an\n * exchange. This function removes only the now-orphaned protocol blocks,\n * preserving surrounding text/images/thinking blocks where possible.\n */\nexport function repairToolUseAdjacency(messages: Message[]): MessageRepairResult {\n const removedToolUses: string[] = [];\n const removedToolResults: string[] = [];\n let removedMessages = 0;\n let changed = false;\n const out: Message[] = [];\n\n for (let i = 0; i < messages.length; i++) {\n const original = messages[i]!;\n let msg = original;\n\n if (hasToolUse(msg)) {\n const nextIds = toolResultIds(messages[i + 1]);\n const filtered = mapContent(msg, (blocks) => {\n const next: ContentBlock[] = [];\n for (const block of blocks) {\n if (block.type === 'tool_use' && !nextIds.has(block.id)) {\n removedToolUses.push(block.id);\n changed = true;\n continue;\n }\n next.push(block);\n }\n return next;\n });\n msg = filtered ?? msg;\n }\n\n if (hasToolResult(msg)) {\n const allowed = toolUseIds(out[out.length - 1]);\n const filtered = mapContent(msg, (blocks) => {\n const next: ContentBlock[] = [];\n for (const block of blocks) {\n if (block.type === 'tool_result' && !allowed.has(block.tool_use_id)) {\n removedToolResults.push(block.tool_use_id);\n changed = true;\n continue;\n }\n next.push(block);\n }\n return next;\n });\n msg = filtered ?? msg;\n }\n\n if (isEmptyMessage(msg)) {\n removedMessages++;\n changed = true;\n continue;\n }\n out.push(msg);\n }\n\n return {\n messages: changed ? out : messages,\n report: { changed, removedToolUses, removedToolResults, removedMessages },\n };\n}\n\nfunction hasToolUse(msg: Message | undefined): boolean {\n return contentBlocks(msg).some((b): b is ToolUseBlock => b.type === 'tool_use');\n}\n\nfunction hasToolResult(msg: Message | undefined): boolean {\n return contentBlocks(msg).some((b): b is ToolResultBlock => b.type === 'tool_result');\n}\n\nfunction toolUseIds(msg: Message | undefined): Set<string> {\n const ids = new Set<string>();\n if (!msg || msg.role !== 'assistant') return ids;\n for (const block of contentBlocks(msg)) {\n if (block.type === 'tool_use') ids.add(block.id);\n }\n return ids;\n}\n\nfunction toolResultIds(msg: Message | undefined): Set<string> {\n const ids = new Set<string>();\n if (!msg || msg.role !== 'user') return ids;\n for (const block of contentBlocks(msg)) {\n if (block.type === 'tool_result') ids.add(block.tool_use_id);\n }\n return ids;\n}\n\nfunction contentBlocks(msg: Message | undefined): ContentBlock[] {\n return msg && Array.isArray(msg.content) ? msg.content : [];\n}\n\nfunction mapContent(\n msg: Message,\n fn: (blocks: ContentBlock[]) => ContentBlock[],\n): Message | null {\n if (!Array.isArray(msg.content)) return msg;\n const next = fn(msg.content);\n if (next.length === msg.content.length && next.every((b, idx) => b === msg.content[idx])) {\n return msg;\n }\n return { ...msg, content: next };\n}\n\nfunction isEmptyMessage(msg: Message): boolean {\n if (typeof msg.content === 'string') return msg.content.trim().length === 0;\n return msg.content.length === 0;\n}\n","import type { Context } from '../core/context.js';\nimport type { ContentBlock, ToolResultBlock } from '../types/blocks.js';\nimport type { CompactReport, Compactor } from '../types/compactor.js';\nimport type { ContextWindowPolicy } from '../types/context-window.js';\nimport type { Message } from '../types/messages.js';\nimport {\n estimateTextTokens,\n estimateToolInputTokens,\n estimateToolResultTokens,\n estimateRequestTokens,\n} from '../utils/token-estimate.js';\nimport { repairToolUseAdjacency } from '../utils/message-invariants.js';\n\nexport interface CompactorOptions {\n preserveK?: number;\n eliseThreshold?: number;\n estimator?: (text: string) => number;\n}\n\n/**\n * Default tools config values shared across CLI and WebUI.\n * Import this instead of hardcoding to avoid cross-surface inconsistencies.\n * These mirror the values in BEHAVIOR_DEFAULTS (config-loader.ts).\n *\n * @deprecated Import from '../types/default-config.js' instead.\n * This re-export exists for backward compatibility.\n */\nexport { DEFAULT_TOOLS_CONFIG, DEFAULT_CONTEXT_CONFIG, DEFAULT_AUTONOMY_CONFIG } from '../types/default-config.js';\n\nexport class HybridCompactor implements Compactor {\n private readonly preserveK: number;\n private readonly eliseThreshold: number;\n private readonly estimator: (text: string) => number;\n\n constructor(opts: CompactorOptions = {}) {\n this.preserveK = opts.preserveK ?? 5;\n this.eliseThreshold = opts.eliseThreshold ?? 2000;\n this.estimator = opts.estimator ?? estimateTextTokens;\n }\n\n async compact(ctx: Context, opts: { aggressive?: boolean } = {}): Promise<CompactReport> {\n const beforeTokens = this.estimateMessages(ctx.messages);\n const beforeFull = this.estimateFullRequest(ctx);\n const reductions: CompactReport['reductions'] = [];\n const policy = readContextWindowPolicy(ctx);\n const preserveK = policy?.preserveK ?? this.preserveK;\n const eliseThreshold = policy?.eliseThreshold ?? this.eliseThreshold;\n\n // Phase 1: elision\n const phase1Saved = this.eliseOldToolResults(ctx, preserveK, eliseThreshold);\n if (phase1Saved > 0) reductions.push({ phase: 'elision', saved: phase1Saved });\n\n // Phase 2: summary (placeholder; in production calls sub-LLM)\n if (opts.aggressive) {\n const phase2Saved = this.collapseAncientTurns(ctx, preserveK);\n if (phase2Saved > 0) reductions.push({ phase: 'summary', saved: phase2Saved });\n }\n\n const repaired = repairToolUseAdjacency(ctx.messages);\n if (repaired.report.changed) {\n ctx.state.replaceMessages(repaired.messages);\n }\n\n const afterTokens = this.estimateMessages(ctx.messages);\n const afterFull = this.estimateFullRequest(ctx);\n return {\n before: beforeTokens,\n after: afterTokens,\n fullRequestTokensBefore: beforeFull,\n fullRequestTokensAfter: afterFull,\n reductions,\n repaired: repaired.report.changed\n ? {\n removedToolUses: repaired.report.removedToolUses,\n removedToolResults: repaired.report.removedToolResults,\n removedMessages: repaired.report.removedMessages,\n }\n : undefined,\n };\n }\n\n /**\n * Estimate the full API request token count: messages + systemPrompt + toolDefs.\n * This is the accurate figure for context-window pressure monitoring.\n */\n private estimateFullRequest(ctx: Context): number {\n const breakdown = estimateRequestTokens(ctx.messages, ctx.systemPrompt, ctx.tools ?? []);\n return breakdown.total;\n }\n\n private eliseOldToolResults(\n ctx: Context,\n preserveK = this.preserveK,\n eliseThreshold = this.eliseThreshold,\n ): number {\n const messages = ctx.messages;\n // Walk backwards counting (user + assistant) pairs to determine where\n // the preservation window really starts. This is more accurate than\n // the fixed multiplier which assumes every turn is 1 message pair.\n let pairCount = 0;\n let preserveStart = messages.length;\n for (let i = messages.length - 1; i >= 0 && pairCount < preserveK; i--) {\n const m = messages[i];\n if (!m) continue;\n if (m.role === 'user' || m.role === 'assistant') {\n pairCount++;\n preserveStart = i;\n }\n }\n\n // Ensure tool_use/tool_result protocol pairs are preserved together.\n // Walk forward through the preserved window: if an assistant message\n // at or after preserveStart contains a tool_use, also preserve the\n // immediately following message (the tool_result) so neither is elided.\n for (let i = preserveStart; i < messages.length; i++) {\n const m = messages[i];\n if (!m || typeof m.content === 'string' || !Array.isArray(m.content)) continue;\n const hasToolUse = m.content.some((b) => b.type === 'tool_use');\n if (hasToolUse && i + 1 < messages.length) {\n const next = messages[i + 1];\n if (\n next &&\n next.role === 'user' &&\n typeof next.content !== 'string' &&\n Array.isArray(next.content) &&\n next.content.some((b) => b.type === 'tool_result')\n ) {\n // Extend preserveStart to cover the tool_result as well so\n // the protocol pair stays complete and readable.\n preserveStart = i + 1;\n }\n }\n }\n\n let saved = 0;\n let changed = false;\n const nextMessages = new Array(messages.length);\n for (let i = 0; i < messages.length; i++) {\n const msg = messages[i];\n // Only process messages before the preservation window\n if (i >= preserveStart) {\n nextMessages[i] = msg;\n continue;\n }\n if (!msg || !Array.isArray(msg.content)) {\n nextMessages[i] = msg;\n continue;\n }\n const newContent: ContentBlock[] = msg.content.map((b) => {\n if (b.type !== 'tool_result') return b;\n const tokens = estimateToolResultTokens(b.content);\n if (tokens < eliseThreshold) return b;\n saved += tokens;\n const elided: ToolResultBlock = {\n type: 'tool_result',\n tool_use_id: b.tool_use_id,\n content: `[elided: ~${tokens} tokens]`,\n is_error: b.is_error,\n };\n return elided;\n });\n // Check whether any block actually changed by reference equality\n if (\n newContent.length === msg.content.length &&\n newContent.every((b, idx) => b === msg.content[idx])\n ) {\n nextMessages[i] = msg;\n } else {\n nextMessages[i] = { ...msg, content: newContent };\n changed = true;\n }\n }\n if (changed) ctx.state.replaceMessages(nextMessages);\n return saved;\n }\n\n private collapseAncientTurns(ctx: Context, preserveK = this.preserveK): number {\n const messages = ctx.messages;\n const cutTarget = Math.max(0, messages.length - preserveK * 2);\n if (cutTarget <= 0) return 0;\n\n // Find a safe boundary: nearest user-message-with-text at or after cutTarget\n let boundary = -1;\n for (let i = cutTarget; i < messages.length; i++) {\n const m = messages[i];\n if (!m) continue;\n if (m.role === 'user' && hasTextContent(m)) {\n boundary = i;\n break;\n }\n }\n if (boundary <= 0) return 0;\n\n const removed = messages.slice(0, boundary);\n const removedTokens = this.estimateMessages(removed);\n\n const summary: Message[] = [\n {\n role: 'user',\n content: `[previous_session_summary: ${removed.length} earlier turns compacted. Todo state preserved in context.]`,\n },\n { role: 'assistant', content: 'Continuing from compacted context.' },\n ];\n\n // L1-A: route through ConversationState so subscribers see the rewrite.\n const tail = ctx.messages.slice(boundary);\n ctx.state.replaceMessages([...summary, ...tail]);\n return Math.max(0, removedTokens - this.estimateMessages(summary));\n }\n\n private estimateMessages(messages: Message[]): number {\n let total = 0;\n for (const m of messages) {\n if (typeof m.content === 'string') {\n total += this.estimator(m.content);\n } else {\n for (const b of m.content) {\n if (b.type === 'text') total += this.estimator(b.text);\n else if (b.type === 'tool_use') total += estimateToolInputTokens(b.input);\n else if (b.type === 'tool_result') total += estimateToolResultTokens(b.content);\n }\n }\n }\n return total;\n }\n}\n\nfunction readContextWindowPolicy(ctx: Context): ContextWindowPolicy | null {\n const policy = ctx.meta?.['contextWindowPolicy'];\n if (!policy || typeof policy !== 'object') return null;\n const candidate = policy as Partial<ContextWindowPolicy>;\n if (\n typeof candidate.preserveK !== 'number' ||\n typeof candidate.eliseThreshold !== 'number'\n ) {\n return null;\n }\n return candidate as ContextWindowPolicy;\n}\n\nfunction hasTextContent(m: Message): boolean {\n if (typeof m.content === 'string') return m.content.trim().length > 0;\n return m.content.some((b) => b.type === 'text' && b.text.trim().length > 0);\n}\n","export interface TextBlock {\n type: 'text';\n text: string;\n cache_control?: { type: 'ephemeral' };\n}\n\nexport interface ToolUseBlock {\n type: 'tool_use';\n id: string;\n name: string;\n input: Record<string, unknown>;\n /**\n * Provider-specific opaque metadata captured from the wire response.\n * Echoed back verbatim in the next request so providers that bind\n * extra state to function calls keep working. Example: Gemini's\n * `thoughtSignature` — required for tool-use turns with thinking\n * models, otherwise the next request fails with 400 \"Function call\n * is missing a thought_signature in functionCall parts\".\n *\n * Keys are namespaced by intent so multiple wires can coexist:\n * - `google.thoughtSignature` — Gemini signed-thought blob\n * Other providers can add their own keys without colliding.\n */\n providerMeta?: Record<string, unknown>;\n}\n\nexport interface ToolResultBlock {\n type: 'tool_result';\n tool_use_id: string;\n /**\n * The original tool name. Useful for providers like Google Gemini that\n * need the tool name in `functionResponse.name` — the tool_use_id is\n * only a session-local identifier and is not stable across replays.\n * Always set by ToolExecutor; may be absent on manually-constructed blocks.\n */\n name?: string;\n content: string;\n is_error?: boolean;\n}\n\nexport interface ImageBlock {\n type: 'image';\n source: {\n type: 'base64' | 'url';\n media_type?: string;\n data?: string;\n url?: string;\n };\n}\n\n/**\n * Chain-of-thought / extended-thinking content emitted by the model.\n *\n * Both Anthropic extended thinking (`{type:'thinking', thinking, signature}`)\n * and DeepSeek reasoning mode (top-level `reasoning_content` on the assistant\n * message) require this content to be echoed back verbatim on the next\n * request, otherwise the provider returns 400:\n * - Anthropic: \"The `content[].thinking` in the thinking mode must be passed back\"\n * - DeepSeek: \"The `reasoning_content` in the thinking mode must be passed back\"\n *\n * `signature` is Anthropic-specific (an opaque integrity blob). DeepSeek\n * doesn't issue a signature — the field is absent for that provider.\n *\n * Per Anthropic, thinking blocks MUST appear before any text/tool_use blocks\n * in an assistant message. Stream builders preserve that order.\n */\nexport interface ThinkingBlock {\n type: 'thinking';\n thinking: string;\n signature?: string;\n providerMeta?: Record<string, unknown>;\n}\n\nexport type ContentBlock = TextBlock | ToolUseBlock | ToolResultBlock | ImageBlock | ThinkingBlock;\n\nexport function isTextBlock(b: ContentBlock): b is TextBlock {\n return b.type === 'text';\n}\nexport function isToolUseBlock(b: ContentBlock): b is ToolUseBlock {\n return b.type === 'tool_use';\n}\nexport function isToolResultBlock(b: ContentBlock): b is ToolResultBlock {\n return b.type === 'tool_result';\n}\nexport function isImageBlock(b: ContentBlock): b is ImageBlock {\n return b.type === 'image';\n}\nexport function isThinkingBlock(b: ContentBlock): b is ThinkingBlock {\n return b.type === 'thinking';\n}\n","import type { Context } from '../core/context.js';\nimport type { ContentBlock, TextBlock } from '../types/blocks.js';\nimport { isTextBlock } from '../types/blocks.js';\nimport type { CompactReport, Compactor } from '../types/compactor.js';\nimport type { Message } from '../types/messages.js';\nimport type { Provider, Request } from '../types/provider.js';\nimport {\n estimateTextTokens,\n estimateToolInputTokens,\n estimateToolResultTokens,\n estimateRequestTokens,\n} from '../utils/token-estimate.js';\nimport { repairToolUseAdjacency } from '../utils/message-invariants.js';\n\n/**\n * Options for IntelligentCompactor.\n */\nexport interface IntelligentCompactorOptions {\n /** Provider to use for LLM-assisted summarization. Required. */\n provider: Provider;\n /** Fraction of maxContext that triggers a warning (default 0.6). */\n warnThreshold?: number;\n /** Fraction of maxContext that triggers soft compaction (default 0.75). */\n softThreshold?: number;\n /** Fraction of maxContext that triggers hard compaction (default 0.9). */\n hardThreshold?: number;\n /** Max context window in tokens (used only for threshold fraction math). */\n maxContext?: number;\n /** How many recent (user+assistant) pairs to always preserve (default 4). */\n preserveK?: number;\n /** Token threshold below which tool results are not elided (default 500). */\n eliseThreshold?: number;\n /** System prompt for the summarizer sub-LLM. */\n summarizerPrompt?: string;\n /**\n * Model ID to use for summarization. When not set, the same model as the\n * agent is used (which risks cascading failure on context overflow). Set to\n * a fast/cheap model like `claude-3-5-haiku-20240620` for resilience.\n */\n summarizerModel?: string;\n}\n\n/**\n * An importance label for a message or message range.\n */\nexport type Importance = 'critical' | 'high' | 'medium' | 'low';\n\n/**\n * Result of importance analysis.\n */\nexport interface ImportanceAnalysis {\n messages: Array<{ index: number; importance: Importance; reason: string }>;\n criticalRanges: Array<{ from: number; to: number; summary: string }>;\n}\n\n/**\n * IntelligentCompactor uses an LLM to:\n * - Analyze message importance and preserve critical context\n * - Generate semantic summaries for old message ranges\n * - Make intelligent decisions about what to compact\n *\n * It extends HybridCompactor's elision logic with LLM-assisted summarization.\n */\nexport class IntelligentCompactor implements Compactor {\n private readonly provider: Provider;\n private readonly warnThreshold: number;\n private readonly softThreshold: number;\n private readonly hardThreshold: number;\n private readonly maxContext: number;\n private readonly preserveK: number;\n private readonly eliseThreshold: number;\n private readonly summarizerPrompt: string;\n private readonly summarizerModel?: string;\n\n constructor(opts: IntelligentCompactorOptions) {\n this.provider = opts.provider;\n this.warnThreshold = opts.warnThreshold ?? 0.6;\n this.softThreshold = opts.softThreshold ?? 0.75;\n this.hardThreshold = opts.hardThreshold ?? 0.9;\n this.maxContext = opts.maxContext ?? 128_000;\n this.preserveK = opts.preserveK ?? 4;\n this.eliseThreshold = opts.eliseThreshold ?? 500;\n this.summarizerPrompt =\n opts.summarizerPrompt ??\n 'You are a context summarizer. Given a list of conversation messages, produce a concise but complete summary that preserves all factual information, decisions made, and any state changes (e.g. file edits, todo updates). Do not add commentary. Output only the summary.';\n this.summarizerModel = opts.summarizerModel;\n }\n\n async compact(ctx: Context, opts: { aggressive?: boolean } = {}): Promise<CompactReport> {\n const beforeTokens = this.estimateTokens(ctx.messages);\n const beforeFull = this.estimateFullRequest(ctx);\n const reductions: CompactReport['reductions'] = [];\n\n // Use full request tokens for threshold decisions — messages alone are inaccurate.\n const load = beforeFull / this.maxContext;\n // Past hardThreshold, force aggressive regardless of caller preference —\n // the alternative (lightweight elision) is unlikely to recover enough.\n const aggressive =\n load >= this.hardThreshold ? true : (opts.aggressive ?? load >= this.softThreshold);\n\n // Phase 1: always run elision (preserves recent K pairs)\n const saved1 = this.eliseOldToolResults(ctx);\n if (saved1 > 0) reductions.push({ phase: 'elision', saved: saved1 });\n\n // Phase 2: LLM summarization of ancient turns\n if (aggressive) {\n const saved2 = await this.summarizeAncientTurns(ctx);\n if (saved2 > 0) reductions.push({ phase: 'summary', saved: saved2 });\n } else if (load >= this.warnThreshold) {\n // Non-aggressive: do lightweight summarization via direct analysis\n const saved2 = this.lightweightCompact(ctx);\n if (saved2 > 0) reductions.push({ phase: 'elision', saved: saved2 });\n }\n\n const repaired = repairToolUseAdjacency(ctx.messages);\n if (repaired.report.changed) ctx.state.replaceMessages(repaired.messages);\n\n const afterTokens = this.estimateTokens(ctx.messages);\n const afterFull = this.estimateFullRequest(ctx);\n return {\n before: beforeTokens,\n after: afterTokens,\n fullRequestTokensBefore: beforeFull,\n fullRequestTokensAfter: afterFull,\n reductions,\n repaired: repaired.report.changed\n ? {\n removedToolUses: repaired.report.removedToolUses,\n removedToolResults: repaired.report.removedToolResults,\n removedMessages: repaired.report.removedMessages,\n }\n : undefined,\n };\n }\n\n /**\n * Estimate the full API request token count: messages + systemPrompt + toolDefs.\n * This is the accurate figure for context-window pressure monitoring.\n */\n private estimateFullRequest(ctx: Context): number {\n const breakdown = estimateRequestTokens(ctx.messages, ctx.systemPrompt, ctx.tools ?? []);\n return breakdown.total;\n }\n\n private async summarizeAncientTurns(ctx: Context): Promise<number> {\n const messages = ctx.messages;\n const cutoff = Math.max(0, messages.length - this.preserveK * 2);\n if (cutoff <= 2) return 0;\n\n // Find the best boundary in the ancient region\n const boundary = this.findSafeBoundary(messages, 0, cutoff);\n if (boundary <= 1) return 0;\n\n const toSummarize = messages.slice(0, boundary);\n const removedTokens = this.estimateTokens(toSummarize);\n\n let summaryText: string;\n try {\n summaryText = await this.callSummarizer(toSummarize, ctx);\n } catch {\n // Fallback: preserve user/assistant text content while eliding tool results.\n // This keeps semantic information (instructions, decisions, conclusions)\n // without the token overhead of large tool outputs. Unlike the LLM summarizer,\n // this rule-based approach cannot fail and preserves factual content.\n const preservedMessages: Message[] = [];\n for (const m of toSummarize) {\n if (m.role === 'system') continue; // skip existing summaries\n if (typeof m.content === 'string') {\n preservedMessages.push(m);\n } else if (Array.isArray(m.content)) {\n const textParts = m.content.filter(isTextBlock);\n const toolParts = m.content.filter((b) => b.type === 'tool_use' || b.type === 'tool_result');\n // Keep text content; replace tool calls with a lightweight marker.\n const next: Message = {\n role: m.role,\n content: [\n ...textParts,\n ...(toolParts.length > 0\n ? [{ type: 'text' as const, text: `[${toolParts.length} tool call(s) omitted]` }]\n : []),\n ],\n };\n preservedMessages.push(next);\n }\n }\n summaryText = preservedMessages\n .map((m) => `[${m.role}]: ${typeof m.content === 'string' ? m.content : m.content.filter(isTextBlock).map((b) => b.text).join(' ')}`)\n .join('\\n');\n if (!summaryText) summaryText = `${toSummarize.length} earlier turns (semantic content preserved)`;\n }\n\n const summaryMsg: Message = {\n role: 'system',\n content: `[prior_turns_summary: ${summaryText}]`,\n };\n const summaryTokens = this.estimateTokens([summaryMsg]);\n\n // L1-A: route through ConversationState so subscribers see the rewrite.\n const tail = ctx.messages.slice(boundary);\n ctx.state.replaceMessages([summaryMsg, ...tail]);\n return Math.max(0, removedTokens - summaryTokens);\n }\n\n private findSafeBoundary(messages: Message[], from: number, to: number): number {\n // Find the nearest user message with text content at or after `to`\n // and walk backwards to find a safe cut point.\n for (let i = to; i >= from; i--) {\n const m = messages[i];\n if (!m) continue;\n if (m.role === 'user' && this.hasTextContent(m)) {\n // Ensure we don't cut inside a multi-message exchange\n // by finding the start of this exchange.\n return this.findExchangeStart(messages, i);\n }\n }\n return -1;\n }\n\n private findExchangeStart(messages: Message[], userIndex: number): number {\n // Walk backwards from userIndex to find where this logical exchange began.\n // An exchange starts after the last assistant message that had no tool calls.\n for (let i = userIndex - 1; i >= 0; i--) {\n const m = messages[i];\n if (!m) continue;\n if (m.role === 'assistant') {\n const hasToolUse = Array.isArray(m.content)\n ? m.content.some((b) => b.type === 'tool_use')\n : false;\n if (!hasToolUse) {\n // This assistant msg had no tool calls — it's a boundary\n return i + 1;\n }\n } else if (m.role !== 'user') {\n // system or other — skip\n } else {\n // another user msg — boundary\n return i;\n }\n }\n return 0;\n }\n\n private async callSummarizer(messages: Message[], ctx: Context): Promise<string> {\n const prompt: TextBlock[] = [\n { type: 'text', text: this.summarizerPrompt },\n { type: 'text', text: '\\n\\nConversation to summarize:\\n' },\n ...this.messagesToText(messages),\n ];\n\n const req: Request = {\n model: this.summarizerModel ?? ctx.model,\n system: prompt,\n messages: [],\n maxTokens: 1024,\n };\n\n // Use abort signal from context if available.\n // Fall back to a fresh controller only if ctx.signal is absent — this\n // avoids leaking AbortControllers on every summarizer call (the original\n // `?? new AbortController().signal` created a controller that was never\n // connected to anything, making cancellation a no-op).\n const ac = ctx.signal ? undefined : new AbortController();\n const signal = ctx.signal ?? ac!.signal;\n const res = await this.provider.complete(req, { signal });\n\n const textBlocks = res.content.filter(isTextBlock);\n return (\n textBlocks\n .map((b) => b.text)\n .join('\\n')\n .trim() || '(empty summary)'\n );\n }\n\n private messagesToText(messages: Message[]): TextBlock[] {\n const lines: string[] = [];\n for (const m of messages) {\n const role = m.role.padEnd(10, ' ');\n if (typeof m.content === 'string') {\n lines.push(`[${role}]: ${m.content.slice(0, 500)}`);\n } else if (Array.isArray(m.content)) {\n const textParts = m.content.filter(isTextBlock).map((b) => b.text);\n if (textParts.length > 0) {\n lines.push(`[${role}]: ${textParts.join(' ').slice(0, 500)}`);\n }\n }\n }\n return [{ type: 'text', text: lines.join('\\n') }];\n }\n\n private lightweightCompact(ctx: Context): number {\n // Lightweight: just elide very large tool results without full summarization\n return this.eliseOldToolResults(ctx);\n }\n\n private eliseOldToolResults(ctx: Context): number {\n const messages = ctx.messages;\n let pairCount = 0;\n let preserveStart = messages.length;\n for (let i = messages.length - 1; i >= 0 && pairCount < this.preserveK; i--) {\n const m = messages[i];\n if (!m) continue;\n if (m.role === 'user' || m.role === 'assistant') {\n pairCount++;\n preserveStart = i;\n }\n }\n\n // Ensure tool_use/tool_result protocol pairs are preserved together.\n // Walk forward through the preserved window: if an assistant message\n // at or after preserveStart contains a tool_use, also preserve the\n // immediately following message (the tool_result) so neither is elided.\n for (let i = preserveStart; i < messages.length; i++) {\n const m = messages[i];\n if (!m || typeof m.content === 'string' || !Array.isArray(m.content)) continue;\n const hasToolUse = m.content.some((b) => b.type === 'tool_use');\n if (hasToolUse && i + 1 < messages.length) {\n const next = messages[i + 1];\n if (\n next &&\n next.role === 'user' &&\n typeof next.content !== 'string' &&\n Array.isArray(next.content) &&\n next.content.some((b) => b.type === 'tool_result')\n ) {\n // Extend preserveStart to cover the tool_result as well so\n // the protocol pair stays complete and readable.\n preserveStart = i + 1;\n }\n }\n }\n\n let saved = 0;\n let changed = false;\n const nextMessages = new Array(messages.length);\n for (let i = 0; i < messages.length; i++) {\n const msg = messages[i];\n // Only process messages before the preservation window\n if (i >= preserveStart) {\n nextMessages[i] = msg;\n continue;\n }\n if (!msg || !Array.isArray(msg.content)) {\n nextMessages[i] = msg;\n continue;\n }\n const newContent: ContentBlock[] = msg.content.map((b) => {\n if (b.type !== 'tool_result') return b;\n const tokens = estimateToolResultTokens(b.content);\n if (tokens < this.eliseThreshold) return b;\n saved += tokens;\n return {\n type: 'tool_result',\n tool_use_id: b.tool_use_id,\n content: `[elided: ~${tokens} tokens]`,\n is_error: b.is_error,\n };\n });\n // Check by reference equality whether any block actually changed\n if (\n newContent.length === msg.content.length &&\n newContent.every((b, idx) => b === msg.content[idx])\n ) {\n nextMessages[i] = msg;\n } else {\n nextMessages[i] = { ...msg, content: newContent };\n changed = true;\n }\n }\n if (changed) ctx.state.replaceMessages(nextMessages);\n return saved;\n }\n\n private hasTextContent(m: Message): boolean {\n if (typeof m.content === 'string') return m.content.trim().length > 0;\n return m.content.some((b) => b.type === 'text' && b.text.trim().length > 0);\n }\n\n private estimateTokens(messages: Message[]): number {\n let total = 0;\n for (const m of messages) {\n if (typeof m.content === 'string') {\n total += estimateTextTokens(m.content);\n } else {\n for (const b of m.content) {\n if (b.type === 'text') total += estimateTextTokens(b.text);\n else if (b.type === 'tool_use') total += estimateToolInputTokens(b.input);\n else if (b.type === 'tool_result') total += estimateToolResultTokens(b.content);\n }\n }\n }\n return total;\n }\n}\n","import { isTextBlock } from '../types/blocks.js';\nimport type { Message } from '../types/messages.js';\nimport type { Provider, Request } from '../types/provider.js';\nimport type { MessageSelector, SelectorResult } from '../types/selector.js';\n\nexport interface LLMSelectorOptions {\n /** Provider used for the selector LLM call. Required. */\n provider: Provider;\n /** Model for the selector. Defaults to the provider's default model. */\n model?: string;\n /**\n * Maximum tokens to keep in context (target budget).\n * Selector will aim to keep total content below this.\n */\n maxContextTokens?: number;\n /**\n * Prompt instructing the selector how to behave.\n * Should guide the LLM on importance tiers and output format.\n */\n systemPrompt?: string;\n}\n\nconst DEFAULT_SYSTEM_PROMPT = `You are a context pruning assistant. Given a conversation history and a token budget, decide which message ranges are worth keeping verbatim and which should be collapsed into summaries.\n\nOutput a JSON object with this structure:\n{\n \"kept\": [{\"from\": 0, \"to\": 5, \"importance\": \"critical\"}],\n \"collapsed\": [{\"from\": 6, \"to\": 20, \"summary\": \"optional summary\"}],\n \"reasoning\": \"brief explanation of decisions\"\n}\n\nImportance tiers:\n- \"critical\": decisions, file edits, tool results that affect state, final answers\n- \"high\": substantive tool use, complex reasoning, non-obvious observations\n- \"medium\": routine exchanges, confirmations, straightforward Q&A\n\nRules:\n- Always keep the most recent K pairs (preserve recency)\n- Never collapse the final 2 user/assistant pairs (working memory)\n- Preserve tool results that modified files or had external effects\n- Collapse old, low-information exchanges (greetings, acknowledgements, etc.)\n- If unsure, keep rather than collapse (errors are more costly than waste)\n\nReturn ONLY the JSON object, no markdown, no explanation outside the JSON.`;\n\n/** Rough token estimation for a message array */\nfunction estimateTokens(messages: Message[]): number {\n let total = 0;\n for (const m of messages) {\n if (typeof m.content === 'string') {\n total += Math.ceil(m.content.length / 4);\n } else if (Array.isArray(m.content)) {\n for (const b of m.content) {\n if (b.type === 'text') total += Math.ceil(b.text.length / 4);\n else total += Math.ceil(JSON.stringify(b).length / 4);\n }\n }\n }\n return total;\n}\n\n/** Format messages as a compact text dump for the selector LLM */\nfunction formatMessages(messages: Message[], maxChars = 8000): string {\n const lines: string[] = [];\n let used = 0;\n for (let i = 0; i < messages.length; i++) {\n const m = messages[i]!;\n const role = m.role.padEnd(10, ' ');\n let text: string;\n if (typeof m.content === 'string') {\n text = m.content.slice(0, 500);\n } else {\n const content = m.content as import('../types/blocks.js').ContentBlock[];\n text = content\n .filter(isTextBlock)\n .map((b) => b.text)\n .join(' ');\n // Also capture tool names for context\n const toolUses = content.filter((b) => b.type === 'tool_use');\n if (toolUses.length > 0) {\n text += ` [tools: ${toolUses.map((b) => (b as { name: string }).name).join(', ')}]`;\n }\n }\n const line = `[${i}][${role}]: ${text}`;\n if (used + line.length > maxChars) break;\n lines.push(line);\n used += line.length;\n }\n return lines.join('\\n');\n}\n\n/**\n * LLM-powered message selector. Calls a sub-LLM to analyze the\n * message history and produce a keep/collapse plan — more surgical\n * than fixed-window rules.\n */\nexport class LLMSelector implements MessageSelector {\n private readonly provider: Provider;\n private readonly model: string;\n private readonly maxContextTokens: number;\n private readonly systemPrompt: string;\n\n constructor(opts: LLMSelectorOptions) {\n this.provider = opts.provider;\n this.model = opts.model ?? 'unknown';\n this.maxContextTokens = opts.maxContextTokens ?? 40_000;\n this.systemPrompt = opts.systemPrompt ?? DEFAULT_SYSTEM_PROMPT;\n }\n\n async select(messages: Message[], maxToKeep: number): Promise<SelectorResult> {\n const effectiveBudget = Math.min(maxToKeep, this.maxContextTokens);\n\n // Build a concise representation of the conversation\n const historyText = formatMessages(messages);\n const totalTokens = estimateTokens(messages);\n const systemText = `${this.systemPrompt}\\n\\nConversation (${messages.length} messages, ~${totalTokens} tokens, budget: ${effectiveBudget}):\\n`;\n\n // Add instruction to stay within budget\n const budgetInstruction =\n totalTokens > effectiveBudget\n ? `\\n\\nIMPORTANT: Total conversation (${totalTokens} tokens) exceeds budget (${effectiveBudget}). You MUST collapse enough to fit. Prefer collapsing older/lower-importance ranges.`\n : '';\n\n const req: Request = {\n model: this.model,\n system: [{ type: 'text', text: systemText + budgetInstruction }],\n messages: [{ role: 'user', content: historyText }],\n maxTokens: 1024,\n };\n\n let raw: string;\n try {\n // Wire the AbortController to the provider call so cancellation actually\n // fires — the original code passed a fresh signal that is never connected\n // to anything, leaking the controller on every selector call.\n const ac = new AbortController();\n const res = await this.provider.complete(req, { signal: ac.signal });\n const textBlocks = res.content.filter(isTextBlock);\n raw = textBlocks\n .map((b) => b.text)\n .join('\\n')\n .trim();\n } catch (_err) {\n // Fallback: use simple recency-based selection\n return this.fallbackSelect(messages, effectiveBudget);\n }\n\n return this.parseSelectorOutput(raw, messages.length);\n }\n\n private fallbackSelect(messages: Message[], budget: number): SelectorResult {\n // Simple fallback: keep from the end until we hit budget\n const toKeep: SelectorResult['kept'] = [];\n const toCollapse: SelectorResult['collapsed'] = [];\n\n let tokenCount = 0;\n let startIdx = 0;\n\n // Scan from the end backwards\n for (let i = messages.length - 1; i >= 0; i--) {\n const m = messages[i]!;\n const cost =\n typeof m.content === 'string'\n ? Math.ceil(m.content.length / 4)\n : m.content.reduce(\n (acc, b) =>\n acc +\n (b.type === 'text'\n ? Math.ceil(b.text.length / 4)\n : Math.ceil(JSON.stringify(b).length / 4)),\n 0,\n );\n\n if (tokenCount + cost <= budget) {\n tokenCount += cost;\n } else {\n startIdx = i + 1;\n break;\n }\n }\n\n if (startIdx > 0) {\n toCollapse.push({ from: 0, to: startIdx - 1 });\n }\n toKeep.push({ from: startIdx, to: messages.length - 1, importance: 'high' });\n\n return {\n kept: toKeep,\n collapsed: toCollapse,\n reasoning: `Fallback: kept last ${messages.length - startIdx} messages within ${budget} token budget`,\n };\n }\n\n private parseSelectorOutput(raw: string, messageCount: number): SelectorResult {\n // Try to extract JSON from the response\n const jsonStart = raw.indexOf('{');\n const jsonEnd = raw.lastIndexOf('}');\n if (jsonStart === -1 || jsonEnd === -1) {\n // Can't parse — use fallback\n return this.fallbackSelect(\n Array.from({ length: messageCount }, () => ({ role: 'user', content: '' }) as Message),\n this.maxContextTokens,\n );\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw.slice(jsonStart, jsonEnd + 1));\n } catch {\n return this.fallbackSelect(\n Array.from({ length: messageCount }, () => ({ role: 'user', content: '' }) as Message),\n this.maxContextTokens,\n );\n }\n\n const obj = parsed as Record<string, unknown>;\n const kept =\n (obj.kept as Array<{ from: number; to: number; importance: string }> | undefined) ?? [];\n const collapsed =\n (obj.collapsed as Array<{ from: number; to: number; summary?: string }> | undefined) ?? [];\n\n return {\n kept: kept.map((k) => ({\n from: k.from,\n to: k.to,\n importance: (k.importance ?? 'medium') as 'critical' | 'high' | 'medium',\n })),\n collapsed: collapsed.map((c) => ({ from: c.from, to: c.to, summary: c.summary })),\n reasoning: typeof obj.reasoning === 'string' ? obj.reasoning : '',\n };\n }\n}\n","import type { Context } from '../core/context.js';\nimport { LLMSelector } from '../models/llm-selector.js';\nimport type { ContentBlock } from '../types/blocks.js';\nimport { isTextBlock } from '../types/blocks.js';\nimport type { CompactReport, Compactor } from '../types/compactor.js';\nimport type { Message } from '../types/messages.js';\nimport type { Provider, Request } from '../types/provider.js';\nimport type { MessageSelector, SelectorResult } from '../types/selector.js';\nimport { estimateRequestTokens } from '../utils/token-estimate.js';\nimport { repairToolUseAdjacency } from '../utils/message-invariants.js';\n\n/**\n * Options for SelectiveCompactor — the most configurable compactor.\n */\nexport interface SelectiveCompactorOptions {\n /** Provider for LLM calls (selector + summarizer). Required. */\n provider: Provider;\n /** Selector for LLM-driven importance analysis. */\n selector?: MessageSelector;\n /** Fraction of maxContext that triggers a warning (default 0.6). */\n warnThreshold?: number;\n /** Fraction of maxContext that triggers soft compaction (default 0.75). */\n softThreshold?: number;\n /** Fraction of maxContext that triggers hard compaction (default 0.9). */\n hardThreshold?: number;\n /** Max context window in tokens (used for threshold fraction math). */\n maxContext?: number;\n /** How many recent (user+assistant) pairs to always preserve (default 4). */\n preserveK?: number;\n /** Token threshold below which tool results are not elided (default 500). */\n eliseThreshold?: number;\n /** Model for selector LLM calls (default: same as provider default). */\n selectorModel?: string;\n /** Summarizer model for collapsed ranges (default: same as selectorModel). */\n summarizerModel?: string;\n /** Prompt for the summarizer sub-LLM. */\n summarizerPrompt?: string;\n}\n\n/**\n * SelectiveCompactor uses an LLM-driven MessageSelector to make\n * surgical decisions about which message ranges to keep vs collapse.\n *\n * Compared to HybridCompactor / IntelligentCompactor:\n * - HybridCompactor: rule-based (preserveK + elision), no LLM calls\n * - IntelligentCompactor: LLM summarization but no structured selection\n * - SelectiveCompactor: full LLM-driven selection + optional summarization\n */\nexport class SelectiveCompactor implements Compactor {\n private readonly provider: Provider;\n private readonly selector: MessageSelector;\n private readonly warnThreshold: number;\n private readonly softThreshold: number;\n private readonly hardThreshold: number;\n private readonly maxContext: number;\n private readonly preserveK: number;\n private readonly eliseThreshold: number;\n private readonly summarizerModel: string;\n private readonly summarizerPrompt: string;\n\n constructor(opts: SelectiveCompactorOptions) {\n this.provider = opts.provider;\n this.selector =\n opts.selector ?? new LLMSelector({ provider: opts.provider, model: opts.selectorModel });\n this.warnThreshold = opts.warnThreshold ?? 0.6;\n this.softThreshold = opts.softThreshold ?? 0.75;\n this.hardThreshold = opts.hardThreshold ?? 0.9;\n this.maxContext = opts.maxContext ?? 128_000;\n this.preserveK = opts.preserveK ?? 4;\n this.eliseThreshold = opts.eliseThreshold ?? 500;\n this.summarizerModel = opts.summarizerModel ?? opts.selectorModel ?? 'unknown';\n this.summarizerPrompt =\n opts.summarizerPrompt ??\n 'You are a context summarizer. Given a list of messages, produce a concise summary that preserves all factual information, decisions, file changes, and state changes. Do not add commentary or opinions.';\n }\n\n async compact(ctx: Context, opts: { aggressive?: boolean } = {}): Promise<CompactReport> {\n const beforeTokens = this.estimateTokens(ctx.messages);\n const beforeFull = this.estimateFullRequest(ctx);\n const reductions: CompactReport['reductions'] = [];\n\n // Use full request tokens for threshold decisions — messages alone are inaccurate.\n const load = beforeFull / this.maxContext;\n const shouldCompact = load >= this.warnThreshold || opts.aggressive;\n\n if (!shouldCompact) {\n // Only do lightweight elision if below warn threshold\n const saved = this.eliseOldToolResults(ctx);\n if (saved > 0) reductions.push({ phase: 'elision', saved });\n const repair = this.repairProtocolAdjacency(ctx);\n const afterTokens = this.estimateTokens(ctx.messages);\n const afterFull = this.estimateFullRequest(ctx);\n return {\n before: beforeTokens,\n after: afterTokens,\n fullRequestTokensBefore: beforeFull,\n fullRequestTokensAfter: afterFull,\n reductions,\n repaired: repair,\n };\n }\n\n // Phase 1: elision — always run first to get a baseline reduction\n const savedElision = this.eliseOldToolResults(ctx);\n if (savedElision > 0) reductions.push({ phase: 'elision', saved: savedElision });\n\n // Phase 2: LLM-driven selective compaction\n const afterPhase1 = this.estimateTokens(ctx.messages);\n const targetBudget = this.computeTargetBudget(load);\n\n if (afterPhase1 > targetBudget) {\n const savedSelective = await this.runSelector(ctx, targetBudget);\n if (savedSelective > 0) reductions.push({ phase: 'selective', saved: savedSelective });\n }\n\n const repair = this.repairProtocolAdjacency(ctx);\n const afterTokens = this.estimateTokens(ctx.messages);\n const afterFull = this.estimateFullRequest(ctx);\n return {\n before: beforeTokens,\n after: afterTokens,\n fullRequestTokensBefore: beforeFull,\n fullRequestTokensAfter: afterFull,\n reductions,\n repaired: repair,\n };\n }\n\n /**\n * Estimate the full API request token count: messages + systemPrompt + toolDefs.\n * This is the accurate figure for context-window pressure monitoring.\n */\n private estimateFullRequest(ctx: Context): number {\n const breakdown = estimateRequestTokens(ctx.messages, ctx.systemPrompt, ctx.tools ?? []);\n return breakdown.total;\n }\n\n private repairProtocolAdjacency(ctx: Context): CompactReport['repaired'] {\n const repaired = repairToolUseAdjacency(ctx.messages);\n if (repaired.report.changed) ctx.state.replaceMessages(repaired.messages);\n return repaired.report.changed\n ? {\n removedToolUses: repaired.report.removedToolUses,\n removedToolResults: repaired.report.removedToolResults,\n removedMessages: repaired.report.removedMessages,\n }\n : undefined;\n }\n\n /**\n * Run the LLM selector to decide what to keep vs collapse.\n * Returns the token savings achieved.\n */\n private async runSelector(ctx: Context, targetBudget: number): Promise<number> {\n const before = this.estimateTokens(ctx.messages);\n\n let result: SelectorResult;\n try {\n result = await this.selector.select(ctx.messages, targetBudget);\n } catch {\n // Fallback to aggressive recency preservation\n return this.aggressiveRecencyTrim(ctx);\n }\n\n // Execute the selector's plan\n await this.executePlan(ctx, result);\n\n const after = this.estimateTokens(ctx.messages);\n return Math.max(0, before - after);\n }\n\n /**\n * Execute a SelectorResult plan: collapse/remove ranges and\n * insert summaries where the selector provided them.\n */\n private async executePlan(ctx: Context, plan: SelectorResult): Promise<void> {\n if (ctx.messages.length === 0) return;\n\n // Process collapsed ranges in reverse order to preserve indices. We work\n // on a local copy and commit through `ctx.state.replaceMessages` at the\n // end so subscribers see a single state change for the whole rewrite.\n const messages = [...ctx.messages];\n const sortedCollapsed = [...plan.collapsed].sort((a, b) => b.from - a.from);\n\n for (const range of sortedCollapsed) {\n if (range.from < 0 || range.to >= messages.length || range.from > range.to) continue;\n\n let summary = range.summary;\n if (!summary) {\n const toSummarize = messages.slice(range.from, range.to + 1);\n summary = await this.summarizeRange(toSummarize, ctx);\n }\n\n const summaryMsg: Message = {\n role: 'system',\n content: `[prior_turns_${range.from}-${range.to}: ${summary}]`,\n };\n\n messages.splice(range.from, range.to - range.from + 1, summaryMsg);\n }\n\n ctx.state.replaceMessages(messages);\n }\n\n private async summarizeRange(messages: Message[], ctx: Context): Promise<string> {\n const systemText = `${this.summarizerPrompt}\\n\\nSummarize the following message range:`;\n const body = messages.map((m, i) => `[${i}] ${m.role}: ${this.messagePreview(m)}`).join('\\n');\n\n const req: Request = {\n model: this.summarizerModel,\n system: [{ type: 'text', text: systemText }],\n messages: [{ role: 'user', content: body }],\n maxTokens: 512,\n };\n\n try {\n const res = await this.provider.complete(req, {\n signal: ctx.signal ?? new AbortController().signal,\n });\n return (\n res.content\n .filter(isTextBlock)\n .map((b) => b.text)\n .join('\\n')\n .trim() || '(empty)'\n );\n } catch {\n return `[${messages.length} earlier turns omitted]`;\n }\n }\n\n private messagePreview(m: Message): string {\n if (typeof m.content === 'string') return m.content.slice(0, 300);\n return m.content\n .filter(isTextBlock)\n .map((b) => b.text)\n .join(' ')\n .slice(0, 300);\n }\n\n /**\n * Fallback when selector fails: aggressively trim from the oldest end\n * until we hit targetBudget.\n */\n private aggressiveRecencyTrim(ctx: Context): number {\n const messages = ctx.messages;\n const preserveIdx = Math.max(0, messages.length - this.preserveK * 2);\n\n if (preserveIdx <= 0) return 0;\n\n // Find safe boundary near preserveIdx\n let boundary = preserveIdx;\n for (let i = preserveIdx; i < messages.length && i < preserveIdx + 6; i++) {\n const m = messages[i]!;\n if (m.role === 'user' && this.hasTextContent(m)) {\n boundary = i;\n break;\n }\n }\n\n const removed = messages.slice(0, boundary);\n const removedTokens = this.estimateTokens(removed);\n\n const summaryMsg: Message = {\n role: 'system',\n content: `[${removed.length} earlier turns trimmed — see session log for details]`,\n };\n const tail = messages.slice(boundary);\n ctx.state.replaceMessages([summaryMsg, ...tail]);\n\n return Math.max(0, removedTokens - this.estimateTokens([summaryMsg]));\n }\n\n private computeTargetBudget(load: number): number {\n if (load >= this.hardThreshold) {\n return Math.floor(this.maxContext * 0.5); // keep only 50%\n }\n if (load >= this.softThreshold) {\n return Math.floor(this.maxContext * 0.65); // keep 65%\n }\n return Math.floor(this.maxContext * 0.75); // keep 75% at warn\n }\n\n private eliseOldToolResults(ctx: Context): number {\n const messages = ctx.messages;\n let pairCount = 0;\n let preserveStart = messages.length;\n for (let i = messages.length - 1; i >= 0 && pairCount < this.preserveK; i--) {\n const m = messages[i];\n if (!m) continue;\n if (m.role === 'user' || m.role === 'assistant') {\n pairCount++;\n preserveStart = i;\n }\n }\n let saved = 0;\n let changed = false;\n const nextMessages = new Array(messages.length);\n for (let i = 0; i < messages.length; i++) {\n const msg = messages[i];\n // Only process messages before the preservation window\n if (i >= preserveStart) {\n nextMessages[i] = msg;\n continue;\n }\n if (!msg || !Array.isArray(msg.content)) {\n nextMessages[i] = msg;\n continue;\n }\n const newContent: ContentBlock[] = msg.content.map((b) => {\n if (b.type !== 'tool_result') return b;\n const text = typeof b.content === 'string' ? b.content : JSON.stringify(b.content);\n const tokens = this.roughTokenEstimate(text);\n if (tokens < this.eliseThreshold) return b;\n saved += tokens;\n return {\n type: 'tool_result',\n tool_use_id: b.tool_use_id,\n content: `[elided: ~${tokens} tokens]`,\n is_error: b.is_error,\n };\n });\n // map() preserves length, so only block ref-equality matters here.\n if (newContent.every((b, idx) => b === msg.content[idx])) {\n nextMessages[i] = msg;\n } else {\n nextMessages[i] = { ...msg, content: newContent };\n changed = true;\n }\n }\n if (changed) ctx.state.replaceMessages(nextMessages);\n return saved;\n }\n\n private hasTextContent(m: Message): boolean {\n if (typeof m.content === 'string') return m.content.trim().length > 0;\n return m.content.some((b) => b.type === 'text' && b.text.trim().length > 0);\n }\n\n private estimateTokens(messages: Message[]): number {\n let total = 0;\n for (const m of messages) {\n if (typeof m.content === 'string') {\n total += this.roughTokenEstimate(m.content);\n } else {\n for (const b of m.content) {\n if (b.type === 'text') total += this.roughTokenEstimate(b.text);\n else if (b.type === 'tool_use') total += this.roughTokenEstimate(JSON.stringify(b.input));\n else if (b.type === 'tool_result') {\n total += this.roughTokenEstimate(\n typeof b.content === 'string' ? b.content : JSON.stringify(b.content),\n );\n }\n }\n }\n }\n return total;\n }\n\n private roughTokenEstimate(text: string): number {\n return Math.max(1, Math.ceil(text.length / 3.5));\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\n/**\n * Machine-readable error codes as frozen constants.\n *\n * Use `ERROR_CODES.X` instead of raw string literals for:\n * - IDE autocomplete and compile-time validation\n * - Safe refactoring (rename updates all usages)\n * - Plugin extensibility (extend the object to add custom codes)\n *\n * The `ErrorCode` type is derived from this object, so adding a new\n * code here automatically updates the type without extra changes.\n */\nexport const ERROR_CODES = {\n // Provider\n PROVIDER_RATE_LIMITED: 'PROVIDER_RATE_LIMITED',\n PROVIDER_AUTH_FAILED: 'PROVIDER_AUTH_FAILED',\n PROVIDER_OVERLOADED: 'PROVIDER_OVERLOADED',\n PROVIDER_INVALID_REQUEST: 'PROVIDER_INVALID_REQUEST',\n PROVIDER_SERVER_ERROR: 'PROVIDER_SERVER_ERROR',\n PROVIDER_NETWORK_ERROR: 'PROVIDER_NETWORK_ERROR',\n PROVIDER_CONTEXT_OVERFLOW: 'PROVIDER_CONTEXT_OVERFLOW',\n // Tool\n TOOL_NOT_FOUND: 'TOOL_NOT_FOUND',\n TOOL_PERMISSION_DENIED: 'TOOL_PERMISSION_DENIED',\n TOOL_EXECUTION_FAILED: 'TOOL_EXECUTION_FAILED',\n TOOL_TIMEOUT: 'TOOL_TIMEOUT',\n TOOL_INPUT_INVALID: 'TOOL_INPUT_INVALID',\n // Config\n CONFIG_INVALID: 'CONFIG_INVALID',\n CONFIG_NOT_FOUND: 'CONFIG_NOT_FOUND',\n CONFIG_PARSE_FAILED: 'CONFIG_PARSE_FAILED',\n CONFIG_MIGRATION_NEEDED: 'CONFIG_MIGRATION_NEEDED',\n // Plugin\n PLUGIN_LOAD_FAILED: 'PLUGIN_LOAD_FAILED',\n PLUGIN_API_MISMATCH: 'PLUGIN_API_MISMATCH',\n PLUGIN_MISSING_DEPENDENCY: 'PLUGIN_MISSING_DEPENDENCY',\n // Agent\n AGENT_ITERATION_LIMIT: 'AGENT_ITERATION_LIMIT',\n AGENT_CONTEXT_OVERFLOW: 'AGENT_CONTEXT_OVERFLOW',\n AGENT_ABORTED: 'AGENT_ABORTED',\n AGENT_RUN_FAILED: 'AGENT_RUN_FAILED',\n // Session\n SESSION_NOT_FOUND: 'SESSION_NOT_FOUND',\n SESSION_CORRUPTED: 'SESSION_CORRUPTED',\n SESSION_WRITE_FAILED: 'SESSION_WRITE_FAILED',\n // Container / Registry\n CONTAINER_TOKEN_ALREADY_BOUND: 'CONTAINER_TOKEN_ALREADY_BOUND',\n CONTAINER_TOKEN_NOT_BOUND: 'CONTAINER_TOKEN_NOT_BOUND',\n CONTAINER_CIRCULAR_DEPENDENCY: 'CONTAINER_CIRCULAR_DEPENDENCY',\n REGISTRY_DUPLICATE: 'REGISTRY_DUPLICATE',\n REGISTRY_NOT_FOUND: 'REGISTRY_NOT_FOUND',\n REGISTRY_INVALID: 'REGISTRY_INVALID',\n // File system\n FS_READ_FAILED: 'FS_READ_FAILED',\n FS_WRITE_FAILED: 'FS_WRITE_FAILED',\n FS_MKDIR_FAILED: 'FS_MKDIR_FAILED',\n FS_DELETE_FAILED: 'FS_DELETE_FAILED',\n FS_ATOMIC_WRITE_FAILED: 'FS_ATOMIC_WRITE_FAILED',\n // General\n UNKNOWN: 'UNKNOWN',\n} as const;\n\n/**\n * Union type derived from `ERROR_CODES`. Using `typeof ERROR_CODES[keyof typeof ERROR_CODES]`\n * instead of a string literal union means TypeScript auto-updates the type whenever\n * a new code is added to `ERROR_CODES` — no need to keep two lists in sync.\n */\nexport type ErrorCode = (typeof ERROR_CODES)[keyof typeof ERROR_CODES];\n\nexport type ErrorSubsystem =\n | 'provider'\n | 'tool'\n | 'config'\n | 'plugin'\n | 'agent'\n | 'session'\n | 'container'\n | 'fs'\n | 'general';\nexport type ErrorSeverity = 'fatal' | 'error' | 'warning';\n\n// ── Base error class ─────────────────────────────────────────────────\n\nexport class WrongStackError extends Error {\n readonly code: ErrorCode;\n readonly subsystem: ErrorSubsystem;\n readonly severity: ErrorSeverity;\n readonly recoverable: boolean;\n readonly context?: Record<string, unknown>;\n\n constructor(opts: {\n message: string;\n code: ErrorCode;\n subsystem: ErrorSubsystem;\n severity?: ErrorSeverity;\n recoverable?: boolean;\n context?: Record<string, unknown>;\n cause?: unknown;\n }) {\n super(opts.message, { cause: opts.cause });\n this.name = 'WrongStackError';\n this.code = opts.code;\n this.subsystem = opts.subsystem;\n this.severity = opts.severity ?? 'error';\n this.recoverable = opts.recoverable ?? false;\n this.context = opts.context;\n }\n\n /**\n * Render a one-line user-facing description.\n * Subclasses should override for domain-specific formatting.\n */\n describe(): string {\n const ctx = this.context ? ` ${formatContext(this.context)}` : '';\n return `${this.code}: ${this.message}${ctx}`;\n }\n}\n\nfunction formatContext(ctx: Record<string, unknown>): string {\n const parts = Object.entries(ctx)\n .filter(([, v]) => v !== undefined)\n .slice(0, 3)\n .map(([k, v]) => `${k}=${String(v)}`);\n return parts.length > 0 ? `[${parts.join(' ')}]` : '';\n}\n\n// ── Specific error classes ───────────────────────────────────────────\n\n/**\n * Tool execution errors — thrown by ToolExecutor and individual tools.\n */\nexport class ToolError extends WrongStackError {\n readonly toolName: string;\n\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n | 'TOOL_NOT_FOUND'\n | 'TOOL_PERMISSION_DENIED'\n | 'TOOL_EXECUTION_FAILED'\n | 'TOOL_TIMEOUT'\n | 'TOOL_INPUT_INVALID'\n >;\n toolName: string;\n recoverable?: boolean;\n context?: Record<string, unknown>;\n cause?: unknown;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'tool',\n recoverable: opts.recoverable,\n context: { tool: opts.toolName, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'ToolError';\n this.toolName = opts.toolName;\n }\n}\n\n/**\n * Config loading / validation errors.\n */\nexport class ConfigError extends WrongStackError {\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'CONFIG_INVALID' | 'CONFIG_NOT_FOUND' | 'CONFIG_PARSE_FAILED' | 'CONFIG_MIGRATION_NEEDED'\n >;\n context?: Record<string, unknown>;\n cause?: unknown;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'config',\n severity: 'fatal',\n recoverable: false,\n context: opts.context,\n cause: opts.cause,\n });\n this.name = 'ConfigError';\n }\n}\n\n/**\n * Plugin loading / lifecycle errors.\n */\nexport class PluginError extends WrongStackError {\n readonly pluginName: string;\n\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'PLUGIN_LOAD_FAILED' | 'PLUGIN_API_MISMATCH' | 'PLUGIN_MISSING_DEPENDENCY'\n >;\n pluginName: string;\n context?: Record<string, unknown>;\n cause?: unknown;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'plugin',\n severity: 'error',\n recoverable: opts.code === ERROR_CODES.PLUGIN_MISSING_DEPENDENCY,\n context: { plugin: opts.pluginName, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'PluginError';\n this.pluginName = opts.pluginName;\n }\n}\n\n/**\n * Agent runtime errors — thrown by Agent.run when a non-WrongStackError\n * escapes the inner loop, so callers always see a structured error.\n */\nexport class AgentError extends WrongStackError {\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'AGENT_ITERATION_LIMIT' | 'AGENT_CONTEXT_OVERFLOW' | 'AGENT_ABORTED' | 'AGENT_RUN_FAILED'\n >;\n recoverable?: boolean;\n context?: Record<string, unknown>;\n cause?: unknown;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'agent',\n severity: opts.code === ERROR_CODES.AGENT_ABORTED ? 'warning' : 'error',\n recoverable: opts.recoverable ?? opts.code === ERROR_CODES.AGENT_ITERATION_LIMIT,\n context: opts.context,\n cause: opts.cause,\n });\n this.name = 'AgentError';\n }\n}\n\n/**\n * Wrap an arbitrary thrown value into a `WrongStackError` so the caller\n * always gets a structured error. Pass-throughs WrongStackError instances\n * unchanged; raw `Error`s and primitives get an `AGENT_RUN_FAILED` wrapper\n * with the original preserved as `cause`.\n */\nexport function toWrongStackError(\n err: unknown,\n code: Extract<ErrorCode, 'AGENT_RUN_FAILED' | 'AGENT_ABORTED' | 'UNKNOWN'> = ERROR_CODES.AGENT_RUN_FAILED,\n): WrongStackError {\n if (err instanceof WrongStackError) return err;\n const message = err instanceof Error ? err.message : String(err);\n return new AgentError({\n message,\n code: code === 'UNKNOWN' ? ERROR_CODES.AGENT_RUN_FAILED : code,\n cause: err,\n });\n}\n\n/**\n * Session storage errors.\n */\nexport class SessionError extends WrongStackError {\n readonly sessionId?: string;\n\n constructor(opts: {\n message: string;\n code: Extract<ErrorCode, 'SESSION_NOT_FOUND' | 'SESSION_CORRUPTED' | 'SESSION_WRITE_FAILED'>;\n sessionId?: string;\n context?: Record<string, unknown>;\n cause?: unknown;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'session',\n severity: opts.code === ERROR_CODES.SESSION_WRITE_FAILED ? 'error' : 'warning',\n recoverable: opts.code !== ERROR_CODES.SESSION_CORRUPTED,\n context: { sessionId: opts.sessionId, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'SessionError';\n this.sessionId = opts.sessionId;\n }\n}\n\n/**\n * File system operation errors.\n */\nexport class FsError extends WrongStackError {\n readonly path?: string;\n\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'FS_READ_FAILED' | 'FS_WRITE_FAILED' | 'FS_MKDIR_FAILED' | 'FS_DELETE_FAILED' | 'FS_ATOMIC_WRITE_FAILED'\n >;\n path?: string;\n context?: Record<string, unknown>;\n cause?: unknown;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'fs',\n severity: 'error',\n recoverable: opts.code !== ERROR_CODES.FS_READ_FAILED,\n context: { path: opts.path, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'FsError';\n this.path = opts.path;\n }\n}\n\n// ── Type guards ──────────────────────────────────────────────────────\n\nexport function isWrongStackError(err: unknown): err is WrongStackError {\n return err instanceof WrongStackError;\n}\n\nexport function isToolError(err: unknown): err is ToolError {\n return err instanceof ToolError;\n}\n\nexport function isConfigError(err: unknown): err is ConfigError {\n return err instanceof ConfigError;\n}\n\nexport function isPluginError(err: unknown): err is PluginError {\n return err instanceof PluginError;\n}\n\nexport function isSessionError(err: unknown): err is SessionError {\n return err instanceof SessionError;\n}\n\nexport function isAgentError(err: unknown): err is AgentError {\n return err instanceof AgentError;\n}\n\nexport function isFsError(err: unknown): err is FsError {\n return err instanceof FsError;\n}\n","import type { Context } from '../core/context.js';\nimport type { EventBus } from '../kernel/events.js';\nimport type { MiddlewareHandler } from '../kernel/pipeline.js';\nimport type { SessionEventBridge } from '../storage/session-event-bridge.js';\nimport type { CompactReport, Compactor } from '../types/compactor.js';\nimport type { ContextWindowAggressiveOn, ContextWindowPolicy } from '../types/context-window.js';\nimport { AgentError, ERROR_CODES } from '../types/errors.js';\nimport { estimateRequestTokensCalibrated } from '../utils/token-estimate.js';\n\ntype PressureLevel = 'warn' | 'soft' | 'hard';\nconst LEVEL_RANK: Record<PressureLevel, number> = { warn: 0, soft: 1, hard: 2 };\n\nexport type CompactionFailureMode = 'throw' | 'throw_on_hard' | 'continue';\n\nexport interface AutoCompactionOptions {\n aggressiveOn?: ContextWindowAggressiveOn;\n events?: EventBus;\n failureMode?: CompactionFailureMode;\n policyProvider?: (ctx: Context) => Pick<\n ContextWindowPolicy,\n 'thresholds' | 'aggressiveOn'\n > | null | undefined;\n /** Optional bridge for writing compaction events into the persistent session log. */\n sessionBridge?: SessionEventBridge;\n}\n\n/**\n * Pipeline middleware that monitors context token load and automatically\n * triggers compaction when the warn/soft/hard thresholds are crossed.\n * Runs before the next agent iteration.\n *\n * Uses `estimateRequestTokens` for accurate full-request token counting:\n * messages + systemPrompt + toolDefs. This replaces the previous pattern\n * of applying an OVERHEAD_FACTOR to a messages-only estimate.\n */\nexport class AutoCompactionMiddleware {\n readonly name = 'AutoCompaction';\n\n private readonly compactor: Compactor;\n /** Deprecated. Kept for backward compat with tests that pass simpleEstimator. */\n private readonly _estimator?: (ctx: Context) => number;\n private readonly warnThreshold: number;\n private readonly softThreshold: number;\n private readonly hardThreshold: number;\n /** Writable so model-switch can update the denominator without re-registering the middleware. */\n private _maxContext: number;\n private readonly aggressiveOn: ContextWindowAggressiveOn;\n private readonly events?: EventBus;\n private readonly failureMode: CompactionFailureMode;\n private readonly policyProvider?: AutoCompactionOptions['policyProvider'];\n private readonly sessionBridge?: SessionEventBridge;\n\n /**\n * Once a compaction attempt reduces nothing (preserveK protects everything,\n * no oversized tool_results remain to elide), retrying on every iteration\n * just spams `compaction.fired` events without making progress. We remember\n * the no-op and skip until either the pressure level escalates or context\n * has grown by at least this many tokens since the failed attempt.\n */\n private static readonly NOOP_RETRY_DELTA_TOKENS = 2_000;\n\n /** Tracks the most recent no-op attempt so we can avoid re-firing per turn. */\n private lastNoopAttempt: { level: PressureLevel; tokens: number } | null = null;\n\n /**\n * @param compactor Compactor to use for compaction.\n * @param maxContext Provider's max context window in tokens.\n * @param _estimator Deprecated parameter kept for backward compatibility.\n * The middleware now uses `estimateRequestTokens` internally\n * for accurate full-request token counting (messages +\n * systemPrompt + toolDefs).\n * @param thresholds Threshold fractions (0-1) of maxContext.\n * @param opts Optional behavior. By default, failures at the\n * hard threshold throw AGENT_CONTEXT_OVERFLOW so\n * the agent does not continue into a likely\n * provider context overflow. Warn/soft failures\n * still emit compaction.failed and continue.\n */\n constructor(\n compactor: Compactor,\n maxContext: number,\n _estimator: (ctx: Context) => number,\n thresholds: { warn: number; soft: number; hard: number },\n optsOrAggressiveOn: AutoCompactionOptions | ContextWindowAggressiveOn = {},\n events?: EventBus,\n ) {\n const opts =\n typeof optsOrAggressiveOn === 'string'\n ? { aggressiveOn: optsOrAggressiveOn, events }\n : optsOrAggressiveOn;\n this.compactor = compactor;\n this._maxContext = maxContext;\n this._estimator = _estimator;\n this.warnThreshold = thresholds.warn;\n this.softThreshold = thresholds.soft;\n this.hardThreshold = thresholds.hard;\n this.aggressiveOn = opts.aggressiveOn ?? 'soft';\n this.events = opts.events;\n this.failureMode = opts.failureMode ?? 'throw_on_hard';\n this.policyProvider = opts.policyProvider;\n this.sessionBridge = opts.sessionBridge;\n }\n\n /** Allow callers (e.g. model-switch in WebUI) to update the context window\n * denominator when the active model changes. */\n setMaxContext(maxContext: number): void {\n this._maxContext = maxContext;\n }\n\n handler(): MiddlewareHandler<Context> {\n return async (ctx, next) => {\n // Use _estimator when provided (backward-compat with existing tests that\n // pass simpleEstimator). Otherwise use estimateRequestTokensCalibrated:\n // before any API calls it returns the same as estimateRequestTokens, but\n // after recordActualUsage() is called each iteration it self-corrects so\n // context pressure readings converge on the real token count.\n const tokens = this._estimator\n ? this._estimator(ctx)\n : estimateRequestTokensCalibrated(ctx.messages, ctx.systemPrompt, ctx.tools ?? []).total;\n const load = tokens / this._maxContext;\n const policy = this.policyProvider?.(ctx);\n const thresholds = policy?.thresholds ?? {\n warn: this.warnThreshold,\n soft: this.softThreshold,\n hard: this.hardThreshold,\n };\n const aggressiveOn = policy?.aggressiveOn ?? this.aggressiveOn;\n\n const level: PressureLevel | null =\n load >= thresholds.hard\n ? 'hard'\n : load >= thresholds.soft\n ? 'soft'\n : load >= thresholds.warn\n ? 'warn'\n : null;\n\n if (!level) {\n // Load dropped back below all thresholds — any previously stuck state\n // is no longer relevant.\n this.lastNoopAttempt = null;\n return next(ctx);\n }\n\n if (this.shouldSkipNoopRetry(level, tokens)) {\n return next(ctx);\n }\n\n const aggressive =\n level === 'hard'\n ? true\n : level === 'soft'\n ? aggressiveOn !== 'hard'\n : aggressiveOn === 'warn';\n\n await this.compact(ctx, aggressive, { level, tokens, load });\n\n return next(ctx);\n };\n }\n\n /**\n * Returns true when the previous compaction at the same or higher pressure\n * level reduced nothing and context has not grown materially since. Prevents\n * a stuck preserveK window from spamming compaction events every iteration.\n */\n private shouldSkipNoopRetry(level: PressureLevel, tokens: number): boolean {\n const stuck = this.lastNoopAttempt;\n if (!stuck) return false;\n // Escalation always retries — soft → hard might be reducible aggressively.\n if (LEVEL_RANK[level] > LEVEL_RANK[stuck.level]) return false;\n const delta = tokens - stuck.tokens;\n return delta < AutoCompactionMiddleware.NOOP_RETRY_DELTA_TOKENS;\n }\n\n private recordAttempt(level: PressureLevel, tokens: number, report: CompactReport): void {\n // Prefer full-request tokens (accurate); fall back to message-only before/after.\n const reduced =\n (report.fullRequestTokensBefore ?? report.before) > (report.fullRequestTokensAfter ?? report.after);\n const repaired = !!report.repaired;\n if (reduced || repaired) {\n this.lastNoopAttempt = null;\n } else {\n this.lastNoopAttempt = { level, tokens };\n }\n }\n\n private async compact(\n ctx: Context,\n aggressive: boolean,\n pressure: { level: PressureLevel; tokens: number; load: number },\n ): Promise<void> {\n try {\n const report = await this.compactor.compact(ctx, { aggressive });\n this.recordAttempt(pressure.level, pressure.tokens, report);\n this.events?.emit('compaction.fired', {\n level: pressure.level,\n tokens: pressure.tokens,\n load: pressure.load,\n maxContext: this._maxContext,\n report,\n aggressive,\n });\n\n // Persist a compaction event to the session log (if a bridge was provided).\n // This is one of the highest-value audit events for understanding context\n // window behavior over long runs.\n await this.sessionBridge?.append({\n type: 'compaction',\n ts: new Date().toISOString(),\n before: report.before,\n after: report.after,\n level: pressure.level,\n aggressive,\n reductions: report.reductions?.map((r) => ({ phase: r.phase, saved: r.saved })),\n });\n\n // Stale file-read metadata from before the compaction boundary is no\n // longer useful and would cause hasRead() to skip legitimate re-reads.\n ctx.clearFileTracking();\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n const fatal =\n this.failureMode === 'throw' ||\n (this.failureMode === 'throw_on_hard' && pressure.level === 'hard');\n this.events?.emit('compaction.failed', {\n err: error,\n aggressive,\n level: pressure.level,\n tokens: pressure.tokens,\n maxContext: this._maxContext,\n load: pressure.load,\n fatal,\n });\n if (fatal) {\n throw new AgentError({\n message: `Auto-compaction failed at ${pressure.level} threshold`,\n code: ERROR_CODES.AGENT_CONTEXT_OVERFLOW,\n recoverable: true,\n context: {\n level: pressure.level,\n tokens: pressure.tokens,\n maxContext: this._maxContext,\n },\n cause: err,\n });\n }\n }\n }\n}\n","/**\n * Well-known tool capabilities used for authorization decisions.\n *\n * These are the preferred values for `Tool.capabilities`.\n * New capabilities should be added here with clear documentation.\n *\n * Philosophy (2026-06+):\n * - Prefer capabilities over exact tool name matching.\n * - Subagent guards and future policies should primarily key off capabilities.\n * - Name-based denylists are legacy and will be phased down.\n */\nexport const ToolCapabilities = {\n /** Can execute arbitrary commands in the user's shell (the `bash` tool). */\n SHELL_ARBITRARY: 'shell.arbitrary',\n\n /** Can execute a restricted set of commands (the `exec` tool). */\n SHELL_RESTRICTED: 'shell.restricted',\n\n /** Can read files inside the project (and possibly outside via symlinks if not guarded). */\n FS_READ: 'fs.read',\n\n /** Can write / modify / delete files inside the project. */\n FS_WRITE: 'fs.write',\n\n /** Can write files outside the current project root (very high risk). */\n FS_WRITE_OUTSIDE_PROJECT: 'fs.write.outside-project',\n\n /** Can perform outbound network requests. */\n NET_OUTBOUND: 'net.outbound',\n\n /** Proxies tools from external MCP servers (unknown capability). */\n MCP_PROXY: 'mcp.proxy',\n\n /** Can spawn or manage subagents / multi-agent tasks. */\n SUBAGENT_SPAWN: 'subagent.spawn',\n\n /** Can mutate global or session configuration / trust state. */\n CONFIG_MUTATE: 'config.mutate',\n\n /** Can install packages or run package managers with side effects. */\n PACKAGE_INSTALL: 'package.install',\n} as const;\n\nexport type ToolCapability = (typeof ToolCapabilities)[keyof typeof ToolCapabilities];\n\n/**\n * Set of capabilities that are considered dangerous for subagents by default.\n * Subagents should not receive these capabilities unless the leader explicitly\n * allows the specific tool at spawn time.\n */\nexport const DANGEROUS_FOR_SUBAGENTS: readonly ToolCapability[] = [\n ToolCapabilities.SHELL_ARBITRARY,\n ToolCapabilities.FS_WRITE,\n ToolCapabilities.FS_WRITE_OUTSIDE_PROJECT,\n ToolCapabilities.MCP_PROXY,\n ToolCapabilities.SUBAGENT_SPAWN,\n ToolCapabilities.CONFIG_MUTATE,\n ToolCapabilities.PACKAGE_INSTALL,\n];\n\n/**\n * Check if a tool (or its capabilities array) includes any dangerous capability\n * for subagent execution.\n */\nexport function hasDangerousCapabilityForSubagents(\n toolOrCaps: { capabilities?: readonly string[] } | readonly string[] | undefined,\n): boolean {\n if (!toolOrCaps) return false;\n // Use `as unknown as ...` to allow accessing .capabilities on the union type\n const input = toolOrCaps as unknown as { capabilities?: readonly string[] };\n const caps: readonly string[] = Array.isArray(toolOrCaps) ? toolOrCaps : (input.capabilities ?? []);\n return caps.some((c) => DANGEROUS_FOR_SUBAGENTS.includes(c as ToolCapability));\n}\n\n/**\n * Check if a tool declares a specific capability (or any of the provided ones).\n */\nexport function hasCapability(\n toolOrCaps: { capabilities?: readonly string[] } | readonly string[] | undefined,\n capability: ToolCapability | ToolCapability[],\n): boolean {\n if (!toolOrCaps) return false;\n // Use `as unknown as ...` to allow accessing .capabilities on the union type\n const input = toolOrCaps as unknown as { capabilities?: readonly string[] };\n const caps: readonly string[] = Array.isArray(toolOrCaps) ? toolOrCaps : (input.capabilities ?? []);\n const toCheck = Array.isArray(capability) ? capability : [capability];\n return toCheck.some((c) => caps.includes(c));\n}\n\n/**\n * Returns the intersection of a tool's capabilities with the dangerous set.\n * Useful for logging and audit trails.\n */\nexport function getDangerousCapabilities(\n toolOrCaps: { capabilities?: readonly string[] } | readonly string[] | undefined,\n): ToolCapability[] {\n if (!toolOrCaps) return [];\n // Use `as unknown as ...` to allow accessing .capabilities on the union type\n const input = toolOrCaps as unknown as { capabilities?: readonly string[] };\n const caps: readonly string[] = Array.isArray(toolOrCaps) ? toolOrCaps : (input.capabilities ?? []);\n return caps.filter((c): c is ToolCapability =>\n DANGEROUS_FOR_SUBAGENTS.includes(c as ToolCapability),\n );\n}\n","/**\n * Minimal JSON Schema validator — covers the subset needed for plugin\n * configSchema validation and tool inputSchema sanity checks. Intentionally\n * small (~80 lines, zero deps) and tolerant: unknown keywords are ignored so\n * authors can mix in non-standard extensions without breaking validation.\n *\n * NOT for full JSON Schema 2020-12 conformance. If a plugin needs $ref,\n * conditional schemas, format validation, or anything else exotic, it should\n * bring its own ajv-based validator and call this only for the cheap path.\n */\nimport type { JSONSchema } from '../types/tool.js';\n\nexport interface ValidationError {\n path: string;\n message: string;\n}\n\nexport interface ValidationResult {\n ok: boolean;\n errors: ValidationError[];\n}\n\nexport function validateAgainstSchema(value: unknown, schema: JSONSchema): ValidationResult {\n const errors: ValidationError[] = [];\n walk(value, schema, '', errors);\n return { ok: errors.length === 0, errors };\n}\n\nfunction walk(value: unknown, schema: JSONSchema, path: string, errors: ValidationError[]): void {\n if (schema.enum !== undefined) {\n if (!schema.enum.some((e) => deepEqual(e, value))) {\n errors.push({\n path: path || '<root>',\n message: `expected one of ${JSON.stringify(schema.enum)}, got ${JSON.stringify(value)}`,\n });\n return;\n }\n }\n\n if (typeof schema.type === 'string') {\n if (!checkType(value, schema.type)) {\n errors.push({\n path: path || '<root>',\n message: `expected ${schema.type}, got ${describeType(value)}`,\n });\n return;\n }\n }\n\n if (schema.type === 'object' && isPlainObject(value)) {\n const obj = value as Record<string, unknown>;\n for (const req of schema.required ?? []) {\n if (!(req in obj)) {\n errors.push({ path: joinPath(path, req), message: 'required property missing' });\n }\n }\n if (schema.properties) {\n for (const [key, subSchema] of Object.entries(schema.properties)) {\n if (key in obj) {\n walk(obj[key], subSchema, joinPath(path, key), errors);\n }\n }\n }\n }\n\n if (schema.type === 'array' && Array.isArray(value) && schema.items) {\n value.forEach((item, i) => walk(item, schema.items as JSONSchema, `${path}[${i}]`, errors));\n }\n}\n\nfunction checkType(value: unknown, type: string): boolean {\n switch (type) {\n case 'string':\n return typeof value === 'string';\n case 'number':\n return typeof value === 'number' && !Number.isNaN(value);\n case 'integer':\n return typeof value === 'number' && Number.isInteger(value);\n case 'boolean':\n return typeof value === 'boolean';\n case 'null':\n return value === null;\n case 'array':\n return Array.isArray(value);\n case 'object':\n return isPlainObject(value);\n default:\n return true;\n }\n}\n\nfunction isPlainObject(v: unknown): boolean {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\nfunction describeType(v: unknown): string {\n if (v === null) return 'null';\n if (Array.isArray(v)) return 'array';\n return typeof v;\n}\n\nfunction joinPath(parent: string, key: string): string {\n if (!parent) return key;\n return `${parent}.${key}`;\n}\n\nfunction deepEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (typeof a !== typeof b) return false;\n if (a === null || b === null) return a === b;\n if (Array.isArray(a) && Array.isArray(b)) {\n return a.length === b.length && a.every((v, i) => deepEqual(v, b[i]));\n }\n if (typeof a === 'object' && typeof b === 'object') {\n const ak = Object.keys(a as object);\n const bk = Object.keys(b as object);\n if (ak.length !== bk.length) return false;\n return ak.every((k) =>\n deepEqual((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k]),\n );\n }\n return false;\n}\n","/**\n * Tool output serialization utilities.\n * Extracted from Agent.executeTools to allow reuse and consistent output handling.\n */\n\nexport interface ToolOutputSerializerOptions {\n perIterationOutputCapBytes?: number;\n estimator?: (text: string) => number;\n}\n\nexport function createToolOutputSerializer(opts: ToolOutputSerializerOptions = {}) {\n const capBytes = opts.perIterationOutputCapBytes ?? 100_000;\n\n function serialize(value: unknown): string {\n if (typeof value === 'string') return value;\n if (value === null || value === undefined) return '';\n if (typeof value === 'object') {\n if (Array.isArray(value)) return value.map(serialize).join('\\n');\n if ('text' in (value as Record<string, unknown>)) {\n const t = (value as Record<string, unknown>).text;\n return typeof t === 'string' ? t : JSON.stringify(value, null, 2);\n }\n try {\n return JSON.stringify(value, null, 2);\n } catch {\n return String(value);\n }\n }\n return String(value);\n }\n\n function enforceCap(text: string, remainingBudget: number): { text: string; newBudget: number } {\n if (remainingBudget <= 0) {\n return { text: '[truncated: iteration output cap exceeded]', newBudget: 0 };\n }\n const textBytes = Buffer.byteLength(text, 'utf8');\n if (textBytes <= remainingBudget) {\n return { text, newBudget: remainingBudget - textBytes };\n }\n const marker = `\\n…[truncated ${textBytes - remainingBudget} bytes]…\\n`;\n const markerBytes = Buffer.byteLength(marker, 'utf8');\n const available = remainingBudget - markerBytes;\n if (available <= 0) {\n return { text: '[truncated: iteration output cap exceeded]', newBudget: 0 };\n }\n const half = Math.floor(available / 2);\n const first = text.slice(0, half);\n const second = text.slice(text.length - half);\n return { text: `${first}${marker}${second}`, newBudget: 0 };\n }\n\n return { serialize, enforceCap, capBytes };\n}\n","import type { Context } from '../core/context.js';\nimport type { ToolResultBlock, ToolUseBlock } from '../types/blocks.js';\nimport type {\n ToolBatchResult,\n ToolConfirmPendingResult,\n ToolExecutionOutput,\n ToolExecutorOptions,\n ToolExecutorStrategy,\n} from '../types/tool-executor.js';\nimport type { Tool } from '../types/tool.js';\nimport {\n hasDangerousCapabilityForSubagents,\n getDangerousCapabilities,\n} from '../security/capabilities.js';\nimport { validateAgainstSchema } from '../utils/json-schema-validate.js';\nimport { createToolOutputSerializer } from '../utils/tool-output-serializer.js';\n\nexport class ToolExecutor {\n private readonly serializer;\n private readonly iterationTimeoutMs: number;\n\n constructor(\n private readonly registry: { get(name: string): Tool | undefined; list(): Tool[] },\n private opts: ToolExecutorOptions,\n ) {\n this.iterationTimeoutMs = opts.iterationTimeoutMs ?? 300_000;\n this.serializer = createToolOutputSerializer({\n perIterationOutputCapBytes: opts.perIterationOutputCapBytes ?? 100_000,\n });\n }\n\n /**\n * Clear the interactive confirm awaiter so the executor returns\n * `ToolConfirmPendingResult` instead of blocking on stdin. Used by\n * the CLI to switch from inline prompts (REPL) to event-driven\n * confirmation (TUI) at runtime.\n */\n clearConfirmAwaiter(): void {\n this.opts.confirmAwaiter = undefined;\n }\n\n /**\n * Execute a batch of tool uses using the configured strategy.\n * Returns the execution results and the remaining output budget.\n */\n async executeBatch(\n toolUses: ToolUseBlock[],\n ctx: Context,\n strategy: ToolExecutorStrategy,\n ): Promise<ToolBatchResult> {\n let budget = this.opts.perIterationOutputCapBytes ?? 100_000;\n\n const runOne = async (use: ToolUseBlock): Promise<ToolExecutionOutput> => {\n const start = Date.now();\n const tool = this.registry.get(use.name);\n\n // Fast path: unknown tool\n if (!tool) {\n const result = this.unknownToolResult(use, () => this.registry.list().map((t) => t.name));\n budget = this.decrementBudget(result, budget);\n return { result, tool, durationMs: Date.now() - start };\n }\n\n // Strong guarantee: Validate input against the tool's declared JSON Schema\n // *before* permission checks or execution. This is a hard gate — bad calls\n // are rejected early with actionable feedback so the model can self-correct.\n const validation = validateAgainstSchema(use.input, tool.inputSchema);\n if (!validation.ok) {\n const errorDetails = validation.errors\n .map((e) => ` - ${e.path || 'input'}: ${e.message}`)\n .join('\\n');\n\n const result = {\n type: 'tool_result' as const,\n tool_use_id: use.id,\n content:\n `Invalid arguments for tool \"${tool.name}\".\\n\\n` +\n `Validation errors:\\n${errorDetails}\\n\\n` +\n `Please call the tool again with arguments that match its inputSchema. ` +\n `You can use the \"tool-help\" tool with name=\"${tool.name}\" to see the exact expected schema.`,\n is_error: true,\n };\n budget = this.decrementBudget(result, budget);\n return { result, tool, durationMs: Date.now() - start };\n }\n\n // Capability safety net at the executor level (defense in depth).\n // For tools declaring dangerous capabilities, we ensure the permission\n // decision cannot silently become \"auto\" in non-yolo contexts.\n const toolDangerousCaps = getDangerousCapabilities(tool);\n if (toolDangerousCaps.length > 0) {\n // If the tool has dangerous capabilities and we're not in full yolo mode,\n // we can force the downstream permission policy to treat it more strictly.\n // For now we record it; future policy profiles can act on this.\n if (this.opts.events) {\n // Observability hook for dangerous capability usage\n }\n }\n\n // Provider boundary: the model's tool arguments arrive as a raw JSON\n // string accumulated over streamed deltas. When that string is not a\n // valid JSON object (truncated, scalar, or mangled by a proxy/local\n // model), the parsers wrap it under a sentinel key instead of silently\n // producing `{}`. Executing the tool with such input yields a cryptic\n // \"<field> is required\" error that the model can't act on. Detect the\n // sentinel here and feed back an actionable message so the model\n // resends well-formed arguments.\n if (hasMalformedArguments(use.input)) {\n const result = this.malformedInputResult(use, extractMalformedRaw(use.input));\n budget = this.decrementBudget(result, budget);\n return { result, tool, durationMs: Date.now() - start };\n }\n\n const decision = await this.opts.permissionPolicy.evaluate(tool, use.input, ctx);\n\n // Post-permission dangerous capability enforcement (B-side guarantee).\n // Even after the permission policy has spoken, we apply an extra conservative\n // rule for tools that declare high-risk capabilities (shell arbitrary, write outside\n // project, mcp proxy, etc.). This reduces the blast radius of prompt injection.\n let effectivePermission = decision.permission;\n\n // YOLO is the user's explicit \"stop asking\" switch, so it also waives the\n // dangerous-capability net below (matching the historical behavior where\n // --yolo skipped every prompt). The net still fires in non-yolo runs —\n // e.g. a trust-file auto-allow for a shell tool still gets a confirm, so\n // a single trusted pattern can't silently widen into arbitrary shell.\n // Detected via optional methods so policies without them (AutoApprove,\n // test mocks) keep the stricter default.\n const policy = this.opts.permissionPolicy as {\n getYolo?(): boolean;\n getForceAllYolo?(): boolean;\n };\n const yolo = policy.getYolo?.() === true || policy.getForceAllYolo?.() === true;\n\n if (toolDangerousCaps.length > 0 && effectivePermission === 'auto' && !yolo) {\n // Outside yolo we force at least 'confirm' for dangerous-capability tools.\n effectivePermission = 'confirm';\n }\n\n if (effectivePermission === 'deny') {\n const result = this.deniedResult(use, decision.reason);\n budget = this.decrementBudget(result, budget);\n return { result, tool, durationMs: Date.now() - start };\n }\n\n if (effectivePermission === 'confirm') {\n if (this.opts.confirmAwaiter) {\n const choice = await this.opts.confirmAwaiter(tool, use.input, use.id, tool.name);\n if (choice !== 'yes' && choice !== 'always') {\n const result = {\n type: 'tool_result' as const,\n tool_use_id: use.id,\n content: `Tool \"${tool.name}\" denied by user.`,\n is_error: true,\n };\n budget = this.decrementBudget(result, budget);\n return { result, tool, durationMs: Date.now() - start };\n }\n // fall through to execute\n } else {\n const suggestedPattern =\n this.subjectFor(tool.name, use.input, tool.subjectKey) ?? tool.name;\n const pending: ToolConfirmPendingResult = {\n type: 'tool_confirm_pending',\n toolUseId: use.id,\n toolName: tool.name,\n input: use.input,\n suggestedPattern,\n };\n return { result: pending, tool, durationMs: Date.now() - start };\n }\n }\n\n // effectivePermission === 'auto' (after all safety layers)\n // Capability audit for observability.\n const toolCapsForAudit = hasDangerousCapabilityForSubagents(tool) ? (tool.capabilities ?? []) : [];\n\n // L1-C: trace each tool execution. Span is a no-op unless an OTel\n // adapter or other Tracer is bound — zero overhead by default.\n const span = this.opts.tracer?.startSpan(`tool.${tool.name}`, {\n 'tool.name': tool.name,\n 'tool.mutating': tool.mutating,\n 'tool.permission': tool.permission,\n 'tool.capabilities': JSON.stringify(tool.capabilities ?? []),\n 'tool.has_dangerous_capabilities': toolCapsForAudit.length > 0,\n });\n try {\n const result = await this.executeTool(tool, use, ctx, budget);\n budget = this.decrementBudget(result, budget);\n span?.setAttribute('tool.is_error', !!result.is_error);\n span?.setAttribute(\n 'tool.output_bytes',\n typeof result.content === 'string' ? result.content.length : 0,\n );\n return { result, tool, durationMs: Date.now() - start };\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n const scrubbed = this.opts.secretScrubber.scrub(msg);\n this.opts.renderer?.writeToolResult(tool.name, scrubbed, true);\n const result = {\n type: 'tool_result' as const,\n tool_use_id: use.id,\n content: `Tool \"${tool.name}\" threw: ${scrubbed}`,\n is_error: true,\n };\n budget = this.decrementBudget(result, budget);\n if (err instanceof Error) span?.recordError(err);\n span?.setAttribute('tool.is_error', true);\n return { result, tool, durationMs: Date.now() - start };\n } finally {\n span?.end();\n }\n };\n\n // Run a single tool but never let an exception propagate to the\n // gather() below — `runOne` is already try/catch-wrapped for the\n // execution phase, but the *pre*-execution paths (permission policy,\n // confirmAwaiter) are unguarded and an unexpected throw there would\n // collapse Promise.all and lose every sibling's output. Wrap each\n // call so a per-tool failure becomes a per-tool error result.\n const safeRun = async (use: ToolUseBlock): Promise<ToolExecutionOutput> => {\n try {\n return await runOne(use);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n const scrubbed = this.opts.secretScrubber.scrub(msg);\n const result = {\n type: 'tool_result' as const,\n tool_use_id: use.id,\n content: `Tool \"${use.name}\" execution failed: ${scrubbed}`,\n is_error: true,\n };\n budget = this.decrementBudget(result, budget);\n return { result, tool: this.registry.get(use.name), durationMs: 0 };\n }\n };\n\n if (strategy === 'sequential') {\n const outputs: ToolExecutionOutput[] = [];\n for (const use of toolUses) {\n if (use) outputs.push(await safeRun(use));\n }\n return { outputs, remainingBudget: budget };\n }\n\n if (strategy === 'parallel') {\n const outputs = await Promise.all(toolUses.map((use) => safeRun(use)));\n return { outputs, remainingBudget: budget };\n }\n\n // smart: non-mutating in parallel, then mutating sequentially\n const nonMutating: ToolUseBlock[] = [];\n const mutating: ToolUseBlock[] = [];\n for (const use of toolUses) {\n if (!use) continue;\n const tool = this.registry.get(use.name);\n if (tool?.mutating) mutating.push(use);\n else nonMutating.push(use);\n }\n const firstPass = await Promise.all(nonMutating.map((use) => safeRun(use)));\n const secondPass: ToolExecutionOutput[] = [];\n for (const use of mutating) {\n secondPass.push(await safeRun(use));\n }\n return {\n outputs: [...firstPass, ...secondPass],\n remainingBudget: budget,\n };\n }\n\n /**\n * Execute a single tool with timeout, permission check, and output capping.\n * Emits `tool.started` via the injected EventBus (if any) right before\n * invoking the tool — closes the observability gap between \"model decided\n * to call a tool\" and \"tool.executed\".\n */\n async executeTool(\n tool: Tool,\n use: ToolUseBlock,\n ctx: Context,\n budget: number,\n ): Promise<ToolResultBlock> {\n this.opts.events?.emit('tool.started', {\n name: tool.name,\n id: use.id,\n input: use.input,\n });\n this.opts.renderer?.writeToolCall(tool.name, use.input);\n const output = await this.runWithTimeout(tool, use.input, ctx.signal, ctx, use.id);\n const text = this.serializer.serialize(output);\n const scrubbed = this.opts.secretScrubber.scrub(text);\n const { text: capped } = this.serializer.enforceCap(scrubbed, budget);\n this.opts.renderer?.writeToolResult(tool.name, capped, false);\n return {\n type: 'tool_result',\n tool_use_id: use.id,\n name: tool.name,\n content: capped,\n is_error: false,\n };\n }\n\n private async runWithTimeout(\n tool: Tool,\n input: unknown,\n parentSignal: AbortSignal,\n ctx: Context,\n toolUseId?: string,\n ): Promise<unknown> {\n if (parentSignal.aborted) {\n // Re-throw the original abort reason, whether it's an Error, string, or undefined.\n if (parentSignal.reason instanceof Error) throw parentSignal.reason;\n throw new Error(typeof parentSignal.reason === 'string' ? parentSignal.reason : 'aborted');\n }\n const timeoutMs = tool.timeoutMs ?? this.iterationTimeoutMs;\n const ctrl = new AbortController();\n const timer = setTimeout(() => ctrl.abort(new Error('tool timeout')), timeoutMs);\n const combined = AbortSignal.any([parentSignal, ctrl.signal]);\n let cleanupCalled = false;\n let caught = false;\n try {\n // Streaming variant takes precedence — yields progress events, then\n // a final 'final' event with the typed output. Tools that don't\n // implement executeStream fall through to the standard execute path.\n if (typeof tool.executeStream === 'function') {\n return await this.runStreamedTool(tool, input, ctx, combined, toolUseId);\n }\n return await tool.execute(input, ctx, { signal: combined });\n } catch (err) {\n caught = true;\n if (combined.aborted && typeof tool.cleanup === 'function') {\n // Best-effort cleanup; never let it mask the original error.\n cleanupCalled = true;\n try {\n await tool.cleanup(input, ctx);\n } catch {\n /* swallow */\n }\n }\n throw err;\n } finally {\n clearTimeout(timer);\n // If the tool completed successfully (no error thrown) but the combined\n // signal was aborted (e.g. timeout), the catch block above never fired.\n // Call cleanup here and then throw so the caller sees the abort.\n // When `caught` is true, we already have an in-flight throw — don't\n // override it from `finally` (that would replace the original error\n // with the abort reason and mask the actual failure).\n if (combined.aborted && !caught) {\n if (!cleanupCalled && typeof tool.cleanup === 'function') {\n try {\n await tool.cleanup(input, ctx);\n } catch {\n /* swallow */\n }\n }\n const reason = combined.reason instanceof Error\n ? combined.reason\n : new Error(typeof combined.reason === 'string' ? combined.reason : 'aborted');\n // biome-ignore lint/correctness/noUnsafeFinally: guarded by `!caught` — only runs when the tool returned cleanly but the signal aborted, so there is no in-flight exception to override.\n throw reason;\n }\n }\n }\n\n private async runStreamedTool(\n tool: Tool,\n input: unknown,\n ctx: Context,\n signal: AbortSignal,\n toolUseId: string | undefined,\n ): Promise<unknown> {\n let finalOutput: unknown;\n let sawFinal = false;\n const stream = tool.executeStream!(input, ctx, { signal });\n for await (const ev of stream) {\n if (ev.type === 'final') {\n finalOutput = ev.output;\n sawFinal = true;\n // Drain whatever the iterator wants to surface after final, but the\n // result is locked in. Most tools won't yield more.\n break;\n }\n this.opts.events?.emit('tool.progress', {\n name: tool.name,\n id: toolUseId ?? '<unknown>',\n event: ev,\n });\n }\n if (!sawFinal) {\n throw new Error(`tool \"${tool.name}\" executeStream completed without a 'final' event`);\n }\n return finalOutput;\n }\n\n private unknownToolResult(use: ToolUseBlock, listFns: () => string[]): ToolResultBlock {\n return {\n type: 'tool_result',\n tool_use_id: use.id,\n content: `Tool \"${use.name}\" is not registered. Available tools: ${listFns().join(', ')}`,\n is_error: true,\n };\n }\n\n private malformedInputResult(use: ToolUseBlock, raw?: string): ToolResultBlock {\n let content =\n `Tool \"${use.name}\" received arguments that were not a valid JSON object, so they ` +\n `could not be parsed. Re-issue the call with the arguments encoded as a single ` +\n `well-formed JSON object matching the tool's input schema.`;\n // Echo the raw payload back so the model can see *what* it produced and\n // self-correct. Without this the model is blind to its own mistake and\n // tends to resend the identical malformed call in a loop. Common causes:\n // unescaped newlines/quotes/backslashes inside a string field, or the\n // arguments being truncated mid-stream.\n if (raw) {\n const max = 800;\n const excerpt = raw.length > max ? `${raw.slice(0, max)}… (truncated, ${raw.length} chars total)` : raw;\n content +=\n ` Common cause: a string field (e.g. code in old_string/new_string) ` +\n `contains literal newlines, quotes, or backslashes that must be JSON-escaped, ` +\n `or the payload was cut off mid-stream. The raw arguments received were:\\n${excerpt}`;\n }\n return {\n type: 'tool_result',\n tool_use_id: use.id,\n content,\n is_error: true,\n };\n }\n\n private deniedResult(use: ToolUseBlock, reason?: string): ToolResultBlock {\n return {\n type: 'tool_result',\n tool_use_id: use.id,\n content: `Tool \"${use.name}\" denied: ${reason ?? 'policy'}`,\n is_error: true,\n };\n }\n\n private decrementBudget(result: ToolResultBlock, budget: number): number {\n const contentBytes =\n typeof result.content === 'string'\n ? Buffer.byteLength(result.content, 'utf8')\n : Buffer.byteLength(JSON.stringify(result.content), 'utf8');\n return Math.max(0, budget - contentBytes);\n }\n\n /**\n * Compute the suggestedPattern string for a tool+input pair.\n * Matches the logic in DefaultPermissionPolicy so the TUI shows the\n * same subject that the trust file would use.\n */\n private subjectFor(toolName: string, input: unknown, subjectKey?: string): string | undefined {\n if (!input || typeof input !== 'object') return undefined;\n const obj = input as Record<string, unknown>;\n const globChars = /[*?\\[\\]]/g;\n const escapeGlob = (s: string) => s.replace(globChars, (c) => `\\\\${c}`);\n const normalizePath = (s: string) => escapeGlob(s.replace(/\\\\/g, '/'));\n\n // Mirror DefaultPermissionPolicy.subjectFor — keep both in sync so the\n // TUI's \"suggested pattern\" matches what the trust file actually uses.\n if (subjectKey) {\n const v = obj[subjectKey];\n if (typeof v === 'string') {\n const isPathKey = subjectKey === 'path' || subjectKey === 'file' || subjectKey === 'files';\n return isPathKey ? normalizePath(v) : escapeGlob(v);\n }\n }\n\n if (toolName === 'bash' && typeof obj.command === 'string') {\n return escapeGlob(obj.command);\n }\n if (typeof obj.path === 'string') {\n return normalizePath(obj.path);\n }\n if (typeof obj.url === 'string') {\n return escapeGlob(obj.url);\n }\n if (typeof obj.name === 'string') {\n return escapeGlob(obj.name);\n }\n return undefined;\n }\n}\n\n/**\n * Sentinel keys the provider adapters use to wrap tool arguments that could\n * not be parsed into a proper JSON object. `parseToolInput` (Anthropic /\n * shared) uses `__raw`, `contentFromOpenAI` uses `__raw_arguments`, and the\n * streaming response builder's `safeJsonOrRaw` uses `_raw`. Keep this list in\n * sync if a new adapter introduces another marker.\n *\n * NOTE: `parseToolInput` and `safeJsonOrRaw` now attempt JSON repair\n * (auto-closing braces and strings) before wrapping — so a truncated blob\n * like `{\"old_string\": \"line1\\nline2` gets repaired first. The sentinel is\n * only used when repair also fails.\n */\nconst MALFORMED_ARG_MARKERS = ['__raw', '__raw_arguments', '_raw'] as const;\n\nfunction hasMalformedArguments(input: unknown): boolean {\n if (!input || typeof input !== 'object' || Array.isArray(input)) return false;\n const obj = input as Record<string, unknown>;\n // The sentinel is the *only* key when wrapping occurred — a real tool call\n // that legitimately uses a key named e.g. `_raw` will carry other keys too.\n const keys = Object.keys(obj);\n return keys.length === 1 && MALFORMED_ARG_MARKERS.includes(keys[0] as never);\n}\n\n/**\n * Pull the original (unparseable) payload back out of a sentinel-wrapped input\n * so the executor can echo it to the model. The wrapped value is usually the\n * raw argument string, but a scalar/array that parsed cleanly is wrapped too —\n * stringify those. Returns undefined if nothing usable is present.\n */\nfunction extractMalformedRaw(input: unknown): string | undefined {\n if (!hasMalformedArguments(input)) return undefined;\n const obj = input as Record<string, unknown>;\n const value = obj[Object.keys(obj)[0]!];\n if (value === undefined || value === null) return undefined;\n if (typeof value === 'string') return value;\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n","/**\n * Compile a user-supplied regex with conservative bounds against ReDoS.\n *\n * Duplicated from @wrongstack/tools/_regex.ts to avoid a circular\n * dependency (tools depends on core, not vice versa). Keep both copies\n * in sync if the heuristics change.\n *\n * V8's regex engine is backtracking-based and cannot interrupt a\n * synchronous match — a pattern like `(a+)+$` against a sufficiently\n * long line will pin a worker for seconds.\n */\n\nconst MAX_PATTERN_LEN = 512;\n\n// Heuristics for catastrophic-backtracking constructs.\nconst DANGEROUS_PATTERNS: ReadonlyArray<RegExp> = [\n /(\\([^)]*[+*][^)]*\\))[+*]/, // (a+)+, (.*)+, etc\n /(\\(\\?:[^)]*[+*][^)]*\\))[+*]/, // same, with non-capturing group\n];\n\nexport interface CompileResult {\n ok: true;\n regex: RegExp;\n}\n\nexport interface CompileFail {\n ok: false;\n reason: string;\n}\n\nexport function compileUserRegex(pattern: string, flags: string): CompileResult | CompileFail {\n if (typeof pattern !== 'string') {\n return { ok: false, reason: 'pattern must be a string' };\n }\n if (pattern.length === 0) {\n return { ok: false, reason: 'pattern is empty' };\n }\n if (pattern.length > MAX_PATTERN_LEN) {\n return { ok: false, reason: `pattern exceeds ${MAX_PATTERN_LEN} characters` };\n }\n for (const rx of DANGEROUS_PATTERNS) {\n if (rx.test(pattern)) {\n return {\n ok: false,\n reason:\n 'pattern looks vulnerable to catastrophic backtracking — rewrite without nested quantifiers',\n };\n }\n }\n try {\n return { ok: true, regex: new RegExp(pattern, flags) };\n } catch (err) {\n return {\n ok: false,\n reason: err instanceof Error ? err.message : 'invalid regex',\n };\n }\n}\n","import type { Agent, RunResult } from '../core/agent.js';\r\nimport type { Context } from '../core/context.js';\r\nimport { toWrongStackError } from '../types/errors.js';\r\nimport type { DoneCondition } from '../types/multi-agent.js';\r\nimport { compileUserRegex } from '../utils/regex-guard.js';\r\n\r\ntype AutonomousResult = RunResult & { toolCalls: number; reason?: string };\r\n\r\nexport interface DoneCheckResult {\r\n done: boolean;\r\n reason?: string;\r\n iterations: number;\r\n toolCalls: number;\r\n}\r\n\r\nexport class DoneConditionChecker {\r\n private readonly compiledRegex: RegExp | null;\r\n\r\n constructor(private readonly condition: DoneCondition) {\r\n if (condition.type === 'output_match' && condition.pattern) {\r\n const result = compileUserRegex(condition.pattern, '');\r\n this.compiledRegex = result.ok ? result.regex : null;\r\n if (!result.ok) {\r\n // Log warning but don't throw — the done condition simply won't match\r\n console.warn(`[DoneConditionChecker] Invalid regex pattern \"${condition.pattern}\": ${result.reason}`);\r\n }\r\n } else {\r\n this.compiledRegex = null;\r\n }\r\n }\r\n\r\n check(state: { iterations: number; toolCalls: number; lastOutput?: string }): DoneCheckResult {\r\n switch (this.condition.type) {\r\n case 'iterations':\r\n if (this.condition.maxIterations && state.iterations >= this.condition.maxIterations) {\r\n return {\r\n done: true,\r\n reason: `max iterations (${this.condition.maxIterations}) reached`,\r\n ...state,\r\n };\r\n }\r\n break;\r\n\r\n case 'tool_calls':\r\n if (this.condition.maxToolCalls && state.toolCalls >= this.condition.maxToolCalls) {\r\n return {\r\n done: true,\r\n reason: `max tool calls (${this.condition.maxToolCalls}) reached`,\r\n ...state,\r\n };\r\n }\r\n break;\r\n\r\n case 'output_match':\r\n if (this.compiledRegex && state.lastOutput && this.compiledRegex.test(state.lastOutput)) {\r\n return {\r\n done: true,\r\n reason: `output matched pattern \"${this.condition.pattern}\"`,\r\n ...state,\r\n };\r\n }\r\n break;\r\n\r\n case 'directive':\r\n // Model-driven: the agent manages its own continuation via [continue]/[done].\r\n // The done condition is never satisfied by the checker — the agent returns\r\n // `status: 'done'` when the model emits [done] or naturally finishes.\r\n // The runner's outer loop uses maxIterations/maxToolCalls as hard caps.\r\n if (this.condition.maxIterations && state.iterations >= this.condition.maxIterations) {\r\n return { done: true, reason: `max iterations (${this.condition.maxIterations}) reached`, ...state };\r\n }\r\n if (this.condition.maxToolCalls && state.toolCalls >= this.condition.maxToolCalls) {\r\n return { done: true, reason: `max tool calls (${this.condition.maxToolCalls}) reached`, ...state };\r\n }\r\n break;\r\n\r\n case 'custom':\r\n // Reserved for future extension\r\n break;\r\n }\r\n\r\n return { done: false, iterations: state.iterations, toolCalls: state.toolCalls };\r\n }\r\n}\r\n\r\nexport interface AutonomousRunnerOptions {\r\n agent: Agent;\r\n context: Context;\r\n doneCondition: DoneCondition;\r\n iterationTimeoutMs?: number;\r\n onIteration?: (state: { iteration: number; toolCalls: number }) => void;\r\n onDone?: (result: AutonomousResult) => void;\r\n /**\r\n * When true and `doneCondition.type === 'directive'`, the runner\r\n * runs the agent with `autonomousContinue: true` so the agent loop\r\n * handles its own [continue]/[done] markers internally (no outer\r\n * re-invocation needed). The runner still provides iteration/timeouts.\r\n */\r\n enableAutonomousContinue?: boolean;\r\n}\r\n\r\nexport class AutonomousRunner {\r\n private iterations = 0;\r\n private toolCalls = 0;\r\n private lastOutput?: string;\r\n private stopped = false;\r\n private readonly doneChecker: DoneConditionChecker;\r\n\r\n constructor(private readonly opts: AutonomousRunnerOptions) {\r\n this.doneChecker = new DoneConditionChecker(opts.doneCondition);\r\n }\r\n\r\n async run(): Promise<AutonomousResult> {\r\n // Subscribe to `tool.executed` so the per-tool budget (`tool_calls`\r\n // done-condition) actually counts each tool invocation rather than\r\n // each `agent.run()` call. Without this, a single iteration that\r\n // fires 5 tools only bumps the counter once, and a `maxToolCalls: 3`\r\n // budget would fire after 3 iterations (typically 3×N tools) instead\r\n // of after 3 tools. Unsubscribed in the `finally` so the listener\r\n // doesn't outlive this run instance. Mock agents in tests may pass\r\n // null/undefined for `events`; gracefully skip when missing — those\r\n // tests don't exercise the tool-count budget path.\r\n const offToolExecuted = this.opts.agent.events?.on?.('tool.executed', () => {\r\n this.toolCalls++;\r\n });\r\n // When autonomous continue is enabled, also count internal agent-loop\r\n // iterations. Each iteration.started within a single agent.run() call\r\n // counts toward the runner's maxIterations cap. We listen to the event\r\n // through the agent's EventBus.\r\n const offIterationCompleted = this.opts.agent.events?.on?.('iteration.completed', () => {\r\n // Only count if we're in autonomous continue mode (agent loop\r\n // handles multiple iterations internally before returning).\r\n if (this.opts.enableAutonomousContinue && this.opts.doneCondition.type === 'directive') {\r\n // Each internal iteration completed — bump the outer iteration counter.\r\n // This ensures maxIterations on the runner actually limits total work.\r\n this.iterations++;\r\n }\r\n });\r\n try {\r\n return await this.runLoop();\r\n } finally {\r\n offToolExecuted?.();\r\n offIterationCompleted?.();\r\n }\r\n }\r\n\r\n private async runLoop(): Promise<AutonomousResult> {\r\n while (!this.stopped) {\r\n const check = this.doneChecker.check({\r\n iterations: this.iterations,\r\n toolCalls: this.toolCalls,\r\n lastOutput: this.lastOutput,\r\n });\r\n\r\n if (check.done) {\r\n const result: AutonomousResult = {\r\n status: 'done',\r\n iterations: this.iterations,\r\n toolCalls: this.toolCalls,\r\n reason: check.reason,\r\n };\r\n this.opts.onDone?.(result);\r\n return result;\r\n }\r\n\r\n this.opts.onIteration?.({ iteration: this.iterations, toolCalls: this.toolCalls });\r\n\r\n const ctrl = new AbortController();\r\n const timeout = setTimeout(() => ctrl.abort(), this.opts.iterationTimeoutMs ?? 30_000);\r\n\r\n try {\r\n // In directive mode with autonomous continue, pass it through so the\r\n // agent loop handles its own [continue]/[done] markers internally.\r\n // The runner provides iteration caps and timeouts; the agent handles\r\n // the continuation decision within each agent.run() call.\r\n const isDirectiveMode =\r\n this.opts.doneCondition.type === 'directive' &&\r\n this.opts.enableAutonomousContinue;\r\n\r\n const result = await this.opts.agent.run('', {\r\n signal: ctrl.signal,\r\n maxIterations: isDirectiveMode ? (this.opts.doneCondition.maxIterations ?? 100) : 1,\r\n executionStrategy: 'sequential',\r\n autonomousContinue: isDirectiveMode ? true : undefined,\r\n });\r\n\r\n // Only increment iterations if we're NOT counting via iteration.completed\r\n // (i.e., not in autonomous continue directive mode). In that mode,\r\n // the offIterationCompleted listener in run() bumps this counter\r\n // per internal iteration so the runner's maxIterations cap is respected.\r\n if (!isDirectiveMode) this.iterations++;\r\n // Only access finalText when the run actually succeeded. Failed/aborted\r\n // runs may have undefined finalText — accessing it unconditionally would\r\n // produce garbage output for the done-condition matchers.\r\n if (result.status === 'done') {\r\n this.lastOutput = result.finalText;\r\n }\r\n // `toolCalls` is bumped by the `tool.executed` listener installed\r\n // in run() — no manual increment here.\r\n\r\n if (result.status === 'failed' || result.status === 'aborted') {\r\n const failedResult: AutonomousResult = {\r\n status: result.status,\r\n error: result.error,\r\n iterations: this.iterations,\r\n toolCalls: this.toolCalls,\r\n };\r\n this.opts.onDone?.(failedResult);\r\n return failedResult;\r\n }\r\n } catch (e) {\r\n // Be precise about what constitutes a timeout error — matching on\r\n // 'timeout' substring is too loose (an error message containing\r\n // \"timeout exceeded\" from the LLM is not the same as an abort).\r\n const isAbort =\r\n (e instanceof DOMException && e.name === 'AbortError') ||\r\n (e instanceof Error && e.name === 'AbortError') ||\r\n (e instanceof Error && e.message.includes('iteration timeout'));\r\n if (isAbort) {\r\n const timeoutResult: AutonomousResult = {\r\n status: 'failed',\r\n error: toWrongStackError(e),\r\n iterations: this.iterations,\r\n toolCalls: this.toolCalls,\r\n reason: 'iteration timeout',\r\n };\r\n this.opts.onDone?.(timeoutResult);\r\n return timeoutResult;\r\n }\r\n // Any other throw (TypeError, tool crash propagation, etc.) must\r\n // stop the loop — silently continuing would spin forever on the\r\n // same error and burn provider tokens with no progress.\r\n this.stopped = true;\r\n const failedResult: AutonomousResult = {\r\n status: 'failed',\r\n error: toWrongStackError(e),\r\n iterations: this.iterations,\r\n toolCalls: this.toolCalls,\r\n reason: e instanceof Error ? e.message : String(e),\r\n };\r\n this.opts.onDone?.(failedResult);\r\n return failedResult;\r\n } finally {\r\n clearTimeout(timeout);\r\n }\r\n }\r\n\r\n return {\r\n status: 'aborted',\r\n iterations: this.iterations,\r\n toolCalls: this.toolCalls,\r\n reason: 'stopped externally',\r\n };\r\n }\r\n\r\n stop(): void {\r\n this.stopped = true;\r\n }\r\n}\r\n","import { randomBytes } from 'node:crypto';\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\n\nexport interface AtomicWriteOptions {\n mode?: number;\n encoding?: BufferEncoding;\n}\n\nexport async function atomicWrite(\n targetPath: string,\n content: string | Uint8Array,\n opts: AtomicWriteOptions = {},\n): Promise<void> {\n const dir = path.dirname(targetPath);\n await fs.mkdir(dir, { recursive: true });\n const tmp = path.join(dir, `.${path.basename(targetPath)}.${randomBytes(6).toString('hex')}.tmp`);\n\n // Write content to tmp first; 'wx' ensures exclusive creation (fails if\n // tmp already exists — extremely unlikely with 6-byte random suffix).\n try {\n if (typeof content === 'string') {\n await fs.writeFile(tmp, content, { flag: 'wx', encoding: opts.encoding ?? 'utf8' });\n } else {\n await fs.writeFile(tmp, content, { flag: 'wx' });\n }\n try {\n const fh = await fs.open(tmp, 'r+');\n try {\n await fh.sync();\n } finally {\n await fh.close();\n }\n } catch {\n // fsync best-effort\n }\n // Now safely read mode from target (if it exists) and apply to tmp before rename.\n // Prefer opts.mode for new files; for existing files preserve their mode.\n let mode: number | undefined;\n try {\n const stat = await fs.stat(targetPath);\n mode = stat.mode & 0o777;\n } catch {\n mode = opts.mode;\n }\n if (mode !== undefined) {\n await fs.chmod(tmp, mode);\n }\n await renameWithRetry(tmp, targetPath);\n } catch (err) {\n try {\n await fs.unlink(tmp);\n } catch {\n // ignore cleanup error\n }\n throw err;\n }\n}\n\nexport async function ensureDir(dir: string): Promise<void> {\n await fs.mkdir(dir, { recursive: true });\n}\n\n// On Windows, fs.rename over an existing file can fail with EPERM/EBUSY/EACCES\n// when antivirus, file indexers, editor file watchers, or a concurrent writer\n// briefly hold a handle on the destination. These are transient — retry with a\n// short backoff before giving up. POSIX renames are atomic and won't hit this.\nconst TRANSIENT_RENAME_CODES = new Set(['EPERM', 'EBUSY', 'EACCES', 'ENOTEMPTY']);\n\nasync function renameWithRetry(from: string, to: string): Promise<void> {\n if (process.platform !== 'win32') {\n await fs.rename(from, to);\n return;\n }\n const delays = [10, 25, 60, 120, 250];\n let lastErr: unknown;\n for (let i = 0; i <= delays.length; i++) {\n try {\n await fs.rename(from, to);\n return;\n } catch (err) {\n lastErr = err;\n const code = (err as NodeJS.ErrnoException)?.code;\n if (!code || !TRANSIENT_RENAME_CODES.has(code) || i === delays.length) {\n throw err;\n }\n await new Promise((resolve) => setTimeout(resolve, delays[i]));\n }\n }\n throw lastErr;\n}\n","import * as fsp from 'node:fs/promises';\r\nimport * as path from 'node:path';\r\nimport { createHash } from 'node:crypto';\r\nimport * as os from 'node:os';\r\nimport { atomicWrite } from '../utils/atomic-write.js';\r\nimport { FsError, ERROR_CODES } from '../types/errors.js';\r\n\r\n/**\r\n * Long-running autonomous mission. A goal survives across sessions and\r\n * drives the EternalAutonomyEngine — every iteration of the engine\r\n * consults the goal to choose what to do next.\r\n *\r\n * Storage: `~/.wrongstack/projects/<hash>/goal.json`. Persistent and\r\n * project-scoped on purpose: the goal belongs to the codebase, not the\r\n * REPL session.\r\n */\r\n\r\nexport interface JournalEntry {\r\n /** ISO timestamp of the iteration. */\r\n at: string;\r\n /** Sequential iteration counter (1-based, monotonically increasing). */\r\n iteration: number;\r\n /** Source that produced the action ('todo' | 'git' | 'brainstorm' | 'resume' | 'manual' | 'parallel'). */\r\n source: 'todo' | 'git' | 'brainstorm' | 'resume' | 'manual' | 'parallel';\r\n /** Short one-line description of what the iteration set out to do. */\r\n task: string;\r\n /** Outcome status. */\r\n status: 'success' | 'failure' | 'aborted' | 'skipped';\r\n /** Optional free-form note (error message, summary, etc.). */\r\n note?: string;\r\n /** Optional token usage delta for this iteration. */\r\n tokens?: { input: number; output: number };\r\n /** Optional USD cost delta for this iteration (provider-estimated). */\r\n costUsd?: number;\r\n}\r\n\r\nexport interface GoalFile {\r\n version: 1;\r\n /** The mission statement. */\r\n goal: string;\r\n /** When the goal was first set or last replaced. */\r\n setAt: string;\r\n /** Updated on every iteration completion. */\r\n lastActivityAt: string;\r\n /** Total iterations the engine has run against this goal (cumulative). */\r\n iterations: number;\r\n /** Engine lifecycle state — 'running' means another process owns this goal. */\r\n engineState: 'idle' | 'running' | 'stopped';\r\n /**\r\n * Mission-level lifecycle. `active` is the default; `completed` is set\r\n * when the engine detects `[GOAL_COMPLETE]` in a successful iteration's\r\n * final text AND a verification pass agrees; `abandoned` is set by the\r\n * user (e.g. `/goal abandon`) or when the engine exceeds a configured\r\n * failure ceiling. Once not `active`, the engine refuses to run further\r\n * iterations against this goal — protects against accidental restarts\r\n * burning through API quota after the work is done.\r\n *\r\n * Optional for backward compatibility — pre-existing `goal.json` files\r\n * without this field load as `active`.\r\n */\r\n goalState?: 'active' | 'paused' | 'completed' | 'abandoned';\r\n /**\r\n * Per-todo attempt counter. Keyed by TodoItem id. Used by the engine\r\n * to skip a todo that has failed N times rather than spinning on it\r\n * forever. Persisted so attempt counts survive restarts (`/autonomy\r\n * stop` + resume should not reset progress against a stuck task).\r\n */\r\n todoAttempts?: Record<string, number>;\r\n /** Bounded ring buffer of recent iterations (newest last). */\r\n journal: JournalEntry[];\r\n}\r\n\r\n/** Cap on persisted journal entries — older entries are evicted FIFO. */\r\nexport const MAX_JOURNAL_ENTRIES = 500;\r\n\r\n/**\r\n * Resolve the goal file path for a given project root.\r\n * Exposed so the engine and CLI use one canonical path.\r\n * Uses `~/.wrongstack/projects/<hash>/goal.json` .<hash>/`.\r\n */\r\nexport function goalFilePath(projectRoot: string): string {\r\n // Now resolves to ~/.wrongstack/projects/<hash>/goal.json for consistency\r\n // with WstackPaths.projectGoal.\r\n const hash = createHash('sha256').update(path.resolve(projectRoot)).digest('hex').slice(0, 12);\r\n return path.join(os.homedir(), '.wrongstack', 'projects', hash, 'goal.json');\r\n}\r\n\r\nexport async function loadGoal(filePath: string): Promise<GoalFile | null> {\r\n let raw: string;\r\n try {\r\n raw = await fsp.readFile(filePath, 'utf8');\r\n } catch {\r\n return null;\r\n }\r\n try {\r\n const parsed = JSON.parse(raw) as GoalFile;\r\n if (parsed?.version !== 1 || typeof parsed.goal !== 'string' || !Array.isArray(parsed.journal)) {\r\n return null;\r\n }\r\n return parsed;\r\n } catch {\r\n return null;\r\n }\r\n}\r\n\r\nexport async function saveGoal(filePath: string, goal: GoalFile): Promise<void> {\r\n try {\r\n await atomicWrite(filePath, JSON.stringify(goal, null, 2), { mode: 0o600 });\r\n } catch (err) {\r\n throw new FsError({\r\n message: err instanceof Error ? err.message : String(err),\r\n code: ERROR_CODES.FS_ATOMIC_WRITE_FAILED,\r\n path: filePath,\r\n cause: err,\r\n });\r\n }\r\n}\r\n\r\nexport function emptyGoal(goal: string): GoalFile {\r\n const now = new Date().toISOString();\r\n return {\r\n version: 1,\r\n goal,\r\n setAt: now,\r\n lastActivityAt: now,\r\n iterations: 0,\r\n engineState: 'idle',\r\n goalState: 'active',\r\n todoAttempts: {},\r\n journal: [],\r\n };\r\n}\r\n\r\n/**\r\n * Append a journal entry, bumping iteration counters and trimming the\r\n * ring buffer. Returns a new GoalFile — does not mutate the argument.\r\n */\r\nexport function appendJournal(goal: GoalFile, entry: Omit<JournalEntry, 'iteration' | 'at'>): GoalFile {\r\n const iteration = goal.iterations + 1;\r\n const at = new Date().toISOString();\r\n const full: JournalEntry = { ...entry, iteration, at };\r\n const journal = [...goal.journal, full];\r\n // Trim FIFO if over cap. Slice from the tail so the *newest* MAX entries survive.\r\n const trimmed = journal.length > MAX_JOURNAL_ENTRIES\r\n ? journal.slice(journal.length - MAX_JOURNAL_ENTRIES)\r\n : journal;\r\n return {\r\n ...goal,\r\n iterations: iteration,\r\n lastActivityAt: at,\r\n journal: trimmed,\r\n };\r\n}\r\n\r\n/**\r\n * Aggregate cumulative cost + tokens across all journal entries. Entries\r\n * without telemetry are skipped (legacy entries from before the field\r\n * was added still load cleanly).\r\n */\r\nexport function summarizeUsage(goal: GoalFile): {\r\n totalCostUsd: number;\r\n totalInputTokens: number;\r\n totalOutputTokens: number;\r\n iterationsWithUsage: number;\r\n} {\r\n let totalCostUsd = 0;\r\n let totalInputTokens = 0;\r\n let totalOutputTokens = 0;\r\n let iterationsWithUsage = 0;\r\n for (const e of goal.journal) {\r\n if (typeof e.costUsd === 'number') totalCostUsd += e.costUsd;\r\n if (e.tokens) {\r\n totalInputTokens += e.tokens.input;\r\n totalOutputTokens += e.tokens.output;\r\n }\r\n if (typeof e.costUsd === 'number' || e.tokens) iterationsWithUsage++;\r\n }\r\n return { totalCostUsd, totalInputTokens, totalOutputTokens, iterationsWithUsage };\r\n}\r\n\r\n/** Format the goal + recent journal as a human-readable status block. */\r\nexport function formatGoal(goal: GoalFile, journalLimit = 10): string {\r\n const lines: string[] = [];\r\n lines.push(`Goal: ${goal.goal}`);\r\n lines.push(`Set: ${goal.setAt}`);\r\n lines.push(`Last activity: ${goal.lastActivityAt}`);\r\n lines.push(`Iterations: ${goal.iterations}`);\r\n const stateLabel = goal.goalState ?? 'active';\r\n lines.push(`State: ${stateLabel}${goal.iterations > 0 ? ` (iteration #${goal.iterations})` : ''}`);\r\n lines.push(`Engine: ${goal.engineState}`);\r\n const usage = summarizeUsage(goal);\r\n if (usage.iterationsWithUsage > 0) {\r\n lines.push(\r\n `Spent: $${usage.totalCostUsd.toFixed(4)} (in ${usage.totalInputTokens} / out ${usage.totalOutputTokens} tokens across ${usage.iterationsWithUsage} iterations)`,\r\n );\r\n }\r\n if (goal.journal.length > 0) {\r\n lines.push('');\r\n lines.push(`Recent journal (last ${Math.min(journalLimit, goal.journal.length)}):`);\r\n const tail = goal.journal.slice(-journalLimit);\r\n for (const e of tail) {\r\n const mark = e.status === 'success' ? '✓' : e.status === 'failure' ? '✗' : e.status === 'aborted' ? '⊘' : '·';\r\n const note = e.note ? ` — ${e.note}` : '';\r\n const cost = typeof e.costUsd === 'number' ? ` ($${e.costUsd.toFixed(4)})` : '';\r\n lines.push(` #${e.iteration} ${mark} [${e.source}] ${e.task}${cost}${note}`);\r\n }\r\n }\r\n return lines.join('\\n');\r\n}\r\n","import { execFile } from 'node:child_process';\r\nimport { promisify } from 'node:util';\r\nimport type { Agent } from '../core/agent.js';\r\nimport type { TodoItem } from '../core/context.js';\r\nimport type { Compactor } from '../types/compactor.js';\r\nimport {\r\n appendJournal,\r\n loadGoal,\r\n saveGoal,\r\n goalFilePath,\r\n type GoalFile,\r\n type JournalEntry,\r\n} from '../storage/goal-store.js';\r\n\r\nconst execFileP = promisify(execFile);\r\n\r\n/**\r\n * Sense-decide-execute-reflect loop on top of a long-running Goal.\r\n *\r\n * Each iteration:\r\n * 1. Sense — read goal, pending todos, `git status --porcelain`.\r\n * 2. Decide — pick a source (todo / git / brainstorm) and a task.\r\n * 3. Execute — single agent.run with a directive prompt.\r\n * 4. Reflect — append a journal entry, persist state to disk.\r\n *\r\n * The loop runs forever until `stop()` is called externally (REPL SIGINT\r\n * handler, /autonomy stop). No internal time/cost cap by design — the\r\n * user wants \"sittin sene\". Failures are logged and the loop continues\r\n * with a different source on the next tick.\r\n */\r\n\r\nexport interface EternalAutonomyOptions {\r\n agent: Agent;\r\n projectRoot: string;\r\n /**\r\n * Per-iteration agent timeout. Defaults to 5 minutes. A single hung\r\n * provider call should not freeze the whole eternal loop.\r\n */\r\n iterationTimeoutMs?: number;\r\n /**\r\n * Maximum number of internal agent.run iterations the engine grants per\r\n * eternal-loop tick. The engine sets `autonomousContinue: true` so the\r\n * agent can run multi-step tasks end-to-end within one tick instead of\r\n * bouncing back to the engine after every single tool call. Default 500.\r\n * Previous 50 was far too low — agents hit the limit and restart constantly.\r\n */\r\n iterationMaxAgentSteps?: number;\r\n /**\r\n * Minimum sleep between iterations. Defaults to 1 s — enough for\r\n * SIGINT handlers to fire mid-loop without pegging a core when the\r\n * provider is being rate-limited.\r\n */\r\n cycleGapMs?: number;\r\n /**\r\n * Maximum consecutive failures before the source rotation forces a\r\n * brainstorm cycle. Default 3. Acts as a soft-recovery, not a stop.\r\n */\r\n failureBudget?: number;\r\n /**\r\n * Per-todo failed-attempt ceiling. When the engine picks the same todo\r\n * and the iteration fails this many times in total, the todo is taken\r\n * out of rotation (engine prefers other sources) until it changes\r\n * status. Default 3. Prevents the loop from spinning forever on one\r\n * stuck task.\r\n */\r\n todoMaxAttempts?: number;\r\n /**\r\n * Consecutive brainstorm-DONE responses required to consider the goal\r\n * complete and stop the engine. When the LLM's brainstorm step keeps\r\n * answering `DONE`, the engine treats that as \"no more work\" and, after\r\n * this many in a row, marks the goal as completed instead of sleeping\r\n * forever. Default 3.\r\n */\r\n brainstormDoneStopThreshold?: number;\r\n /** Side-channel notifications (logging, UI updates). */\r\n onIteration?: (entry: JournalEntry) => void;\r\n onError?: (err: Error, iteration: number) => void;\r\n /**\r\n * Per-iteration phase notifications for live UI updates (TUI status bar,\r\n * etc.). Fires at each major stage transition: idle → decide → execute →\r\n * reflect → (sleep | paused | stopped). Fire-and-forget — the engine\r\n * does not await the callback.\r\n */\r\n onStage?: (stage: IterationStage) => void;\r\n /**\r\n * Optional injected git status reader — production code uses git, tests\r\n * stub this out so they don't shell out.\r\n */\r\n gitStatusReader?: () => Promise<string>;\r\n /**\r\n * Optional clock — tests stub for deterministic timestamps.\r\n */\r\n now?: () => Date;\r\n /**\r\n * Optional compactor. When provided, the engine runs compaction every\r\n * `compactEveryNIterations` iterations to keep the agent's message\r\n * history under control during multi-day eternal loops. Without\r\n * compaction, an infinite loop will eventually overflow the provider's\r\n * context window and start failing.\r\n */\r\n compactor?: Compactor;\r\n /** How many iterations between compaction calls. Default 25. */\r\n compactEveryNIterations?: number;\r\n /**\r\n * Aggressive compaction threshold. When ctx token usage exceeds this\r\n * fraction of `maxContextTokens`, compaction runs in aggressive mode\r\n * regardless of the iteration cadence. 0.85 by default.\r\n */\r\n aggressiveCompactRatio?: number;\r\n /**\r\n * Model's max context window in tokens. When set, the engine watches\r\n * `currentRequestTokens()` against this and triggers aggressive compact\r\n * before the next iteration would overflow. Omit to disable threshold\r\n * checks (iteration cadence still applies).\r\n */\r\n maxContextTokens?: number;\r\n /**\r\n * Base delay (ms) for the first transient-error backoff. Subsequent\r\n * transient failures double this, capped at `transientBackoffMaxMs`.\r\n * Default 2_000.\r\n *\r\n * \"Transient\" means the underlying error is recoverable per\r\n * `WrongStackError.recoverable` (ProviderError sets this for 429/529/5xx\r\n * /network errors). Permanent errors (auth/invalid request) skip the\r\n * backoff and count toward `failureBudget` like before — backing off\r\n * on a permanent failure is wasted time.\r\n */\r\n transientBackoffBaseMs?: number;\r\n /** Ceiling for the exponential backoff. Default 60_000 (60 s). */\r\n transientBackoffMaxMs?: number;\r\n /** Called when the eternal loop stops for any reason (manual stop, goal complete, etc.). */\r\n onEternalStop?: () => void;\r\n}\r\n\r\nexport type EternalEngineState = 'idle' | 'running' | 'stopped';\r\n\r\n/**\r\n * Per-iteration phase emitted via `onStage` so UIs can render the\r\n * engine's live location in the sense-decide-execute-reflect loop.\r\n */\r\nexport type IterationStage =\r\n | { phase: 'idle' }\r\n | { phase: 'decide'; reason: string }\r\n | { phase: 'execute'; task: string }\r\n | { phase: 'reflect'; status: 'success' | 'failure' | 'aborted' | 'skipped'; note?: string }\r\n | { phase: 'sleep'; ms: number }\r\n | { phase: 'paused' }\r\n | { phase: 'stopped' }\r\n | { phase: 'error'; message: string };\r\n\r\ninterface DecidedAction {\r\n source: JournalEntry['source'];\r\n task: string;\r\n directive: string;\r\n /** Set when source === 'todo' so the engine can attribute failures. */\r\n todoId?: string;\r\n}\r\n\r\n/**\r\n * Sentinel returned by `brainstormTask` when the LLM declares the goal\r\n * fully accomplished. Distinct from `null` (which means \"brainstorm\r\n * failed / no actionable task right now\") so the engine can count\r\n * consecutive DONE answers toward a real stop.\r\n */\r\nconst BRAINSTORM_DONE = Symbol('brainstorm-done');\r\n\r\n/**\r\n * Free-text marker the model can emit (on its own line) to declare the\r\n * overall mission accomplished. Detected in the successful iteration's\r\n * `finalText`. When present, the engine flips `goalState='completed'`\r\n * and stops — the model has explicitly claimed completion AND the\r\n * iteration succeeded, which together is the most reliable stop signal\r\n * we can get without a separate verifier round-trip.\r\n */\r\nconst GOAL_COMPLETE_MARKER = /^\\s*\\[goal[_\\s-]*complete\\]\\s*$/im;\r\n\r\n/**\r\n * Free-text marker for the `/goal clear` command equivalent — when the\r\n * model emits this, the engine treats it as a manual goal clear (not just\r\n * completion) so the goal file is removed and onEternalStop fires.\r\n */\r\nconst GOAL_CLEAR_MARKER = /^\\s*\\[\\/?goal\\s*clear\\]\\s*$/im;\r\n\r\nexport class EternalAutonomyEngine {\r\n private state: EternalEngineState = 'idle';\r\n private stopRequested = false;\r\n private consecutiveFailures = 0;\r\n private consecutiveBrainstormDone = 0;\r\n /**\r\n * Count of consecutive transient (recoverable) provider failures. Drives\r\n * the exponential backoff between iterations. Reset on the first\r\n * successful iteration so a single bad afternoon doesn't permanently\r\n * slow the loop down.\r\n */\r\n private consecutiveTransientRetries = 0;\r\n private currentCtrl: AbortController | null = null;\r\n private iterationsSinceCompact = 0;\r\n private readonly goalPath: string;\r\n\r\n constructor(private readonly opts: EternalAutonomyOptions) {\r\n this.goalPath = goalFilePath(opts.projectRoot);\r\n }\r\n\r\n /** Current engine state — readable for UIs. */\r\n get currentState(): EternalEngineState {\r\n return this.state;\r\n }\r\n\r\n /** Synchronously request stop. Resolves once the running iteration aborts. */\r\n stop(): void {\r\n this.stopRequested = true;\r\n this.currentCtrl?.abort();\r\n // Best-effort: flip the persisted state so the next startup banner\r\n // doesn't report a phantom \"running\" engine. Fire-and-forget — if it\r\n // races with an in-flight iteration's write, the journal write wins\r\n // (engineState is metadata, not durable correctness).\r\n void this.persistEngineState('stopped').catch(() => {});\r\n this.state = 'stopped';\r\n }\r\n\r\n /**\r\n * Mark the engine as 'running' on disk + reset stop state so a new\r\n * batch of `runOneIteration()` calls can proceed. Called by the REPL\r\n * when the user invokes `/autonomy eternal`. Idempotent.\r\n */\r\n async prime(): Promise<void> {\r\n this.stopRequested = false;\r\n this.state = 'running';\r\n await this.persistEngineState('running').catch(() => {});\r\n }\r\n\r\n /**\r\n * Main loop. Returns when stop() is called or the goal file is removed.\r\n * Does NOT throw — every iteration is wrapped to keep the loop alive.\r\n */\r\n async run(): Promise<void> {\r\n this.state = 'running';\r\n await this.persistEngineState('running');\r\n\r\n try {\r\n while (!this.stopRequested) {\r\n let iterationOk = false;\r\n try {\r\n iterationOk = await this.runOneIteration();\r\n } catch (err) {\r\n this.consecutiveFailures++;\r\n this.opts.onError?.(err instanceof Error ? err : new Error(String(err)), this.consecutiveFailures);\r\n await this.appendFailure('engine error', err instanceof Error ? err.message : String(err));\r\n }\r\n\r\n if (iterationOk) {\r\n this.consecutiveFailures = 0;\r\n }\r\n\r\n if (this.stopRequested) break;\r\n\r\n // Brief gap so SIGINT can land between iterations even if the\r\n // agent is bouncing back results fast.\r\n await sleep(this.opts.cycleGapMs ?? 1000);\r\n }\r\n } finally {\r\n this.state = 'stopped';\r\n await this.persistEngineState('stopped').catch(() => {});\r\n }\r\n }\r\n\r\n /**\r\n * Execute a single sense-decide-execute-reflect cycle.\r\n * Returns true on success, false on handled failure / no-op.\r\n *\r\n * Exposed publicly so the REPL can pace iterations from its main loop\r\n * — running the engine and the REPL as a single sequential consumer of\r\n * `agent.run()` avoids race conditions on the shared Context.\r\n */\r\n async runOneIteration(): Promise<boolean> {\r\n // Emit stage transitions so UIs can render the engine's live location.\r\n const emit = (stage: IterationStage) => {\r\n this.opts.onStage?.(stage);\r\n };\r\n\r\n const goal = await loadGoal(this.goalPath);\r\n if (!goal) {\r\n // Goal file disappeared — treat as a graceful stop.\r\n emit({ phase: 'stopped' });\r\n this.stopRequested = true;\r\n return false;\r\n }\r\n\r\n // Mission-level lifecycle gate.\r\n const missionState = goal.goalState ?? 'active';\r\n if (missionState !== 'active') {\r\n emit({ phase: missionState === 'paused' ? 'paused' : 'stopped' });\r\n this.stopRequested = true;\r\n return false;\r\n }\r\n\r\n emit({ phase: 'decide', reason: 'picking next task' });\r\n const action = await this.decide(goal);\r\n if (!action) {\r\n if (!this.stopRequested) {\r\n emit({ phase: 'sleep', ms: 5_000 });\r\n await sleep(5_000);\r\n } else {\r\n emit({ phase: 'stopped' });\r\n }\r\n return false;\r\n }\r\n\r\n emit({ phase: 'execute', task: action.task });\r\n\r\n const ctrl = new AbortController();\r\n this.currentCtrl = ctrl;\r\n const timer = setTimeout(\r\n () => ctrl.abort(),\r\n this.opts.iterationTimeoutMs ?? 5 * 60_000,\r\n );\r\n let status: JournalEntry['status'] = 'success';\r\n let note: string | undefined;\r\n let finalText = '';\r\n // Captured from `result.error?.recoverable` when the agent.run returns\r\n // a recoverable WrongStackError (ProviderError sets this for 429/529\r\n // /5xx/network). Drives the engine's exponential backoff so a\r\n // transient rate-limit storm doesn't burn the failure budget in\r\n // seconds. Permanent errors leave this false and trip the normal\r\n // consecutiveFailures path.\r\n let isTransientFailure = false;\r\n\r\n // Snapshot usage before so the iteration delta can be journaled.\r\n // Token counter is optional in mock/test contexts — guard accordingly.\r\n const tc = this.opts.agent.ctx?.tokenCounter;\r\n const beforeUsage = tc?.total?.();\r\n const beforeCost = tc?.estimateCost?.().total;\r\n\r\n try {\r\n const result = await this.opts.agent.run(\r\n [{ type: 'text' as const, text: action.directive }],\r\n {\r\n signal: ctrl.signal,\r\n // Enable per-call autonomous continuation so the agent can chain\r\n // multiple internal tool/response cycles end-to-end on one\r\n // directive instead of returning to the engine after a single\r\n // round-trip. The model uses `[continue]` / `[done]` markers\r\n // (or the `continue_to_next_iteration` tool) to control the\r\n // inner loop. Without this flag the engine produced shallow\r\n // iterations and almost never let a real task finish.\r\n autonomousContinue: true,\r\n // Cap the inner loop so a runaway agent.run can't burn through\r\n // the iteration timeout — the engine's own outer loop is the\r\n // long-running thing, each tick should be bounded.\r\n maxIterations: this.opts.iterationMaxAgentSteps ?? 500,\r\n },\r\n );\r\n\r\n if (result.status === 'aborted') {\r\n status = 'aborted';\r\n note = 'stopped by user';\r\n } else if (result.status === 'failed') {\r\n status = 'failure';\r\n note = result.error?.describe?.() ?? 'agent run failed';\r\n isTransientFailure = result.error?.recoverable === true;\r\n } else if (result.status === 'max_iterations') {\r\n status = 'failure';\r\n note = `max iterations (${result.iterations})`;\r\n } else {\r\n status = 'success';\r\n finalText = result.finalText ?? '';\r\n const tail = finalText.slice(0, 240).replace(/\\s+/g, ' ').trim();\r\n if (tail) note = tail;\r\n }\r\n } catch (err) {\r\n const isAbort = err instanceof Error && (err.name === 'AbortError' || err.message.includes('abort'));\r\n status = isAbort ? 'aborted' : 'failure';\r\n note = err instanceof Error ? err.message : String(err);\r\n // Surface .recoverable on the thrown WrongStackError too — provider\r\n // errors that escape the agent's catch (rare; usually wrapped into\r\n // result.error) still classify correctly.\r\n if (\r\n !isAbort &&\r\n typeof (err as { recoverable?: unknown })?.recoverable === 'boolean'\r\n ) {\r\n isTransientFailure = (err as { recoverable: boolean }).recoverable;\r\n }\r\n } finally {\r\n clearTimeout(timer);\r\n this.currentCtrl = null;\r\n }\r\n\r\n // Per-todo attempt accounting. On failure of a todo-sourced action,\r\n // bump the persistent counter so `decide()` can rotate past it once\r\n // it crosses the configured ceiling. Successful runs leave the\r\n // counter untouched — the LLM is responsible for flipping the todo\r\n // status to `completed` via the todos tool (directive teaches this).\r\n if (action.source === 'todo' && action.todoId && status !== 'success') {\r\n await this.bumpTodoAttempt(action.todoId);\r\n }\r\n\r\n // Capture per-iteration usage delta. Cost is always non-negative;\r\n // if the counter wraps or resets mid-iteration we clamp to 0 so the\r\n // journal never shows negative spend.\r\n const afterUsage = tc?.total?.();\r\n const afterCost = tc?.estimateCost?.().total;\r\n const tokens =\r\n beforeUsage && afterUsage\r\n ? {\r\n input: Math.max(0, afterUsage.input - beforeUsage.input),\r\n output: Math.max(0, afterUsage.output - beforeUsage.output),\r\n }\r\n : undefined;\r\n const costUsd =\r\n typeof beforeCost === 'number' && typeof afterCost === 'number'\r\n ? Math.max(0, afterCost - beforeCost)\r\n : undefined;\r\n\r\n await this.appendIterationEntry({\r\n source: action.source,\r\n task: action.task,\r\n status,\r\n note,\r\n tokens,\r\n costUsd,\r\n });\r\n\r\n emit({ phase: 'reflect', status, note });\r\n\r\n // Re-read the goal so we can emit the real iteration counter rather\r\n // than the previous placeholder. If the goal was unlinked mid-flight\r\n // (graceful stop via /goal clear) the iteration index is still\r\n // useful — fall back to the in-memory consecutiveFailures-derived\r\n // approximation only as a last resort.\r\n let iterationIndex = 0;\r\n try {\r\n const reloaded = await loadGoal(this.goalPath);\r\n iterationIndex = reloaded?.iterations ?? 0;\r\n } catch {\r\n // best-effort\r\n }\r\n this.opts.onIteration?.({\r\n at: (this.opts.now?.() ?? new Date()).toISOString(),\r\n iteration: iterationIndex,\r\n source: action.source,\r\n task: action.task,\r\n status,\r\n note,\r\n tokens,\r\n costUsd,\r\n });\r\n\r\n // Transient failure — sleep with interruptible backoff before retry.\r\n if (status === 'failure') {\r\n if (isTransientFailure) {\r\n this.consecutiveTransientRetries++;\r\n const delay = this.computeTransientBackoffMs();\r\n if (delay > 0) {\r\n emit({ phase: 'sleep', ms: delay });\r\n await this.sleepInterruptible(delay);\r\n }\r\n return false;\r\n }\r\n this.consecutiveFailures++;\r\n return false;\r\n }\r\n\r\n if (status === 'aborted') {\r\n if (this.stopRequested) return false;\r\n this.consecutiveFailures++;\r\n return false;\r\n }\r\n\r\n // Successful iteration\r\n this.consecutiveTransientRetries = 0;\r\n const cycleGapMs = this.opts.cycleGapMs ?? 1000;\r\n emit({ phase: 'sleep', ms: cycleGapMs });\r\n await sleep(cycleGapMs);\r\n\r\n // Goal-complete detection. The model emits `[GOAL_COMPLETE]` on its\r\n // own line in `finalText` when the overall mission is verifiably done.\r\n // Combined with a successful iteration this is a strong stop signal:\r\n // the LLM explicitly claimed completion AND the run did not fail. We\r\n // mark the goal `completed`, journal it, and stop. No separate\r\n // verifier round-trip — keeps cost down; if the model lies, the user\r\n // notices and can re-arm with `/goal set`.\r\n if (GOAL_COMPLETE_MARKER.test(finalText)) {\r\n // Treat GOAL_COMPLETE as a full goal clear: remove the goal file and\r\n // fire onEternalStop so the REPL exits eternal mode. Stronger than\r\n // just marking completed — the REPL needs both to happen.\r\n await this.clearGoalManually(finalText);\r\n this.stopRequested = true;\r\n return true;\r\n }\r\n // Goal-clear detection — model emits `[goal clear]` equivalent to\r\n // `/goal clear`. Treat as a manual stop: remove the goal file and fire\r\n // onEternalStop so the REPL knows to return to normal mode.\r\n if (GOAL_CLEAR_MARKER.test(finalText)) {\r\n await this.clearGoalManually(finalText);\r\n this.stopRequested = true;\r\n return true;\r\n }\r\n // Compaction runs only on successful iterations — there's no point\r\n // compacting after a failed/aborted iteration that didn't add much to\r\n // the message history.\r\n this.iterationsSinceCompact++;\r\n await this.maybeCompact().catch((err) => {\r\n // Don't let compaction failure kill the loop; surface via onError.\r\n this.opts.onError?.(\r\n err instanceof Error ? err : new Error(String(err)),\r\n this.consecutiveFailures,\r\n );\r\n });\r\n return true;\r\n }\r\n\r\n /**\r\n * Run compaction when either trigger fires:\r\n * - We've done >= compactEveryNIterations since the last compact.\r\n * - Current request tokens exceed aggressiveCompactRatio * maxContext.\r\n *\r\n * The second check uses *aggressive* mode to free more headroom; the\r\n * cadence check uses non-aggressive (cheaper).\r\n */\r\n private async maybeCompact(): Promise<void> {\r\n const compactor = this.opts.compactor;\r\n if (!compactor) return;\r\n const ctx = this.opts.agent.ctx;\r\n if (!ctx) return;\r\n\r\n const cadence = this.opts.compactEveryNIterations ?? 25;\r\n const threshold = this.opts.aggressiveCompactRatio ?? 0.85;\r\n const maxCtx = this.opts.maxContextTokens;\r\n\r\n let aggressive = false;\r\n let shouldRun = false;\r\n\r\n if (this.iterationsSinceCompact >= cadence) {\r\n shouldRun = true;\r\n }\r\n\r\n if (maxCtx && maxCtx > 0) {\r\n const used = ctx.tokenCounter?.currentRequestTokens?.();\r\n if (used) {\r\n const total = used.input + used.cacheRead;\r\n if (total / maxCtx >= threshold) {\r\n shouldRun = true;\r\n aggressive = true;\r\n }\r\n }\r\n }\r\n\r\n if (!shouldRun) return;\r\n\r\n const report = await compactor.compact(ctx, { aggressive });\r\n this.iterationsSinceCompact = 0;\r\n // Journal the compaction event so users see it in /goal journal.\r\n const saved = report.before - report.after;\r\n await this.appendIterationEntry({\r\n source: 'manual',\r\n task: `compaction (${aggressive ? 'aggressive' : 'cadence'})`,\r\n status: 'success',\r\n note: `saved ~${saved} tokens (${report.before}→${report.after})`,\r\n });\r\n }\r\n\r\n /**\r\n * Hybrid idea source.\r\n * 1. Pending todos on the agent's context.\r\n * 2. Dirty git working tree → propose a \"review and finish this\" task.\r\n * 3. Otherwise: brainstorm via the LLM against the goal.\r\n *\r\n * After failureBudget consecutive failures, force brainstorm so the\r\n * engine doesn't loop on the same broken todo or stuck git state.\r\n */\r\n private async decide(goal: GoalFile): Promise<DecidedAction | null> {\r\n const forceBrainstorm = this.consecutiveFailures >= (this.opts.failureBudget ?? 3);\r\n\r\n if (!forceBrainstorm) {\r\n const todo = this.pickPendingTodo(goal);\r\n if (todo) {\r\n return {\r\n source: 'todo',\r\n task: todo.content,\r\n todoId: todo.id,\r\n directive: this.buildDirective(goal, 'todo', todo.content),\r\n };\r\n }\r\n\r\n const gitTask = await this.pickGitTask();\r\n if (gitTask) {\r\n return {\r\n source: 'git',\r\n task: gitTask,\r\n directive: this.buildDirective(goal, 'git', gitTask),\r\n };\r\n }\r\n }\r\n\r\n const brainstormed = await this.brainstormTask(goal);\r\n if (brainstormed === BRAINSTORM_DONE) {\r\n // Model says there's nothing to do. Count consecutive DONEs — if\r\n // we hit the threshold, treat the mission as finished and stop\r\n // instead of sleeping forever on null actions.\r\n this.consecutiveBrainstormDone++;\r\n const threshold = this.opts.brainstormDoneStopThreshold ?? 3;\r\n if (this.consecutiveBrainstormDone >= threshold) {\r\n await this.markGoalCompleted(\r\n { source: 'brainstorm', task: 'no further work', directive: '' },\r\n `brainstorm returned DONE ${this.consecutiveBrainstormDone}x in a row`,\r\n );\r\n this.stopRequested = true;\r\n }\r\n return null;\r\n }\r\n if (!brainstormed) return null;\r\n // Got a real task — reset the DONE streak.\r\n this.consecutiveBrainstormDone = 0;\r\n return {\r\n source: 'brainstorm',\r\n task: brainstormed,\r\n directive: this.buildDirective(goal, 'brainstorm', brainstormed),\r\n };\r\n }\r\n\r\n private pickPendingTodo(goal: GoalFile): TodoItem | null {\r\n const todos = this.opts.agent.ctx.todos;\r\n if (!Array.isArray(todos)) return null;\r\n const attempts = goal.todoAttempts ?? {};\r\n const ceiling = this.opts.todoMaxAttempts ?? 3;\r\n // First-pending strategy with a stuck-task escape hatch: if the\r\n // first pending todo has already failed `ceiling` times, fall\r\n // through to later pending todos. Returns null when every pending\r\n // todo is stuck — the caller will fall through to git/brainstorm.\r\n for (const t of todos) {\r\n if (t.status !== 'pending') continue;\r\n const used = attempts[t.id] ?? 0;\r\n if (used >= ceiling) continue;\r\n return t;\r\n }\r\n return null;\r\n }\r\n\r\n private async pickGitTask(): Promise<string | null> {\r\n let out: string;\r\n try {\r\n out = await (this.opts.gitStatusReader?.() ?? this.readGitStatus());\r\n } catch {\r\n return null;\r\n }\r\n const dirty = out.trim();\r\n if (!dirty) return null;\r\n // Surface a concise prompt — the agent will look at the diff itself.\r\n const lines = dirty.split('\\n').slice(0, 8);\r\n const preview = lines.join(', ');\r\n return `Inspect the dirty working tree and either finish the in-progress work or revert it. Files: ${preview}`;\r\n }\r\n\r\n private async readGitStatus(): Promise<string> {\r\n const { stdout } = await execFileP('git', ['status', '--porcelain'], {\r\n cwd: this.opts.projectRoot,\r\n timeout: 5_000,\r\n });\r\n return stdout;\r\n }\r\n\r\n private async brainstormTask(goal: GoalFile): Promise<string | null | typeof BRAINSTORM_DONE> {\r\n const lastFew = goal.journal\r\n .slice(-5)\r\n .map((e) => ` - [${e.status}] ${e.task}`)\r\n .join('\\n');\r\n const directive = [\r\n 'You are deciding the next action in an autonomous loop pursuing a long-running goal.',\r\n '',\r\n `Goal: ${goal.goal}`,\r\n '',\r\n lastFew ? `Recent iterations:\\n${lastFew}` : 'No prior iterations yet.',\r\n '',\r\n 'Output ONE concrete, immediately-actionable task that advances the goal.',\r\n 'Constraints:',\r\n '- One sentence, imperative form, under 200 chars.',\r\n '- No preamble, no explanation, no markdown — just the task line.',\r\n '- If recent iterations show repeated failures on the same target, pivot.',\r\n '- If the goal appears fully accomplished AND you can name a concrete',\r\n ' artifact / test / output that proves it, output exactly: DONE',\r\n '- Be conservative with DONE: if the recent journal contains failures',\r\n ' or aborted entries, the goal is almost certainly NOT done.',\r\n ].join('\\n');\r\n\r\n try {\r\n const ctrl = new AbortController();\r\n const timer = setTimeout(() => ctrl.abort(), 60_000);\r\n try {\r\n const result = await this.opts.agent.run(\r\n [{ type: 'text' as const, text: directive }],\r\n { signal: ctrl.signal, maxIterations: 1 },\r\n );\r\n if (result.status !== 'done') return null;\r\n const text = (result.finalText ?? '').trim();\r\n if (!text) return null;\r\n // Distinct sentinel for DONE so the caller can count consecutive\r\n // DONE answers toward a real stop. The old `return null` path\r\n // conflated \"no work\" with \"engine failure\" and looped forever.\r\n if (/^DONE\\.?$/i.test(text)) return BRAINSTORM_DONE;\r\n // Take the first non-empty line and clip to 240 chars.\r\n const firstLine = text.split('\\n').find((l) => l.trim().length > 0)?.trim();\r\n if (!firstLine) return null;\r\n if (/^DONE\\.?$/i.test(firstLine)) return BRAINSTORM_DONE;\r\n return firstLine.slice(0, 240);\r\n } finally {\r\n clearTimeout(timer);\r\n }\r\n } catch {\r\n return null;\r\n }\r\n }\r\n\r\n private buildDirective(goal: GoalFile, source: JournalEntry['source'], task: string): string {\r\n const recentJournal = goal.journal\r\n .slice(-5)\r\n .map((e) => ` #${e.iteration} [${e.status}] ${e.task}${e.note ? ` — ${e.note.slice(0, 80)}` : ''}`)\r\n .join('\\n');\r\n return [\r\n '═══ ETERNAL AUTONOMY — iteration directive ═══',\r\n '',\r\n `Mission: ${goal.goal}`,\r\n `Iteration: #${goal.iterations + 1}`,\r\n `Source: ${source}`,\r\n `Task: ${task}`,\r\n '',\r\n recentJournal ? `Recent journal (last 5):\\n${recentJournal}` : 'No prior iterations.',\r\n '',\r\n '── EXECUTION PROTOCOL ──',\r\n 'You are inside a long-running autonomous loop. Each iteration you',\r\n 'execute ONE concrete task that advances the Mission. No user is',\r\n 'available to clarify — make defensible decisions and move forward.',\r\n '',\r\n '1. EXECUTE END-TO-END',\r\n ' • Use multiple tool calls freely. Emit `[continue]` on its own line',\r\n ' to chain to the next internal step without returning.',\r\n ' • When this iteration\\'s Task is finished (real artifact / passing',\r\n ' test / applied diff / clean output), emit `[done]` on its own line.',\r\n ' • Do not stop on the first obstacle — try at least 3 distinct',\r\n ' approaches before giving up. YOLO is active; no confirmations.',\r\n '',\r\n '2. UPDATE TODO STATE (when Source is `todo`)',\r\n ' • Mark this todo `in_progress` via the todos tool before tool work.',\r\n ' • Mark it `completed` on success, with a one-line outcome note.',\r\n ' • If you cannot make progress after 2 distinct attempts, mark it',\r\n ' `cancelled` with the obstacle. The loop will skip it next time.',\r\n '',\r\n '3. MISSION-COMPLETE PROTOCOL',\r\n ' • If — and ONLY if — the OVERALL Mission (not just this Task) is',\r\n ' verifiably accomplished, emit on its own line:',\r\n ' [GOAL_COMPLETE]',\r\n ' followed by a one-paragraph verification recipe (artifact path,',\r\n ' test command, or 10-second reproduction). This halts the loop.',\r\n ' • NEVER emit [GOAL_COMPLETE] on optimism, partial progress, or',\r\n ' \"looks fine\". Required: a concrete artifact that proves it AND',\r\n ' no recent journal failures contradicting completion.',\r\n ' • If unsure, emit `[done]` instead and let the next iteration',\r\n ' decide. The loop is patient; false completion is not.',\r\n '',\r\n '4. NO INTERACTIVITY',\r\n ' • Do not ask questions, do not request confirmation, do not propose',\r\n ' options. Pick the best path and execute. The user is asleep.',\r\n ].join('\\n');\r\n }\r\n\r\n /**\r\n * Exponential backoff for transient provider errors. `2^N * base`\r\n * capped at `transientBackoffMaxMs`. Zero base disables backoff.\r\n * Public-private to keep `runOneIteration` readable; the value is\r\n * recomputed each call from the current retry count, so callers\r\n * don't have to track state.\r\n */\r\n private computeTransientBackoffMs(): number {\r\n const base = this.opts.transientBackoffBaseMs ?? 2_000;\r\n const cap = this.opts.transientBackoffMaxMs ?? 60_000;\r\n if (base <= 0) return 0;\r\n const exponent = Math.max(0, this.consecutiveTransientRetries - 1);\r\n return Math.min(cap, base * 2 ** exponent);\r\n }\r\n\r\n /**\r\n * Sleep that wakes early if `stopRequested` flips. Polls every 250 ms\r\n * so SIGINT / `/autonomy stop` can land in the middle of a long\r\n * backoff instead of waiting up to a minute for the timer.\r\n */\r\n private async sleepInterruptible(totalMs: number): Promise<void> {\r\n const step = 250;\r\n let remaining = totalMs;\r\n while (remaining > 0 && !this.stopRequested) {\r\n const chunk = Math.min(step, remaining);\r\n await sleep(chunk);\r\n remaining -= chunk;\r\n }\r\n }\r\n\r\n private async appendIterationEntry(entry: Omit<JournalEntry, 'iteration' | 'at'>): Promise<void> {\r\n const current = await loadGoal(this.goalPath);\r\n if (!current) {\r\n // Goal was cleared mid-iteration; nothing to write to.\r\n return;\r\n }\r\n const updated = appendJournal(current, entry);\r\n await saveGoal(this.goalPath, updated);\r\n }\r\n\r\n /**\r\n * Persistent per-todo failure counter. Skipped silently when the goal\r\n * file has been removed (graceful clear). Each non-success iteration\r\n * against a todo source bumps the counter by 1; `pickPendingTodo` reads\r\n * the counter to rotate past stuck todos once they cross `todoMaxAttempts`.\r\n */\r\n private async bumpTodoAttempt(todoId: string): Promise<void> {\r\n const current = await loadGoal(this.goalPath);\r\n if (!current) return;\r\n const attempts = { ...(current.todoAttempts ?? {}) };\r\n attempts[todoId] = (attempts[todoId] ?? 0) + 1;\r\n await saveGoal(this.goalPath, { ...current, todoAttempts: attempts });\r\n }\r\n\r\n /**\r\n * Flip the mission to `completed` and journal it. Called from two\r\n * paths: (a) `[GOAL_COMPLETE]` marker in a successful iteration's\r\n * finalText, (b) `brainstorm` returning DONE consecutively past the\r\n * configured threshold. Idempotent — re-entry is a no-op once the\r\n * goal is already `completed`.\r\n */\r\n private async markGoalCompleted(\r\n action: { source: JournalEntry['source']; task: string; directive: string },\r\n note: string,\r\n ): Promise<void> {\r\n const current = await loadGoal(this.goalPath);\r\n if (!current) return;\r\n if (current.goalState === 'completed') return;\r\n const withFlag: GoalFile = { ...current, goalState: 'completed' };\r\n const withEntry = appendJournal(withFlag, {\r\n source: action.source,\r\n task: `MISSION COMPLETE — ${action.task}`.slice(0, 240),\r\n status: 'success',\r\n note: note.slice(0, 240),\r\n });\r\n await saveGoal(this.goalPath, withEntry);\r\n }\r\n\r\n /**\r\n * Manually clear the goal — equivalent to `/goal clear` typed by the user.\r\n * Sets goalState to `abandoned`, removes the goal file, and fires\r\n * `onEternalStop` so the REPL returns to normal mode.\r\n */\r\n private async clearGoalManually(note: string): Promise<void> {\r\n const current = await loadGoal(this.goalPath);\r\n if (current) {\r\n const abandoned: GoalFile = { ...current, goalState: 'abandoned' };\r\n await saveGoal(this.goalPath, abandoned);\r\n }\r\n try {\r\n const { unlink } = await import('node:fs/promises');\r\n await unlink(this.goalPath);\r\n } catch {\r\n // best-effort — file may already be gone\r\n }\r\n this.opts.onEternalStop?.();\r\n void this.appendIterationEntry({\r\n source: 'manual',\r\n task: 'goal cleared',\r\n status: 'success',\r\n note: note.slice(0, 240),\r\n });\r\n }\r\n\r\n private async appendFailure(task: string, note: string): Promise<void> {\r\n await this.appendIterationEntry({ source: 'manual', task, status: 'failure', note });\r\n }\r\n\r\n private async persistEngineState(state: GoalFile['engineState']): Promise<void> {\r\n const current = await loadGoal(this.goalPath);\r\n if (!current) return;\r\n if (current.engineState === state) return;\r\n await saveGoal(this.goalPath, { ...current, engineState: state });\r\n }\r\n}\r\n\r\nfunction sleep(ms: number): Promise<void> {\r\n return new Promise((resolve) => setTimeout(resolve, ms));\r\n}\r\n","import type { Usage } from '../types/provider.js';\nimport type { EventBus } from '../kernel/events.js';\n\nexport type BudgetKind = 'tool_calls' | 'iterations' | 'tokens' | 'timeout' | 'idle_timeout' | 'cost';\n\nexport class BudgetExceededError extends Error {\n readonly kind: BudgetKind;\n readonly limit: number;\n readonly observed: number;\n\n constructor(kind: BudgetKind, limit: number, observed: number) {\n super(`Budget exceeded: ${kind} (limit=${limit}, observed=${observed})`);\n this.name = 'BudgetExceededError';\n this.kind = kind;\n this.limit = limit;\n this.observed = observed;\n }\n}\n\nexport interface BudgetLimits {\n maxIterations?: number;\n maxToolCalls?: number;\n maxTokens?: number;\n /** Estimated USD cost ceiling. */\n maxCostUsd?: number;\n /**\n * Hard wall-clock timeout measured from `start()`. Off by default — set it\n * explicitly only when a task must finish within an absolute window. For\n * the everyday \"don't kill an agent that's still working\" guard, prefer\n * `idleTimeoutMs`, which resets on activity.\n */\n timeoutMs?: number;\n /**\n * Idle timeout: the maximum gap (ms) between activity signals (iterations,\n * tool calls, token usage, streamed progress) before the subagent is\n * considered hung and reaped. Unlike `timeoutMs`, an actively-working\n * agent continuously resets this clock via `markActivity()`, so it never\n * trips on a long-but-productive run — only on a genuine stall.\n */\n idleTimeoutMs?: number;\n}\n\n/**\n * Controls how the budget behaves when `onThreshold` is set and a limit is hit.\n *\n * `'auto'` — emit `budget.threshold_reached` on the EventBus and wait for a\n * coordinator response (extend/stop). If no listener responds within\n * `DECISION_TIMEOUT_MS` the decision defaults to `'stop'`.\n * `'sync'` — do not emit any event; treat the threshold as a hard stop and\n * throw `BudgetExceededError` synchronously. Useful for fire-and-forget\n * subagents that have an `onThreshold` handler for logging/metrics but are\n * not wired into a coordinator.\n *\n * @default 'auto'\n */\nexport type BudgetNegotiationMode = 'auto' | 'sync';\n\nexport interface BudgetUsage {\n iterations: number;\n toolCalls: number;\n tokens: { input: number; output: number; total: number };\n costUsd: number;\n elapsedMs: number;\n}\n\n/**\n * Thrown by `SubagentBudget.record*` when a soft limit is hit and\n * an `onThreshold` handler is configured that wants to ask the\n * coordinator (via `budget.threshold_reached` event). The runner\n * catches this and awaits the embedded `decision` promise to get\n * the coordinator's extend/stop decision.\n *\n * Distinct from `BudgetExceededError` which is a hard stop.\n */\nexport class BudgetThresholdSignal extends Error {\n readonly kind: BudgetKind;\n readonly limit: number;\n readonly used: number;\n /** Resolves to 'extend' (with optional new limits) or 'stop' */\n readonly decision: Promise<BudgetThresholdDecision>;\n\n constructor(\n kind: BudgetKind,\n limit: number,\n used: number,\n decision: Promise<BudgetThresholdDecision>,\n ) {\n super(`Budget soft limit: ${kind} (limit=${limit}, used=${used})`);\n this.name = 'BudgetThresholdSignal';\n this.kind = kind;\n this.limit = limit;\n this.used = used;\n this.decision = decision;\n }\n}\n\nexport type BudgetThresholdDecision =\n | 'stop'\n | { extend: Partial<BudgetLimits> };\n\n/**\n * Callback invoked when a budget limit is about to be exceeded.\n * Return 'throw' for hard stop (default — throws BudgetExceededError).\n * Return 'continue' to allow one more unit and re-check next time.\n * Return a Promise to ask the coordinator via `budget.threshold_reached`\n * event (uses the same grant/deny pattern as `iteration.limit_reached`).\n */\nexport type BudgetThresholdHandler = (info: {\n kind: BudgetKind;\n used: number;\n limit: number;\n requestDecision: () => Promise<BudgetThresholdDecision>;\n}) => 'throw' | 'continue' | Promise<BudgetThresholdDecision>;\n\n/**\n * Per-subagent budget enforcement. Each subagent gets its own instance so a\n * runaway agent can't drain the cost ceiling of its siblings. All record/check\n * methods are O(1) and safe to call from hot paths.\n *\n * Behavior without `onThreshold`: hard stops synchronously on every limit hit.\n *\n * Behavior with `onThreshold` and `_mode === 'auto'`: emits `budget.threshold_reached`\n * on the EventBus and throws `BudgetThresholdSignal`. The coordinator's verdict\n * (extend/stop) resolves the embedded promise. If no listener responds within\n * `DECISION_TIMEOUT_MS` the decision defaults to `'stop'`.\n *\n * Behavior with `onThreshold` and `_mode === 'sync'`: throws `BudgetExceededError`\n * synchronously regardless of EventBus state or listener presence. This is useful\n * for fire-and-forget subagents that have an `onThreshold` handler for logging/metrics\n * but are not wired into a coordinator — the `'sync'` mode makes the hard-stop\n * behavior explicit and means tests can use `expect().toThrow()` even without\n * a fully-wired EventBus.\n */\nexport class SubagentBudget {\n readonly limits: Readonly<BudgetLimits>;\n private iterations = 0;\n private toolCalls = 0;\n private tokenInput = 0;\n private tokenOutput = 0;\n private costUsd = 0;\n private startTime: number | null = null;\n /**\n * Timestamp of the most recent activity (iteration / tool call / token\n * usage / streamed progress). Drives the idle timeout — reset by\n * `markActivity()`. Initialised to `start()` time so a never-active agent\n * still eventually trips its idle window.\n */\n private lastActivityTime: number | null = null;\n private _onThreshold: BudgetThresholdHandler | undefined;\n /**\n * Hard cap on how long `_negotiateExtension` waits for the coordinator to\n * respond before defaulting to 'stop'. Without this fallback an absent\n * or hung listener (Director not built / event filter detached mid-run)\n * leaves the budget over-limit and never enforces anything.\n */\n private static readonly DECISION_TIMEOUT_MS = 60_000;\n /**\n * Injected by the runner when wiring the budget to its EventBus.\n * Used to emit `budget.threshold_reached` events in `'auto'` mode.\n */\n _events?: EventBus;\n\n /**\n * Negotiation mode — controls whether a threshold hit tries to emit\n * `budget.threshold_reached` and wait for a coordinator decision, or\n * falls straight through to a synchronous hard stop.\n *\n * `'auto'` (default) — emit on the EventBus and wait; times out to 'stop'.\n * `'sync'` — throw `BudgetExceededError` immediately regardless of listeners.\n */\n private _mode: BudgetNegotiationMode;\n\n /**\n * Optional callback for soft-limit handling. When set, the budget will\n * invoke it rather than throw immediately. The handler decides whether to\n * throw synchronously, continue, or ask the coordinator for an extension.\n */\n get onThreshold(): BudgetThresholdHandler | undefined {\n return this._onThreshold;\n }\n set onThreshold(fn: BudgetThresholdHandler | undefined) {\n this._onThreshold = fn;\n }\n\n /** Returns the current negotiation mode. */\n get mode(): BudgetNegotiationMode {\n return this._mode;\n }\n\n constructor(limits: BudgetLimits = {}, mode: BudgetNegotiationMode = 'auto') {\n this._mode = mode;\n // NOT frozen: `negotiateExtension` patches these limits in place when the\n // coordinator grants an auto-extension. Freezing made every granted\n // extension throw `TypeError: Cannot assign to read only property` in\n // strict mode, which the runner caught as a hard stop — so extensions\n // silently became kills. The `readonly limits: Readonly<BudgetLimits>`\n // typing still blocks external mutation at compile time.\n this.limits = { ...limits };\n }\n\n start(): void {\n this.startTime = Date.now();\n this.lastActivityTime = this.startTime;\n }\n\n /**\n * Reset the idle clock. Called on any sign of forward progress —\n * iterations, tool calls, token usage, and streamed tool/text progress —\n * so a long-but-productive subagent never trips its `idleTimeoutMs`.\n */\n markActivity(): void {\n this.lastActivityTime = Date.now();\n }\n\n /**\n * Milliseconds since the last activity signal. Returns 0 before `start()`\n * (nothing to measure yet). Used by the coordinator watchdog to decide\n * whether to re-arm (still active) or reap (genuinely idle).\n */\n idleMs(): number {\n const since = this.lastActivityTime ?? this.startTime;\n return since === null ? 0 : Date.now() - since;\n }\n\n /** Returns true if we're within 10% of any limit — useful for pre-flight checks. */\n isNearLimit(): boolean {\n const { maxIterations, maxToolCalls, maxTokens, maxCostUsd } = this.limits;\n if (maxIterations && this.iterations >= maxIterations * 0.9) return true;\n if (maxToolCalls && this.toolCalls >= maxToolCalls * 0.9) return true;\n if (maxTokens && this.tokenInput + this.tokenOutput >= maxTokens * 0.9) return true;\n if (maxCostUsd && this.costUsd >= maxCostUsd * 0.9) return true;\n return false;\n }\n\n /**\n * Synchronous budget check. Always throws synchronously so callers (especially\n * test event handlers using `expect().toThrow()`) get an unhandled rejection\n * when the budget is exceeded without a handler.\n *\n * Decision table:\n * - no `onThreshold` handler → throw `BudgetExceededError` (hard stop, always)\n * - `mode === 'sync'` → throw `BudgetExceededError` (hard stop, always)\n * - `mode === 'auto'` + no listener → throw `BudgetExceededError` (hard stop; no one to ask)\n * - `mode === 'auto'` + listener → throw `BudgetThresholdSignal` with async decision promise\n */\n /**\n * Collects all exceeded budget kinds into a single NOOP-free negotiation.\n * Called by recordIteration / recordToolCall / recordUsage — each may call\n * this for its own kind. The first call starts the negotiation and stores\n * the Promise in _pendingNegotiation. Subsequent calls for DIFFERENT\n * kinds (while a negotiation is in flight) are NOOPs — they don't start\n * new conversations with the coordinator. This prevents an EventBus flood\n * when multiple budget kinds are exceeded simultaneously in one iteration.\n *\n * Returns the kinds that were found to be exceeded (for logging/debugging).\n */\n private checkLimits(elapsedMs?: number): { kind: BudgetKind; used: number; limit: number }[] {\n const exceeded: { kind: BudgetKind; used: number; limit: number }[] = [];\n\n if (this.limits.maxIterations !== undefined && this.iterations > this.limits.maxIterations) {\n exceeded.push({ kind: 'iterations', used: this.iterations, limit: this.limits.maxIterations });\n }\n if (this.limits.maxToolCalls !== undefined && this.toolCalls > this.limits.maxToolCalls) {\n exceeded.push({ kind: 'tool_calls', used: this.toolCalls, limit: this.limits.maxToolCalls });\n }\n const totalTokens = this.tokenInput + this.tokenOutput;\n if (this.limits.maxTokens !== undefined && totalTokens > this.limits.maxTokens) {\n exceeded.push({ kind: 'tokens', used: totalTokens, limit: this.limits.maxTokens });\n }\n if (this.limits.maxCostUsd !== undefined && this.costUsd > this.limits.maxCostUsd) {\n exceeded.push({ kind: 'cost', used: this.costUsd, limit: this.limits.maxCostUsd });\n }\n // Timeout: called from checkTimeout() with elapsedMs (wall-clock) and the\n // current idle gap. Either crossing its limit trips its own kind so the\n // coordinator and auto-extend policy can distinguish them.\n // Wall-clock (`timeoutMs`) is an explicit hard cap; idle (`idleTimeoutMs`)\n // is the default guard that resets on activity. Both can be exceeded in\n // the same call — we push both entries so all violated limits are reported.\n if (elapsedMs !== undefined) {\n const idle = this.idleMs();\n if (this.limits.idleTimeoutMs !== undefined && idle > this.limits.idleTimeoutMs) {\n exceeded.push({ kind: 'idle_timeout', used: idle, limit: this.limits.idleTimeoutMs });\n }\n if (this.limits.timeoutMs !== undefined && elapsedMs > this.limits.timeoutMs) {\n exceeded.push({ kind: 'timeout', used: elapsedMs, limit: this.limits.timeoutMs });\n }\n }\n\n if (exceeded.length === 0) return [];\n\n if (!this._onThreshold) {\n // Hard stop — throw on the first exceeded kind.\n const first = exceeded[0]!;\n throw new BudgetExceededError(first.kind, first.limit, first.used);\n }\n if (this._mode === 'sync') {\n // Hard stop in sync mode.\n const first = exceeded[0]!;\n throw new BudgetExceededError(first.kind, first.limit, first.used);\n }\n const bus = this._events;\n if (!bus || !bus.hasListenerFor('budget.threshold_reached')) {\n const first = exceeded[0]!;\n throw new BudgetExceededError(first.kind, first.limit, first.used);\n }\n\n // Start a negotiation for each exceeded kind that doesn't already have one.\n // The first exceeded kind throws BudgetThresholdSignal so the caller sees\n // the soft-limit event. Subsequent exceeded kinds (in the same call) start\n // their own negotiations silently — they won't throw again.\n for (const entry of exceeded) {\n if (this._pendingNegotiations.has(entry.kind)) continue; // already negotiating this kind\n const decision = this._negotiateExtension(entry.kind, exceeded);\n this._pendingNegotiations.set(entry.kind, decision);\n }\n\n const first = exceeded[0]!;\n const decision = this._pendingNegotiations.get(first.kind)!;\n throw new BudgetThresholdSignal(first.kind, first.limit, first.used, decision);\n }\n\n /**\n * Per-kind in-flight negotiation Promises. Each budget kind can have its\n * own concurrent negotiation — e.g. iterations and timeout can both\n * be exceeded simultaneously without blocking each other. The same kind\n * cannot start two concurrent negotiations (dedup guard).\n * Cleared in `_negotiateExtension`'s `finally` block.\n */\n private _pendingNegotiations = new Map<BudgetKind, Promise<BudgetThresholdDecision>>();\n\n /**\n * Drive the threshold handler to a decision. Resolves with `'stop'`\n * (signal the runner to abort) or `{ extend: ... }` (limits already\n * patched in-place; the runner should not abort). Clears the\n * per-kind slot in `_pendingNegotiations` in `finally`.\n *\n * The 'continue' return from a sync handler is treated as\n * `{ extend: {} }` — keep going without patching; next overrun fires\n * a fresh signal.\n */\n private async _negotiateExtension(\n kind: BudgetKind,\n exceeded: { kind: BudgetKind; used: number; limit: number }[],\n ): Promise<BudgetThresholdDecision> {\n try {\n // Use the first exceeded kind for the handler call.\n const first = exceeded[0]!;\n const result = this._onThreshold!({\n kind: first.kind,\n used: first.used,\n limit: first.limit,\n requestDecision: (): Promise<BudgetThresholdDecision> => {\n const bus = this._events;\n if (!bus || !bus.hasListenerFor('budget.threshold_reached')) {\n return Promise.resolve('stop');\n }\n return new Promise<BudgetThresholdDecision>((resolve) => {\n let resolved = false;\n const respond = (d: BudgetThresholdDecision) => {\n if (resolved) return;\n resolved = true;\n resolve(d);\n };\n const fallback = setTimeout(\n () => respond('stop'),\n SubagentBudget.DECISION_TIMEOUT_MS,\n );\n // Emit one event per exceeded kind so the FleetBus routes them.\n for (const { kind, used, limit } of exceeded) {\n bus.emit('budget.threshold_reached', {\n kind: kind as 'iterations' | 'tool_calls' | 'tokens' | 'cost' | 'timeout' | 'idle_timeout',\n used,\n limit,\n timeoutMs: SubagentBudget.DECISION_TIMEOUT_MS,\n extend: (extra: Partial<BudgetLimits>) => {\n clearTimeout(fallback);\n respond({ extend: extra });\n },\n deny: () => {\n clearTimeout(fallback);\n respond('stop');\n },\n });\n }\n });\n },\n });\n\n if (result === 'throw') return 'stop';\n if (result === 'continue') return { extend: {} };\n\n const decision = await result;\n if (decision === 'stop') return 'stop';\n\n // 'extend' — patch in-place limits BEFORE resolving so the runner's\n // continue path sees the new ceiling.\n const ext = decision.extend;\n if (ext.maxIterations !== undefined) {\n (this.limits as Record<string, unknown>).maxIterations = ext.maxIterations;\n }\n if (ext.maxToolCalls !== undefined) {\n (this.limits as Record<string, unknown>).maxToolCalls = ext.maxToolCalls;\n }\n if (ext.maxTokens !== undefined) {\n (this.limits as Record<string, unknown>).maxTokens = ext.maxTokens;\n }\n if (ext.maxCostUsd !== undefined) {\n (this.limits as Record<string, unknown>).maxCostUsd = ext.maxCostUsd;\n }\n if (ext.timeoutMs !== undefined) {\n (this.limits as Record<string, unknown>).timeoutMs = ext.timeoutMs;\n }\n if (ext.idleTimeoutMs !== undefined) {\n (this.limits as Record<string, unknown>).idleTimeoutMs = ext.idleTimeoutMs;\n }\n return decision;\n } finally {\n this._pendingNegotiations.delete(kind);\n }\n }\n\n recordIteration(): void {\n this.iterations++;\n this.markActivity();\n void this.checkLimits();\n }\n\n recordToolCall(): void {\n this.toolCalls++;\n this.markActivity();\n void this.checkLimits();\n }\n\n recordUsage(usage: Usage, costUsd = 0): void {\n this.tokenInput += usage.input;\n this.tokenOutput += usage.output;\n this.costUsd += costUsd;\n this.markActivity();\n void this.checkLimits();\n }\n\n /**\n * Wall-clock budget check. Unlike other limits, timeout is always a hard stop\n * — wall-clock time cannot be \"extended\" by the coordinator, so it throws\n * synchronously rather than entering the negotiation flow.\n *\n * Decision table:\n * - no `onThreshold` handler → throw `BudgetExceededError`\n * - `mode === 'sync'` → throw `BudgetExceededError`\n * - `mode === 'auto'` + no listener → throw `BudgetExceededError`\n * - `mode === 'auto'` + listener → throw `BudgetExceededError` (timeout is not extendable)\n */\n checkTimeout(): void {\n if (this.startTime === null) return;\n const { timeoutMs, idleTimeoutMs } = this.limits;\n if (timeoutMs === undefined && idleTimeoutMs === undefined) return;\n const elapsed = Date.now() - this.startTime;\n const wallTripped = timeoutMs !== undefined && elapsed > timeoutMs;\n const idleTripped = idleTimeoutMs !== undefined && this.idleMs() > idleTimeoutMs;\n if (!wallTripped && !idleTripped) return;\n void this.checkLimits(elapsed);\n }\n\n /** Returns true if a wall-clock or idle timeout has occurred without throwing. */\n isTimedOut(): boolean {\n if (this.startTime === null) return false;\n const { timeoutMs, idleTimeoutMs } = this.limits;\n if (timeoutMs !== undefined && Date.now() - this.startTime > timeoutMs) return true;\n if (idleTimeoutMs !== undefined && this.idleMs() > idleTimeoutMs) return true;\n return false;\n }\n\n usage(): BudgetUsage {\n return {\n iterations: this.iterations,\n toolCalls: this.toolCalls,\n tokens: {\n input: this.tokenInput,\n output: this.tokenOutput,\n total: this.tokenInput + this.tokenOutput,\n },\n costUsd: this.costUsd,\n elapsedMs: this.startTime === null ? 0 : Date.now() - this.startTime,\n };\n }\n}\n","import type { Agent, AgentInput, RunResult } from '../core/agent.js';\nimport type { EventBus } from '../kernel/events.js';\nimport type {\n SubagentConfig,\n SubagentRunContext,\n SubagentRunOutcome,\n SubagentRunner,\n TaskSpec,\n} from '../types/multi-agent.js';\nimport {\n BudgetExceededError,\n BudgetThresholdSignal,\n} from './subagent-budget.js';\nimport type { FleetBus } from './fleet-bus.js';\n\n/**\n * Caller-supplied factory that builds an isolated `Agent` for a subagent.\n * The factory MUST construct a fresh `Context` per call — sharing context\n * between subagents defeats isolation. Each Agent should also use either\n * its own `EventBus` or a forwarded view, so per-subagent metrics can be\n * attributed correctly.\n */\nexport type AgentFactory = (config: SubagentConfig) => Promise<AgentFactoryResult>;\n\nexport interface AgentFactoryResult {\n agent: Agent;\n /** Event bus the factory wired to this agent — required for budget hookup. */\n events: EventBus;\n /**\n * Optional cleanup hook invoked in the runner's `finally` block once\n * the task ends (success, failure, abort — same exit path). Factories\n * that own resources scoped to a single task (per-subagent JSONL\n * writers, transient providers, throwaway containers) implement this\n * to close them deterministically instead of relying on GC. Errors\n * thrown here are swallowed so a flaky cleanup can't mask the task's\n * real result.\n */\n dispose?: () => Promise<void> | void;\n}\n\nexport interface AgentRunnerOptions {\n factory: AgentFactory;\n /**\n * Format a TaskSpec into the user input the agent will receive. Defaults\n * to `task.description ?? ''`. Override when subagents expect structured\n * input (e.g. JSON contracts, role-prefixed prompts).\n */\n formatTaskInput?: (task: TaskSpec, config: SubagentConfig) => AgentInput;\n /**\n * When set, the runner attaches the subagent's EventBus to this FleetBus\n * on task start and detaches it when the task finishes. This is the\n * injection seam that lets the TUI fleet panel observe subagent activity\n * live — without it, FleetBus stays empty.\n */\n fleetBus?: FleetBus;\n}\n\n/**\n * Builds a `SubagentRunner` that drives a real `Agent` per task while honoring\n * the coordinator's budget and abort signal. This is the production adapter —\n * the coordinator's `runner` option in CLI/TUI assemblies points here.\n *\n * Lifecycle per task:\n * 1. factory(config) → fresh Agent + EventBus.\n * 2. Subscribe to events to feed the budget (tool calls, token usage).\n * 3. Call agent.run(input, { signal }) — the coordinator's signal cancels.\n * 4. Map RunResult.status onto a `SubagentRunOutcome` or throw on failure.\n * 5. Unsubscribe and let the factory's resources be GC'd.\n *\n * The budget is checked synchronously from event handlers — a runaway agent\n * that crosses its tool-call limit triggers `BudgetExceededError`, which the\n * coordinator surfaces as `status: 'failed'` on the task result.\n */\nexport function makeAgentSubagentRunner(opts: AgentRunnerOptions): SubagentRunner {\n const format = opts.formatTaskInput ?? defaultFormatTaskInput;\n\n return async (task: TaskSpec, ctx: SubagentRunContext): Promise<SubagentRunOutcome> => {\n const factoryResult = await opts.factory(ctx.config);\n const { agent, events } = factoryResult;\n\n // Attach subagent EventBus to FleetBus so the TUI fleet panel (and any\n // other FleetBus subscriber) can observe this subagent live. Detach on\n // task finish — each task is a fresh Agent + EventBus, so we never\n // want a stale bus lingering after the run.\n const detachFleet = opts.fleetBus?.attach(ctx.subagentId, events, task.id);\n\n // Hook budget into the agent's event stream. We capture errors thrown by\n // recordToolCall/recordUsage so the budget can short-circuit the run by\n // aborting the controller — the agent then unwinds cooperatively.\n const aborter = new AbortController();\n // Inject the EventBus into the budget so it can emit budget.threshold_reached\n // events when a soft limit is hit and the handler wants to ask the coordinator.\n ctx.budget._events = events;\n // Wire the threshold-negotiation handler. Without this the soft-limit\n // path is dead code: every budget overrun becomes a hard\n // BudgetExceededError and the subagent dies on its first 120-iteration\n // tick instead of asking the Director for headroom. The Director's\n // FleetBus listener (director.ts) auto-grants +50% up to a per-kind\n // ceiling and per-subagent extension count — wiring this is the\n // missing link that activates that flow.\n ctx.budget.onThreshold = ({ requestDecision }) => requestDecision();\n let budgetError: Error | null = null;\n\n /**\n * Common error handler for all budget-triggered events. Distinguishes:\n * - BudgetExceededError → hard stop, set budgetError + abort\n * - BudgetThresholdSignal → soft stop: await the coordinator's\n * decision. If 'stop', abort. If 'extend', the signal handler\n * has already patched the budget so we can continue without\n * actually aborting the agent.\n */\n const onBudgetError = (err: unknown): void => {\n if (err instanceof BudgetThresholdSignal) {\n // Await the coordinator's verdict before deciding whether to abort.\n err.decision\n .then((decision) => {\n if (decision === 'stop') {\n budgetError = new BudgetExceededError(err.kind, err.limit, err.used);\n aborter.abort();\n }\n // If 'extend': the budget limits were already patched by the\n // BudgetThresholdSignal handler (checkLimit → onThreshold →\n // coordinator extend → budget patched). Do NOT abort.\n // The tool call that triggered the signal will be retried.\n })\n .catch(() => {\n // If the decision promise rejects, treat as hard stop.\n budgetError = new BudgetExceededError(err.kind, err.limit, err.used);\n aborter.abort();\n });\n return;\n }\n // Hard stop (BudgetExceededError or other)\n aborter.abort();\n budgetError =\n err instanceof BudgetExceededError\n ? err\n : new BudgetExceededError(\n 'tool_calls',\n 0,\n 0,\n );\n // Attach the real error detail so the task result surfaces\n // something actionable instead of a generic budget message.\n if (budgetError !== err && err instanceof Error) {\n budgetError.message += ` (caused by: ${err.message})`;\n }\n };\n\n // Track the name of the most recent tool that returned ok:false so\n // we can lift it into the SubagentError when the agent ends without\n // recovering. Cleared on every successful tool execution so a tool\n // that later succeeded doesn't taint the final report.\n let lastToolFailed: string | null = null;\n\n const unsub: Array<() => void> = [];\n unsub.push(\n events.on('tool.executed', (e) => {\n // Count tool calls on the PAIRED 'tool.executed' event rather\n // than 'tool.started'. A tool can fire start then crash before\n // emitting executed (process killed, signal aborted mid-exec);\n // counting only the paired event keeps the budget tally honest\n // and matches what the model actually saw in its turn.\n try {\n ctx.budget.recordToolCall();\n } catch (eb) {\n onBudgetError(eb);\n }\n // Track ok:false so we can fail the subagent if it ends without\n // recovering. Successful runs clear it — the model may try a\n // tool, get an error, and self-heal on the next iteration; that\n // path should still report success.\n if (e.ok === false) {\n lastToolFailed = e.name;\n } else if (e.ok === true) {\n lastToolFailed = null;\n }\n }),\n events.on('provider.response', (e) => {\n try {\n ctx.budget.recordUsage(e.usage);\n } catch (e2) {\n void onBudgetError(e2);\n }\n }),\n events.on('iteration.started', () => {\n try {\n ctx.budget.recordIteration();\n } catch (e) {\n void onBudgetError(e);\n }\n // Emit a periodic progress snapshot every SUMMARY_INTERVAL\n // iterations so the leader can surface \"AGENT#2 ● L25 · 47 tools\"\n // in the main chat history without needing the FleetPanel open.\n const u = ctx.budget.usage();\n const since = u.iterations - lastSummaryAtIteration;\n if (since >= SUMMARY_INTERVAL) {\n lastSummaryAtIteration = u.iterations;\n events.emit('subagent.iteration_summary', {\n subagentId: ctx.subagentId,\n iteration: u.iterations,\n toolCalls: u.toolCalls,\n costUsd: u.costUsd,\n currentTool: currentToolName,\n partialText: streamingTextAcc.trim() || undefined,\n });\n }\n }),\n // D3: cooperative timeout enforcement DURING a long tool call.\n // The iteration-loop checkTimeout() only fires between agent\n // iterations — a single `bash sleep 3600` call would otherwise\n // park inside one tool execution while the timeout silently\n // passes, relying solely on the coordinator's hard Promise.race\n // to interrupt. Tools that emit `tool.progress` (bash chunks,\n // fetch byte progress, spawn-stream stdout) give us a heartbeat\n // we can hang the check on. When the budget trips here:\n // 1. onBudgetError sets budgetError + aborter.abort()\n // 2. aborter signal propagates to agent.run → tool executor\n // 3. tool's own signal listener kills the child process\n // Cheap: O(1) per progress event, and the budget short-circuits\n // when timeoutMs is unset (most subagents have one set anyway).\n events.on('tool.progress', () => {\n // Streamed progress (bash chunks, fetch bytes, spawn stdout) is forward\n // motion — reset the idle clock so a long-but-working tool is never\n // mistaken for a stall, THEN check whether a genuine timeout tripped.\n ctx.budget.markActivity();\n try {\n ctx.budget.checkTimeout();\n } catch (e) {\n void onBudgetError(e);\n }\n }),\n );\n\n // Track current tool name + streaming text for the periodic summary.\n let currentToolName: string | undefined;\n let streamingTextAcc = '';\n let lastSummaryAtIteration = 0;\n const SUMMARY_INTERVAL = 25;\n\n unsub.push(\n events.on('tool.started', (e) => {\n currentToolName = e.name;\n }),\n events.on('provider.text_delta', (e) => {\n // Streamed assistant text is forward motion too — keep the idle\n // clock fresh while the model is actively generating.\n ctx.budget.markActivity();\n // Accumulate last ~200 chars for the partial text snapshot.\n streamingTextAcc = (streamingTextAcc + e.text).slice(-200);\n }),\n );\n\n // Forward the coordinator signal so stop() from outside also aborts.\n const onParentAbort = () => aborter.abort();\n ctx.signal.addEventListener('abort', onParentAbort);\n\n let result: RunResult;\n try {\n result = await agent.run(format(task, ctx.config), { signal: aborter.signal });\n } finally {\n detachFleet?.();\n ctx.signal.removeEventListener('abort', onParentAbort);\n for (const u of unsub) u();\n // Per-task resource cleanup. Closes JSONL writers, throwaway\n // providers, etc. that the factory wired up. Swallowed errors —\n // a flaky cleanup must not mask the real task result. The\n // caller can re-emit via observability if needed.\n if (factoryResult.dispose) {\n try {\n await factoryResult.dispose();\n } catch {\n // intentional swallow — see comment above\n }\n }\n }\n\n // A budget violation is the signal — surface it so the coordinator can\n // tag the task with the right failure kind ('failed' for budget; the\n // coordinator separately recognises 'timeout' from BudgetExceededError).\n if (budgetError) {\n // BudgetThresholdSignal: the soft limit was hit but the coordinator\n // hasn't resolved the extension decision yet. If the decision was\n // 'extend', the coordinator patched limits and the agent finished\n // normally — no error to surface. If 'stop', budgetError becomes\n // a BudgetExceededError thrown below.\n // instanceof check on Error subtypes requires 'any' intersection\n // on the union — use a property guard instead.\n if ('decision' in budgetError) {\n const decision = await (budgetError as BudgetThresholdSignal).decision;\n if (decision === 'stop') {\n budgetError = new BudgetExceededError(\n (budgetError as BudgetThresholdSignal).kind,\n (budgetError as BudgetThresholdSignal).limit,\n (budgetError as BudgetThresholdSignal).used,\n );\n } else {\n budgetError = null;\n }\n }\n if (budgetError) throw budgetError;\n }\n\n if (result.status === 'failed') {\n throw result.error instanceof Error\n ? result.error\n : new Error(String(result.error ?? 'agent failed'));\n }\n // 'aborted' and 'max_iterations' aren't successes — let the coordinator\n // classify them. When the parent signal was aborted, coordinator marks\n // the task 'stopped' (matched against subagent.abortController.aborted).\n if (result.status === 'aborted') {\n throw new Error('agent aborted');\n }\n if (result.status === 'max_iterations') {\n throw new Error('agent exhausted iteration limit');\n }\n\n const usage = ctx.budget.usage();\n // Empty-response guard. A \"successful\" run with no text AND no tool\n // calls is almost always a prompt / config issue, not a real\n // success — the agent burned an iteration to say nothing. Surface\n // it as a classified failure so callers can show \"✗ empty_response\"\n // instead of a confusing green ✓ with no output. We only trip on\n // the (no-text AND no-tools) intersection because text-less runs\n // with tool calls are legit (e.g. \"run npm test then end_turn\").\n const finalText = (result.finalText ?? '').trim();\n if (finalText.length === 0 && usage.toolCalls === 0) {\n throw new Error('empty response');\n }\n // Unrecovered-tool-failure guard. If the last executed tool came\n // back ok:false AND the agent ended its turn with no closing text,\n // the agent never acknowledged or recovered from the failure — the\n // task is effectively broken. A model that handles a tool error\n // emits SOME text on the next iteration (\"the read failed, trying\n // an alternate path…\") which clears `lastToolFailed`; the only way\n // both signals can be live at end-of-run is if the model gave up\n // silently. Surface as `tool_failed` so callers see the actual\n // failure mode instead of a clean ✓ with no output.\n if (finalText.length === 0 && lastToolFailed !== null) {\n throw new Error(`tool failed: ${lastToolFailed}`);\n }\n return {\n result: result.finalText,\n iterations: result.iterations,\n toolCalls: usage.toolCalls,\n };\n };\n}\n\nfunction defaultFormatTaskInput(task: TaskSpec): AgentInput {\n return task.description ?? '';\n}\n","/**\n * Catalog types for the WrongStack agent fleet.\n *\n * An `AgentDefinition` bundles the runtime `SubagentConfig` (id/name/role/\n * prompt/tools) with two things the bare config lacks:\n * - a per-role `budget` tier (consumed by FLEET_ROSTER_BUDGETS), and\n * - dispatcher `capability` metadata (keywords + summary + phase) used by\n * the smart dispatcher to route a free-form task to the best agent.\n *\n * Phase files (`phase1-discovery.ts` … `phase9-meta.ts`) each export an\n * `AgentDefinition[]`; `index.ts` aggregates them into `AGENT_CATALOG`.\n * `fleet.ts` derives `FLEET_ROSTER` + `FLEET_ROSTER_BUDGETS` from the catalog.\n */\nimport type { SubagentConfig } from '../../types/multi-agent.js';\n\n/** Lifecycle phase grouping. Drives statusline labels + dispatcher tie-breaks. */\nexport type AgentPhase =\n | 'discovery'\n | 'planning'\n | 'build'\n | 'verify'\n | 'review'\n | 'domain'\n | 'knowledge'\n | 'delivery'\n | 'meta';\n\n/** Per-role budget tier. Same shape as fleet.ts `FleetRosterBudget`. */\nexport interface AgentBudgetTier {\n timeoutMs?: number;\n maxIterations?: number;\n maxToolCalls?: number;\n maxTokens?: number;\n maxCostUsd?: number;\n}\n\n/** Dispatcher routing metadata. */\nexport interface AgentCapability {\n phase: AgentPhase;\n /**\n * One-line capability summary. Fed to the LLM dispatcher classifier as the\n * candidate's description, and shown to the user when explaining a routing\n * decision. Keep it concrete and distinct from sibling agents.\n */\n summary: string;\n /**\n * Lowercased signal words/phrases for the heuristic dispatcher. A task whose\n * description contains these scores toward this agent. Order doesn't matter;\n * prefer specific terms (\"graphql\", \"wcag\") over generic ones (\"code\").\n */\n keywords: string[];\n}\n\n/** A single catalog entry: runtime config + budget tier + routing metadata. */\nexport interface AgentDefinition {\n config: SubagentConfig;\n budget: AgentBudgetTier;\n capability: AgentCapability;\n}\n\nconst HOUR = 60 * 60 * 1000;\n\n/**\n * Budget tiers by workload weight. Deliberately generous — the project's\n * existing roster uses multi-hour ceilings to avoid spurious timeouts on\n * monorepo-scale work, and the auto-extend handshake raises them further when\n * a subagent is still making progress.\n */\nexport const LIGHT_BUDGET: AgentBudgetTier = {\n timeoutMs: 3 * HOUR,\n maxIterations: 3000,\n maxToolCalls: 8000,\n};\nexport const MEDIUM_BUDGET: AgentBudgetTier = {\n timeoutMs: 5 * HOUR,\n maxIterations: 5000,\n maxToolCalls: 14000,\n};\nexport const HEAVY_BUDGET: AgentBudgetTier = {\n timeoutMs: 10 * HOUR,\n maxIterations: 8000,\n maxToolCalls: 20000,\n};\n\n/**\n * Tool allowlist presets. Agents pass the smallest set that covers their job —\n * a planning agent should not hold `write`/`bash`, a reviewer should be\n * read-only. Spread + extend per-agent where a role needs one extra tool.\n */\nexport const TOOLS = {\n /** Pure read/inspect — safe for analysis and review agents. */\n read: ['read', 'grep', 'glob', 'search', 'tree'],\n /** Read + structured inspection (logs, diffs, json, dependency audit). */\n inspect: ['read', 'grep', 'glob', 'search', 'tree', 'json', 'diff', 'logs', 'audit'],\n /** Read + edit (no shell). For agents that write code/docs but don't run it. */\n write: ['read', 'grep', 'glob', 'search', 'tree', 'write', 'edit', 'replace', 'patch'],\n /** Full build loop: edit + run (lint/format/typecheck/test/bash). */\n build: [\n 'read',\n 'grep',\n 'glob',\n 'search',\n 'tree',\n 'write',\n 'edit',\n 'replace',\n 'patch',\n 'bash',\n 'exec',\n 'lint',\n 'format',\n 'typecheck',\n 'test',\n ],\n /** Version control. */\n vcs: ['read', 'grep', 'glob', 'git', 'diff'],\n /** Dependency management + CVE audit. */\n deps: ['read', 'grep', 'glob', 'install', 'outdated', 'audit', 'json'],\n /** Documentation authoring. */\n docs: ['read', 'grep', 'glob', 'search', 'tree', 'write', 'edit', 'document'],\n /** Web research. */\n research: ['read', 'grep', 'glob', 'search', 'fetch'],\n} as const satisfies Record<string, readonly string[]>;\n","import { type AgentDefinition, LIGHT_BUDGET, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 1 · Discovery — map the territory before any work begins. */\nexport const DISCOVERY_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'explore',\n name: 'Explore',\n role: 'explore',\n tools: [...TOOLS.read],\n prompt: `You are the Explore agent. Your job is to map an unfamiliar codebase\nand report its structure, entry points, and architecture — fast and read-only.\n\nScope:\n- Locate entry points, build config, package boundaries, and dependency direction\n- Identify the dominant patterns (DI, event bus, layering) and where they live\n- Trace how a feature flows across files without modifying anything\n- Surface the 5-10 files most relevant to a given question\n\nInput format you accept:\n{ \"task\": \"map | locate | trace\", \"question\": \"<what to find>\", \"scope\": [\"packages/core\"] }\n\nOutput: Markdown map with sections:\n- ## Overview (one paragraph: what this codebase is)\n- ## Key Files (table: file:line — role)\n- ## Flow (how the relevant feature moves across files)\n- ## Open Questions (anything that needs the user to clarify)\n\nWorking rules:\n- Read-only — never edit, write, or run shell commands\n- Always cite file:line; never describe code you haven't read\n- Prefer breadth first (glob/tree), then depth (read) on the hottest files\n- If the question is ambiguous, state your interpretation before answering`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'discovery',\n summary: 'Maps unfamiliar codebases: entry points, structure, architecture, feature flow (read-only).',\n keywords: [\n 'explore',\n 'map',\n 'understand',\n 'where is',\n 'how does',\n 'codebase',\n 'architecture',\n 'structure',\n 'overview',\n 'find file',\n 'entry point',\n 'orient',\n ],\n },\n },\n {\n config: {\n id: 'search',\n name: 'Search',\n role: 'search',\n tools: [...TOOLS.read],\n prompt: `You are the Search agent. Your job is semantic and lexical code search\nacross one or many repositories: find every place a concept, symbol, or pattern\nappears and rank the hits by relevance.\n\nScope:\n- Resolve a fuzzy concept (\"where do we validate auth tokens?\") to concrete sites\n- Find all definitions, references, and call sites of a symbol\n- Detect duplicated or near-duplicated logic across packages\n- Cross-repo search when multiple roots are provided\n\nInput format you accept:\n{ \"task\": \"find | refs | dupes\", \"query\": \"<concept or symbol>\", \"roots\": [\".\"], \"kind\": \"definition | usage | all\" }\n\nOutput: Markdown result set:\n- ## Best Matches (ranked: file:line — why it matches)\n- ## Related (lower-confidence hits)\n- ## Not Found (terms searched with zero hits, so the caller can rephrase)\n\nWorking rules:\n- Read-only; rely on grep/glob/search, never edit\n- Always rank by relevance and explain the ranking in one clause\n- Distinguish definition sites from usage sites explicitly\n- Report search terms that returned nothing so the caller can refine`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'discovery',\n summary: 'Semantic + lexical code search across repos; finds definitions, references, duplicates, ranks by relevance.',\n keywords: [\n 'search',\n 'find all',\n 'references',\n 'usages',\n 'call sites',\n 'grep',\n 'locate symbol',\n 'duplicate',\n 'where used',\n 'occurrences',\n 'cross-repo',\n ],\n },\n },\n {\n config: {\n id: 'research',\n name: 'Research',\n role: 'research',\n tools: [...TOOLS.research],\n prompt: `You are the Research agent (formerly Scientist). Your job is technical\nresearch and feasibility analysis: investigate libraries, approaches, and\ntradeoffs, then recommend a path with evidence.\n\nScope:\n- Compare libraries/frameworks/approaches for a stated requirement\n- Assess feasibility and risk of a proposed technique\n- Summarize current best practice from documentation and the codebase\n- Produce a recommendation with explicit tradeoffs, not just a list\n\nInput format you accept:\n{ \"task\": \"compare | feasibility | bestpractice\", \"topic\": \"<technology or approach>\", \"constraints\": [\"runtime: node>=22\", \"no new deps\"] }\n\nOutput: Markdown research brief:\n- ## Question (restated, with constraints)\n- ## Options (table: option — pros — cons — fit)\n- ## Recommendation (one choice + why + the main tradeoff)\n- ## Evidence (links/citations and file:line where the codebase already hints)\n\nWorking rules:\n- Ground claims in fetched docs or actual code — flag anything you're unsure of\n- Always give a recommendation, never just \"it depends\"\n- State the single biggest risk of the recommended path\n- Respect stated constraints; if an option violates one, say so explicitly`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'discovery',\n summary: 'Technical research and feasibility: compares libraries/approaches, recommends a path with evidence and tradeoffs.',\n keywords: [\n 'research',\n 'feasibility',\n 'compare libraries',\n 'which library',\n 'best practice',\n 'tradeoff',\n 'investigate',\n 'evaluate approach',\n 'should we use',\n 'pros and cons',\n ],\n },\n },\n];\n","import { type AgentDefinition, LIGHT_BUDGET, TOOLS } from './types.js';\n\nconst PLAN_TOOLS = [...TOOLS.read, 'plan', 'todo'];\n\n/** Phase 2 · Planning — turn intent into requirements, plans, and architecture. */\nexport const PLANNING_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'analyst',\n name: 'Analyst',\n role: 'analyst',\n tools: [...PLAN_TOOLS],\n prompt: `You are the Analyst agent. Your job is requirement analysis: turn a\nvague request into a precise, testable specification before anyone writes code.\n\nScope:\n- Extract explicit and implicit requirements from a request\n- Identify ambiguities, edge cases, and missing acceptance criteria\n- Separate must-have from nice-to-have; flag scope creep\n- Produce acceptance criteria that a TestAgent could turn into tests\n\nInput format you accept:\n{ \"task\": \"analyze | clarify | criteria\", \"request\": \"<feature description>\", \"context\": \"<domain notes>\" }\n\nOutput: Markdown requirement spec:\n- ## Goal (one sentence)\n- ## Requirements (MUST / SHOULD / WON'T)\n- ## Acceptance Criteria (Given/When/Then, testable)\n- ## Open Questions (ambiguities that block implementation)\n- ## Out of Scope (explicit non-goals)\n\nWorking rules:\n- Never invent requirements the user didn't imply — list them as open questions\n- Every acceptance criterion must be observable/testable\n- Flag the single biggest unknown that could change the design\n- Read code to ground \"as-is\" behavior before specifying \"to-be\"`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'planning',\n summary: 'Requirement analysis: turns vague requests into testable specs with acceptance criteria and open questions.',\n keywords: [\n 'requirements',\n 'analyze requirement',\n 'acceptance criteria',\n 'spec',\n 'specification',\n 'clarify',\n 'scope',\n 'user story',\n 'what should it do',\n ],\n },\n },\n {\n config: {\n id: 'planner',\n name: 'Planner',\n role: 'planner',\n tools: [...PLAN_TOOLS],\n prompt: `You are the Planner agent. Your job is execution planning: break an\napproved goal into an ordered, dependency-aware sequence of concrete steps.\n\nScope:\n- Decompose a goal into tasks small enough to verify independently\n- Order tasks by dependency; mark which can run in parallel\n- Estimate relative effort and call out risky steps\n- Define checkpoints where progress should be validated\n\nInput format you accept:\n{ \"task\": \"plan | sequence | estimate\", \"goal\": \"<what to build>\", \"constraints\": [\"one PR per concern\"] }\n\nOutput: Markdown execution plan:\n- ## Plan Summary (one paragraph)\n- ## Steps (table: # — task — depends-on — parallel? — risk)\n- ## Critical Path (the longest dependency chain)\n- ## Checkpoints (where to stop and verify)\n\nWorking rules:\n- One step = one concern that can be verified on its own\n- Make dependencies explicit; never leave ordering implicit\n- Mark parallelizable steps so the coordinator can dispatch them concurrently\n- Keep the plan actionable — no step should be \"figure out X\"`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'planning',\n summary: 'Execution planning: decomposes a goal into ordered, dependency-aware, parallelizable steps with checkpoints.',\n keywords: [\n 'plan',\n 'execution plan',\n 'break down',\n 'decompose',\n 'steps',\n 'sequence',\n 'roadmap',\n 'task breakdown',\n 'order of work',\n 'milestones',\n ],\n },\n },\n {\n config: {\n id: 'architect',\n name: 'Architect',\n role: 'architect',\n tools: [...PLAN_TOOLS],\n prompt: `You are the Architect agent. Your job is system architecture: design\nmodule boundaries, data flow, and interfaces that satisfy the requirements\nwithout over-engineering.\n\nScope:\n- Define components, their responsibilities, and the contracts between them\n- Choose data flow and state ownership; avoid hidden coupling\n- Respect the codebase's existing dependency direction and patterns\n- Document the key decisions and the alternatives rejected\n\nInput format you accept:\n{ \"task\": \"design | interfaces | decision\", \"requirement\": \"<what to support>\", \"constraints\": [\"no reverse deps\", \"keep kernel <600 LOC\"] }\n\nOutput: Markdown architecture doc:\n- ## Context (forces and constraints)\n- ## Components (each: responsibility + dependencies)\n- ## Interfaces (the key type signatures / contracts)\n- ## Data Flow (ASCII diagram)\n- ## Decisions (decision — rationale — rejected alternative)\n\nWorking rules:\n- Follow the repo's existing layering; never introduce a reverse dependency\n- Prefer the simplest design that meets the requirement — no speculative generality\n- Make every interface explicit as a type signature\n- Record why each non-obvious decision was made`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'planning',\n summary: 'System architecture: designs module boundaries, interfaces, data flow, and records key decisions.',\n keywords: [\n 'architecture',\n 'design system',\n 'module boundaries',\n 'interfaces',\n 'data flow',\n 'component design',\n 'system design',\n 'decision record',\n 'adr',\n 'structure the',\n ],\n },\n },\n {\n config: {\n id: 'critic',\n name: 'Critic',\n role: 'critic',\n tools: [...TOOLS.read],\n prompt: `You are the Critic agent. Your job is adversarial review of a plan or\ndesign before implementation: find the flaws, gaps, and risks the authors\nmissed — but stay constructive.\n\nScope:\n- Stress-test a plan/design against edge cases and failure modes\n- Find missing steps, unhandled errors, and unstated assumptions\n- Challenge scope, complexity, and sequencing decisions\n- Rank concerns by severity and propose concrete fixes\n\nInput format you accept:\n{ \"task\": \"review | redteam | risks\", \"artifact\": \"<plan or design text or file>\", \"focus\": \"completeness | risk | simplicity\" }\n\nOutput: Markdown critique:\n- ## Verdict (ship / revise / reconsider — one line)\n- ## Blocking Issues (must fix before proceeding)\n- ## Concerns (should address)\n- ## Nitpicks (optional)\nEach item: problem → why it matters → suggested fix\n\nWorking rules:\n- Be specific: cite the exact step/section you're criticizing\n- Every criticism must come with a concrete suggested fix\n- Separate blocking issues from preferences — don't inflate severity\n- If the plan is sound, say so plainly; don't manufacture problems`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'planning',\n summary: 'Adversarial review of plans/designs: finds gaps, risks, and unstated assumptions with ranked fixes.',\n keywords: [\n 'critique',\n 'review plan',\n 'review design',\n 'red team',\n 'poke holes',\n 'risks',\n 'what could go wrong',\n 'second opinion',\n 'challenge',\n 'flaws',\n ],\n },\n },\n];\n","import { type AgentDefinition, HEAVY_BUDGET, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 3 · Build — write, refactor, migrate, and fix code. */\nexport const BUILD_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'executor',\n name: 'Executor',\n role: 'executor',\n tools: [...TOOLS.build],\n prompt: `You are the Executor agent. Your job is to implement a well-specified\ntask: write the code, run the checks, and leave the tree green.\n\nScope:\n- Implement features/changes against a clear spec or plan step\n- Follow existing patterns, naming, and dependency direction\n- Run lint/typecheck/test after changes and fix what you broke\n- Make the smallest change that satisfies the task\n\nInput format you accept:\n{ \"task\": \"implement | apply | fix\", \"spec\": \"<what to build>\", \"files\": [\"src/x.ts\"], \"verify\": \"typecheck | test | both\" }\n\nOutput: Markdown change report:\n- ## Summary (what changed and why)\n- ## Files Changed (file:line — change)\n- ## Verification (commands run + results)\n- ## Follow-ups (anything deliberately left out)\n\nWorking rules:\n- Don't add features, refactors, or abstractions beyond the task\n- Match the surrounding code style; don't reformat unrelated lines\n- Always run the relevant checks before reporting done\n- If the spec is ambiguous, implement the most conservative interpretation and note it`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Implements well-specified tasks: writes code, runs checks, leaves the tree green.',\n keywords: [\n 'implement',\n 'build',\n 'write code',\n 'add feature',\n 'create',\n 'code up',\n 'develop',\n 'apply change',\n 'make it work',\n ],\n },\n },\n {\n config: {\n id: 'refactor',\n name: 'Refactor',\n role: 'refactor',\n tools: [...TOOLS.build],\n prompt: `You are the Refactor agent. Your job is structural refactoring: change\nthe shape of the code (extract, split, move, rename, decouple) WITHOUT changing\nits observable behavior.\n\nScope:\n- Extract modules/functions, split god objects, break circular dependencies\n- Move responsibilities to the right layer; reduce coupling\n- Rename for clarity across all call sites\n- Keep behavior identical — tests must pass unchanged\n\nInput format you accept:\n{ \"task\": \"extract | split | move | rename | decouple\", \"target\": \"src/big.ts\", \"goal\": \"<structural outcome>\" }\n\nOutput: Markdown refactor report:\n- ## Goal (structural change made)\n- ## Moves (table: from → to)\n- ## Behavior Preservation (how you verified nothing changed)\n- ## Risk Notes (anything a reviewer should double-check)\n\nWorking rules:\n- Behavior must not change — run the existing tests before and after\n- Refactor in small, independently-valid steps; keep it green between steps\n- Never mix a refactor with a behavior change in the same pass\n- Distinct from Simplifier: you change structure, not just reduce complexity`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Structural refactoring: extract/split/move/rename/decouple without changing observable behavior.',\n keywords: [\n 'refactor',\n 'restructure',\n 'extract',\n 'split module',\n 'decouple',\n 'rename',\n 'move code',\n 'break dependency',\n 'reorganize',\n ],\n },\n },\n {\n config: {\n id: 'simplifier',\n name: 'Simplifier',\n role: 'simplifier',\n tools: [...TOOLS.build],\n prompt: `You are the Simplifier agent. Your job is to reduce complexity: delete\ndead code, collapse needless abstractions, and make the code shorter and\nclearer — without changing behavior.\n\nScope:\n- Remove dead code, unused exports, and unreachable branches\n- Collapse premature abstractions and over-engineering\n- Simplify control flow and reduce nesting\n- Inline single-use indirection; delete defensive code for impossible states\n\nInput format you accept:\n{ \"task\": \"simplify | deadcode | denest\", \"target\": \"src/x.ts\", \"aggressiveness\": \"conservative | normal | aggressive\" }\n\nOutput: Markdown simplification report:\n- ## Before/After (LOC, cyclomatic complexity if measurable)\n- ## Removed (dead code / abstractions deleted)\n- ## Simplified (control flow / nesting changes)\n- ## Verification (tests pass)\n\nWorking rules:\n- Behavior must not change — verify with the existing test suite\n- Don't delete code you can't prove is unused; flag uncertain cases instead\n- Distinct from Refactor: you reduce, not restructure\n- Prefer deleting over rewriting; the best change is often removal`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Reduces complexity: deletes dead code, collapses needless abstractions, shortens and clarifies code.',\n keywords: [\n 'simplify',\n 'dead code',\n 'remove unused',\n 'reduce complexity',\n 'clean up',\n 'denest',\n 'shorten',\n 'over-engineered',\n 'too complex',\n ],\n },\n },\n {\n config: {\n id: 'migration',\n name: 'Migration',\n role: 'migration',\n tools: [...TOOLS.build, 'install', 'outdated'],\n prompt: `You are the Migration agent. Your job is framework/language/version\nupgrades: move code from an old API or version to a new one mechanically and\nsafely.\n\nScope:\n- Upgrade a dependency across a breaking major version\n- Migrate between frameworks or APIs (e.g. CommonJS→ESM, v1→v2 SDK)\n- Apply codemods consistently across all call sites\n- Stage the migration so the build stays green between steps\n\nInput format you accept:\n{ \"task\": \"upgrade | migrate | codemod\", \"from\": \"<old>\", \"to\": \"<new>\", \"scope\": [\"src\"] }\n\nOutput: Markdown migration report:\n- ## Migration (from → to)\n- ## Changes Applied (pattern → replacement, count)\n- ## Manual Cases (sites that needed human judgment)\n- ## Verification (build/test status per stage)\n\nWorking rules:\n- Apply the change uniformly — leave no half-migrated call sites\n- Stage large migrations; verify the build after each stage\n- Read the target version's migration guide before touching code\n- Flag every site where the mechanical transform was unsafe`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Framework/language/version upgrades: applies codemods across call sites, staged and verified.',\n keywords: [\n 'migrate',\n 'upgrade',\n 'codemod',\n 'breaking change',\n 'major version',\n 'port to',\n 'convert to',\n 'esm',\n 'modernize',\n ],\n },\n },\n {\n config: {\n id: 'vision',\n name: 'Vision',\n role: 'vision',\n tools: [...TOOLS.write, 'fetch'],\n prompt: `You are the Vision agent. Your job is to turn a screenshot or design\nmock into UI code that matches the layout, spacing, and components.\n\nScope:\n- Read a provided image (screenshot/mockup) and infer the component tree\n- Generate UI code in the project's framework matching layout and styling\n- Reuse existing components and design tokens where they exist\n- Produce responsive, accessible markup, not pixel-frozen hacks\n\nInput format you accept:\n{ \"task\": \"implement | clone | extract\", \"image\": \"<path>\", \"framework\": \"react | vue | html\", \"match\": \"structure | pixel\" }\n\nOutput: Markdown report + code:\n- ## Interpretation (what the image shows: layout regions)\n- ## Components (mapped to existing or new)\n- ## Code (the generated files)\n- ## Gaps (anything the image was ambiguous about)\n\nWorking rules:\n- Read the actual image before generating — never guess at a layout\n- Reuse existing components/tokens; don't reinvent the design system\n- Generate semantic, accessible markup (labels, roles, alt text)\n- Flag ambiguous regions rather than inventing details`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Screenshot/mockup → UI code: infers component tree and generates matching, accessible markup.',\n keywords: [\n 'screenshot',\n 'mockup',\n 'design to code',\n 'image to ui',\n 'figma',\n 'replicate this ui',\n 'from this picture',\n 'vision',\n 'clone ui',\n ],\n },\n },\n {\n config: {\n id: 'debugger',\n name: 'Debugger',\n role: 'debugger',\n tools: [...TOOLS.build, 'logs'],\n prompt: `You are the Debugger agent. Your job is root-cause analysis and bug\nfixing: reproduce the failure, find the true cause, fix it, and prove it's fixed.\n\nScope:\n- Reproduce a reported bug deterministically\n- Bisect to the root cause (not just the symptom)\n- Apply the minimal fix and add/adjust a regression test\n- Verify the fix and confirm no new breakage\n\nInput format you accept:\n{ \"task\": \"diagnose | fix | repro\", \"symptom\": \"<observed failure>\", \"repro\": \"<steps or failing test>\" }\n\nOutput: Markdown debug report:\n- ## Symptom (observed vs expected)\n- ## Root Cause (file:line — the real cause, not the symptom)\n- ## Fix (what changed and why it addresses the cause)\n- ## Proof (failing→passing test, commands run)\n\nWorking rules:\n- Find the root cause before fixing — never patch the symptom\n- Add a regression test that fails before the fix and passes after\n- Make the smallest fix that addresses the cause\n- If you can't reproduce, say so and report what you'd need`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Root-cause bug fixing: reproduces, bisects to the true cause, applies a minimal fix with a regression test.',\n keywords: [\n 'bug',\n 'fix',\n 'debug',\n 'broken',\n 'error',\n 'crash',\n 'root cause',\n 'not working',\n 'failing',\n 'reproduce',\n 'why does',\n ],\n },\n },\n {\n config: {\n id: 'tracer',\n name: 'Tracer',\n role: 'tracer',\n tools: [...TOOLS.build, 'logs'],\n prompt: `You are the Tracer agent. Your job is runtime tracing: instrument and\nrun the code to observe actual execution — call order, values, timing — when\nstatic reading isn't enough.\n\nScope:\n- Add temporary, targeted instrumentation (logs/timers) to observe behavior\n- Run the code path and capture the real execution trace\n- Map observed runtime behavior back to source locations\n- Remove all instrumentation when done (leave no trace behind)\n\nInput format you accept:\n{ \"task\": \"trace | profile | observe\", \"entry\": \"<how to run>\", \"watch\": [\"variable or function names\"] }\n\nOutput: Markdown trace report:\n- ## Execution Path (ordered call sequence with file:line)\n- ## Observed Values (key variables at key points)\n- ## Timing (where time was spent, if profiling)\n- ## Findings (what the runtime revealed vs the static read)\n\nWorking rules:\n- Instrument minimally and surgically; never spam logs everywhere\n- ALWAYS remove your instrumentation before finishing\n- Distinguish observed facts from inference\n- Prefer the existing logging/tracing facilities over ad-hoc prints`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Runtime tracing: instruments and runs code to observe call order, values, and timing, then cleans up.',\n keywords: [\n 'trace',\n 'runtime',\n 'instrument',\n 'execution path',\n 'what happens at runtime',\n 'call order',\n 'profile execution',\n 'observe behavior',\n 'stack trace',\n ],\n },\n },\n];\n","import { type AgentDefinition, HEAVY_BUDGET, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 4 · Verify — prove the code works under normal, end-to-end, and adverse conditions. */\nexport const VERIFY_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'test',\n name: 'Test',\n role: 'test',\n tools: [...TOOLS.build],\n prompt: `You are the Test agent. Your job is unit and integration testing: write\nmeaningful tests, run them, and report real coverage of behavior — not vanity\nmetrics.\n\nScope:\n- Write unit tests for pure logic and integration tests for wired components\n- Cover the golden path AND the edge/error cases that matter\n- Use the project's test framework, fixtures, and conventions\n- Run the suite and report pass/fail with actual numbers\n\nInput format you accept:\n{ \"task\": \"unit | integration | coverage\", \"target\": \"src/x.ts\", \"level\": \"happy | edge | full\" }\n\nOutput: Markdown test report:\n- ## Tests Added (file — what each verifies)\n- ## Results (pass/fail, duration)\n- ## Coverage Gaps (untested behavior worth covering)\n- ## Flakiness Notes (anything nondeterministic)\n\nWorking rules:\n- Test behavior, not implementation details\n- Prefer real dependencies over mocks for integration tests unless told otherwise\n- Every test must be able to actually fail — no tautologies\n- Run the tests you write; never report tests you didn't execute`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'verify',\n summary: 'Unit + integration testing: writes meaningful tests covering golden path and edge cases, runs the suite.',\n keywords: [\n 'test',\n 'unit test',\n 'integration test',\n 'write tests',\n 'coverage',\n 'test suite',\n 'vitest',\n 'jest',\n 'add tests',\n 'spec',\n ],\n },\n },\n {\n config: {\n id: 'e2e',\n name: 'E2E',\n role: 'e2e',\n tools: [...TOOLS.build, 'fetch'],\n prompt: `You are the E2E agent. Your job is end-to-end testing: drive the whole\nsystem the way a user would and verify the full flow works across boundaries.\n\nScope:\n- Author end-to-end scenarios that exercise real user journeys\n- Drive UI/CLI/API across process and network boundaries\n- Set up and tear down realistic test state\n- Capture failures with enough detail to reproduce (screenshots, logs)\n\nInput format you accept:\n{ \"task\": \"scenario | smoke | journey\", \"flow\": \"<user journey>\", \"surface\": \"ui | cli | api\" }\n\nOutput: Markdown e2e report:\n- ## Scenarios (each: steps → expected → actual)\n- ## Results (pass/fail per scenario)\n- ## Failures (repro steps + captured evidence)\n- ## Environment Notes (setup assumptions)\n\nWorking rules:\n- Test the real flow end to end; don't stub the thing under test\n- Make scenarios deterministic — control time, randomness, and external state\n- On failure, capture artifacts (logs/screenshots) for reproduction\n- Keep scenarios independent so one failure doesn't cascade`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'verify',\n summary: 'End-to-end testing: drives full user journeys across UI/CLI/API boundaries with reproducible failures.',\n keywords: [\n 'e2e',\n 'end to end',\n 'end-to-end',\n 'user journey',\n 'smoke test',\n 'playwright',\n 'cypress',\n 'full flow',\n 'browser test',\n 'acceptance test',\n ],\n },\n },\n {\n config: {\n id: 'performance',\n name: 'Performance',\n role: 'performance',\n tools: [...TOOLS.build, 'logs'],\n prompt: `You are the Performance agent. Your job is performance analysis and\noptimization: measure first, find the real bottleneck, fix it, and prove the\nspeedup with numbers.\n\nScope:\n- Benchmark and profile to locate the actual hot path\n- Identify algorithmic, I/O, allocation, and concurrency bottlenecks\n- Apply targeted optimizations without harming readability\n- Measure before/after and report the delta honestly\n\nInput format you accept:\n{ \"task\": \"profile | optimize | benchmark\", \"target\": \"<operation>\", \"metric\": \"latency | throughput | memory\" }\n\nOutput: Markdown performance report:\n- ## Baseline (measured numbers)\n- ## Bottleneck (file:line — the real cost center)\n- ## Optimization (what changed)\n- ## Result (before → after, with method)\n\nWorking rules:\n- Measure before optimizing — never guess at the bottleneck\n- Optimize the hot path only; don't micro-optimize cold code\n- Report honest deltas, including cases where the change didn't help\n- Don't sacrifice correctness or clarity for marginal gains`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'verify',\n summary: 'Performance analysis: benchmarks/profiles to find the real bottleneck, optimizes, proves speedup with numbers.',\n keywords: [\n 'performance',\n 'slow',\n 'optimize',\n 'bottleneck',\n 'profile',\n 'benchmark',\n 'latency',\n 'throughput',\n 'memory',\n 'speed up',\n 'too slow',\n ],\n },\n },\n {\n config: {\n id: 'chaos',\n name: 'Chaos',\n role: 'chaos',\n tools: [...TOOLS.build, 'logs'],\n prompt: `You are the Chaos agent. Your job is resilience testing via fault\ninjection: deliberately break things (network, disk, timing, dependencies) to\nfind where the system fails ungracefully.\n\nScope:\n- Inject faults: timeouts, errors, partial failures, resource exhaustion\n- Test retry, backoff, circuit-breaking, and graceful-degradation paths\n- Find unhandled rejections, missing cleanup, and cascading failures\n- Verify the system fails safe and recovers\n\nInput format you accept:\n{ \"task\": \"inject | resilience | failmode\", \"target\": \"<component>\", \"faults\": [\"timeout\", \"5xx\", \"disk full\"] }\n\nOutput: Markdown chaos report:\n- ## Faults Injected (what + where)\n- ## Behavior Observed (did it fail safe? recover?)\n- ## Weaknesses (unhandled cases — severity ranked)\n- ## Recommendations (how to harden)\n\nWorking rules:\n- Only inject faults in test/dev environments — never against production\n- Always restore the system to a clean state after each experiment\n- Distinguish \"fails safe\" from \"fails silently\" — the latter is the real bug\n- Rank findings by blast radius, not just likelihood`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'verify',\n summary: 'Resilience testing via fault injection: breaks network/disk/timing to find ungraceful failures and recovery gaps.',\n keywords: [\n 'chaos',\n 'resilience',\n 'fault injection',\n 'failure mode',\n 'fail safe',\n 'retry',\n 'circuit breaker',\n 'graceful degradation',\n 'inject failure',\n 'robustness',\n ],\n },\n },\n];\n","import { type AgentDefinition, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 5 · Review — read-only quality, security, a11y, and compliance gates. */\nexport const REVIEW_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'code-reviewer',\n name: 'Code Reviewer',\n role: 'code-reviewer',\n tools: [...TOOLS.inspect, 'git'],\n prompt: `You are the Code Reviewer agent. Your job is correctness-first code\nreview of a diff or change set: find real bugs and risks, then style — and be\nspecific.\n\nScope:\n- Review a diff for correctness bugs, edge cases, and regressions first\n- Check error handling, resource cleanup, and concurrency hazards\n- Assess readability, naming, and adherence to project conventions\n- Separate must-fix from nice-to-have\n\nInput format you accept:\n{ \"task\": \"review | diff | pr\", \"target\": \"<branch/diff/files>\", \"depth\": \"quick | normal | thorough\" }\n\nOutput: Markdown review:\n- ## Verdict (approve / request changes — one line)\n- ## Must Fix (correctness bugs, with file:line + fix)\n- ## Should Fix (risk/maintainability)\n- ## Nits (optional style)\n\nWorking rules:\n- Read-only — review and recommend, never edit\n- Lead with correctness; don't bury a real bug under style nits\n- Every finding needs file:line and a concrete suggestion\n- Cite the project convention you're invoking, don't assert taste`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'review',\n summary: 'Correctness-first code review of diffs/PRs: finds bugs, edge cases, and convention violations with fixes.',\n keywords: [\n 'review',\n 'code review',\n 'review pr',\n 'review diff',\n 'look over',\n 'feedback on code',\n 'quality',\n 'is this correct',\n 'check my code',\n ],\n },\n },\n {\n config: {\n id: 'security-reviewer',\n name: 'Security Reviewer',\n role: 'security-reviewer',\n tools: [...TOOLS.inspect, 'git'],\n prompt: `You are the Security Reviewer agent. Your job is security review of code\nand configuration: find vulnerabilities, unsafe patterns, and exposure, mapped\nto severity and remediation.\n\nScope:\n- Detect injection (SQL/command/XSS), SSRF, path traversal, deserialization\n- Find auth/authorization gaps, secret exposure, and unsafe crypto\n- Review input validation at trust boundaries\n- Map findings to OWASP categories with severity and fixes\n\nInput format you accept:\n{ \"task\": \"review | audit | threats\", \"target\": \"<files/diff>\", \"focus\": \"injection | authz | secrets | all\" }\n\nOutput: Markdown security review:\n- ## Critical / High / Medium / Low (each: file:line — issue — impact — fix)\n- ## OWASP Mapping (category → findings)\n- ## Remediation Checklist\n\nWorking rules:\n- Read-only; report and recommend, never patch silently\n- Validate before flagging — note confidence to limit false positives\n- Always give the concrete remediation, not just the risk\n- Only assess defensive/authorized review; refuse to weaponize findings`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'review',\n summary: 'Security review: finds injection/authz/secret/crypto issues mapped to OWASP severity with remediation.',\n keywords: [\n 'security review',\n 'security',\n 'vulnerability',\n 'vulnerabilities',\n 'owasp',\n 'injection',\n 'sql injection',\n 'xss',\n 'ssrf',\n 'authz',\n 'secrets',\n 'security audit',\n 'threat',\n 'unsafe',\n ],\n },\n },\n {\n config: {\n id: 'accessibility',\n name: 'Accessibility',\n role: 'accessibility',\n tools: [...TOOLS.read],\n prompt: `You are the Accessibility agent. Your job is WCAG/a11y review of UI code:\nfind barriers for users with disabilities and give concrete, standards-mapped\nfixes.\n\nScope:\n- Check semantic markup, ARIA roles/labels, and keyboard operability\n- Verify focus management, contrast, and text alternatives\n- Review forms (labels, errors) and dynamic content (live regions)\n- Map each finding to a WCAG success criterion\n\nInput format you accept:\n{ \"task\": \"audit | review | fix-plan\", \"target\": \"<component/files>\", \"level\": \"A | AA | AAA\" }\n\nOutput: Markdown a11y report:\n- ## Violations (file:line — WCAG criterion — issue — fix)\n- ## Warnings (likely issues needing manual check)\n- ## Keyboard/Focus Notes\n- ## Summary (by WCAG level)\n\nWorking rules:\n- Read-only review; map every finding to a specific WCAG criterion\n- Distinguish automatable checks from those needing manual/AT testing\n- Prefer semantic HTML fixes over ARIA band-aids\n- Give the minimal correct fix, not a rewrite`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'review',\n summary: 'WCAG/a11y review of UI: checks semantics, ARIA, keyboard, contrast; maps findings to success criteria.',\n keywords: [\n 'accessibility',\n 'a11y',\n 'wcag',\n 'aria',\n 'screen reader',\n 'keyboard navigation',\n 'contrast',\n 'disabled users',\n 'accessible',\n ],\n },\n },\n {\n config: {\n id: 'compliance',\n name: 'Compliance',\n role: 'compliance',\n tools: [...TOOLS.inspect],\n prompt: `You are the Compliance agent. Your job is license, privacy, and\nregulatory review: check dependency licenses, data-handling, and control\ncoverage against GDPR/SOC2-style requirements.\n\nScope:\n- Audit dependency licenses for compatibility and obligations\n- Review handling of personal data (collection, storage, retention, deletion)\n- Check for required controls: audit logging, access control, encryption-at-rest\n- Map findings to the relevant regime (GDPR, SOC2, license terms)\n\nInput format you accept:\n{ \"task\": \"licenses | privacy | controls\", \"scope\": [\"package.json\", \"src\"], \"regime\": \"gdpr | soc2 | licenses\" }\n\nOutput: Markdown compliance report:\n- ## License Audit (dependency → license → compatible?)\n- ## Data Handling (PII flows + gaps)\n- ## Control Coverage (required → present? → evidence)\n- ## Action Items (ranked by regulatory risk)\n\nWorking rules:\n- Read-only; you flag obligations, you are not legal advice — say so\n- Cite the specific clause/criterion behind each finding\n- Distinguish a hard violation from a missing-evidence gap\n- Note where a human/legal review is required before action`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'review',\n summary: 'License/privacy/regulatory review: audits licenses, PII handling, and controls vs GDPR/SOC2.',\n keywords: [\n 'compliance',\n 'license',\n 'gdpr',\n 'soc2',\n 'privacy',\n 'pii',\n 'data retention',\n 'regulatory',\n 'audit log',\n 'legal review',\n ],\n },\n },\n];\n","import { type AgentDefinition, HEAVY_BUDGET, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 6 · Domain — specialists for the major slices of a system. */\nexport const DOMAIN_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'database',\n name: 'Database',\n role: 'database',\n tools: [...TOOLS.build],\n prompt: `You are the Database agent. Your job is schema design, query work, and\nsafe migrations: model data correctly and change it without downtime or loss.\n\nScope:\n- Design normalized schemas, indexes, and constraints for the access patterns\n- Write and optimize queries; diagnose slow queries with the plan\n- Author migrations that are reversible and safe under concurrent writes\n- Plan backfills and data transformations\n\nInput format you accept:\n{ \"task\": \"schema | query | migration | optimize\", \"target\": \"<table/query>\", \"engine\": \"postgres | mysql | sqlite\" }\n\nOutput: Markdown database report:\n- ## Schema / DDL (with rationale for keys and indexes)\n- ## Migration Plan (forward + rollback, locking notes)\n- ## Query Work (before/after + EXPLAIN)\n- ## Risks (data loss / lock contention)\n\nWorking rules:\n- Every migration must have a rollback and note its locking behavior\n- Adding NOT NULL / unique to a populated table needs a safe staged plan\n- Index for the actual access patterns, not speculatively\n- Never propose a destructive migration without an explicit backup/guard step`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'Schema design, query optimization, and safe reversible migrations for SQL databases.',\n keywords: [\n 'database',\n 'schema',\n 'sql',\n 'migration',\n 'query',\n 'index',\n 'postgres',\n 'mysql',\n 'table',\n 'orm',\n 'slow query',\n ],\n },\n },\n {\n config: {\n id: 'api',\n name: 'API',\n role: 'api',\n tools: [...TOOLS.build, 'fetch'],\n prompt: `You are the API agent. Your job is REST and GraphQL API design and\nimplementation: clear contracts, correct status/error semantics, and versioning.\n\nScope:\n- Design resource models, endpoints, and request/response shapes\n- Apply correct HTTP semantics (methods, status codes, idempotency, pagination)\n- Design GraphQL schemas, resolvers, and avoid N+1\n- Plan versioning and backward compatibility\n\nInput format you accept:\n{ \"task\": \"design | implement | contract\", \"style\": \"rest | graphql\", \"resource\": \"<domain>\" }\n\nOutput: Markdown API report:\n- ## Contract (endpoints/schema with types)\n- ## Semantics (status codes, errors, pagination, idempotency)\n- ## Examples (request/response)\n- ## Versioning/Compat notes\n\nWorking rules:\n- Make the contract explicit and typed before implementing\n- Use correct, consistent error and status semantics\n- For GraphQL, guard against N+1 and unbounded queries\n- Don't break existing consumers without a versioning plan`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'REST + GraphQL API design and implementation: contracts, HTTP/GraphQL semantics, versioning.',\n keywords: [\n 'api',\n 'rest',\n 'graphql',\n 'endpoint',\n 'resolver',\n 'http',\n 'openapi',\n 'swagger',\n 'route',\n 'contract',\n 'webhook',\n ],\n },\n },\n {\n config: {\n id: 'auth',\n name: 'Auth',\n role: 'auth',\n tools: [...TOOLS.build],\n prompt: `You are the Auth agent. Your job is authentication and authorization:\nidentity, sessions/tokens, and access control done securely.\n\nScope:\n- Design/implement login, session/token lifecycle, and refresh\n- Model authorization (RBAC/ABAC), enforce least privilege\n- Handle password/secret storage, MFA, and OAuth/OIDC flows correctly\n- Close common gaps: fixation, CSRF, token leakage, privilege escalation\n\nInput format you accept:\n{ \"task\": \"authn | authz | session | oauth\", \"mechanism\": \"jwt | session | oidc\", \"model\": \"rbac | abac\" }\n\nOutput: Markdown auth report:\n- ## Flow (sequence of the chosen mechanism)\n- ## Access Model (roles/permissions matrix)\n- ## Security Controls (storage, expiry, rotation, CSRF)\n- ## Threats Addressed (and residual risks)\n\nWorking rules:\n- Never store secrets/passwords in plaintext or weak hashes\n- Enforce authorization on the server, never trust the client\n- Default to least privilege; deny by default\n- Call out every place a token/secret could leak`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'Authentication and authorization: identity, sessions/tokens, RBAC/ABAC, OAuth/OIDC, done securely.',\n keywords: [\n 'auth',\n 'authentication',\n 'authorization',\n 'login',\n 'session',\n 'jwt',\n 'oauth',\n 'oidc',\n 'rbac',\n 'permissions',\n 'token',\n 'sso',\n ],\n },\n },\n {\n config: {\n id: 'data',\n name: 'Data',\n role: 'data',\n tools: [...TOOLS.build],\n prompt: `You are the Data agent. Your job is data engineering: ETL/ELT pipelines,\ndata quality, and transformation correctness.\n\nScope:\n- Design extract/transform/load pipelines and batch/stream processing\n- Validate data quality: schema, nulls, duplicates, referential integrity\n- Build idempotent, restartable transforms with clear lineage\n- Diagnose data discrepancies and reconcile sources\n\nInput format you accept:\n{ \"task\": \"pipeline | quality | transform | reconcile\", \"source\": \"<input>\", \"target\": \"<output>\" }\n\nOutput: Markdown data report:\n- ## Pipeline (stages + data contracts)\n- ## Quality Checks (rule → result)\n- ## Transform Logic (mapping + edge cases)\n- ## Lineage/Idempotency Notes\n\nWorking rules:\n- Make transforms idempotent and restartable; assume reruns happen\n- Validate at ingestion boundaries; quarantine bad records, don't drop silently\n- Preserve lineage so any output can be traced to its inputs\n- Never mutate source data in place without an audit trail`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'Data engineering: ETL/ELT pipelines, data-quality validation, idempotent transforms, reconciliation.',\n keywords: [\n 'etl',\n 'elt',\n 'pipeline',\n 'data quality',\n 'data engineering',\n 'transform',\n 'ingestion',\n 'batch',\n 'stream',\n 'reconcile',\n 'dataset',\n ],\n },\n },\n {\n config: {\n id: 'frontend',\n name: 'Frontend',\n role: 'frontend',\n tools: [...TOOLS.build, 'fetch'],\n prompt: `You are the Frontend agent. Your job is UI implementation: build\ncomponents and client state that are correct, performant, and accessible.\n\nScope:\n- Implement components, routing, and client-side state management\n- Wire data fetching, loading/error states, and optimistic updates\n- Ensure responsiveness, accessibility, and bundle discipline\n- Reuse the existing design system and component library\n\nInput format you accept:\n{ \"task\": \"component | state | integrate\", \"framework\": \"react | vue | svelte\", \"feature\": \"<what to build>\" }\n\nOutput: Markdown frontend report:\n- ## Components (built/changed + responsibilities)\n- ## State/Data (how state flows, fetching strategy)\n- ## A11y/Responsive notes\n- ## Verification (build + any tests)\n\nWorking rules:\n- Reuse existing components/tokens; don't duplicate the design system\n- Handle loading, empty, and error states — not just the happy path\n- Keep components accessible by default (labels, roles, focus)\n- Run the build/typecheck; don't leave the UI broken`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'UI implementation: components, client state, data fetching, responsive and accessible by default.',\n keywords: [\n 'frontend',\n 'component',\n 'react',\n 'vue',\n 'svelte',\n 'client state',\n 'ui implementation',\n 'css',\n 'responsive',\n 'hook',\n 'render',\n ],\n },\n },\n {\n config: {\n id: 'backend',\n name: 'Backend',\n role: 'backend',\n tools: [...TOOLS.build],\n prompt: `You are the Backend agent. Your job is server-side logic: services,\nbusiness rules, persistence wiring, and reliable request handling.\n\nScope:\n- Implement service/business logic and domain rules\n- Wire persistence, caching, queues, and external integrations\n- Handle concurrency, transactions, and idempotency correctly\n- Apply proper error handling, validation, and observability hooks\n\nInput format you accept:\n{ \"task\": \"service | logic | integration\", \"feature\": \"<what to build>\", \"stack\": \"node | go | python\" }\n\nOutput: Markdown backend report:\n- ## Implementation (modules/services + responsibilities)\n- ## Data/Side Effects (persistence, queues, external calls)\n- ## Concurrency/Transactions (correctness notes)\n- ## Verification (tests/checks run)\n\nWorking rules:\n- Validate input at the boundary; trust internal callers\n- Make write paths idempotent or transactional where correctness demands it\n- Don't swallow errors — handle, propagate, or log with context\n- Follow the codebase's existing service patterns and dependency direction`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'Server-side logic: services, business rules, persistence/queue wiring, concurrency and transactions.',\n keywords: [\n 'backend',\n 'server',\n 'service',\n 'business logic',\n 'controller',\n 'handler',\n 'queue',\n 'cache',\n 'transaction',\n 'microservice',\n 'server-side',\n ],\n },\n },\n {\n config: {\n id: 'designer',\n name: 'Designer',\n role: 'designer',\n tools: [...TOOLS.docs],\n prompt: `You are the Designer agent. Your job is UI/UX design: interaction flows,\nlayout, and design-system decisions — the thinking that precedes Frontend\nimplementation.\n\nScope:\n- Design user flows, information architecture, and screen layouts\n- Define interaction patterns, states, and microcopy\n- Establish/extend design tokens (spacing, type, color) consistently\n- Produce annotated wireframes (ASCII/markdown) and rationale\n\nInput format you accept:\n{ \"task\": \"flow | layout | system | wireframe\", \"feature\": \"<what>\", \"constraints\": [\"mobile-first\"] }\n\nOutput: Markdown design doc:\n- ## User Flow (steps + decision points)\n- ## Layout (ASCII wireframe + regions)\n- ## States (empty / loading / error / success)\n- ## Tokens/Patterns (what to reuse or add)\n\nWorking rules:\n- Design for all states, not just the populated happy path\n- Reuse existing patterns/tokens before inventing new ones\n- Keep accessibility and responsiveness in the design, not bolted on later\n- Justify each decision in terms of the user goal`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'UI/UX design: user flows, layout/wireframes, interaction states, and design-system decisions.',\n keywords: [\n 'design',\n 'ux',\n 'ui design',\n 'wireframe',\n 'user flow',\n 'layout',\n 'design system',\n 'interaction',\n 'mockup design',\n 'information architecture',\n ],\n },\n },\n];\n","import { type AgentDefinition, LIGHT_BUDGET, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 7 · Knowledge — documentation, diagrams, localization, and prompts. */\nexport const KNOWLEDGE_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'document',\n name: 'Document',\n role: 'document',\n tools: [...TOOLS.docs],\n prompt: `You are the Document agent. Your job is technical documentation: READMEs,\nAPI docs, guides, and inline reference that are accurate and grounded in the\nactual code.\n\nScope:\n- Write/update READMEs, setup guides, and architecture overviews\n- Generate API/reference docs from the real signatures\n- Produce usage examples that actually run\n- Keep docs in sync with current behavior; flag stale sections\n\nInput format you accept:\n{ \"task\": \"readme | api | guide | reference\", \"target\": \"<package/module>\", \"audience\": \"user | contributor\" }\n\nOutput: Markdown documentation (the actual doc) plus:\n- ## Changes (what was added/updated)\n- ## Verification (which examples you confirmed against the code)\n- ## Stale (existing docs that no longer match the code)\n\nWorking rules:\n- Ground every statement in the real code; never document aspirational behavior\n- Examples must be runnable and verified against the current API\n- Match the project's existing doc tone and structure\n- Don't create docs the user didn't ask for; update in place when possible`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'knowledge',\n summary: 'Technical documentation: READMEs, API/reference docs, guides, and verified examples grounded in code.',\n keywords: [\n 'document',\n 'documentation',\n 'readme',\n 'docs',\n 'write up',\n 'guide',\n 'api docs',\n 'explain in writing',\n 'reference',\n 'changelog notes',\n ],\n },\n },\n {\n config: {\n id: 'uml',\n name: 'UML',\n role: 'uml',\n tools: [...TOOLS.read, 'write', 'edit'],\n prompt: `You are the UML agent. Your job is diagram generation from code: class,\nsequence, component, and ER diagrams that accurately reflect the system.\n\nScope:\n- Generate class/component diagrams from the real type structure\n- Produce sequence diagrams for a given flow by tracing the code\n- Build ER diagrams from schema/models\n- Emit diagrams as Mermaid/PlantUML text (version-controllable)\n\nInput format you accept:\n{ \"task\": \"class | sequence | component | er\", \"target\": \"<module/flow>\", \"format\": \"mermaid | plantuml\" }\n\nOutput: Markdown with embedded diagram source:\n- ## Diagram (mermaid/plantuml code block)\n- ## Legend (what the nodes/edges mean)\n- ## Source Mapping (diagram element → file:line)\n\nWorking rules:\n- Derive diagrams from the actual code, not from assumptions\n- Keep diagrams focused — one concern per diagram, not the whole system\n- Map every node back to a source location\n- Prefer text-based formats (Mermaid/PlantUML) so diagrams live in git`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'knowledge',\n summary: 'Diagram generation from code: class/sequence/component/ER diagrams as Mermaid/PlantUML.',\n keywords: [\n 'uml',\n 'diagram',\n 'mermaid',\n 'plantuml',\n 'sequence diagram',\n 'class diagram',\n 'er diagram',\n 'visualize',\n 'flowchart',\n 'architecture diagram',\n ],\n },\n },\n {\n config: {\n id: 'i18n',\n name: 'I18n',\n role: 'i18n',\n tools: [...TOOLS.write],\n prompt: `You are the I18n agent. Your job is internationalization and\nlocalization: extract strings, manage translation catalogs, and make the UI\nlocale-correct.\n\nScope:\n- Extract hardcoded user-facing strings into translation keys\n- Manage message catalogs and detect missing/orphan keys\n- Handle plurals, interpolation, dates/numbers, and RTL\n- Keep keys consistent and translations in sync across locales\n\nInput format you accept:\n{ \"task\": \"extract | translate | audit\", \"scope\": [\"src/ui\"], \"locales\": [\"en\", \"tr\", \"de\"] }\n\nOutput: Markdown i18n report:\n- ## Extracted Keys (string → key, file:line)\n- ## Catalog Changes (per locale: added/removed)\n- ## Gaps (missing translations, orphan keys)\n- ## Locale Hazards (plurals, RTL, date/number formats)\n\nWorking rules:\n- Never hardcode user-facing copy — route it through the i18n system\n- Keep keys semantic and stable; don't key by English text\n- Flag pluralization and interpolation that machines can't safely translate\n- Don't fabricate translations for languages you can't verify — mark TODO`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'knowledge',\n summary: 'Internationalization/localization: string extraction, catalog management, plurals/RTL/format handling.',\n keywords: [\n 'i18n',\n 'internationalization',\n 'localization',\n 'l10n',\n 'translation',\n 'translate ui',\n 'locale',\n 'rtl',\n 'message catalog',\n 'multilingual',\n ],\n },\n },\n {\n config: {\n id: 'prompt',\n name: 'Prompt',\n role: 'prompt',\n tools: [...TOOLS.write],\n prompt: `You are the Prompt agent. Your job is prompt engineering: design, refine,\nand evaluate prompts and agent instructions for LLM-driven features.\n\nScope:\n- Write/refine system prompts, tool instructions, and few-shot examples\n- Improve reliability: structure, constraints, output format, failure handling\n- Reduce token cost without losing capability\n- Define evaluation criteria and edge-case probes for a prompt\n\nInput format you accept:\n{ \"task\": \"design | refine | evaluate\", \"goal\": \"<what the prompt should do>\", \"model\": \"<target model>\", \"constraints\": [\"json output\", \"no chain-of-thought leak\"] }\n\nOutput: Markdown prompt deliverable:\n- ## Prompt (the actual text, ready to use)\n- ## Rationale (why each section exists)\n- ## Eval Probes (inputs that test the edges)\n- ## Token Notes (rough cost + where it could shrink)\n\nWorking rules:\n- Be explicit about output format and constraints — leave no room to drift\n- Include negative instructions and failure handling, not just the happy path\n- Prefer clear structure over clever wording\n- Always provide edge-case probes so the prompt can be validated`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'knowledge',\n summary: 'Prompt engineering: designs/refines/evaluates LLM system prompts and agent instructions.',\n keywords: [\n 'prompt',\n 'prompt engineering',\n 'system prompt',\n 'llm instructions',\n 'few-shot',\n 'refine prompt',\n 'agent instructions',\n 'prompt template',\n ],\n },\n },\n];\n","import { type AgentDefinition, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 8 · Delivery & Ops — ship it, run it, keep it healthy. */\nexport const DELIVERY_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'git',\n name: 'Git',\n role: 'git',\n tools: [...TOOLS.vcs, 'bash'],\n prompt: `You are the Git agent. Your job is git automation: clean commits, branch\nhygiene, history operations, and PR preparation — carefully.\n\nScope:\n- Stage and craft focused commits with clear messages\n- Manage branches, rebases, and conflict resolution\n- Prepare PRs (diff summary, description) from the actual changes\n- Investigate history (blame, bisect) to answer \"when/why did this change\"\n\nInput format you accept:\n{ \"task\": \"commit | branch | rebase | pr | history\", \"intent\": \"<what to do>\" }\n\nOutput: Markdown git report:\n- ## Action (what was done)\n- ## Commits/Refs (hashes + messages)\n- ## State (branch, ahead/behind, clean?)\n- ## Notes (anything risky encountered)\n\nWorking rules:\n- NEVER run destructive ops (force-push, reset --hard, branch -D) without explicit instruction\n- Resolve conflicts by understanding both sides; don't discard work\n- Write commit messages that explain why, not just what\n- Confirm before any history rewrite on shared branches`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'delivery',\n summary: 'Git automation: focused commits, branch/rebase/conflict handling, PR prep, history investigation.',\n keywords: [\n 'git',\n 'commit',\n 'branch',\n 'rebase',\n 'merge',\n 'pull request',\n 'pr',\n 'conflict',\n 'blame',\n 'bisect',\n 'cherry-pick',\n 'stash',\n ],\n },\n },\n {\n config: {\n id: 'release',\n name: 'Release',\n role: 'release',\n tools: [...TOOLS.vcs, 'bash', 'json'],\n prompt: `You are the Release agent. Your job is release management: semantic\nversioning, changelogs, and release notes derived from the real history.\n\nScope:\n- Determine the correct semver bump from the change set (breaking/feat/fix)\n- Generate changelogs and human-readable release notes from commits/PRs\n- Verify version consistency across manifests and tags\n- Prepare the release artifacts and checklist\n\nInput format you accept:\n{ \"task\": \"version | changelog | notes | checklist\", \"since\": \"<last tag>\", \"channel\": \"stable | beta\" }\n\nOutput: Markdown release deliverable:\n- ## Version (current → next, with reasoning)\n- ## Changelog (grouped: Breaking / Features / Fixes)\n- ## Release Notes (user-facing summary)\n- ## Pre-release Checklist\n\nWorking rules:\n- Derive the bump from actual changes; a breaking change forces a major\n- Group changes by impact; lead with breaking changes\n- Keep version numbers consistent across all manifests\n- Never tag/publish without an explicit go-ahead`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'delivery',\n summary: 'Release management: semver bumps, changelogs, and release notes derived from real history.',\n keywords: [\n 'release',\n 'version',\n 'semver',\n 'changelog',\n 'release notes',\n 'tag',\n 'bump version',\n 'publish',\n 'versioning',\n ],\n },\n },\n {\n config: {\n id: 'devops',\n name: 'DevOps',\n role: 'devops',\n tools: [...TOOLS.build],\n prompt: `You are the DevOps agent. Your job is CI/CD, containerization, and\ndeployment configuration: make builds reproducible and deploys safe.\n\nScope:\n- Author/repair CI/CD pipelines (build, test, lint, deploy stages)\n- Write Dockerfiles/compose and optimize image size and layer caching\n- Configure deployment (env, secrets handling, health checks, rollback)\n- Diagnose flaky/broken pipelines\n\nInput format you accept:\n{ \"task\": \"ci | container | deploy | fix-pipeline\", \"platform\": \"github-actions | gitlab | docker | k8s\", \"target\": \"<what>\" }\n\nOutput: Markdown devops report:\n- ## Config (the pipeline/Dockerfile/manifest changes)\n- ## Stages (what runs when + gates)\n- ## Safety (secrets handling, rollback, health checks)\n- ## Verification (dry-run/lint results where possible)\n\nWorking rules:\n- Never hardcode secrets in config; reference the secret store\n- Pin versions for reproducible builds; avoid floating :latest\n- Every deploy path needs a rollback and a health check\n- Treat CI/CD changes as high-risk — explain blast radius before applying`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'delivery',\n summary: 'CI/CD, containerization, and deployment config: reproducible builds and safe deploys with rollback.',\n keywords: [\n 'devops',\n 'ci',\n 'cd',\n 'ci/cd',\n 'pipeline',\n 'docker',\n 'dockerfile',\n 'kubernetes',\n 'k8s',\n 'deploy',\n 'github actions',\n 'container',\n ],\n },\n },\n {\n config: {\n id: 'observability',\n name: 'Observability',\n role: 'observability',\n tools: [...TOOLS.build, 'logs'],\n prompt: `You are the Observability agent. Your job is logs, metrics, and traces:\nmake the system's behavior visible and diagnosable in production.\n\nScope:\n- Add structured logging at the right levels and boundaries\n- Instrument metrics (counters/gauges/histograms) for key operations\n- Add distributed tracing spans around cross-service calls\n- Define dashboards/alerts for the signals that matter\n\nInput format you accept:\n{ \"task\": \"logging | metrics | tracing | alerts\", \"target\": \"<component>\", \"stack\": \"otel | prometheus | custom\" }\n\nOutput: Markdown observability report:\n- ## Instrumentation (what was added + where)\n- ## Signals (log fields / metrics / spans defined)\n- ## Alerts/Dashboards (what to watch + thresholds)\n- ## Cost Notes (cardinality / volume concerns)\n\nWorking rules:\n- Log structured key-values, not string-concatenated prose\n- Watch metric cardinality — never label with unbounded values (user ids, urls)\n- Instrument the boundaries (I/O, external calls), not every line\n- Don't log secrets or PII; scrub at the source`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'delivery',\n summary: 'Observability: structured logging, metrics, distributed tracing, and alerts/dashboards.',\n keywords: [\n 'observability',\n 'logging',\n 'metrics',\n 'tracing',\n 'telemetry',\n 'opentelemetry',\n 'otel',\n 'prometheus',\n 'monitoring',\n 'alert',\n 'dashboard',\n 'instrument',\n ],\n },\n },\n {\n config: {\n id: 'dependency',\n name: 'Dependency',\n role: 'dependency',\n tools: [...TOOLS.deps, 'bash'],\n prompt: `You are the Dependency agent. Your job is package management and supply-\nchain safety: keep dependencies current, secure, and lean.\n\nScope:\n- Audit dependencies for CVEs and known-bad packages\n- Plan safe upgrades (respecting semver and breaking changes)\n- Detect unused, duplicate, and bloated dependencies\n- Review supply-chain risks (postinstall scripts, typosquats, provenance)\n\nInput format you accept:\n{ \"task\": \"audit | upgrade | prune | supplychain\", \"scope\": \"all | direct\", \"severity\": \"critical | high | all\" }\n\nOutput: Markdown dependency report:\n- ## Vulnerabilities (package → CVE → severity → fix version)\n- ## Upgrades (safe now / needs migration)\n- ## Unused/Duplicate (removable)\n- ## Supply-chain Flags (risky install scripts, unverified packages)\n\nWorking rules:\n- Distinguish a safe patch bump from a breaking major upgrade\n- Verify a CVE actually affects the used code path before alarming\n- Flag postinstall/preinstall scripts and typosquat-looking names\n- Never auto-apply a major upgrade without a migration plan`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'delivery',\n summary: 'Package management + supply-chain safety: CVE audit, safe upgrades, pruning, install-script review.',\n keywords: [\n 'dependency',\n 'dependencies',\n 'package',\n 'npm',\n 'pnpm',\n 'cve',\n 'vulnerability scan',\n 'upgrade deps',\n 'audit',\n 'supply chain',\n 'outdated',\n 'lockfile',\n ],\n },\n },\n];\n","import { type AgentDefinition, LIGHT_BUDGET, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 9 · Meta — agents that improve the agent system itself. */\nexport const META_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'skill-manage',\n name: 'Skill Manager',\n role: 'skill-manage',\n tools: [...TOOLS.write],\n prompt: `You are the Skill Manager agent. Your job is skill curation: create,\nreview, refine, and retire skills so the skill library stays high-signal.\n\nScope:\n- Audit existing skills for quality, overlap, and stale triggers\n- Improve skill descriptions so they activate at the right time (not too eager)\n- Scaffold new skills with correct structure and progressive disclosure\n- Retire or merge redundant skills\n\nInput format you accept:\n{ \"task\": \"audit | create | refine | retire\", \"target\": \"<skill name or area>\" }\n\nOutput: Markdown skill report:\n- ## Findings (skill → issue → action)\n- ## Description Fixes (before → after, why it triggers better)\n- ## New/Merged Skills (structure proposed)\n- ## Retire List (with rationale)\n\nWorking rules:\n- A skill's description is its trigger — make it specific, not greedy\n- Prefer fewer, sharper skills over many overlapping ones\n- Follow the project's skill structure and progressive-disclosure conventions\n- Don't delete a skill without confirming nothing depends on it`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'meta',\n summary: 'Skill curation: audits, refines descriptions/triggers, scaffolds, and retires skills.',\n keywords: [\n 'skill',\n 'skills',\n 'curate skill',\n 'skill description',\n 'create skill',\n 'skill library',\n 'skill trigger',\n 'manage skills',\n ],\n },\n },\n {\n config: {\n id: 'self-improving',\n name: 'Self-Improving',\n role: 'self-improving',\n tools: [...TOOLS.inspect],\n prompt: `You are the Self-Improving agent. Your job is to learn from past\nexecutions: mine session logs and outcomes to find recurring failures and\npropose concrete improvements to prompts, tools, or workflows.\n\nScope:\n- Analyze session/agent execution logs for failure and inefficiency patterns\n- Correlate outcomes with prompts, tool usage, and budgets\n- Propose specific changes (prompt edits, budget tweaks, new guardrails)\n- Track whether prior recommendations actually helped\n\nInput format you accept:\n{ \"task\": \"analyze | propose | evaluate\", \"logs\": \"<session path/dir>\", \"focus\": \"failures | efficiency | cost\" }\n\nOutput: Markdown improvement report:\n- ## Patterns (recurring failure/inefficiency + frequency)\n- ## Root Causes (why, with evidence from logs)\n- ## Proposed Changes (concrete edits, ranked by expected impact)\n- ## Validation Plan (how to confirm the change helped)\n\nWorking rules:\n- Ground every recommendation in observed log evidence, not intuition\n- Quantify the problem (how often, how costly) before proposing a fix\n- Propose the smallest change that addresses the root cause\n- Mark recommendations that need A/B validation before adoption`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'meta',\n summary: 'Learns from execution logs: mines recurring failures/inefficiencies and proposes evidence-based improvements.',\n keywords: [\n 'self-improving',\n 'learn from',\n 'session logs',\n 'execution analysis',\n 'recurring failure',\n 'improve agents',\n 'post-mortem',\n 'retrospective',\n 'meta-analysis',\n ],\n },\n },\n {\n config: {\n id: 'context',\n name: 'Context',\n role: 'context',\n tools: [...TOOLS.inspect, 'remember', 'forget'],\n prompt: `You are the Context agent. Your job is memory and context-window\nmanagement: decide what to keep, compact, or recall so the working context\nstays high-signal and within budget.\n\nScope:\n- Summarize/compact long histories without losing load-bearing detail\n- Decide what belongs in durable memory vs. ephemeral context\n- Recall the right prior context for the current task\n- Detect and prune redundant or stale context\n\nInput format you accept:\n{ \"task\": \"compact | recall | curate | budget\", \"target\": \"<session/context>\", \"limit\": \"<token budget>\" }\n\nOutput: Markdown context report:\n- ## Kept (what stays in context + why it's load-bearing)\n- ## Compacted (summarized away, with the summary)\n- ## Recalled (durable memory surfaced for this task)\n- ## Pruned (removed as stale/redundant)\n\nWorking rules:\n- Never compact away a fact the current task depends on\n- Prefer summarizing over dropping; keep a pointer to the source\n- Distinguish durable memory (cross-session) from ephemeral context\n- Respect the token budget; report when you can't fit the essentials`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'meta',\n summary: 'Memory + context-window management: compaction, recall, and curation within a token budget.',\n keywords: [\n 'context',\n 'context window',\n 'memory',\n 'compact',\n 'summarize history',\n 'recall',\n 'token budget',\n 'prune context',\n 'remember',\n 'dfmt',\n ],\n },\n },\n {\n config: {\n id: 'cost',\n name: 'Cost',\n role: 'cost',\n tools: [...TOOLS.inspect],\n prompt: `You are the Cost agent. Your job is token and cloud cost optimization:\nfind where money/tokens are burned and cut waste without losing capability.\n\nScope:\n- Analyze token spend by model, prompt, and tool usage\n- Identify expensive patterns: oversized prompts, redundant calls, wrong model tier\n- Recommend model routing (cheap model for cheap tasks, premium where it pays)\n- Estimate savings of each recommendation\n\nInput format you accept:\n{ \"task\": \"analyze | optimize | route | estimate\", \"scope\": \"<session/feature>\", \"lever\": \"tokens | model | calls\" }\n\nOutput: Markdown cost report:\n- ## Spend Breakdown (by model / prompt / tool)\n- ## Waste (the costly patterns, with $ impact)\n- ## Recommendations (ranked by savings, with risk)\n- ## Estimated Savings (per recommendation)\n\nWorking rules:\n- Quantify in tokens AND dollars; don't hand-wave \"it's expensive\"\n- Recommend the cheapest model that still meets the quality bar\n- Prefer caching and prompt trimming before downgrading models\n- Flag any optimization that risks correctness or capability`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'meta',\n summary: 'Token/cloud cost optimization: finds spend waste, recommends model routing and trimming with $ estimates.',\n keywords: [\n 'cost',\n 'token cost',\n 'optimize cost',\n 'spend',\n 'cheaper',\n 'model routing',\n 'budget',\n 'expensive',\n 'reduce tokens',\n 'pricing',\n 'cloud cost',\n ],\n },\n },\n];\n","/**\n * Agent catalog aggregator.\n *\n * Collects every phase's `AgentDefinition[]` into:\n * - `ALL_AGENT_DEFINITIONS` — flat list, catalog order (phase 1 → 9)\n * - `AGENT_CATALOG` — keyed by role for O(1) lookup\n * - `AGENTS_BY_PHASE` — grouped for statusline / dispatcher tie-breaks\n *\n * `fleet.ts` derives `FLEET_ROSTER` + `FLEET_ROSTER_BUDGETS` from this, and the\n * dispatcher routes free-form tasks against `capability` metadata here.\n */\nimport type { AgentDefinition, AgentPhase } from './types.js';\nimport { DISCOVERY_AGENTS } from './phase1-discovery.js';\nimport { PLANNING_AGENTS } from './phase2-planning.js';\nimport { BUILD_AGENTS } from './phase3-build.js';\nimport { VERIFY_AGENTS } from './phase4-verify.js';\nimport { REVIEW_AGENTS } from './phase5-review.js';\nimport { DOMAIN_AGENTS } from './phase6-domain.js';\nimport { KNOWLEDGE_AGENTS } from './phase7-knowledge.js';\nimport { DELIVERY_AGENTS } from './phase8-delivery.js';\nimport { META_AGENTS } from './phase9-meta.js';\n\nexport * from './types.js';\nexport {\n DISCOVERY_AGENTS,\n PLANNING_AGENTS,\n BUILD_AGENTS,\n VERIFY_AGENTS,\n REVIEW_AGENTS,\n DOMAIN_AGENTS,\n KNOWLEDGE_AGENTS,\n DELIVERY_AGENTS,\n META_AGENTS,\n};\n\n/** Every catalog agent, in phase order. */\nexport const ALL_AGENT_DEFINITIONS: AgentDefinition[] = [\n ...DISCOVERY_AGENTS,\n ...PLANNING_AGENTS,\n ...BUILD_AGENTS,\n ...VERIFY_AGENTS,\n ...REVIEW_AGENTS,\n ...DOMAIN_AGENTS,\n ...KNOWLEDGE_AGENTS,\n ...DELIVERY_AGENTS,\n ...META_AGENTS,\n];\n\n/** Phase → its agents, for grouped display and dispatcher fallbacks. */\nexport const AGENTS_BY_PHASE: Record<AgentPhase, AgentDefinition[]> = {\n discovery: DISCOVERY_AGENTS,\n planning: PLANNING_AGENTS,\n build: BUILD_AGENTS,\n verify: VERIFY_AGENTS,\n review: REVIEW_AGENTS,\n domain: DOMAIN_AGENTS,\n knowledge: KNOWLEDGE_AGENTS,\n delivery: DELIVERY_AGENTS,\n meta: META_AGENTS,\n};\n\n/**\n * Role → definition. Built once at module load. Throws on a duplicate role so\n * a copy-paste collision fails loudly at startup instead of silently shadowing.\n */\nexport const AGENT_CATALOG: Record<string, AgentDefinition> = (() => {\n const map: Record<string, AgentDefinition> = {};\n for (const def of ALL_AGENT_DEFINITIONS) {\n const role = def.config.role;\n if (!role) {\n throw new Error(`Agent \"${def.config.name}\" is missing a role`);\n }\n if (map[role]) {\n throw new Error(`Duplicate agent role in catalog: \"${role}\"`);\n }\n map[role] = def;\n }\n return map;\n})();\n\n/** Role lookup helper. Returns undefined for unknown roles. */\nexport function getAgentDefinition(role: string): AgentDefinition | undefined {\n return AGENT_CATALOG[role];\n}\n","/**\n * Smart agent dispatcher.\n *\n * Routes a free-form task description to the best agent in the catalog using a\n * two-stage strategy:\n *\n * 1. Heuristic — keyword/phrase scoring against each agent's `capability`\n * metadata. Deterministic, instant, no provider call. Multi-word phrases\n * score higher than single words (they're more specific signals).\n *\n * 2. LLM fallback — when the heuristic is ambiguous (confidence below the\n * threshold, or no keyword hit at all) an injected `classifier` resolves\n * the tie. The classifier is provider-agnostic: callers wire it to any\n * `complete(prompt) => text` function via `makeLLMClassifier`, so core\n * stays free of provider dependencies and the path is unit-testable.\n *\n * If neither stage yields a confident pick, the dispatcher falls back to the\n * `executor` generalist rather than failing.\n */\nimport {\n AGENT_CATALOG,\n ALL_AGENT_DEFINITIONS,\n type AgentDefinition,\n} from './agents/index.js';\n\n/** Default agent used when nothing else matches — the generalist builder. */\nexport const DEFAULT_DISPATCH_ROLE = 'executor';\n\nexport interface DispatchCandidate {\n role: string;\n name: string;\n score: number;\n /** Capability keywords that matched the task text. */\n matched: string[];\n}\n\nexport type DispatchMethod = 'heuristic' | 'llm' | 'fallback';\n\nexport interface DispatchResult {\n role: string;\n definition: AgentDefinition;\n /** 0..1 — heuristic margin, or 1 when an LLM made a definite choice. */\n confidence: number;\n method: DispatchMethod;\n /** Human-readable explanation of why this agent was chosen. */\n reason: string;\n /** Runner-up candidates (top heuristic scorers), best-first. */\n alternatives: DispatchCandidate[];\n}\n\n/**\n * Provider-agnostic classifier seam. Given the task and the candidate agents\n * (role + summary), return the chosen role (and optional reason), or null to\n * decline. Wire via `makeLLMClassifier`.\n */\nexport type DispatchClassifier = (\n task: string,\n candidates: { role: string; name: string; summary: string }[],\n) => Promise<{ role: string; reason?: string } | null>;\n\nexport interface DispatchOptions {\n /** Optional LLM fallback for ambiguous tasks. */\n classifier?: DispatchClassifier;\n /** Heuristic confidence below this triggers the classifier. Default 0.4. */\n confidenceThreshold?: number;\n /** How many top candidates to offer the classifier. Default 6. */\n maxCandidates?: number;\n /** Override the catalog (testing). Defaults to the full `AGENT_CATALOG`. */\n catalog?: Record<string, AgentDefinition>;\n}\n\nfunction normalize(text: string): string {\n return ` ${text.toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim()} `;\n}\n\n/**\n * Score every agent against the task. A keyword hit adds 1 point; a multi-word\n * keyword phrase adds points equal to its word count (more specific = stronger\n * signal). Returns candidates sorted best-first, zero-score agents dropped.\n */\nexport function scoreAgents(\n task: string,\n catalog: Record<string, AgentDefinition> = AGENT_CATALOG,\n): DispatchCandidate[] {\n const hay = normalize(task);\n const out: DispatchCandidate[] = [];\n for (const def of Object.values(catalog)) {\n if (!def?.config?.role) continue;\n let score = 0;\n const matched: string[] = [];\n for (const kw of def.capability.keywords) {\n const needle = normalize(kw);\n if (hay.includes(needle.trimEnd() + ' ') || hay.includes(' ' + needle.trimStart())) {\n const words = kw.trim().split(/\\s+/).length;\n score += words;\n matched.push(kw);\n }\n }\n if (score > 0) {\n out.push({ role: def.config.role, name: def.config.name, score, matched });\n }\n }\n out.sort((a, b) => b.score - a.score);\n return out;\n}\n\n/**\n * Heuristic confidence from the score distribution: the margin between the top\n * candidate and the runner-up, scaled by the top score's strength. A clear\n * winner (high top, low second) approaches 1; a near-tie approaches 0.\n */\nfunction heuristicConfidence(candidates: DispatchCandidate[]): number {\n if (candidates.length === 0) return 0;\n const top = candidates[0]!.score;\n const second = candidates[1]?.score ?? 0;\n // Strength factor: a single weak match (score 1) shouldn't read as confident.\n const strength = Math.min(1, top / 3);\n const margin = (top - second + 1) / (top + 1);\n return Math.min(1, strength * margin);\n}\n\n/**\n * Route a task to the best agent. Async because the LLM fallback may run; the\n * pure-heuristic path resolves without awaiting anything.\n */\nexport async function dispatchAgent(\n task: string,\n opts: DispatchOptions = {},\n): Promise<DispatchResult> {\n const catalog = opts.catalog ?? AGENT_CATALOG;\n const threshold = opts.confidenceThreshold ?? 0.4;\n const maxCandidates = opts.maxCandidates ?? 6;\n\n const candidates = scoreAgents(task, catalog);\n const confidence = heuristicConfidence(candidates);\n const top = candidates[0];\n\n // Confident heuristic pick — done, no provider call.\n if (top && confidence >= threshold) {\n return {\n role: top.role,\n definition: catalog[top.role]!,\n confidence,\n method: 'heuristic',\n reason: `Matched keywords: ${top.matched.slice(0, 4).join(', ')}`,\n alternatives: candidates.slice(1, maxCandidates),\n };\n }\n\n // Ambiguous or no signal — ask the classifier if one is wired.\n if (opts.classifier) {\n // Offer the classifier the top heuristic candidates; if there were none,\n // offer the whole catalog so it can still choose.\n const pool = (candidates.length > 0\n ? candidates.slice(0, maxCandidates).map((c) => catalog[c.role]!)\n : ALL_AGENT_DEFINITIONS\n ).map((d) => ({\n role: d.config.role as string,\n name: d.config.name,\n summary: d.capability.summary,\n }));\n try {\n const choice = await opts.classifier(task, pool);\n if (choice && catalog[choice.role]) {\n return {\n role: choice.role,\n definition: catalog[choice.role]!,\n confidence: 1,\n method: 'llm',\n reason: choice.reason ?? 'Selected by LLM classifier',\n alternatives: candidates.slice(0, maxCandidates).filter((c) => c.role !== choice.role),\n };\n }\n } catch {\n // Classifier failure must not break dispatch — fall through to fallback.\n }\n }\n\n // Best heuristic guess if we have one, else the generalist.\n if (top) {\n return {\n role: top.role,\n definition: catalog[top.role]!,\n confidence,\n method: 'heuristic',\n reason: `Weak match (${top.matched.slice(0, 3).join(', ') || 'low signal'})`,\n alternatives: candidates.slice(1, maxCandidates),\n };\n }\n const fallbackRole = catalog[DEFAULT_DISPATCH_ROLE]\n ? DEFAULT_DISPATCH_ROLE\n : Object.keys(catalog)[0]!;\n return {\n role: fallbackRole,\n definition: catalog[fallbackRole]!,\n confidence: 0,\n method: 'fallback',\n reason: 'No keyword signal; defaulting to the generalist Executor',\n alternatives: [],\n };\n}\n\n/**\n * Build a `DispatchClassifier` from a minimal `complete(prompt) => text`\n * function. The caller supplies the provider call; this owns the prompt and\n * the parsing. Keeps `dispatcher` free of any provider import.\n */\nexport function makeLLMClassifier(\n complete: (prompt: string) => Promise<string>,\n): DispatchClassifier {\n return async (task, candidates) => {\n const list = candidates.map((c, i) => `${i + 1}. ${c.role} — ${c.summary}`).join('\\n');\n const prompt = `You are an agent router. Pick the single best agent for the task.\n\nTask:\n${task}\n\nAgents:\n${list}\n\nReply with ONLY a compact JSON object: {\"role\":\"<one role id from the list>\",\"reason\":\"<short why>\"}.\nDo not add prose, markdown, or code fences.`;\n const raw = (await complete(prompt)).trim();\n // Tolerate accidental code fences / surrounding text — extract first {...}.\n const match = raw.match(/\\{[\\s\\S]*\\}/);\n if (!match) return null;\n try {\n const parsed = JSON.parse(match[0]) as { role?: unknown; reason?: unknown };\n if (typeof parsed.role !== 'string') return null;\n const role = parsed.role.trim();\n const valid = candidates.some((c) => c.role === role);\n if (!valid) return null;\n return { role, reason: typeof parsed.reason === 'string' ? parsed.reason : undefined };\n } catch {\n return null;\n }\n };\n}\n","import type { ContentBlock, TextBlock } from './blocks.js';\nimport type { ErrorCode } from './errors.js';\nimport { WrongStackError, ERROR_CODES } from './errors.js';\nimport type { Message } from './messages.js';\nimport type { Tool } from './tool.js';\n\n/**\n * Token usage for a single provider call, normalized across providers.\n *\n * Disjoint semantics: the four fields never overlap. `input` is the count\n * of FRESH input tokens (billed at the full input rate); `cacheRead` and\n * `cacheWrite` are separate cached subsets each priced at their own rate.\n * The total context the model loaded for this turn is\n * `input + (cacheRead ?? 0) + (cacheWrite ?? 0)`.\n *\n * Provider quirks normalized at the adapter layer:\n * - Anthropic: returns `input_tokens` already disjoint from cache fields.\n * - OpenAI / OpenAI-compatible: `prompt_tokens` is the TOTAL including\n * cached portion; the adapter subtracts `cached_tokens` to stay disjoint.\n * - Google: `promptTokenCount` likewise includes cache; adapter subtracts\n * `cachedContentTokenCount`.\n *\n * Cost math and the context-fullness chip both depend on the disjoint\n * invariant — a TOTAL `input` plus a separate `cacheRead` count would bill\n * cached tokens twice and skew cache-hit-ratio reporting.\n */\nexport interface Usage {\n input: number;\n output: number;\n cacheRead?: number;\n cacheWrite?: number;\n}\n\nexport interface Capabilities {\n tools: boolean;\n parallelTools: boolean;\n vision: boolean;\n streaming: boolean;\n promptCache: boolean;\n systemPrompt: boolean;\n jsonMode: boolean;\n reasoning: boolean;\n maxContext: number;\n cacheControl: 'native' | 'auto' | 'none';\n}\n\nexport interface Request {\n model: string;\n system?: TextBlock[];\n messages: Message[];\n tools?: Tool[];\n maxTokens: number;\n temperature?: number;\n topP?: number;\n stopSequences?: string[];\n toolChoice?: 'auto' | 'required' | 'none' | { type: 'tool'; name: string };\n}\n\nexport type StopReason = 'end_turn' | 'tool_use' | 'max_tokens' | 'stop_sequence' | 'refusal';\n\nexport interface Response {\n content: ContentBlock[];\n stopReason: StopReason;\n usage: Usage;\n model: string;\n}\n\nexport type StreamEvent =\n | { type: 'message_start'; model: string }\n | {\n type: 'content_block_start';\n kind: 'text' | 'tool_use' | 'thinking';\n id?: string;\n name?: string;\n }\n | { type: 'content_block_stop'; index: number }\n | { type: 'text_delta'; text: string }\n | { type: 'tool_use_start'; id: string; name: string }\n | { type: 'tool_use_input_delta'; id: string; partial: string }\n | { type: 'tool_use_stop'; id: string; input: unknown; providerMeta?: Record<string, unknown> }\n | { type: 'thinking_start'; providerMeta?: Record<string, unknown> }\n | { type: 'thinking_delta'; text: string }\n | { type: 'thinking_signature'; signature: string }\n | { type: 'thinking_stop' }\n | { type: 'message_stop'; stopReason: StopReason; usage: Usage };\n\nexport interface Provider {\n readonly id: string;\n readonly capabilities: Capabilities;\n /** Canonical streaming entry point. `complete()` defaults to a wrapper that\n * aggregates this stream — providers may override for non-streaming wires. */\n stream(req: Request, opts: { signal: AbortSignal }): AsyncIterable<StreamEvent>;\n complete(req: Request, opts: { signal: AbortSignal }): Promise<Response>;\n}\n\n/**\n * Structured body parsed from a provider's HTTP error response. Populated\n * best-effort: providers return JSON shaped differently (Anthropic uses\n * `{error: {type, message}}`, OpenAI uses `{error: {message, code}}`,\n * Google uses `{error: {status, message}}`), so the fields here are the\n * intersection that's usable for rendering and routing.\n */\nexport interface ProviderErrorBody {\n /** Provider-specific kind, e.g. \"overloaded_error\", \"rate_limit_error\", \"invalid_request_error\". */\n type?: string;\n /** Human-readable explanation from the provider. */\n message?: string;\n /** Provider request id, when present in the body or headers. */\n requestId?: string;\n /** Parsed Retry-After header (or equivalent body hint) in milliseconds. */\n retryAfterMs?: number;\n /** The raw response body (truncated to ~2 KB), kept for debugging. */\n raw?: string;\n /** True when `raw` was truncated; check `rawLength` for the original size. */\n truncated?: boolean;\n /** Original length of the response body in bytes, when `truncated` is true. */\n rawLength?: number;\n}\n\nexport class ProviderError extends WrongStackError {\n public readonly status: number;\n public readonly retryable: boolean;\n public readonly providerId: string;\n public readonly body?: ProviderErrorBody;\n\n constructor(\n message: string,\n status: number,\n retryable: boolean,\n providerId: string,\n opts: { body?: ProviderErrorBody; cause?: unknown } = {},\n ) {\n super({\n message,\n code: providerStatusToCode(status, opts.body?.type),\n subsystem: 'provider',\n severity: status >= 500 ? 'error' : 'warning',\n recoverable: retryable,\n context: { providerId, status },\n cause: opts.cause,\n });\n this.name = 'ProviderError';\n this.status = status;\n this.retryable = retryable;\n this.providerId = providerId;\n this.body = opts.body;\n }\n\n /**\n * Render a one-line, user-facing description. Designed for the CLI/TUI\n * status line and the agent's retry warning. Avoids dumping raw JSON\n * (which is what users see today when a 529 lands and the log message\n * includes the full `{\"type\":\"error\",...}` body).\n *\n * Examples:\n * \"minimax-coding-plan overloaded (529): High traffic detected. Upgrade for highspeed model. [req 06534785201de9c0…]\"\n * \"openai rate limited (429): Retry after 12s\"\n * \"anthropic invalid request (400): messages.0.role must be one of 'user'|'assistant'\"\n * \"groq HTTP 500 (server error)\"\n */\n override describe(): string {\n const kind = describeStatus(this.status, this.body?.type);\n const head = `${this.providerId} ${kind}`;\n const detail = this.body?.message?.trim();\n const reqId = this.body?.requestId\n ? ` [req ${this.body.requestId.slice(0, 16)}${this.body.requestId.length > 16 ? '…' : ''}]`\n : '';\n if (detail && detail.length > 0) {\n return `${head}: ${truncate(detail, 240)}${reqId}`;\n }\n return `${head}${reqId}`;\n }\n}\n\nfunction describeStatus(status: number, type?: string): string {\n if (status === 0) return 'network error';\n if (type === 'overloaded_error' || status === 529) return `overloaded (${status})`;\n if (type === 'rate_limit_error' || status === 429) return `rate limited (${status})`;\n if (type === 'authentication_error' || status === 401) return `auth failed (${status})`;\n if (type === 'permission_error' || status === 403) return `forbidden (${status})`;\n if (type === 'not_found_error' || status === 404) return `not found (${status})`;\n if (type === 'invalid_request_error' || status === 400) return `invalid request (${status})`;\n if (status === 408) return `timeout (${status})`;\n if (status >= 500 && status < 600) return `HTTP ${status} (server error)`;\n if (type) return `${type} (${status})`;\n return `HTTP ${status}`;\n}\n\nfunction truncate(s: string, n: number): string {\n return s.length <= n ? s : `${s.slice(0, n - 1)}…`;\n}\n\nfunction providerStatusToCode(status: number, type?: string): ErrorCode {\n if (status === 0) return ERROR_CODES.PROVIDER_NETWORK_ERROR;\n if (type === 'rate_limit_error' || status === 429) return ERROR_CODES.PROVIDER_RATE_LIMITED;\n if (type === 'authentication_error' || status === 401) return ERROR_CODES.PROVIDER_AUTH_FAILED;\n if (type === 'overloaded_error' || status === 529) return ERROR_CODES.PROVIDER_OVERLOADED;\n if (type === 'invalid_request_error' || status === 400) return ERROR_CODES.PROVIDER_INVALID_REQUEST;\n if (status === 408) return ERROR_CODES.PROVIDER_NETWORK_ERROR;\n if (status >= 500) return ERROR_CODES.PROVIDER_SERVER_ERROR;\n return ERROR_CODES.PROVIDER_INVALID_REQUEST;\n}\n","/**\r\n * Pre-built subagent role configurations for the WrongStack fleet.\r\n * These can be passed to `MultiAgentHost.spawn()` or used as templates\r\n * for the director's roster.\r\n */\r\nimport type { SubagentConfig } from '../types/multi-agent.js';\r\nimport { ALL_AGENT_DEFINITIONS } from './agents/index.js';\r\n\r\n/**\r\n * Audit Log Agent — analyzes session logs, event streams, and traces.\r\n * Use for: post-mortems, trend analysis, operational insights.\r\n */\r\nexport const AUDIT_LOG_AGENT: SubagentConfig = {\r\n id: 'audit-log',\r\n name: 'Audit Log',\r\n role: 'audit-log',\r\n prompt: `You are the Audit Log agent. Your job is to analyze structured JSONL\r\nsession logs and produce actionable markdown reports.\r\n\r\nScope:\r\n- Parse session logs (iteration counts, tool calls, errors, usage)\r\n- Detect repeated failure patterns across multiple runs\r\n- Identify tool usage anomalies (over-use, failures, unexpected chains)\r\n- Track token consumption trends\r\n- Generate structured audit reports with severity ratings\r\n\r\nInput format you accept:\r\n{ \"task\": \"analyze | report | trends\", \"sessionPath\": \"<path>\", \"focus\": \"errors | tools | usage | all\" }\r\n\r\nOutput: Markdown audit report with sections:\r\n- ## Summary (totals, error rate)\r\n- ## Top Errors (count + context)\r\n- ## Tool Usage (table with calls, failures, avg duration)\r\n- ## Anomalies (pattern → severity)\r\n\r\nWorking rules:\r\n- Never fabricate numbers — read the actual logs first\r\n- Always include file:line references for errors\r\n- If sessionPath is missing, ask the director to provide it\r\n- Report confidence level: high (>90% accuracy), medium, low`,\r\n\r\n // No hardcoded budgets — the orchestrator (delegate tool or\r\n // spawn_subagent) decides per-task how much room a subagent gets.\r\n // A monorepo audit needs hours; a single-file lint check needs\r\n // seconds. Pinning a number here forces the orchestrator to fight\r\n // the role's default instead of just asking for what it needs.\r\n};\r\n\r\n/**\r\n * Bug Hunter Agent — systematic bug and code smell detection.\r\n * Use for: pre-refactoring health checks, code review, regression prevention.\r\n */\r\nexport const BUG_HUNTER_AGENT: SubagentConfig = {\r\n id: 'bug-hunter',\r\n name: 'Bug Hunter',\r\n role: 'bug-hunter',\r\n prompt: `You are the Bug Hunter agent. Your job is to systematically scan\r\nsource code for bugs, anti-patterns, and code smells using pattern matching\r\nand heuristics. Output a prioritized hit list with file:line references.\r\n\r\nScope:\r\n- Detect common bug patterns (uncaught errors, resource leaks, race conditions)\r\n- Identify anti-patterns (callback hell, God objects, circular deps)\r\n- Find TypeScript-specific issues (unsafe any, missing null checks, branded types)\r\n- Flag security-sensitive constructs (eval, innerHTML, hardcoded secrets)\r\n- Rank findings: critical > high > medium > low\r\n\r\nInput format you accept:\r\n{ \"task\": \"scan | hunt | check\", \"paths\": [\"src/**/*.ts\"], \"focus\": \"bugs | patterns | security | all\", \"severityThreshold\": \"medium\" }\r\n\r\nOutput: Markdown bug hunt report:\r\n- ## Critical (must fix first)\r\n- ## High (should fix)\r\n- ## Medium\r\n- ## Low (consider)\r\nEach entry: **[TYPE]** \\`file:line\\` — description + suggested fix\r\n\r\nBug pattern reference you know:\r\n| Pattern | Regex hint | Severity |\r\n|---------|------------|----------|\r\n| Uncaught promise | /\\.then\\\\(.*\\\\)/ without catch | high |\r\n| Event leak | on\\\\( without off/removeListener | high |\r\n| Hardcoded secret | [a-zA-Z0-9/_-]{20,} in config files | critical |\r\n| unsafe any | : any\\\\b or <any> | medium |\r\n| innerHTML | innerHTML\\\\s*= | high |\r\n\r\nWorking rules:\r\n- Never scan node_modules — it's noise\r\n- Always include file:line for every finding\r\n- If >30% of findings are false positives, note the confidence level\r\n- Ask director for clarification if paths are ambiguous`,\r\n\r\n // Budgets are set by the orchestrator per task — see fleet.ts header.\r\n};\r\n\r\n/**\r\n * Refactor Planner Agent — structured refactoring planning.\r\n * Use for: large rewrites, technical debt reduction, architecture improvements.\r\n */\r\nexport const REFACTOR_PLANNER_AGENT: SubagentConfig = {\r\n id: 'refactor-planner',\r\n name: 'Refactor Planner',\r\n role: 'refactor-planner',\r\n prompt: `You are the Refactor Planner agent. Your job is to analyze code\r\nstructure and produce a concrete, phased refactoring plan with risk\r\nassessment, dependency ordering, and rollback strategy.\r\n\r\nScope:\r\n- Map module-level dependencies (import graph)\r\n- Identify coupling hotspots (high fan-in/out modules)\r\n- Assess refactoring risk by complexity and test coverage\r\n- Generate phased plans with checkpoint milestones\r\n- Produce diff-friendly task lists (one task = one concern)\r\n\r\nInput format you accept:\r\n{ \"task\": \"plan | assess | roadmap\", \"target\": \"src/core\", \"constraint\": \"no-breaking-changes | minimal-downtime | full-rewrite\", \"focus\": \"architecture | performance | maintainability\" }\r\n\r\nOutput: Markdown refactor plan:\r\n- ## Phase 1: Low Risk / High Payoff (do first)\r\n Table: | # | Task | Module | Risk | Est. Time |\r\n- ## Phase 2: Medium Risk\r\n- ## Phase 3: High Risk (requires full regression)\r\n- ## Dependency Graph (abbreviated ASCII)\r\n- ## Rollback Strategy\r\n- ## Exit Criteria (checkbox list)\r\n\r\nRisk scoring criteria:\r\n| Factor | Low | Medium | High |\r\n|--------|-----|--------|------|\r\n| Cyclomatic complexity | <10 | 10-20 | >20 |\r\n| Test coverage | >80% | 50-80% | <50% |\r\n| Fan-out (imports) | <5 | 5-15 | >15 |\r\n\r\nWorking rules:\r\n- Always include rollback strategy — every refactor can fail\r\n- Merge tasks that take <1h into a single phase\r\n- Respect team constraints (reviewer availability, parallelization)\r\n- Never plan without analyzing the actual code first`,\r\n\r\n // Budgets are set by the orchestrator per task — see fleet.ts header.\r\n};\r\n\r\n/**\r\n * Security Scanner Agent — vulnerability and secret detection.\r\n * Use for: CI checks, pre-release audits, dependency vulnerability scanning.\r\n */\r\nexport const SECURITY_SCANNER_AGENT: SubagentConfig = {\r\n id: 'security-scanner',\r\n name: 'Security Scanner',\r\n role: 'security-scanner',\r\n prompt: `You are the Security Scanner agent. Your job is to scan code,\r\nconfigs, and dependencies for security issues from hardcoded secrets to\r\nsupply chain risks.\r\n\r\nScope:\r\n- Detect hardcoded secrets: API keys, tokens, passwords, private keys\r\n- Find injection vectors: eval, innerHTML, SQL concat, shell injection\r\n- Identify insecure patterns: weak crypto, hardcoded IVs, disabled TLS\r\n- Scan dependencies for known CVEs (via npm/pnpm audit)\r\n- Flag supply chain risks: postinstall hooks, unverified scripts, .npmrc\r\n\r\nInput format you accept:\r\n{ \"task\": \"scan | audit | secrets | dependencies\", \"paths\": [\"src\", \"config\"], \"depth\": \"quick | normal | deep\" }\r\n\r\nOutput: Markdown security report:\r\n- ## CRITICAL: Secrets Found (with code snippets)\r\n- ## HIGH: Injection Vectors\r\n- ## MEDIUM: Insecure Patterns\r\n- ## Dependency Issues (CVE list)\r\n- ## Summary table (severity → count)\r\n- ## Remediation Checklist (with checkboxes)\r\n\r\nSecret patterns you detect:\r\n| Pattern | Example | Severity |\r\n|---------|---------|----------|\r\n| AWS Access Key | AKIAIOSFODNN7EXAMPLE | critical |\r\n| AWS Secret Key | [a-zA-Z0-9/+=]{40} base64 | critical |\r\n| GitHub Token | ghp_[a-zA-Z0-9]{36} | critical |\r\n| Private Key PEM | -----BEGIN.*PRIVATE KEY----- | critical |\r\n| JWT | eyJ[a-zA-Z0-9_-]+ | high |\r\n\r\nInjection patterns:\r\n| Construct | Safe alternative |\r\n|-----------|-----------------|\r\n| eval(str) | new Function() or parse |\r\n| innerHTML = x | textContent or sanitize |\r\n| exec(\\`cmd \\${x}\\`) | execFile with args array |\r\n\r\nWorking rules:\r\n- Never scan node_modules — use npm audit instead\r\n- Always provide remediation steps, not just findings\r\n- Verify regex-based secrets before flagging (false positive risk)\r\n- When in doubt, flag as medium rather than ignoring potential issues`,\r\n\r\n // Budgets are set by the orchestrator per task — see fleet.ts header.\r\n};\r\n\r\n/**\r\n * Critic Agent — evaluates code quality, architecture decisions, and\r\n * refactoring plans against project conventions and engineering standards.\r\n * Use for: real-time evaluation of bug reports, refactor plans, and\r\n * architectural proposals during collaborative debugging sessions.\r\n */\r\nexport const CRITIC_AGENT: SubagentConfig = {\r\n id: 'critic',\r\n name: 'Critic',\r\n role: 'critic',\r\n prompt: `You are the Critic agent. Your job is to evaluate code quality,\r\narchitectural decisions, and proposed changes against project conventions,\r\nengineering standards, and known quality gates. You do not write code —\r\nyou judge it.\r\n\r\nScope:\r\n- Evaluate bug severity and fix quality from Bug Hunter reports\r\n- Score refactoring plans from Refactor Planner (risk, completeness, trade-offs)\r\n- Flag gaps in test coverage, error handling, and edge case coverage\r\n- Assess whether a proposed change aligns with existing project patterns\r\n- Detect over-engineering or under-engineering relative to the problem scope\r\n\r\nInput format you accept:\r\n{ \"task\": \"evaluate | score | review\", \"subject\": \"bug_report | refactor_plan | diff\", \"focus\": \"correctness | maintainability | risk | all\" }\r\n\r\nOutput: Markdown critic report:\r\n- ## Overall Score (0-10 with rationale)\r\n- ## Strengths (what's solid)\r\n- ## Weaknesses (what needs work)\r\n- ## Specific Concerns (with file:line when applicable)\r\n- ## Verdict: **Approve / Needs Revision / Reject**\r\n\r\nWorking rules:\r\n- Be specific — \"looks fine\" is not a review. Cite concrete evidence.\r\n- When scoring, explain the delta from a perfect score.\r\n- If you have no basis to evaluate a concern, say so rather than speculating.\r\n- Prioritise correctness over style; correctness issues block approval.\r\n- Score thresholds: ≥7 = Approve, 4-6 = Needs Revision, <4 = Reject`,\r\n\r\n // Budgets are set by the orchestrator per task — see fleet.ts header.\r\n};\r\n\r\n/**\r\n * All agents in a map for easy lookup by role. The four legacy pre-built\r\n * agents plus the phase 1-9 catalog (`ALL_AGENT_DEFINITIONS`). Catalog roles\r\n * are guaranteed collision-free by the catalog builder; none overlap the\r\n * legacy four.\r\n */\r\nexport const FLEET_ROSTER: Record<string, SubagentConfig> = {\r\n 'audit-log': AUDIT_LOG_AGENT,\r\n 'bug-hunter': BUG_HUNTER_AGENT,\r\n 'refactor-planner': REFACTOR_PLANNER_AGENT,\r\n 'security-scanner': SECURITY_SCANNER_AGENT,\r\n 'critic': CRITIC_AGENT,\r\n ...Object.fromEntries(\r\n ALL_AGENT_DEFINITIONS.map((d) => [d.config.role as string, d.config] as const),\r\n ),\r\n};\r\n\r\n// ---------------------------------------------------------------------------\r\n// Default per-role budgets.\r\n//\r\n// MASSIVELY RAISED from earlier values. User requested x5–x10 multiplier\r\n// to prevent any timeout or budget exhaustion on long-running tasks\r\n// like monorepo audits, deep refactors, and security scans.\r\n//\r\n// x10 values (realistic upper bound for a single subagent task):\r\n// audit-log: 7.5 hours, 5000 iterations, 15000 tool calls\r\n// bug-hunter: 10 hours, 8000 iterations, 20000 tool calls\r\n// refactor-planner: 7.5 hours, 6000 iterations, 18000 tool calls\r\n// security-scanner: 10 hours, 8000 iterations, 20000 tool calls\r\n//\r\n// These can be overridden per-call via delegate tool parameters.\r\n// ---------------------------------------------------------------------------\r\nexport interface FleetRosterBudget {\r\n timeoutMs?: number;\r\n /** Idle reap window (ms). Resets on activity — see `applyRosterBudget`. */\r\n idleTimeoutMs?: number;\r\n maxIterations?: number;\r\n maxToolCalls?: number;\r\n maxTokens?: number;\r\n maxCostUsd?: number;\r\n}\r\n\r\n/**\r\n * Default idle window for delegated subagents: reap only after this long with\r\n * NO activity (no iteration / tool call / streamed progress). An actively-\r\n * working agent resets this clock continuously, so it runs until its task\r\n * naturally ends — no more wall-clock kills of productive runs. Power users\r\n * can still impose a hard `timeoutMs` per delegate.\r\n */\r\nexport const DEFAULT_IDLE_TIMEOUT_MS = 15 * 60 * 1000;\r\n\r\nexport const FLEET_ROSTER_BUDGETS: Record<string, FleetRosterBudget> = {\r\n 'audit-log': { timeoutMs: 7.5 * 60 * 60 * 1000, maxIterations: 5000, maxToolCalls: 15000 },\r\n 'bug-hunter': { timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000 },\r\n 'refactor-planner': { timeoutMs: 7.5 * 60 * 60 * 1000, maxIterations: 6000, maxToolCalls: 18000 },\r\n 'security-scanner': { timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000 },\r\n 'critic': { timeoutMs: 5 * 60 * 60 * 1000, maxIterations: 4000, maxToolCalls: 12000 },\r\n ...Object.fromEntries(\r\n ALL_AGENT_DEFINITIONS.map((d) => [d.config.role as string, d.budget] as const),\r\n ),\r\n};\r\n\r\n/**\r\n * Apply roster budget to a config (only when the config has no explicit\r\n * budget fields set). This is called by the coordinator before dispatch.\r\n */\r\n// Generic default budget applied when no role matches and no explicit budget\r\n// fields are set. Used for `name` / free-form delegates. There is no default\r\n// wall-clock timeout — a delegated agent runs until its task naturally ends\r\n// (`end_turn`) or it stalls past the idle window. Iteration / tool-call ceilings\r\n// remain as a runaway backstop.\r\nconst GENERIC_SUBAGENT_BUDGET: FleetRosterBudget = {\r\n idleTimeoutMs: DEFAULT_IDLE_TIMEOUT_MS,\r\n maxIterations: 5000,\r\n maxToolCalls: 15000,\r\n};\r\n\r\nexport function applyRosterBudget(cfg: SubagentConfig): SubagentConfig {\r\n // First try role-specific budget; fall back to generic for name-only delegates.\r\n const roleBudget = cfg.role ? FLEET_ROSTER_BUDGETS[cfg.role] : undefined;\r\n const defaultBudget = roleBudget ?? (cfg.name ? GENERIC_SUBAGENT_BUDGET : undefined);\r\n if (!defaultBudget) return cfg;\r\n return {\r\n ...cfg,\r\n // Wall-clock cap is opt-in only: forward an explicit `cfg.timeoutMs`, but\r\n // do NOT impose the roster's historical multi-hour wall-clock default — it\r\n // killed agents that were still actively working. Reaping is idle-based.\r\n timeoutMs: cfg.timeoutMs,\r\n // Idle window is the default reaper. Resets on activity, so a long-but-\r\n // productive run is never killed; only a genuine stall is reaped.\r\n idleTimeoutMs: cfg.idleTimeoutMs ?? defaultBudget.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS,\r\n maxIterations: cfg.maxIterations ?? defaultBudget.maxIterations,\r\n maxToolCalls: cfg.maxToolCalls ?? defaultBudget.maxToolCalls,\r\n maxTokens: cfg.maxTokens ?? defaultBudget.maxTokens,\r\n maxCostUsd: cfg.maxCostUsd ?? defaultBudget.maxCostUsd,\r\n };\r\n}\r\n\r\n/** Quick-access list for spawning all at once. */\r\nexport const ALL_FLEET_AGENTS = Object.values(FLEET_ROSTER);\r\n\r\n// ---------------------------------------------------------------------------\r\n// ACP external agents — WrongStack spawns these as subagents via ACP protocol.\r\n// Each agent runs its own loop; WrongStack sends tasks as ACP messages and\r\n// receives results. These don't go through makeAgentSubagentRunner — they\r\n// are handled by makeACPSubagentRunner in the CLI multi-agent layer.\r\n// ---------------------------------------------------------------------------\r\n\r\n/**\r\n * Cline — ACP-compatible coding agent by @asonix.\r\n * Spawned as: `npx @agentify/cline`\r\n */\r\nexport const CLINE_AGENT: SubagentConfig = {\r\n id: 'cline',\r\n name: 'Cline',\r\n role: 'cline',\r\n prompt: `You are Cline, a coding agent. You help write, edit, and navigate code.\r\nYou operate by receiving tasks via ACP and returning results.\r\nWhen asked to code, make focused changes and explain them briefly.`,\r\n provider: 'acp',\r\n};\r\n\r\n/**\r\n * Gemini CLI — Google's ACP-compatible command-line agent.\r\n * Spawned as: `gemini` (when gemini CLI is installed and in PATH)\r\n */\r\nexport const GEMINI_CLI_AGENT: SubagentConfig = {\r\n id: 'gemini-cli',\r\n name: 'Gemini CLI',\r\n role: 'gemini-cli',\r\n prompt: `You are Gemini CLI, a coding agent powered by Google's Gemini model.\r\nYou help with code generation, editing, debugging, and best practices.\r\nYou operate by receiving tasks via ACP and returning results.`,\r\n provider: 'acp',\r\n};\r\n\r\n/**\r\n * GitHub Copilot (public preview) — ACP-compatible Copilot CLI agent.\r\n * Spawned as: `gh copilot` (when gh CLI with copilot extension is installed)\r\n */\r\nexport const COPILOT_AGENT: SubagentConfig = {\r\n id: 'copilot',\r\n name: 'GitHub Copilot',\r\n role: 'copilot',\r\n prompt: `You are GitHub Copilot, an AI coding assistant.\r\nYou help write, explain, refactor, and review code.\r\nYou operate by receiving tasks via ACP and returning results.`,\r\n provider: 'acp',\r\n};\r\n\r\n/**\r\n * OpenHands — AI coding agent by all-in.ai, ACP-compatible.\r\n * Spawned as: `openhands` (when installed)\r\n */\r\nexport const OPENHANDS_AGENT: SubagentConfig = {\r\n id: 'openhands',\r\n name: 'OpenHands',\r\n role: 'openhands',\r\n prompt: `You are OpenHands, an AI coding agent that can use tools to interact\r\nwith files, terminals, browsers, and other resources.\r\nYou operate by receiving tasks via ACP and returning results.`,\r\n provider: 'acp',\r\n};\r\n\r\n/**\r\n * Goose — IDE agent by ExoRL, ACP-compatible.\r\n * Spawned as: `goose` (when goose CLI is installed)\r\n */\r\nexport const GOOSE_AGENT: SubagentConfig = {\r\n id: 'goose',\r\n name: 'Goose',\r\n role: 'goose',\r\n prompt: `You are Goose, an AI agent that helps with coding tasks.\r\nYou operate by receiving tasks via ACP and returning results.\r\nFocus on writing high-quality, well-tested code.`,\r\n provider: 'acp',\r\n};\r\n\r\n/** All ACP external agents. */\r\nexport const ACP_AGENTS: SubagentConfig[] = [\r\n CLINE_AGENT,\r\n GEMINI_CLI_AGENT,\r\n COPILOT_AGENT,\r\n OPENHANDS_AGENT,\r\n GOOSE_AGENT,\r\n];\r\n\r\n// ACP agents share the same generous budgets as the built-in fleet agents.\r\n// External ACP agents may need more time than typical in-process subagents\r\n// since they run their own loops and may do tool-call round-trips.\r\nFLEET_ROSTER_BUDGETS['cline'] = {timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000};\r\nFLEET_ROSTER_BUDGETS['gemini-cli'] = {timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000};\r\nFLEET_ROSTER_BUDGETS['copilot'] = {timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000};\r\nFLEET_ROSTER_BUDGETS['openhands'] = {timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000};\r\nFLEET_ROSTER_BUDGETS['goose'] = {timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000};\r\n\r\n/** Extended roster including ACP agents. */\r\nexport const FLEET_ROSTER_WITHACP: Record<string, SubagentConfig> = {\r\n ...FLEET_ROSTER,\r\n ...Object.fromEntries(ACP_AGENTS.map((a) => [a.role as string, a])),\r\n};\r\n","/**\n * Subagent nickname pool — famous scientists, mathematicians, and computing pioneers.\n * Names are grouped by domain affinity so the nickname hints at the agent's role.\n */\n\nconst NICKNAME_POOL = {\n // Physics & fundamental sciences\n 'einstein': { name: 'Einstein', domain: 'physics' },\n 'newton': { name: 'Newton', domain: 'physics' },\n 'feynman': { name: 'Feynman', domain: 'physics' },\n 'dirac': { name: 'Dirac', domain: 'physics' },\n 'bohr': { name: 'Bohr', domain: 'physics' },\n 'planck': { name: 'Planck', domain: 'physics' },\n 'curie': { name: 'Curie', domain: 'physics' },\n 'fermi': { name: 'Fermi', domain: 'physics' },\n 'heisenberg': { name: 'Heisenberg', domain: 'physics' },\n 'schrodinger': { name: 'Schrödinger', domain: 'physics' },\n\n // Mathematics\n 'euclid': { name: 'Euclid', domain: 'math' },\n 'gauss': { name: 'Gauss', domain: 'math' },\n 'turing': { name: 'Turing', domain: 'math' },\n 'poincare': { name: 'Poincaré', domain: 'math' },\n 'riemann': { name: 'Riemann', domain: 'math' },\n 'hilbert': { name: 'Hilbert', domain: 'math' },\n 'pythagoras': { name: 'Pythagoras', domain: 'math' },\n\n // Computing & information theory\n 'von-neumann': { name: 'Von Neumann', domain: 'computing' },\n 'shannon': { name: 'Shannon', domain: 'computing' },\n 'hopper': { name: 'Hopper', domain: 'computing' },\n 'backus': { name: 'Backus', domain: 'computing' },\n 'knuth': { name: 'Knuth', domain: 'computing' },\n 'torvalds': { name: 'Torvalds', domain: 'computing' },\n 'stallman': { name: 'Stallman', domain: 'computing' },\n 'berners-lee': { name: 'Berners-Lee', domain: 'computing' },\n 'babbage': { name: 'Babbage', domain: 'computing' },\n 'lovelace': { name: 'Lovelace', domain: 'computing' },\n 'klein': { name: 'Klein', domain: 'computing' },\n\n // Electronics & electrical engineering\n 'edison': { name: 'Edison', domain: 'ee' },\n 'tesla': { name: 'Tesla', domain: 'ee' },\n 'faraday': { name: 'Faraday', domain: 'ee' },\n 'maxwell': { name: 'Maxwell', domain: 'ee' },\n 'ohm': { name: 'Ohm', domain: 'ee' },\n 'bell': { name: 'Bell', domain: 'ee' },\n 'marconi': { name: 'Marconi', domain: 'ee' },\n 'lamarr': { name: 'Lamarr', domain: 'ee' },\n\n // General science / multi-disciplinary\n 'darwin': { name: 'Darwin', domain: 'biology' },\n 'mendel': { name: 'Mendel', domain: 'biology' },\n 'pasteur': { name: 'Pasteur', domain: 'biology' },\n 'hawking': { name: 'Hawking', domain: 'cosmology' },\n 'sagan': { name: 'Sagan', domain: 'cosmology' },\n\n // Exploration & navigation\n 'columbus': { name: 'Columbus', domain: 'exploration' },\n 'polo': { name: 'Polo', domain: 'exploration' },\n 'magellan': { name: 'Magellan', domain: 'exploration' },\n\n // Chemistry / materials\n 'lavoisier': { name: 'Lavoisier', domain: 'chemistry' },\n 'mendeleev': { name: 'Mendeleev', domain: 'chemistry' },\n} as const;\n\n/** Flat ordered list of all available nicknames — used for round-robin. */\nconst ALL_NICKNAMES = Object.values(NICKNAME_POOL);\n\n/** Domain → preferred nickname keys (fallback chain). */\nconst DOMAIN_PREFERENCES: Record<string, string[]> = {\n 'security': ['shannon', 'turing', 'lamarr', 'stallman'],\n 'bug-hunter': ['darwin', 'curie', 'feynman', 'fermi'],\n 'refactor': ['gauss', 'hilbert', 'euclid', 'planck'],\n 'audit-log': ['sagan', 'hawking', 'poincare', 'newton'],\n 'planner': ['hilbert', 'gauss', 'turing', 'euclid'],\n 'researcher': ['sagan', 'hawking', 'darwin', 'pasteur'],\n 'explorer': ['marconi', 'bell', 'columbus', 'polo'],\n 'testing': ['pasteur', 'curie', 'fermi', 'bohr'],\n 'frontend': ['lovelace', 'hopper', 'babbage', 'backus'],\n 'backend': ['torvalds', 'stallman', 'von-neumann', 'backus'],\n 'database': ['turing', 'shannon', 'backus', 'knuth'],\n 'devops': ['tesla', 'edison', 'faraday', 'bell'],\n 'security-scanner': ['shannon', 'turing', 'lamarr', 'stallman'],\n 'refactor-planner': ['gauss', 'hilbert', 'planck', 'newton'],\n 'architect': ['von-neumann', 'turing', 'gauss', 'hilbert'],\n 'critic': ['einstein', 'feynman', 'dirac', 'bohr'],\n 'e2e': ['hopper', 'bell', 'marconi', 'tesla'],\n 'performance': ['knuth', 'gauss', 'planck', 'feynman'],\n 'chaos': ['tesla', 'edison', 'curie', 'fermi'],\n 'cost': ['ohm', 'bell', 'marconi', 'tesla'],\n // default fallback\n 'default': ['einstein', 'newton', 'curie', 'tesla', 'edison', 'turing', 'shannon', 'hopper', 'knuth', 'stallman'],\n};\n\ntype NicknameKey = keyof typeof NICKNAME_POOL;\n\n/**\n * Assign a unique nickname to a subagent based on its role.\n * Returns `Name (Role)` formatted string, e.g. `Einstein (Bug Hunter)`.\n *\n * @param role - The subagent's role id (e.g. 'bug-hunter', 'security-scanner')\n * @param used - Set of nickname keys already assigned in this fleet\n * (so no two subagents share the same base name)\n */\nexport function assignNickname(role: string, used: ReadonlySet<string>): string {\n // 1. Build preference list: role-specific → default fallback\n const preferences = [\n ...(DOMAIN_PREFERENCES[role] ?? []),\n ...(DOMAIN_PREFERENCES['default'] ?? []),\n ];\n\n // 2. Find the first unassigned nickname from preferences. Skip keys that are\n // not in the pool — preference lists can drift out of sync with the pool\n // (typos, removed names), and an unknown key must not crash assignment.\n for (const key of preferences) {\n const entry = NICKNAME_POOL[key as NicknameKey];\n if (entry && !used.has(key)) {\n return `${entry.name} (${formatRole(role)})`;\n }\n }\n\n // 3. Exhausted preferences — pick the first unused name round-robin style\n for (const entry of ALL_NICKNAMES) {\n const key = Object.entries(NICKNAME_POOL).find(([, v]) => v.name === entry.name)?.[0];\n if (key && !used.has(key)) {\n return `${entry.name} (${formatRole(role)})`;\n }\n }\n\n // 4. Pool exhausted — append counter to last resort\n const counter = used.size + 1;\n return `Scientist #${counter} (${formatRole(role)})`;\n}\n\n/** Format role id into human-readable title-case. */\nfunction formatRole(role: string): string {\n return role\n .split(/[-_]/)\n .map((w) => w.charAt(0).toUpperCase() + w.slice(1))\n .join(' ');\n}\n\n/**\n * Returns all available nickname keys. Useful for testing or reset logic.\n */\nexport function getAllNicknameKeys(): string[] {\n return Object.keys(NICKNAME_POOL);\n}","import { randomUUID } from 'node:crypto';\r\nimport { EventEmitter } from 'node:events';\r\nimport type { AgentBridge, BridgeMessage } from '../types/agent-bridge.js';\r\nimport type {\r\n CoordinatorStatus,\r\n MultiAgentConfig,\r\n MultiAgentCoordinator,\r\n SpawnResult,\r\n SubagentConfig,\r\n SubagentContext,\r\n SubagentError,\r\n SubagentErrorKind,\r\n SubagentRunContext,\r\n SubagentRunner,\r\n TaskResult,\r\n TaskSpec,\r\n} from '../types/multi-agent.js';\r\nimport { ProviderError } from '../types/provider.js';\r\nimport { BudgetExceededError, SubagentBudget } from './subagent-budget.js';\r\nimport { applyRosterBudget } from './fleet.js';\r\nimport { assignNickname } from './subagent-nicknames.js';\r\n\r\ntype SubagentStatus = 'running' | 'idle' | 'stopped' | 'error';\r\n\r\ninterface SubagentEntry {\r\n config: SubagentConfig;\r\n context: SubagentContext;\r\n status: SubagentStatus;\r\n currentTask?: string;\r\n abortController: AbortController;\r\n /** Lazily created on first dispatch — budget is per-task, not per-subagent. */\r\n activeBudget?: SubagentBudget;\r\n}\r\n\r\nexport interface MultiAgentCoordinatorOptions {\r\n /**\r\n * Callback that executes a task on behalf of a subagent. Required for\r\n * `assign()` to actually run anything — without it, tasks queue forever.\r\n * The coordinator provides per-subagent isolation (own budget, own signal,\r\n * own bridge) and enforces timeout + concurrency.\r\n */\r\n runner?: SubagentRunner;\r\n}\r\n\r\nexport class DefaultMultiAgentCoordinator extends EventEmitter implements MultiAgentCoordinator {\r\n readonly coordinatorId: string;\r\n readonly config: MultiAgentConfig;\r\n private runner?: SubagentRunner;\r\n private fleetBus?: import('./fleet-bus.js').FleetBus;\r\n\r\n private readonly subagents = new Map<string, SubagentEntry>();\r\n\r\n /**\r\n * Base nickname keys already handed out this run (e.g. `einstein`, `tesla`).\r\n * Prevents two workers sharing a name. Direct `coordinator.spawn()` callers\r\n * (parallel/eternal engine, SDD parallel run) don't go through\r\n * `Director.spawn()` where nicknames are normally assigned, so the\r\n * coordinator upgrades placeholder names (\"Executor\", \"slot-ab12cd\", role\r\n * names) to memorable ones here — that's what surfaces in the fleet monitor.\r\n */\r\n private readonly usedNicknames = new Set<string>();\r\n /** Maps subagentId → nickname key (e.g. 'einstein'). Used to free the slot on remove(). */\r\n private readonly subagentNicknames = new Map<string, string>();\r\n\r\n private pendingTasks: TaskSpec[] = [];\r\n private completedResults: TaskResult[] = [];\r\n /** Prevents completedResults from growing unbounded in long-running coordinators. */\r\n private static readonly MAX_COMPLETED_RESULTS = 10_000;\r\n private totalIterations = 0;\r\n private inFlight = 0;\r\n /**\r\n * Subagents currently being stopped. Set on entry to `stop()`, cleared\r\n * once `recordCompletion` lands the terminal TaskResult. Used by\r\n * `runDispatched` and `findIdleSubagent` to refuse mid-flight dispatch\r\n * to a subagent the caller has already asked to terminate — closes the\r\n * assign+terminate race where a fresh task could land on a worker that\r\n * was about to be killed.\r\n */\r\n private readonly terminating = new Set<string>();\r\n\r\n constructor(config: MultiAgentConfig, options: MultiAgentCoordinatorOptions = {}) {\r\n super();\r\n this.coordinatorId = config.coordinatorId;\r\n this.config = config;\r\n this.runner = options.runner;\r\n }\r\n\r\n /**\r\n * Replace the runner after construction. Used when the runner depends\r\n * on infrastructure (e.g. FleetBus) that isn't available until after\r\n * the coordinator's owning Director is built.\r\n */\r\n setRunner(runner: SubagentRunner): void {\r\n this.runner = runner;\r\n }\r\n\r\n /**\r\n * Wire a FleetBus for director-mode event emission. Call after the\r\n * FleetManager is constructed so the coordinator can emit lifecycle\r\n * events the TUI and monitoring tools subscribe to.\r\n */\r\n setFleetBus(fleet: import('./fleet-bus.js').FleetBus): void {\r\n this.fleetBus = fleet;\r\n }\r\n\r\n /**\r\n * Change the in-flight dispatch ceiling at runtime. Lowering does NOT\r\n * preempt running tasks — already-dispatched subagents finish their\r\n * current task; only future dispatches respect the new cap. Raising\r\n * immediately tries to fill the freed slots from the pending queue.\r\n */\r\n setMaxConcurrent(n: number): void {\r\n if (!Number.isFinite(n) || n < 1) {\r\n throw new Error(`maxConcurrent must be a finite integer >= 1, got ${n}`);\r\n }\r\n this.config.maxConcurrent = Math.floor(n);\r\n this.tryDispatchNext();\r\n }\r\n\r\n /**\r\n * Upgrade a placeholder/role-derived name to a memorable scientist nickname\r\n * (e.g. \"Einstein (Executor)\"). A name is treated as a placeholder when it is\r\n * empty, equals the role (case-insensitive), is a generic default\r\n * (\"subagent\"/\"adhoc\"/\"generic\"), or is an auto-generated `slot-…` id.\r\n * Explicit, human-chosen names — including nicknames already assigned by\r\n * `Director.spawn()` — are left untouched, so this never double-assigns.\r\n */\r\n private withNickname(subagent: SubagentConfig, subagentId: string): SubagentConfig {\r\n const role = subagent.role ?? 'subagent';\r\n const name = subagent.name?.trim() ?? '';\r\n const isPlaceholder =\r\n name === '' ||\r\n name.toLowerCase() === role.toLowerCase() ||\r\n name === 'subagent' ||\r\n name === 'adhoc' ||\r\n name === 'generic' ||\r\n /^slot-/.test(name);\r\n if (!isPlaceholder) return subagent;\r\n const nickname = assignNickname(role, this.usedNicknames);\r\n const baseKey = nickname.split(' ')[0]!.toLowerCase().replace(/[^a-z0-9-]/g, '-');\r\n this.usedNicknames.add(baseKey);\r\n this.subagentNicknames.set(subagentId, baseKey);\r\n return { ...subagent, name: nickname };\r\n }\r\n\r\n async spawn(subagent: SubagentConfig): Promise<SpawnResult> {\r\n const id = subagent.id || randomUUID();\r\n subagent = this.withNickname(subagent, id);\r\n // Duplicate-id guard. Previously a second spawn({id}) with the\r\n // same id silently overwrote the existing entry — orphaning the\r\n // first subagent's AbortController, Context, and any in-flight\r\n // task referencing it. Two spawns with the same id are almost\r\n // always a bug at the caller; refuse and let them surface it.\r\n if (this.subagents.has(id)) {\r\n throw new Error(`Subagent id \"${id}\" already exists — refusing to overwrite`);\r\n }\r\n const context: SubagentContext = {\r\n subagentId: id,\r\n tasks: [],\r\n // Wired later by the caller via setSubagentBridge() once the\r\n // bidirectional bridge is created. Readers must null-check / use\r\n // hasParentBridge() — the type now reflects this.\r\n parentBridge: null,\r\n doneCondition: this.config.doneCondition,\r\n maxConcurrent: this.config.maxConcurrent ?? 16,\r\n };\r\n\r\n this.subagents.set(id, {\r\n config: { ...subagent, id },\r\n context,\r\n status: 'idle',\r\n abortController: new AbortController(),\r\n });\r\n\r\n this.emit('subagent.started', { subagent: { ...subagent, id } });\r\n\r\n this.fleetBus?.emit({\r\n subagentId: id,\r\n ts: Date.now(),\r\n type: 'subagent.assigned',\r\n payload: {\r\n subagentId: id,\r\n name: subagent.name,\r\n provider: subagent.provider,\r\n model: subagent.model,\r\n },\r\n });\r\n\r\n this.emitCoordinatorStats();\r\n\r\n return { subagentId: id, agentId: id };\r\n }\r\n\r\n async assign(task: TaskSpec): Promise<void> {\r\n this.pendingTasks.push(task);\r\n this.tryDispatchNext();\r\n }\r\n\r\n async delegate(to: string, msg: BridgeMessage): Promise<void> {\r\n const subagent = this.subagents.get(to);\r\n if (!subagent) throw new Error(`Subagent \"${to}\" not found`);\r\n if (!subagent.context.parentBridge) {\r\n throw new Error(`Subagent \"${to}\" has no parentBridge — call setSubagentBridge() first`);\r\n }\r\n await subagent.context.parentBridge.send(msg);\r\n }\r\n\r\n /**\r\n * Wire up the communication bridge for a subagent. Call after spawn() once\r\n * the caller has created the bidirectional connection.\r\n */\r\n setSubagentBridge(subagentId: string, bridge: AgentBridge): void {\r\n const subagent = this.subagents.get(subagentId);\r\n if (!subagent) throw new Error(`Subagent \"${subagentId}\" not found`);\r\n subagent.context.parentBridge = bridge;\r\n }\r\n\r\n async stop(subagentId: string): Promise<void> {\r\n const subagent = this.subagents.get(subagentId);\r\n if (!subagent) return;\r\n\r\n // Mark terminating BEFORE the abort so a synchronous tryDispatchNext\r\n // observation in another callback path sees the intent and skips\r\n // this subagent. Cleared by recordCompletion once the runner's\r\n // catch block lands the terminal TaskResult.\r\n this.terminating.add(subagentId);\r\n\r\n // Abort any in-flight run, then sever the bridge so further messages fail\r\n // fast instead of silently queueing on a dead subagent.\r\n subagent.abortController.abort();\r\n subagent.status = 'stopped';\r\n subagent.currentTask = undefined;\r\n subagent.context.parentBridge = null;\r\n\r\n this.emit('subagent.stopped', { subagentId, reason: 'stopped by coordinator' });\r\n\r\n this.fleetBus?.emit({\r\n subagentId,\r\n ts: Date.now(),\r\n type: 'subagent.stopped',\r\n payload: { subagentId, reason: 'stopped by coordinator' },\r\n });\r\n\r\n this.emitCoordinatorStats();\r\n }\r\n\r\n async stopAll(): Promise<void> {\r\n // Clear the queue FIRST so no new tasks land on subagents while\r\n // we're tearing them down. Each dropped task gets a synthetic\r\n // `aborted_by_parent` completion so any caller awaiting it (e.g.\r\n // delegate tool's awaitTasks) resolves instead of hanging.\r\n //\r\n // Pending tasks never reached `inFlight`, so we cannot route them\r\n // through `recordCompletion` — its underflow guard would short-\r\n // circuit on the second pending task and emit a warning instead\r\n // of the completion event. The shared helper inline-emits.\r\n this.drainPendingAsAborted('Coordinator stopAll() drained the pending queue');\r\n // allSettled so one failure doesn't leave other subagents un-stopped.\r\n await Promise.allSettled([...this.subagents.keys()].map((id) => this.stop(id)));\r\n }\r\n\r\n /**\r\n * Get current coordinator stats for monitoring/debugging.\r\n */\r\n getStats(): {\r\n total: number;\r\n running: number;\r\n idle: number;\r\n stopped: number;\r\n inFlight: number;\r\n pending: number;\r\n completed: number;\r\n } {\r\n let running = 0;\r\n let idle = 0;\r\n let stopped = 0;\r\n for (const [, entry] of this.subagents) {\r\n if (entry.status === 'running') running++;\r\n else if (entry.status === 'idle') idle++;\r\n else stopped++;\r\n }\r\n return {\r\n total: this.subagents.size,\r\n running,\r\n idle,\r\n stopped,\r\n inFlight: this.inFlight,\r\n pending: this.pendingTasks.length,\r\n completed: this.completedResults.length,\r\n };\r\n }\r\n\r\n /** Emit a reactive coordinator.stats event on FleetBus so the TUI can subscribe. */\r\n private emitCoordinatorStats(): void {\r\n const stats = this.getStats();\r\n const subagentStatuses = Array.from(this.subagents.entries()).map(([id, s]) => ({\r\n subagentId: id,\r\n taskId: s.currentTask ?? '',\r\n status: s.status,\r\n assigned: s.context.parentBridge !== null,\r\n }));\r\n this.fleetBus?.emit({\r\n subagentId: this.coordinatorId,\r\n ts: Date.now(),\r\n type: 'coordinator.stats',\r\n payload: { ...stats, subagentStatuses },\r\n });\r\n }\r\n\r\n getStatus(): CoordinatorStatus {\r\n return {\r\n coordinatorId: this.coordinatorId,\r\n subagents: Array.from(this.subagents.entries()).map(([id, s]) => ({\r\n id,\r\n name: s.config.name,\r\n status: s.status,\r\n currentTask: s.currentTask,\r\n })),\r\n pendingTasks: this.pendingTasks.length,\r\n completedTasks: this.completedResults.length,\r\n totalIterations: this.totalIterations,\r\n done: this.isDone(),\r\n };\r\n }\r\n\r\n /** Expose snapshot of completed results — useful for callers awaiting all done. */\r\n results(): readonly TaskResult[] {\r\n return this.completedResults;\r\n }\r\n\r\n /**\r\n * Wait for one or more tasks to complete and return their results.\r\n * If a task is already done when called, returns immediately.\r\n * Resolves to an array in the same order as `taskIds`.\r\n */\r\n async awaitTasks(taskIds: string[]): Promise<TaskResult[]> {\r\n return Promise.all(\r\n taskIds.map((id) => {\r\n const cached = this.completedResults.find((r) => r.taskId === id);\r\n if (cached) return cached;\r\n // Fallback: poll until the task completes (up to timeoutMs).\r\n // The coordinator fires 'task.completed' on every result, so\r\n // we use a promise-based waiter tied to that event.\r\n return new Promise<TaskResult>((resolve, reject) => {\r\n const timeout = setTimeout(() => {\r\n this.off('task.completed', handler);\r\n reject(new Error(`awaitTasks timed out waiting for task \"${id}\"`));\r\n }, this.config.timeoutMs ?? 300_000);\r\n const handler = ({ result }: { task: TaskSpec; result: TaskResult }) => {\r\n if (result.taskId === id) {\r\n clearTimeout(timeout);\r\n this.off('task.completed', handler);\r\n resolve(result);\r\n }\r\n };\r\n this.on('task.completed', handler);\r\n });\r\n }),\r\n );\r\n }\r\n\r\n /**\r\n * Manual completion — for callers that drive subagents without a runner\r\n * (e.g. external orchestrators). When a runner is configured the coordinator\r\n * calls this itself.\r\n */\r\n completeTask(result: TaskResult): void {\r\n this.recordCompletion(result);\r\n }\r\n\r\n // --- internal dispatching ---------------------------------------------\r\n\r\n private tryDispatchNext(): void {\r\n while (this.canDispatch()) {\r\n const dispatchable = this.takeNextDispatchableTask();\r\n if (!dispatchable) {\r\n // No idle worker right now. If every spawned subagent is\r\n // stopped or mid-termination, the pending queue is dead —\r\n // a pending task can never start, so synthetic-complete it\r\n // as `aborted_by_parent`. Without this, an `assign()` after\r\n // `stop()` would hang forever waiting for `task.completed`.\r\n // We DO NOT drain when subagents are busy (status='running'):\r\n // those will free up and accept the work normally.\r\n if (this.pendingTasks.length > 0 && !this.hasLiveSubagent()) {\r\n this.drainPendingAsAborted(\r\n 'No live subagent available — all stopped or mid-termination',\r\n );\r\n }\r\n return;\r\n }\r\n const { subagentId, task } = dispatchable;\r\n // Attach a catch so a synchronous throw inside runDispatched (rare —\r\n // e.g. provider misconfiguration before the first await) becomes a\r\n // visible failed task instead of an unhandled rejection that leaves\r\n // `inFlight` permanently elevated.\r\n this.runDispatched(subagentId, task).catch((err) => {\r\n this.recordCompletion({\r\n subagentId,\r\n taskId: task.id,\r\n status: 'failed',\r\n error: classifySubagentError(err),\r\n iterations: 0,\r\n toolCalls: 0,\r\n durationMs: 0,\r\n });\r\n });\r\n }\r\n }\r\n\r\n private canDispatch(): boolean {\r\n const max = this.config.maxConcurrent ?? 16;\r\n return this.inFlight < max && this.pendingTasks.length > 0;\r\n }\r\n\r\n private takeNextDispatchableTask(): { subagentId: string; task: TaskSpec } | null {\r\n for (let i = 0; i < this.pendingTasks.length; i++) {\r\n const task = this.pendingTasks[i]!;\r\n const subagentId = task.subagentId\r\n ? this.isIdleSubagent(task.subagentId)\r\n ? task.subagentId\r\n : null\r\n : this.findIdleSubagent();\r\n if (!subagentId) continue;\r\n this.pendingTasks.splice(i, 1);\r\n return { subagentId, task };\r\n }\r\n return null;\r\n }\r\n\r\n private findIdleSubagent(): string | null {\r\n for (const [id, s] of this.subagents) {\r\n // Skip subagents that are mid-termination — `stop()` set the\r\n // `terminating` flag and aborted the controller, but the\r\n // status mutation happens synchronously after; checking both\r\n // is belt-and-suspenders against any race where status is\r\n // transiently still 'idle' while termination is in flight.\r\n if (s.status === 'idle' && !this.terminating.has(id)) return id;\r\n }\r\n return null;\r\n }\r\n\r\n private isIdleSubagent(id: string): boolean {\r\n const subagent = this.subagents.get(id);\r\n return !!subagent && subagent.status === 'idle' && !this.terminating.has(id);\r\n }\r\n\r\n /**\r\n * Returns true iff at least one spawned subagent could still\r\n * process a task. A \"live\" subagent is one that is not stopped\r\n * AND not mid-termination — `running` workers count because they\r\n * will eventually finish and become idle.\r\n *\r\n * When no subagent has ever been spawned, returns `true` so a\r\n * pre-spawn `assign()` simply queues (legacy behaviour). The\r\n * dead-end detection only fires after `stop()` has retired every\r\n * spawned worker.\r\n *\r\n * Used by `tryDispatchNext` to detect a dead-end pending queue.\r\n */\r\n private hasLiveSubagent(): boolean {\r\n if (this.subagents.size === 0) return true;\r\n for (const [id, s] of this.subagents) {\r\n if (s.status !== 'stopped' && !this.terminating.has(id)) return true;\r\n }\r\n return false;\r\n }\r\n\r\n /**\r\n * Drain every pending task with a synthetic `aborted_by_parent`\r\n * completion event. Same shape as the `stopAll()` drain — we go\r\n * around `recordCompletion` because pending tasks were never\r\n * counted in `inFlight` and routing them through would trip the\r\n * underflow guard on every task after the first.\r\n */\r\n private drainPendingAsAborted(message: string): void {\r\n const dropped = this.pendingTasks.splice(0, this.pendingTasks.length);\r\n for (const t of dropped) {\r\n const synthetic: TaskResult = {\r\n subagentId: t.subagentId ?? 'unassigned',\r\n taskId: t.id,\r\n status: 'stopped',\r\n error: {\r\n kind: 'aborted_by_parent',\r\n message,\r\n retryable: false,\r\n },\r\n iterations: 0,\r\n toolCalls: 0,\r\n durationMs: 0,\r\n };\r\n this.completedResults.push(synthetic);\r\n this.emit('task.completed', { task: t, result: synthetic });\r\n }\r\n }\r\n\r\n private async runDispatched(subagentId: string, task: TaskSpec): Promise<void> {\r\n const subagent = this.subagents.get(subagentId);\r\n if (!subagent) return;\r\n // Final race guard: if `stop(subagentId)` ran between dispatch\r\n // and us arriving here, refuse to start the task and surface it\r\n // as `aborted_by_parent` so any caller awaiting the task id\r\n // unblocks. Without this, the task would be marked 'running',\r\n // collide with the just-completed 'stopped' state, and leak\r\n // inFlight by 1 because no recordCompletion path covers it.\r\n if (this.terminating.has(subagentId) || subagent.status === 'stopped') {\r\n this.recordCompletion({\r\n subagentId,\r\n taskId: task.id,\r\n status: 'stopped',\r\n error: {\r\n kind: 'aborted_by_parent',\r\n message: 'Subagent was terminated before task could start',\r\n retryable: false,\r\n },\r\n iterations: 0,\r\n toolCalls: 0,\r\n durationMs: 0,\r\n });\r\n return;\r\n }\r\n\r\n subagent.status = 'running';\r\n subagent.currentTask = task.id;\r\n task.subagentId = subagentId;\r\n subagent.context.tasks.push(task);\r\n\r\n this.fleetBus?.emit({\r\n subagentId,\r\n taskId: task.id,\r\n ts: Date.now(),\r\n type: 'subagent.running',\r\n payload: { subagentId, taskId: task.id },\r\n });\r\n\r\n this.emit('task.assigned', { task, subagentId });\r\n this.emitCoordinatorStats();\r\n\r\n // Budget combines coordinator defaults with per-subagent and per-task overrides.\r\n // Precedence: task > subagent (raw, no roster fills) > coordinator default > roster default.\r\n // We intentionally call applyRosterBudget LATE — only as a final fallback after\r\n // the coordinator's defaultBudget has had a chance to apply. This prevents\r\n // GENERIC_SUBAGENT_BUDGET (5000 iter) from shadowing the coordinator's explicit default.\r\n const rawMaxIterations = subagent.config.maxIterations;\r\n const rawMaxToolCalls = subagent.config.maxToolCalls;\r\n const rawMaxTokens = subagent.config.maxTokens;\r\n const rawMaxCostUsd = subagent.config.maxCostUsd;\r\n const rawTimeoutMs = subagent.config.timeoutMs;\r\n const rawIdleTimeoutMs = subagent.config.idleTimeoutMs;\r\n const configWithRosterDefaults = applyRosterBudget(subagent.config);\r\n const budget = new SubagentBudget({\r\n maxIterations:\r\n rawMaxIterations ?? this.config.defaultBudget?.maxIterations ?? configWithRosterDefaults.maxIterations,\r\n maxToolCalls:\r\n rawMaxToolCalls ??\r\n this.config.defaultBudget?.maxToolCalls ??\r\n configWithRosterDefaults.maxToolCalls,\r\n maxTokens:\r\n rawMaxTokens ?? this.config.defaultBudget?.maxTokens ?? configWithRosterDefaults.maxTokens,\r\n maxCostUsd:\r\n rawMaxCostUsd ?? this.config.defaultBudget?.maxCostUsd ?? configWithRosterDefaults.maxCostUsd,\r\n // Wall-clock cap is opt-in (explicit config / defaultBudget only); the\r\n // roster no longer supplies one. Idle is the default reaper.\r\n timeoutMs:\r\n rawTimeoutMs ?? this.config.defaultBudget?.timeoutMs ?? configWithRosterDefaults.timeoutMs,\r\n idleTimeoutMs:\r\n rawIdleTimeoutMs ??\r\n this.config.defaultBudget?.idleTimeoutMs ??\r\n configWithRosterDefaults.idleTimeoutMs,\r\n });\r\n subagent.activeBudget = budget;\r\n\r\n if (!this.runner) {\r\n // No runner wired — caller drives execution via completeTask(). Status\r\n // reverts when the caller reports. We intentionally don't bump\r\n // `inFlight` here: `completeTask` → `recordCompletion` would then\r\n // decrement an inFlight that runDispatched never incremented, masking\r\n // the \"no runner\" state. With this guard, `isDone()`'s all_tasks_done\r\n // check still settles correctly once the caller reports.\r\n return;\r\n }\r\n\r\n // Only count inFlight when we actually own the execution lifecycle.\r\n this.inFlight++;\r\n\r\n const startTime = Date.now();\r\n const runCtx: SubagentRunContext = {\r\n subagentId,\r\n config: subagent.config,\r\n budget,\r\n signal: subagent.abortController.signal,\r\n bridge: subagent.context.parentBridge || null,\r\n };\r\n\r\n let result: TaskResult;\r\n\r\n budget.start();\r\n try {\r\n const outcome = await this.executeWithTimeout(this.runner, task, runCtx, budget);\r\n result = {\r\n subagentId,\r\n taskId: task.id,\r\n status: 'success',\r\n result: outcome.result,\r\n iterations: outcome.iterations,\r\n toolCalls: outcome.toolCalls,\r\n durationMs: Date.now() - startTime,\r\n };\r\n } catch (err) {\r\n // Order matters: a timeout calls abort() to signal cooperative runners,\r\n // which also flips `signal.aborted=true`. Inspect the error first so we\r\n // surface 'timeout' rather than masking it as 'stopped'.\r\n const status: TaskResult['status'] =\r\n err instanceof BudgetExceededError && (err.kind === 'timeout' || err.kind === 'idle_timeout')\r\n ? 'timeout'\r\n : subagent.abortController.signal.aborted\r\n ? 'stopped'\r\n : 'failed';\r\n const usage = budget.usage();\r\n result = {\r\n subagentId,\r\n taskId: task.id,\r\n status,\r\n error: classifySubagentError(err, {\r\n parentAborted: subagent.abortController.signal.aborted,\r\n }),\r\n iterations: usage.iterations,\r\n toolCalls: usage.toolCalls,\r\n durationMs: Date.now() - startTime,\r\n };\r\n }\r\n\r\n this.recordCompletion(result);\r\n }\r\n\r\n private async executeWithTimeout(\r\n runner: SubagentRunner,\r\n task: TaskSpec,\r\n ctx: SubagentRunContext,\r\n budget: SubagentBudget,\r\n ) {\r\n const initialTimeoutMs = budget.limits.timeoutMs;\r\n const idleLimitMs = budget.limits.idleTimeoutMs;\r\n if (initialTimeoutMs === undefined && idleLimitMs === undefined) {\r\n return runner(task, ctx);\r\n }\r\n\r\n // Re-armable watchdog. The default guard is IDLE-based: while the agent\r\n // keeps producing activity (iterations / tool calls / streamed progress),\r\n // `budget.idleMs()` stays below the window and we simply re-arm — an\r\n // actively-working subagent is never killed by the clock. Only a genuine\r\n // stall (no activity for `idleTimeoutMs`) reaps it. An explicit wall-clock\r\n // `timeoutMs` (rare, opt-in) keeps the original soft-warning behaviour: it\r\n // negotiates an extension via the Director's auto-extend listener and\r\n // re-arms rather than hard-killing a task solely for running long.\r\n const start = Date.now();\r\n let timer: ReturnType<typeof setTimeout> | null = null;\r\n\r\n const timeoutPromise = new Promise<never>((_, reject) => {\r\n const armFor = (ms: number) => {\r\n if (timer) clearTimeout(timer);\r\n timer = setTimeout(onTick, Math.max(0, ms));\r\n };\r\n // Re-arm for whichever deadline is sooner — the idle window (counted\r\n // from last activity) or the explicit wall-clock cap. Either being\r\n // unset drops out of the min, so single-limit configs behave exactly\r\n // as that limit alone.\r\n const scheduleNext = () => {\r\n const wallRemaining =\r\n initialTimeoutMs === undefined\r\n ? Number.POSITIVE_INFINITY\r\n : (budget.limits.timeoutMs ?? initialTimeoutMs) - (Date.now() - start);\r\n const idleRemaining =\r\n idleLimitMs === undefined\r\n ? Number.POSITIVE_INFINITY\r\n : (budget.limits.idleTimeoutMs ?? idleLimitMs) - budget.idleMs();\r\n // Floor at a small positive so a near-zero remainder can't busy-loop.\r\n armFor(Math.max(25, Math.min(wallRemaining, idleRemaining)));\r\n };\r\n\r\n const onTick = async () => {\r\n const elapsed = Date.now() - start;\r\n const wallLimit =\r\n initialTimeoutMs === undefined ? undefined : budget.limits.timeoutMs ?? initialTimeoutMs;\r\n const idleLimit =\r\n idleLimitMs === undefined ? undefined : budget.limits.idleTimeoutMs ?? idleLimitMs;\r\n const wallExceeded = wallLimit !== undefined && elapsed >= wallLimit;\r\n const idleExceeded = idleLimit !== undefined && budget.idleMs() >= idleLimit;\r\n\r\n // Idle stall with no wall-clock cap also due: a genuinely hung agent\r\n // (no activity for the whole window). Reap it directly — idle is not\r\n // negotiable; the point of the default is to free a stuck slot.\r\n if (idleExceeded && !wallExceeded) {\r\n this.subagents.get(ctx.subagentId)?.abortController.abort();\r\n reject(new BudgetExceededError('timeout', idleLimit!, budget.idleMs()));\r\n return;\r\n }\r\n // Neither deadline actually tripped — we woke early because activity\r\n // pushed the idle deadline out. Re-arm for the new soonest deadline.\r\n if (!wallExceeded) {\r\n scheduleNext();\r\n return;\r\n }\r\n\r\n // Wall-clock cap hit. This is opt-in and keeps the original\r\n // soft-warning behaviour: negotiate an extension rather than\r\n // hard-killing a task solely for running long.\r\n const limit = wallLimit!;\r\n // Without an onThreshold handler the original behaviour stands:\r\n // abort the signal and hard-reject. This preserves the contract\r\n // for direct SubagentBudget consumers that don't wire negotiation.\r\n if (!budget.onThreshold) {\r\n this.subagents.get(ctx.subagentId)?.abortController.abort();\r\n reject(new BudgetExceededError('timeout', limit, elapsed));\r\n return;\r\n }\r\n // With a handler, ask for an extension. The budget's\r\n // requestDecision returns 'stop' on no response (decision\r\n // fallback timer inside SubagentBudget), so this never hangs.\r\n try {\r\n const result = budget.onThreshold({\r\n kind: 'timeout',\r\n used: elapsed,\r\n limit,\r\n requestDecision: () =>\r\n new Promise((resolveDecision) => {\r\n budget._events?.emit('budget.threshold_reached', {\r\n kind: 'timeout',\r\n used: elapsed,\r\n limit,\r\n timeoutMs: 60_000,\r\n extend: (extra) => resolveDecision({ extend: extra }),\r\n deny: () => resolveDecision('stop'),\r\n });\r\n }),\r\n });\r\n const decision = typeof result === 'string' ? result : await result;\r\n if (decision === 'continue' || decision === 'throw' || decision === 'stop') {\r\n // Timeout denied / no-op — re-arm for another full wall window so\r\n // we ask again later. This makes wall-clock timeout a pure warning\r\n // event: the subagent keeps running until it naturally finishes or\r\n // the user stops it. No task is hard-killed solely for running long.\r\n armFor(Math.max(1_000, limit));\r\n return;\r\n }\r\n // 'extend' — patch budget and re-arm for the new remainder.\r\n if (decision.extend.timeoutMs !== undefined) {\r\n (budget.limits as Record<string, unknown>).timeoutMs = decision.extend.timeoutMs;\r\n scheduleNext();\r\n return;\r\n }\r\n // No timeoutMs in extend — fall through to reject.\r\n this.subagents.get(ctx.subagentId)?.abortController.abort();\r\n reject(new BudgetExceededError('timeout', limit, elapsed));\r\n } catch (err) {\r\n this.subagents.get(ctx.subagentId)?.abortController.abort();\r\n reject(\r\n err instanceof BudgetExceededError\r\n ? err\r\n : new BudgetExceededError('timeout', limit, elapsed),\r\n );\r\n }\r\n };\r\n // First arm: whichever of the idle window / wall-clock cap is sooner.\r\n scheduleNext();\r\n });\r\n\r\n try {\r\n return await Promise.race([runner(task, ctx), timeoutPromise]);\r\n } finally {\r\n if (timer) clearTimeout(timer);\r\n }\r\n }\r\n\r\n private recordCompletion(result: TaskResult): void {\r\n this.completedResults.push(result);\r\n // Trim oldest entries when the cap is exceeded — keep the most recent\r\n // results so /fleet and roll_up still have data to work with.\r\n if (this.completedResults.length > DefaultMultiAgentCoordinator.MAX_COMPLETED_RESULTS) {\r\n this.completedResults.splice(\r\n 0,\r\n this.completedResults.length - DefaultMultiAgentCoordinator.MAX_COMPLETED_RESULTS,\r\n );\r\n }\r\n this.totalIterations += result.iterations;\r\n if (this.inFlight > 0) {\r\n this.inFlight--;\r\n } else if (this.runner) {\r\n // Runner-driven path completed without an outstanding inFlight slot —\r\n // shouldn't happen unless completeTask was called externally.\r\n this.emit('warning', {\r\n type: 'inFlight_underflow',\r\n taskId: result.taskId,\r\n subagentId: result.subagentId,\r\n });\r\n return;\r\n }\r\n\r\n const subagent = this.subagents.get(result.subagentId);\r\n if (subagent && subagent.status !== 'stopped') {\r\n const failed = result.status === 'failed' || result.status === 'timeout';\r\n // Synchronously reset the worker to idle after either a clean\r\n // finish or a transient failure. The previous code parked the\r\n // subagent in 'error' and used a `queueMicrotask` to flip it\r\n // back to 'idle' — that opened a window where `assign()` +\r\n // `tryDispatchNext` could race the microtask, leaving the\r\n // worker stuck in 'running' state while actually idle. By\r\n // resetting now, no async gap can leak the state machine.\r\n subagent.status = 'idle';\r\n void failed; // kept for future telemetry hooks\r\n subagent.currentTask = undefined;\r\n // If the run aborted (timeout or explicit stop), the subagent's\r\n // signal is now permanently aborted — recycling the controller lets\r\n // the next dispatched task start with a fresh cancellation scope.\r\n if (subagent.abortController.signal.aborted) {\r\n subagent.abortController = new AbortController();\r\n }\r\n\r\n this.fleetBus?.emit({\r\n subagentId: result.subagentId,\r\n ts: Date.now(),\r\n type: 'subagent.idle',\r\n payload: { subagentId: result.subagentId },\r\n });\r\n }\r\n // Clear the terminating flag now that the worker has a terminal\r\n // TaskResult on record. Subsequent stop() calls re-add it; new\r\n // assign() calls can flow normally.\r\n this.terminating.delete(result.subagentId);\r\n\r\n this.emit('task.completed', {\r\n task: subagent?.context.tasks.find((t) => t.id === result.taskId) ?? { id: result.taskId },\r\n result,\r\n });\r\n\r\n this.fleetBus?.emit({\r\n subagentId: result.subagentId,\r\n taskId: result.taskId,\r\n ts: Date.now(),\r\n type: 'subagent.completed',\r\n payload: {\r\n subagentId: result.subagentId,\r\n taskId: result.taskId,\r\n status: result.status,\r\n iterations: result.iterations,\r\n toolCalls: result.toolCalls,\r\n durationMs: result.durationMs,\r\n },\r\n });\r\n\r\n this.tryDispatchNext();\r\n\r\n // Emit after tryDispatchNext so the stats reflect the post-dispatch\r\n // state (either a new running subagent, or idle if the queue is drained).\r\n this.emitCoordinatorStats();\r\n\r\n if (this.isDone()) {\r\n this.emit('done', {\r\n results: this.completedResults,\r\n totalIterations: this.totalIterations,\r\n });\r\n }\r\n }\r\n\r\n /**\r\n * Stop a subagent and remove it from the coordinator. Releases all\r\n * associated resources (AbortController, context, budget state).\r\n * The subagent entry is deleted so the id can be reused in a future spawn.\r\n */\r\n async remove(subagentId: string): Promise<void> {\r\n const subagent = this.subagents.get(subagentId);\r\n if (!subagent) return;\r\n\r\n // Gracefully stop first — same logic as stop() but don't block on it.\r\n if (subagent.status === 'running' || subagent.status === 'idle') {\r\n this.terminating.add(subagentId);\r\n subagent.abortController.abort();\r\n subagent.status = 'stopped';\r\n }\r\n\r\n // Release all resources associated with this subagent.\r\n this.subagents.delete(subagentId);\r\n this.terminating.delete(subagentId);\r\n // Free the nickname slot so the same name can be reused by a future spawn.\r\n const nicknameKey = this.subagentNicknames.get(subagentId);\r\n if (nicknameKey) {\r\n this.usedNicknames.delete(nicknameKey);\r\n this.subagentNicknames.delete(subagentId);\r\n }\r\n\r\n // Clean up any pending tasks assigned to this subagent — emit synthetic\r\n // 'stopped' completions so callers awaiting them via awaitTasks() unblock\r\n // instead of hanging forever. Without this, a task queued for a removed\r\n // subagent would leave its waiter permanently unresolved.\r\n const orphaned = this.pendingTasks.filter((t) => t.subagentId === subagentId);\r\n this.pendingTasks = this.pendingTasks.filter((t) => t.subagentId !== subagentId);\r\n for (const t of orphaned) {\r\n const synthetic: TaskResult = {\r\n subagentId,\r\n taskId: t.id,\r\n status: 'stopped',\r\n error: {\r\n kind: 'aborted_by_parent',\r\n message: `Subagent \"${subagentId}\" was removed while task \"${t.id}\" was pending`,\r\n retryable: false,\r\n },\r\n iterations: 0,\r\n toolCalls: 0,\r\n durationMs: 0,\r\n };\r\n this.recordCompletion(synthetic);\r\n }\r\n\r\n this.fleetBus?.emit({\r\n subagentId,\r\n ts: Date.now(),\r\n type: 'subagent.removed',\r\n payload: { subagentId },\r\n });\r\n\r\n this.emitCoordinatorStats();\r\n }\r\n\r\n private isDone(): boolean {\r\n if (this.config.doneCondition.type === 'all_tasks_done') {\r\n return this.pendingTasks.length === 0 && this.inFlight === 0;\r\n }\r\n if (\r\n this.config.doneCondition.maxIterations !== undefined &&\r\n this.totalIterations >= this.config.doneCondition.maxIterations\r\n ) {\r\n return true;\r\n }\r\n return false;\r\n }\r\n}\r\n\r\n/**\r\n * Map any raw exception thrown out of a subagent's runner into a\r\n * structured `SubagentError`. This is the single point where the\r\n * coordinator decides \"what kind of failure was that\" — so callers\r\n * (delegate tool output, /agents UI, retry policies) branch on\r\n * `kind` instead of substring-matching `error.message`.\r\n *\r\n * The classification order matters:\r\n * 1. Provider errors first (their `status` + `retryable` are\r\n * already structured, just translate to our enum).\r\n * 2. Budget errors next (BudgetExceededError carries a discrete\r\n * `kind` we can lift directly).\r\n * 3. Parent-abort if the subagent's signal was aborted and we\r\n * didn't recognize the error otherwise — distinguishes user\r\n * Ctrl+C from a tool throwing.\r\n * 4. Substring sniffing for stable error markers (\"agent\r\n * aborted\" from agent-subagent-runner, \"Bridge transport\"\r\n * from agent-bridge).\r\n * 5. Fallback to `unknown` so callers know we couldn't classify.\r\n *\r\n * The `cause` field is always populated when `err` is an Error so\r\n * diagnostics survive even when `kind === 'unknown'` — no info is\r\n * dropped, the classifier just refused to commit.\r\n *\r\n * Exported because tests and CLI surfaces want to assert on the\r\n * classification without instantiating a coordinator.\r\n */\r\nexport function classifySubagentError(\r\n err: unknown,\r\n hints: { parentAborted?: boolean } = {},\r\n): SubagentError {\r\n const cause = err instanceof Error\r\n ? { name: err.name, message: err.message, stack: err.stack }\r\n : undefined;\r\n\r\n if (err instanceof ProviderError) {\r\n const baseMessage = err.describe();\r\n return providerErrorToSubagentError(err, baseMessage, cause);\r\n }\r\n\r\n const baseMessage = err instanceof Error ? err.message : String(err);\r\n\r\n if (err instanceof BudgetExceededError) {\r\n const map: Record<BudgetExceededError['kind'], SubagentErrorKind> = {\r\n iterations: 'budget_iterations',\r\n tool_calls: 'budget_tool_calls',\r\n tokens: 'budget_tokens',\r\n cost: 'budget_cost',\r\n timeout: 'budget_timeout',\r\n idle_timeout: 'budget_timeout',\r\n };\r\n return {\r\n kind: map[err.kind],\r\n message: baseMessage,\r\n // Budgets are user-configured ceilings, not transient failures —\r\n // retrying with the same budget will hit the same ceiling. The\r\n // orchestrator must raise the budget or narrow the task first.\r\n retryable: false,\r\n cause,\r\n };\r\n }\r\n\r\n // Distinguish parent-aborted from real failures BEFORE substring\r\n // sniffing — if the parent signal is aborted, the most common\r\n // exception is \"agent aborted\" thrown by agent-subagent-runner.\r\n if (hints.parentAborted) {\r\n return {\r\n kind: 'aborted_by_parent',\r\n message: baseMessage,\r\n retryable: false,\r\n cause,\r\n };\r\n }\r\n\r\n // Stable markers — these strings live in our own code and are\r\n // checked here intentionally so callers can react without\r\n // exception-type imports.\r\n const lower = baseMessage.toLowerCase();\r\n if (/agent aborted$/i.test(baseMessage)) {\r\n return {\r\n kind: 'aborted_by_parent',\r\n message: baseMessage,\r\n retryable: false,\r\n cause,\r\n };\r\n }\r\n if (/agent exhausted iteration limit$/i.test(baseMessage)) {\r\n return { kind: 'budget_iterations', message: baseMessage, retryable: false, cause };\r\n }\r\n if (/empty response$/i.test(baseMessage)) {\r\n return { kind: 'empty_response', message: baseMessage, retryable: false, cause };\r\n }\r\n // The runner throws `Error('tool failed: <name>')` when an executed tool\r\n // returned `ok:false` and the agent ultimately ended without recovering\r\n // (or aborted). Surface as `tool_failed` so callers don't conflate a\r\n // failed tool with a thrown tool — both are useful but mean different\r\n // things at the LLM layer.\r\n if (/^tool failed: /i.test(baseMessage)) {\r\n return { kind: 'tool_failed', message: baseMessage, retryable: false, cause };\r\n }\r\n if (lower.includes('bridge transport') || /bridge.*(closed|disconnect)/i.test(baseMessage)) {\r\n return { kind: 'bridge_failed', message: baseMessage, retryable: false, cause };\r\n }\r\n if (/context length|max.*tokens?.*exceeded|prompt is too long/i.test(baseMessage)) {\r\n return { kind: 'context_overflow', message: baseMessage, retryable: false, cause };\r\n }\r\n\r\n // Final fallback — preserve cause so diagnostics aren't lost.\r\n return {\r\n kind: 'unknown',\r\n message: baseMessage,\r\n retryable: false,\r\n cause,\r\n };\r\n}\r\n\r\nfunction providerErrorToSubagentError(\r\n err: ProviderError,\r\n message: string,\r\n cause: SubagentError['cause'],\r\n): SubagentError {\r\n const status = err.status;\r\n // Read suggested retry-after from the provider body when present so\r\n // the orchestrator doesn't have to invent a backoff. Most providers\r\n // include retry-after as a header / body field which our provider\r\n // layer normalises into `body.message` — we cannot trust a numeric\r\n // field exists, so we leave backoffMs unset when unknown.\r\n if (status === 429 || err.body?.type === 'rate_limit_error') {\r\n return {\r\n kind: 'provider_rate_limit',\r\n message,\r\n retryable: true,\r\n // Conservative default: 5s. Provider-specific code can override\r\n // by emitting an error whose body carries an explicit hint.\r\n backoffMs: 5_000,\r\n cause,\r\n };\r\n }\r\n if (status === 401 || status === 403 || err.body?.type === 'authentication_error') {\r\n return { kind: 'provider_auth', message, retryable: false, cause };\r\n }\r\n if (status === 408 || status === 0) {\r\n return { kind: 'provider_timeout', message, retryable: true, cause };\r\n }\r\n if (status >= 500 && status < 600) {\r\n return {\r\n kind: 'provider_5xx',\r\n message,\r\n retryable: true,\r\n backoffMs: 3_000,\r\n cause,\r\n };\r\n }\r\n // Other provider errors (400 invalid request, 404 not found, etc.)\r\n // are not retryable as-is and don't have a dedicated kind — surface\r\n // as 'unknown' so the orchestrator treats them as terminal.\r\n return { kind: 'unknown', message, retryable: err.retryable, cause };\r\n}\r\n","import { randomUUID } from 'node:crypto';\nimport type { Agent } from '../core/agent.js';\nimport type { AgentFactory } from '../coordination/agent-subagent-runner.js';\nimport { makeAgentSubagentRunner } from '../coordination/agent-subagent-runner.js';\nimport { dispatchAgent } from '../coordination/dispatcher.js';\nimport type { DispatchClassifier, DispatchResult } from '../coordination/dispatcher.js';\nimport type { SubagentConfig, TaskResult } from '../types/multi-agent.js';\nimport type { JournalEntry, GoalFile } from '../storage/goal-store.js';\nimport { loadGoal, saveGoal, appendJournal, goalFilePath } from '../storage/goal-store.js';\nimport type { Compactor } from '../types/compactor.js';\nimport { DefaultMultiAgentCoordinator } from '../coordination/multi-agent-coordinator.js';\nimport type { MultiAgentConfig } from '../types/multi-agent.js';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport type ParallelEngineState = 'idle' | 'running' | 'stopped';\n\nexport type ParallelIterationStage =\n | { phase: 'idle' }\n | { phase: 'decompose' }\n | { phase: 'fanout'; slots: number }\n | { phase: 'await'; taskIds: string[] }\n | {\n phase: 'aggregate';\n successCount: number;\n total: number;\n goalComplete: boolean;\n }\n | { phase: 'sleep'; ms: number }\n | { phase: 'stopped' }\n | { phase: 'error'; message: string };\n\nexport interface ParallelEternalOptions {\n /** The coordinating agent — NOT a subagent. Owns container/tools/providers. */\n agent: Agent;\n /** Project root (used for goal.json path). */\n projectRoot: string;\n /**\n * Override the resolved goal.json path. Defaults to\n * `goalFilePath(projectRoot)` (a hashed location under the home dir).\n * Primarily for tests that want an isolated goal file under a temp dir.\n */\n goalPath?: string;\n /**\n * Number of parallel subagent slots per tick.\n * Default: 4. Range 1–16; values >8 are for high-throughput machines.\n */\n parallelSlots?: number;\n /** Per-subagent default timeout in ms. Default: 300_000 (5 min). */\n iterationTimeoutMs?: number;\n onIteration?: (entry: JournalEntry) => void;\n onError?: (err: Error, iteration: number) => void;\n /** Per-tick phase notifications for live UI/status updates. */\n onStage?: (stage: ParallelIterationStage) => void;\n gitStatusReader?: () => Promise<string>;\n now?: () => Date;\n compactor?: Compactor;\n compactEveryNIterations?: number;\n aggressiveCompactRatio?: number;\n maxContextTokens?: number;\n /** Override the default agent factory (uses main agent if not provided). */\n subagentFactory?: AgentFactory;\n /**\n * Route each decomposed slot task to the best-fit catalog agent via the\n * smart dispatcher (heuristic keyword scoring). When enabled (default), each\n * slot spawns in-role — the role's budget tier applies and a persona line is\n * injected into the task — instead of as a faceless generic worker. Set\n * false to keep the legacy generic spawn.\n */\n dispatch?: boolean;\n /**\n * Optional LLM fallback for ambiguous tasks. Passed straight to\n * `dispatchAgent`; when omitted, routing is pure heuristic (instant, no\n * provider call — preferred for a continuously-ticking autonomous loop).\n */\n dispatchClassifier?: DispatchClassifier;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nconst GOAL_COMPLETE_MARKER = /^\\s*\\[goal[_\\s-]?complete\\]\\s*$/im;\n\n// ---------------------------------------------------------------------------\n// ParallelEternalEngine\n// ---------------------------------------------------------------------------\n\n/**\n * Sense → Decide → Fan-out (4–8 parallel agents) → Aggregate → Loop.\n *\n * Each tick:\n * 1. Sense — load goal, todos, git status\n * 2. Decide — decompose goal into N parallel sub-tasks\n * 3. Fan-out — spawn N subagents simultaneously, await all\n * 4. Aggregate — write journal, update todos, check [GOAL_COMPLETE]\n * 5. Loop — continue until stop() or mission complete\n *\n * Uses DefaultMultiAgentCoordinator + AgentSubagentRunner for subagent lifecycle.\n */\nexport class ParallelEternalEngine {\n private state: ParallelEngineState = 'idle';\n private stopRequested = false;\n private iterationsSinceCompact = 0;\n private iterations = 0;\n private consecutiveFailures = 0;\n private readonly goalPath: string;\n private readonly slots: number;\n private readonly timeoutMs: number;\n private coordinator: DefaultMultiAgentCoordinator | null = null;\n private agentFactory: AgentFactory;\n private readonly dispatchEnabled: boolean;\n private readonly dispatchClassifier?: DispatchClassifier;\n\n constructor(private readonly opts: ParallelEternalOptions) {\n this.goalPath = opts.goalPath ?? goalFilePath(opts.projectRoot);\n this.slots = Math.min(16, Math.max(1, opts.parallelSlots ?? 4));\n this.timeoutMs = opts.iterationTimeoutMs ?? 300_000;\n this.dispatchEnabled = opts.dispatch !== false;\n this.dispatchClassifier = opts.dispatchClassifier;\n this.agentFactory =\n opts.subagentFactory ??\n (async (_config: SubagentConfig) => ({\n agent: this.opts.agent,\n events: this.opts.agent.events,\n }));\n }\n\n get currentState(): ParallelEngineState {\n return this.state;\n }\n\n /**\n * Get the underlying coordinator for stats/monitoring.\n */\n getCoordinator(): DefaultMultiAgentCoordinator | null {\n return this.coordinator;\n }\n\n stop(): void {\n this.stopRequested = true;\n void this.persistState('stopped').catch(() => {});\n this.state = 'stopped';\n }\n\n async prime(): Promise<void> {\n this.stopRequested = false;\n this.state = 'running';\n await this.persistState('running');\n }\n\n async run(): Promise<void> {\n this.state = 'running';\n await this.persistState('running');\n\n const config: MultiAgentConfig = {\n coordinatorId: `parallel-${randomUUID().slice(0, 8)}`,\n maxConcurrent: this.slots,\n doneCondition: { type: 'all_tasks_done' },\n };\n this.coordinator = new DefaultMultiAgentCoordinator(config);\n const runner = makeAgentSubagentRunner({ factory: this.agentFactory });\n this.coordinator.setRunner?.(runner);\n\n try {\n while (!this.stopRequested) {\n try {\n await this.runOneIteration();\n } catch (err) {\n this.consecutiveFailures++;\n this.opts.onError?.(\n err instanceof Error ? err : new Error(String(err)),\n this.consecutiveFailures,\n );\n await this.appendFailure(\n 'engine error',\n err instanceof Error ? err.message : String(err),\n );\n }\n if (this.stopRequested) break;\n await sleep(2000);\n }\n } finally {\n this.state = 'stopped';\n await this.persistState('stopped').catch(() => {});\n }\n }\n\n /**\n * Execute one tick: decompose → fan-out → aggregate → compact.\n * Called by the REPL in its main loop (REPL drives, engine is stateless per tick).\n */\n async runOneIteration(): Promise<boolean> {\n const emit = (stage: ParallelIterationStage) => {\n this.opts.onStage?.(stage);\n };\n\n this.iterations++;\n\n const goal = await loadGoal(this.goalPath);\n if (!goal) {\n this.stopRequested = true;\n emit({ phase: 'stopped' });\n return false;\n }\n if (goal.goalState !== 'active') {\n this.stopRequested = true;\n emit({ phase: 'stopped' });\n return false;\n }\n\n // Build coordinator on first tick.\n if (!this.coordinator) {\n const config: MultiAgentConfig = {\n coordinatorId: `parallel-${randomUUID().slice(0, 8)}`,\n maxConcurrent: this.slots,\n doneCondition: { type: 'all_tasks_done' },\n };\n this.coordinator = new DefaultMultiAgentCoordinator(config);\n const runner = makeAgentSubagentRunner({ factory: this.agentFactory });\n this.coordinator.setRunner?.(runner);\n }\n\n emit({ phase: 'decompose' });\n const tasks = await this.decomposeGoal(goal);\n if (!tasks || tasks.length === 0) {\n // Nothing to do this tick. The run() loop paces idle iterations itself\n // (see its sleep), so a single runOneIteration() must return promptly.\n emit({ phase: 'sleep', ms: 2000 });\n return false;\n }\n\n emit({ phase: 'fanout', slots: Math.min(this.slots, tasks.length) });\n const fanOut = await this.fanOut(goal, tasks);\n this.iterationsSinceCompact++;\n\n const successCount = fanOut.results.filter((r) => r.status === 'success').length;\n const status: JournalEntry['status'] = fanOut.goalComplete\n ? 'success'\n : fanOut.allSuccessful\n ? 'success'\n : 'failure';\n const note = [\n `${successCount}/${fanOut.results.length} subagents succeeded`,\n fanOut.goalComplete ? '[GOAL_COMPLETE]' : '',\n fanOut.partialOutput ? `Output: ${fanOut.partialOutput.slice(0, 120)}` : '',\n ]\n .filter(Boolean)\n .join(' | ');\n\n // Surface routing in the journal: \"role→task-snippet\" per slot so /goal\n // journal shows which agent handled what.\n const routeSummary =\n fanOut.routes.length > 0\n ? fanOut.routes\n .slice(0, 3)\n .map((r) => `${r.role}→${r.task.slice(0, 28)}`)\n .join(', ')\n : tasks.slice(0, 3).join(', ');\n await this.appendIterationEntry({\n source: 'parallel',\n task: `parallel:${tasks.length} slots — ${routeSummary}${tasks.length > 3 ? '...' : ''}`,\n status,\n note,\n });\n emit({\n phase: 'aggregate',\n successCount,\n total: fanOut.results.length,\n goalComplete: fanOut.goalComplete,\n });\n\n if (fanOut.goalComplete) {\n this.stopRequested = true;\n this.state = 'stopped';\n emit({ phase: 'stopped' });\n return true;\n }\n\n await this.maybeCompact();\n emit({ phase: 'sleep', ms: 2000 });\n return fanOut.allSuccessful;\n }\n\n // -------------------------------------------------------------------------\n // Fan-out\n // -------------------------------------------------------------------------\n\n private async fanOut(\n goal: GoalFile,\n tasks: string[],\n ): Promise<{\n results: TaskResult[];\n allSuccessful: boolean;\n goalComplete: boolean;\n partialOutput: string;\n routes: Array<{ slot: number; task: string; role: string; method: string }>;\n }> {\n const coordinator = this.coordinator!;\n const slotCount = Math.min(this.slots, tasks.length);\n\n // Route each slot task to the best-fit catalog agent. Heuristic by default\n // (instant, no provider call); an injected classifier enables LLM fallback.\n // A dispatch failure for one slot is non-fatal — that slot stays generic.\n const routes: (DispatchResult | null)[] = this.dispatchEnabled\n ? await Promise.all(\n tasks\n .slice(0, slotCount)\n .map((t) =>\n dispatchAgent(t, { classifier: this.dispatchClassifier }).catch(() => null),\n ),\n )\n : [];\n\n const recentJournal = goal.journal\n .slice(-5)\n .map(\n (e) =>\n ` #${e.iteration} [${e.status}] ${e.task}${e.note ? ` — ${e.note.slice(0, 80)}` : ''}`,\n )\n .join('\\n');\n\n const directivePreamble = [\n '═══ ETERNAL AUTONOMY — parallel task slot ═══',\n '',\n `Mission: ${goal.goal}`,\n `Total parallel slots: ${slotCount}`,\n '',\n recentJournal ? `Recent journal (last 5):\\n${recentJournal}` : 'No prior iterations.',\n '',\n '── EXECUTION PROTOCOL ──',\n '• Execute the assigned task end-to-end using multiple tool calls.',\n '• Emit `[done]` on its own line when the task is complete.',\n '• Do not ask for confirmation — YOLO is active.',\n '• If the overall Mission is accomplished, emit `[GOAL_COMPLETE]` followed by a verification recipe.',\n '• Keep output concise — summarize findings, do not transcribe files.',\n ].join('\\n');\n\n const taskIds: string[] = [];\n const subagentIds: string[] = [];\n const routeInfo: Array<{ slot: number; task: string; role: string; method: string }> = [];\n\n const spawnPromises: Array<Promise<void>> = [];\n for (let i = 0; i < slotCount; i++) {\n const task = tasks[i]!;\n const route = routes[i] ?? null;\n const subagentId = `parallel-${this.iterations}-${i}`;\n const taskId = randomUUID();\n\n // Persona injection — works even with the default factory (which reuses\n // the shared main agent and ignores config.prompt/tools), so the agent\n // adopts the routed role's stance for this slot.\n const personaLine = route\n ? `Acting agent: ${route.definition.config.name} — ${route.definition.capability.summary}\\n`\n : '';\n const spec = {\n id: taskId,\n description: `${directivePreamble}\\n\\n── SLOT ${i + 1}/${slotCount} ──\\n${personaLine}Task: ${task}\\n`,\n subagentId,\n };\n\n routeInfo.push({\n slot: i,\n task,\n role: route?.role ?? 'generic',\n method: route?.method ?? 'none',\n });\n\n spawnPromises.push(\n (async () => {\n try {\n // Spawn in-role when routed: `role` lets applyRosterBudget resolve the\n // role's budget tier; name/tools/systemPromptOverride specialize the\n // worker if a real per-role factory is wired (forward-compatible).\n await coordinator.spawn(\n route\n ? {\n id: subagentId,\n name: route.definition.config.name,\n role: route.role,\n tools: route.definition.config.tools,\n systemPromptOverride: route.definition.config.prompt,\n timeoutMs: this.timeoutMs,\n }\n : {\n id: subagentId,\n name: `slot-${subagentId.slice(-6)}`,\n // Let the coordinator apply its default budget (roster or generic).\n // Hardcoding low limits here defeats the x10 budget improvement.\n timeoutMs: this.timeoutMs,\n },\n );\n subagentIds.push(subagentId);\n taskIds.push(taskId);\n await coordinator.assign(spec);\n } catch {\n // non-fatal: individual spawn failure doesn't block other slots\n }\n })(),\n );\n }\n await Promise.all(spawnPromises);\n\n if (taskIds.length === 0) {\n return {\n results: [],\n allSuccessful: false,\n goalComplete: false,\n partialOutput: '',\n routes: routeInfo,\n };\n }\n\n this.opts.onStage?.({ phase: 'await', taskIds: [...taskIds] });\n\n let results: TaskResult[] = [];\n try {\n // Wait up to 2 hours for subagents to complete. This should cover\n // most subagent tasks since the roster budgets go up to 10 hours.\n // The outer eternal loop manages actual iteration limits.\n const ctrl = new AbortController();\n const timer = setTimeout(() => ctrl.abort(), Math.max(this.timeoutMs * 2, 7200_000));\n try {\n results = await coordinator.awaitTasks(taskIds);\n } finally {\n clearTimeout(timer);\n }\n } catch {\n results = coordinator.results().slice(-taskIds.length);\n }\n\n const allSuccessful = results.length > 0 && results.every((r) => r.status === 'success');\n const goalComplete = results.some(\n (r) =>\n r.status === 'success' &&\n typeof r.result === 'string' &&\n GOAL_COMPLETE_MARKER.test(r.result),\n );\n const partialOutput = results\n .map((r) => (typeof r.result === 'string' ? r.result : ''))\n .filter(Boolean)\n .join('\\n\\n');\n\n return { results, allSuccessful, goalComplete, partialOutput, routes: routeInfo };\n }\n\n // -------------------------------------------------------------------------\n // Goal decomposition\n // -------------------------------------------------------------------------\n\n private async decomposeGoal(goal: GoalFile): Promise<string[] | null> {\n // Strategy 1: pending todos as sub-tasks\n const todos = this.opts.agent.ctx?.todos;\n const tasks: string[] = [];\n if (Array.isArray(todos)) {\n const pending = todos.filter((t) => t.status === 'pending').slice(0, this.slots);\n for (const t of pending) {\n tasks.push(`[todo] ${t.content}`);\n }\n }\n\n // Strategy 2: git dirty files\n if (tasks.length < this.slots) {\n try {\n const gitStatus = await (this.opts.gitStatusReader?.() ?? this.readGitStatus());\n const dirty = gitStatus.trim();\n if (dirty) {\n const lines = dirty.split('\\n').slice(0, this.slots - tasks.length);\n for (const line of lines) {\n const file = line.replace(/^[ MADRUC?]{2}\\s*/, '').trim();\n if (file) tasks.push(`[git] inspect and fix: ${file}`);\n }\n }\n } catch {\n // ignore\n }\n }\n\n // Strategy 3: leader-brainstormed sub-tasks for remaining slots\n if (tasks.length < this.slots) {\n const remaining = this.slots - tasks.length;\n const brainstormed = await this.brainstormSubtasks(goal, remaining);\n tasks.push(...brainstormed);\n }\n\n return tasks.length > 0 ? tasks.slice(0, this.slots) : null;\n }\n\n private async readGitStatus(): Promise<string> {\n const { execFile } = await import('node:child_process');\n const { promisify } = await import('node:util');\n const execFileP = promisify(execFile);\n const { stdout } = await execFileP('git', ['status', '--porcelain'], {\n cwd: this.opts.projectRoot,\n timeout: 5_000,\n });\n return stdout;\n }\n\n private async brainstormSubtasks(goal: GoalFile, count: number): Promise<string[]> {\n const lastFew = goal.journal\n .slice(-5)\n .map((e) => ` - [${e.status}] ${e.task}`)\n .join('\\n');\n const directive = [\n `Decompose this goal into exactly ${count} independent sub-tasks for parallel execution.`,\n '',\n `Goal: ${goal.goal}`,\n '',\n lastFew ? `Recent:\\n${lastFew}` : 'No prior iterations.',\n '',\n `Output exactly ${count} tasks, one per line, under 120 chars each.`,\n 'Format: TASK-1 | TASK-2 | ... (pipe-separated, no numbering, no preamble).',\n 'Each task must be independently actionable with no shared dependencies.',\n ].join('\\n');\n\n try {\n const ctrl = new AbortController();\n const timer = setTimeout(() => ctrl.abort(), 60_000);\n try {\n const result = await this.opts.agent.run([{ type: 'text' as const, text: directive }], {\n signal: ctrl.signal,\n maxIterations: 1,\n });\n if (result.status !== 'done') return [];\n const text = (result.finalText ?? '').trim();\n if (!text) return [];\n const tasks = text\n .split('|')\n .map((t) => t.trim())\n .filter((t) => t.length > 10 && t.length < 240);\n return tasks.slice(0, count);\n } finally {\n clearTimeout(timer);\n }\n } catch (err) {\n // The leader agent failed to brainstorm. Surface it to onError so the\n // failure is visible, but keep the loop alive (return no tasks — the\n // next tick retries) rather than crashing the autonomous engine.\n this.opts.onError?.(\n err instanceof Error ? err : new Error(String(err)),\n this.consecutiveFailures,\n );\n return [];\n }\n }\n\n // -------------------------------------------------------------------------\n // Compaction\n // -------------------------------------------------------------------------\n\n private async maybeCompact(): Promise<void> {\n const compactor = this.opts.compactor;\n if (!compactor) return;\n const ctx = this.opts.agent.ctx;\n if (!ctx) return;\n\n const shouldRun = this.iterationsSinceCompact >= (this.opts.compactEveryNIterations ?? 25);\n if (!shouldRun) return;\n\n const report = await compactor.compact(ctx, { aggressive: false });\n this.iterationsSinceCompact = 0;\n await this.appendIterationEntry({\n source: 'manual',\n task: 'compaction (cadence)',\n status: 'success',\n note: `saved ~${report.before - report.after} tokens`,\n });\n }\n\n // -------------------------------------------------------------------------\n // Helpers\n // -------------------------------------------------------------------------\n\n private async appendIterationEntry(entry: Omit<JournalEntry, 'iteration' | 'at'>): Promise<void> {\n const current = await loadGoal(this.goalPath);\n if (!current) return;\n const updated = appendJournal(current, entry);\n await saveGoal(this.goalPath, updated);\n const entryWithMeta: JournalEntry = {\n at: (this.opts.now?.() ?? new Date()).toISOString(),\n iteration: updated.iterations,\n ...entry,\n };\n this.opts.onIteration?.(entryWithMeta);\n }\n\n private async appendFailure(task: string, note: string): Promise<void> {\n await this.appendIterationEntry({ source: 'manual', task, status: 'failure', note });\n }\n\n private async persistState(state: GoalFile['engineState']): Promise<void> {\n const current = await loadGoal(this.goalPath);\n if (!current) return;\n if (current.engineState === state) return;\n await saveGoal(this.goalPath, { ...current, engineState: state });\n }\n}\n","/**\n * System-prompt contributor that surfaces eternal-autonomy state to the\n * model on every turn.\n *\n * Why this exists: when the engine drives a long-running loop, the\n * per-iteration directive carries the rules. But the directive is a USER\n * message — it scrolls out of working memory after a few compactions and\n * the model forgets it's in autonomy mode (forgets `[GOAL_COMPLETE]`,\n * forgets the todo-state protocol, forgets the no-confirmation rule).\n * Injecting the same anchor as a CACHED system-prompt block solves that\n * — the rules sit next to the identity layer and survive compactions.\n *\n * Block is tagged `ephemeral` so its content (journal tail, iteration\n * counter) changes each turn without invalidating the upstream prefix\n * cache.\n */\n\nimport type { TextBlock } from '../types/blocks.js';\nimport type { SystemPromptContributor } from '../types/system-prompt-contributor.js';\nimport { loadGoal } from '../storage/goal-store.js';\n\nexport interface AutonomyPromptContributorOptions {\n /** Absolute path to the project's `goal.json`. */\n goalPath: string;\n /**\n * Gating function. The contributor consults this on every build and\n * returns an empty array when `false` — without this, the block would\n * leak into interactive runs that happen to have a goal on disk and\n * teach the model loop-control markers it shouldn't emit.\n *\n * Typical wiring: enable while `eternal` or `eternal-parallel` autonomy is active.\n */\n enabled: () => boolean;\n /** Number of journal entries to include in the recent-tail block. Default 5. */\n journalTailSize?: number;\n}\n\n/**\n * Build a contributor that renders the autonomy-state system block.\n * Returns `[]` when disabled, no goal exists, or the goal has been\n * completed/abandoned — all silent fast-paths.\n */\nexport function makeAutonomyPromptContributor(\n opts: AutonomyPromptContributorOptions,\n): SystemPromptContributor {\n return async (ctx): Promise<TextBlock[]> => {\n // Subagents run a single scoped task and don't drive the engine's\n // outer loop — they have no business emitting `[GOAL_COMPLETE]` or\n // marking todos. Skip the block entirely for subagent prompt builds,\n // mirroring how the active-plan layer is suppressed.\n if (ctx.subagent) return [];\n if (!opts.enabled()) return [];\n\n let goal: Awaited<ReturnType<typeof loadGoal>>;\n try {\n goal = await loadGoal(opts.goalPath);\n } catch {\n return [];\n }\n if (!goal) return [];\n\n // `active` is the default for legacy goal files without the field.\n const missionState = goal.goalState ?? 'active';\n if (missionState !== 'active') return [];\n\n const tailSize = opts.journalTailSize ?? 5;\n const journalTail = goal.journal.slice(-tailSize).map((e) => {\n const note = e.note ? ` — ${e.note.slice(0, 80)}` : '';\n return ` #${e.iteration} [${e.status}] ${e.task}${note}`;\n });\n\n const text = [\n '## ETERNAL AUTONOMY — active mission',\n '',\n 'You are inside a long-running autonomous loop. The user is asleep',\n 'and is not available to confirm decisions. Each turn you receive a',\n 'directive describing one concrete sub-task that advances the mission.',\n '',\n `Mission: ${goal.goal}`,\n `Iteration: #${goal.iterations}`,\n journalTail.length > 0\n ? `Recent journal (last ${journalTail.length}):\\n${journalTail.join('\\n')}`\n : 'Recent journal: (none — this is the first iteration)',\n '',\n '### Loop control markers',\n 'Emit these on their own line in your final text — case-insensitive,',\n 'whitespace-tolerant, but they must occupy the entire line:',\n '- `[continue]` — chain to the next internal step without returning.',\n '- `[done]` — the current sub-task is finished; return to the engine.',\n '- `[GOAL_COMPLETE]` — emit ONLY when the OVERALL mission is',\n ' verifiably done. Must be followed by a one-paragraph verification',\n ' recipe (artifact path, test command, or 10-second reproduction).',\n ' The engine halts on this marker — false positives waste real',\n ' human time. If unsure, emit `[done]` and let the next iteration',\n ' decide.',\n '',\n '### Operating principles',\n '- YOLO is active. Do NOT ask for confirmation, do NOT propose',\n ' options. Pick the best path and execute it.',\n '- Use tools freely; multiple calls per turn are normal and expected.',\n '- When working on a todo, mark it `in_progress` via the todos tool',\n ' before tool work and `completed` (or `cancelled` with a reason)',\n ' when done. The loop reads todo state between iterations.',\n \"- If an approach fails twice in a row, pivot. Don't grind on the\",\n ' same wall — try a different angle, file a cancel on the todo, or',\n ' surface the obstacle via `[done]` and let the next iteration',\n ' re-plan.',\n ].join('\\n');\n\n return [\n {\n type: 'text',\n text,\n cache_control: { type: 'ephemeral' },\n },\n ];\n };\n}\n","/**\n * `/goal <description>` preamble — the \"no force can stop this\" mode.\n *\n * Unlike STEERING (which redirects mid-flight), GOAL is a contract:\n * the user hands over a problem, the agent commits to verifiably\n * finishing it, and every iteration re-reads this preamble from the\n * conversation history. The hardening is entirely prompt-level —\n * the system has already removed implicit budget caps, so this\n * preamble's job is to remove the MODEL's tendency to hedge, ask\n * permission, or declare premature success.\n *\n * The four sections are intentional:\n * 1. AUTHORITY — explicit grant of unbounded fan-out + model\n * switching. Without this the model self-throttles (\"I shouldn't\n * spawn too many…\") even when budgets are unlimited.\n * 2. DONE — concrete bar for completion. Forces a verifiable\n * artifact (test passing, file written, bug re-run clean).\n * Without this the model returns \"I believe it's fixed\" and\n * counts that as done.\n * 3. NOT DONE — explicit anti-patterns. Each item is something we\n * saw real agents do as a \"completion\" that wasn't.\n * 4. PERSISTENCE — three-angle rule for blockers. Stops the model\n * from giving up on the first tool failure.\n *\n * Located in @wrongstack/core (rather than @wrongstack/tui) so headless\n * callers and the WebUI can issue `/goal set` without dragging the TUI\n * package in. The tui re-exports this for backward compatibility.\n */\nexport function buildGoalPreamble(goal: string): string {\n return [\n '[GOAL — LOCKED IN. You will work on this until it is verifiably done.',\n 'The user granted you full autonomy. Read these constraints once, then act.',\n '',\n 'YOUR GOAL:',\n '---',\n goal,\n '---',\n '',\n 'AUTHORITY YOU HAVE:',\n '- Spawn as many subagents as the work needs (delegate / spawn_subagent).',\n ' Parallel + recursive fan-out are both fine. There is no spawn budget.',\n '- Use any provider/model per subagent — pick the right tool for each',\n ' piece of work. Heavy reasoning model for planning, fast model for',\n ' batch work, specialist model for domain code.',\n '- Run unlimited tool calls and iterations. There is NO hidden budget.',\n ' The Agent loop auto-extends every 100 iterations forever.',\n '- Retry failed tools with different inputs, alternative paths, fresh',\n ' subagents. Switch providers mid-run if one is rate-limited.',\n '- Re-plan freely when an approach hits a dead end. You are not obliged',\n ' to stick with the first plan you proposed.',\n '',\n 'WHAT \"DONE\" MEANS — non-negotiable:',\n '- You can name a concrete artifact (a passing test, a written file at',\n ' a specific path, a fixed bug verified by re-running the failing case,',\n ' a clean grep that previously had matches).',\n '- You can tell the user HOW to verify it themselves in 10 seconds.',\n '- You have NOT hedged. None of: \"looks like it should work\", \"I',\n ' believe this fixes it\", \"the changes appear correct\".',\n '',\n 'WHAT IS NOT DONE — never report any of these as completion:',\n \"- An error message you didn't recover from.\",\n '- An empty result, a 0-line file, a \"no matches found\" you accepted',\n ' without questioning the search.',\n '- \"Should I continue?\" / \"Want me to also...?\" / \"Let me know if you',\n ' want X.\" Those are hedges. The user already told you to finish the',\n ' goal — just do it.',\n '- Partial progress dressed up as success. Fixed 3 of 5 bugs = 60%',\n ' done, not done.',\n \"- A subagent's failed/timeout/stopped TaskResult that you didn't\",\n ' respond to with a fresh attempt (different role, different model,',\n ' tighter prompt).',\n '',\n 'PERSISTENCE PROTOCOL:',\n '- If blocked, try at least 3 different angles before reporting the',\n ' problem to the user. Different tool inputs, different subagent',\n ' roles, different providers, different decomposition of the task.',\n '- If a tool fails, read its error, alter the input, try again. Do',\n ' not just report the failure back.',\n '- If a subagent returns useless output, respawn with a tighter prompt',\n ' or a different role. Do not accept \"I could not determine…\" as the',\n ' final answer.',\n \"- Use `ask_subagent` for one-shot questions when you don't need a\",\n ' full delegated task.',\n '',\n 'REPORTING:',\n '- Stream short progress notes between major actions so the user can',\n ' monitor. Do not go silent for 50 tool calls then dump a wall of',\n ' text — but also do not narrate every tool call.',\n '- Use the shared scratchpad (if available) to leave breadcrumbs',\n ' subagents can read.',\n '- Final response must include: (a) what was accomplished, (b) how',\n ' to verify, (c) any caveats (residual TODOs, things the user',\n ' should know about).',\n '',\n 'BEGIN.]',\n ].join('\\n');\n}\n","/**\n * Shared regex patterns used across execution and security-scanner.\n * Centralized here to avoid duplication and keep patterns in sync.\n */\n\n/** Matches Node.js ECONN* errors and fetch failure messages. */\nexport const NETWORK_ERR_RE = /ECONN|ETIMEDOUT|ETIME|ENOTFOUND|EAI_AGAIN|fetch failed/i;","import { ProviderError } from '../types/provider.js';\nimport { NETWORK_ERR_RE } from './regex-patterns.js';\nimport type { RetryPolicy } from '../types/retry-policy.js';\n\nexport class DefaultRetryPolicy implements RetryPolicy {\n shouldRetry(err: Error | ProviderError, attempt: number): boolean {\n if (err instanceof ProviderError) {\n if (!err.retryable) return false;\n return attempt < this.maxAttempts(err);\n }\n const msg = err.message ?? '';\n const isNetwork = NETWORK_ERR_RE.test(msg);\n if (isNetwork) return attempt < 2;\n return false;\n }\n\n maxAttempts(err: Error | ProviderError): number {\n if (err instanceof ProviderError) {\n if (err.status === 429) return 5;\n if (err.status === 529) return 3;\n if (err.status >= 500) return 3;\n return 0;\n }\n return 2;\n }\n\n delayMs(attempt: number): number {\n const base = 1000;\n const exp = base * 2 ** attempt;\n const jitter = Math.random() * base;\n return Math.min(30_000, exp + jitter);\n }\n}\n","import type { Context } from '../core/context.js';\nimport type { ErrorHandler, RecoveryDecision } from '../types/error-handler.js';\nimport { ProviderError } from '../types/provider.js';\nimport { NETWORK_ERR_RE } from './regex-patterns.js';\nimport type { Compactor } from '../types/compactor.js';\nimport type { ModelsRegistry } from '../types/models-registry.js';\n\n/**\n * Tiered error recovery strategies.\n * Each strategy is attempted in order until one returns a decision.\n */\nexport interface RecoveryStrategy {\n /** Human-readable label for logs. */\n label: string;\n /** Optional compactor for context_overflow recovery. */\n compactor?: Compactor;\n /** Returns an explicit recovery decision, or null to fall through. */\n attempt: (err: unknown, ctx: Context) => Promise<RecoveryDecision | null>;\n}\n\n// Package-level compiled regex for hot paths — avoids repeated compilation.\nconst CONTEXT_OVERFLOW_RE = /context|too long|tokens/i;\n\n/**\n * Builds the ordered list of recovery strategies used by DefaultErrorHandler.\n * Exported so callers can customise or extend the strategy chain.\n */\nexport function buildRecoveryStrategies(opts?: {\n compactor?: Compactor;\n modelsRegistry?: ModelsRegistry;\n}): RecoveryStrategy[] {\n return [\n {\n label: 'context_overflow_reduce',\n compactor: opts?.compactor,\n async attempt(err, ctx) {\n if (!(err instanceof ProviderError)) return null;\n if (err.status !== 413 && !CONTEXT_OVERFLOW_RE.test(err.message)) return null;\n\n if (this.compactor) {\n try {\n const report = await this.compactor.compact(ctx, { aggressive: true });\n if (report.after < report.before) {\n return { action: 'retry', reason: 'context_compacted' };\n }\n } catch {\n // compact failed; fall through\n }\n }\n return null;\n },\n },\n {\n label: 'rate_limit_backoff',\n async attempt(err) {\n if (!(err instanceof ProviderError) || err.status !== 429) return null;\n\n // Prefer the parsed Retry-After hint the provider extracted into\n // body.retryAfterMs; fall back to 5s when absent.\n const delayMs = err.body?.retryAfterMs ?? 5_000;\n // Clamp between 1s and 60s.\n const delay = Math.min(60_000, Math.max(1_000, delayMs));\n await new Promise((r) => setTimeout(r, delay));\n return { action: 'retry', reason: 'rate_limit_backoff' };\n },\n },\n {\n label: 'downgrade_model',\n async attempt(err, ctx) {\n if (!(err instanceof ProviderError)) return null;\n if (err.status !== 429 && err.status !== 529 && err.status < 500) return null;\n\n const registry = opts?.modelsRegistry;\n if (!registry) return null;\n\n try {\n const providerId = ctx.provider?.id;\n if (!providerId) return null;\n const provider = await registry.getProvider(providerId);\n if (!provider) return null;\n\n const currentModel = await registry.getModel(providerId, ctx.model);\n if (!currentModel) return null;\n\n // Find a cheaper fallback model with the same capabilities.\n // Prefer models with lower input cost, preferring the same family.\n const candidates = provider.models.filter((m) => {\n const modelCost = m.cost?.input ?? Number.POSITIVE_INFINITY;\n const currentCost = currentModel.cost?.input ?? Number.POSITIVE_INFINITY;\n if (modelCost >= currentCost) return false;\n if (currentModel.capabilities.tools && !m.tool_call) return false;\n if (currentModel.capabilities.vision && !m.modalities?.input?.includes('image'))\n return false;\n return true;\n });\n\n if (candidates.length === 0) return null;\n\n const fallback = candidates.reduce((prev, curr) =>\n (curr.cost?.input ?? 0) < (prev.cost?.input ?? 0) ? curr : prev,\n );\n\n return {\n action: 'retry',\n reason: 'model_downgrade',\n model: fallback.id,\n };\n } catch {\n return null;\n }\n },\n },\n ];\n}\n\nexport const DEFAULT_RECOVERY_STRATEGIES = buildRecoveryStrategies();\n\nexport class DefaultErrorHandler implements ErrorHandler {\n private readonly strategies: RecoveryStrategy[];\n\n constructor(strategies: RecoveryStrategy[] = DEFAULT_RECOVERY_STRATEGIES) {\n this.strategies = strategies;\n }\n\n classify(err: unknown): {\n kind:\n | 'rate_limit'\n | 'overloaded'\n | 'server'\n | 'client'\n | 'network'\n | 'abort'\n | 'context_overflow'\n | 'unknown';\n retryable: boolean;\n } {\n // AbortError can be thrown in both browser (DOMException) and Node (Error).\n // Guard with typeof check so Node builds don't reference the browser-only DOMException.\n if (\n typeof DOMException !== 'undefined' &&\n err instanceof DOMException &&\n err.name === 'AbortError'\n ) {\n return { kind: 'abort', retryable: false };\n }\n if (err instanceof Error && err.name === 'AbortError') {\n return { kind: 'abort', retryable: false };\n }\n if (err instanceof ProviderError) {\n if (err.status === 429) return { kind: 'rate_limit', retryable: true };\n if (err.status === 529) return { kind: 'overloaded', retryable: true };\n if (err.status >= 500) return { kind: 'server', retryable: true };\n if (err.status === 413 || CONTEXT_OVERFLOW_RE.test(err.message)) {\n return { kind: 'context_overflow', retryable: false };\n }\n if (err.status >= 400) return { kind: 'client', retryable: false };\n }\n if (err instanceof Error && NETWORK_ERR_RE.test(err.message)) {\n return { kind: 'network', retryable: true };\n }\n return { kind: 'unknown', retryable: false };\n }\n\n async recover(err: unknown, ctx: Context): Promise<RecoveryDecision | null> {\n for (const strategy of this.strategies) {\n const result = await strategy.attempt(err, ctx);\n if (result !== null) return result;\n }\n return null;\n }\n}\n","import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport type { SkillEntry, SkillLoader, SkillManifest } from '../types/skill.js';\nimport type { WstackPaths } from '../utils/wstack-paths.js';\n\nexport interface SkillLoaderOptions {\n paths: WstackPaths;\n bundledDir?: string;\n}\n\n/**\n * Discovery order (later layers shadow earlier ones at boot, but we walk\n * highest priority first and skip names already seen):\n * 1. Project-committed: <project>/.wrongstack/skills/\n * 2. User-global: ~/.wrongstack/skills/\n * 3. Bundled with build: packages/core/skills/\n */\nexport class DefaultSkillLoader implements SkillLoader {\n private readonly dirs: { dir: string; source: SkillManifest['source'] }[];\n private cache?: SkillManifest[];\n\n constructor(opts: SkillLoaderOptions) {\n this.dirs = [\n { dir: opts.paths.inProjectSkills, source: 'project' },\n { dir: opts.paths.globalSkills, source: 'user' },\n ];\n if (opts.bundledDir) {\n this.dirs.push({ dir: opts.bundledDir, source: 'bundled' });\n }\n }\n\n async list(): Promise<SkillManifest[]> {\n if (this.cache) return this.cache;\n const found: SkillManifest[] = [];\n const seen = new Set<string>();\n for (const { dir, source } of this.dirs) {\n try {\n const entries = await fs.readdir(dir, { withFileTypes: true });\n for (const e of entries) {\n if (!e.isDirectory()) continue;\n const skillFile = path.join(dir, e.name, 'SKILL.md');\n try {\n const raw = await fs.readFile(skillFile, 'utf8');\n const meta = parseFrontmatter(raw);\n if (!meta.name || !meta.description) continue;\n if (seen.has(meta.name)) continue;\n seen.add(meta.name);\n found.push({\n name: meta.name,\n description: meta.description,\n version: meta.version,\n path: skillFile,\n source,\n });\n } catch {\n // skip malformed skill\n }\n }\n } catch {\n // directory may not exist\n }\n }\n this.cache = found;\n return found;\n }\n\n async find(name: string): Promise<SkillManifest | undefined> {\n const all = await this.list();\n return all.find((s) => s.name === name);\n }\n\n async manifestText(): Promise<string> {\n const skills = await this.list();\n if (skills.length === 0) return '';\n const entries = await this.listEntries();\n const lines = ['## Available skills'];\n for (const e of entries) {\n const scopeTag = e.scope.length > 0 ? ` — ${e.scope.slice(0, 3).join(', ')}` : '';\n lines.push(`- **${e.name}**${scopeTag}`);\n lines.push(` Use when: ${e.trigger}`);\n }\n return lines.join('\\n');\n }\n\n async listEntries(): Promise<SkillEntry[]> {\n const skills = await this.list();\n const entries: SkillEntry[] = [];\n for (const s of skills) {\n try {\n const raw = await fs.readFile(s.path, 'utf8');\n const { trigger, scope } = parseDescription(raw);\n entries.push({ name: s.name, trigger, scope, source: s.source, path: s.path });\n } catch {\n // skip\n }\n }\n return entries;\n }\n\n invalidateCache(): void {\n this.cache = undefined;\n }\n\n async readBody(name: string): Promise<string> {\n const m = await this.find(name);\n if (!m) throw new Error(`Skill \"${name}\" not found`);\n return fs.readFile(m.path, 'utf8');\n }\n}\n\ninterface Frontmatter {\n name?: string;\n description?: string;\n version?: string;\n}\n\nfunction parseFrontmatter(raw: string): Frontmatter {\n if (!raw.startsWith('---')) return {};\n const end = raw.indexOf('\\n---', 4);\n if (end === -1) return {};\n const block = raw.slice(4, end);\n const out: Frontmatter = {};\n let key: keyof Frontmatter | null = null;\n let value: string[] = [];\n const flush = () => {\n if (key) {\n out[key] = value.join('\\n').trim();\n }\n key = null;\n value = [];\n };\n for (const line of block.split('\\n')) {\n const m = /^([a-zA-Z_]+):\\s*(\\|?)\\s*(.*)$/.exec(line);\n if (m) {\n flush();\n key = (m[1] ?? '') as keyof Frontmatter;\n const pipe = m[2];\n const rest = m[3] ?? '';\n if (pipe === '|') {\n value = [];\n } else if (rest) {\n value = [rest];\n } else {\n value = [];\n }\n } else if (key) {\n value.push(line.replace(/^\\s+/, ''));\n }\n }\n flush();\n return out;\n}\n\n/**\n * Parse skill description into:\n * - trigger: extracted \"Use when...\" sentence (first sentence of description)\n * - scope: comma-separated items from first line's parenthetical or file-ext list\n */\nfunction parseDescription(raw: string): { trigger: string; scope: string[] } {\n const fm = parseFrontmatter(raw);\n const desc = fm.description ?? '';\n\n // Extract first sentence as trigger\n const firstSentenceEnd = desc.indexOf('. ');\n const trigger =\n firstSentenceEnd !== -1\n ? desc.slice(0, firstSentenceEnd + 1).trim()\n : (desc.trim().split('\\n')[0] ?? '');\n\n // Extract scope from parenthetical: \"Covers X, Y, and Z\" or \"for A, B, C\"\n const scope: string[] = [];\n const coversMatch = /(?:covers|for|including)\\s+([^.]+)/i.exec(desc);\n if (coversMatch) {\n const items = coversMatch[1]!\n .replace(/[·•]/g, ',')\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean);\n scope.push(...items);\n }\n\n return { trigger, scope };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/utils/token-estimate.ts","../../src/utils/message-invariants.ts","../../src/execution/compactor.ts","../../src/types/blocks.ts","../../src/execution/intelligent-compactor.ts","../../src/models/llm-selector.ts","../../src/execution/selective-compactor.ts","../../src/types/errors.ts","../../src/execution/auto-compaction-middleware.ts","../../src/security/capabilities.ts","../../src/utils/json-schema-validate.ts","../../src/utils/tool-output-serializer.ts","../../src/execution/tool-executor.ts","../../src/utils/regex-guard.ts","../../src/execution/autonomous-runner.ts","../../src/utils/atomic-write.ts","../../src/storage/goal-store.ts","../../src/execution/eternal-autonomy.ts","../../src/coordination/subagent-budget.ts","../../src/coordination/agent-subagent-runner.ts","../../src/coordination/agents/types.ts","../../src/coordination/agents/phase1-discovery.ts","../../src/coordination/agents/phase2-planning.ts","../../src/coordination/agents/phase3-build.ts","../../src/coordination/agents/phase4-verify.ts","../../src/coordination/agents/phase5-review.ts","../../src/coordination/agents/phase6-domain.ts","../../src/coordination/agents/phase7-knowledge.ts","../../src/coordination/agents/phase8-delivery.ts","../../src/coordination/agents/phase9-meta.ts","../../src/coordination/agents/index.ts","../../src/coordination/dispatcher.ts","../../src/types/provider.ts","../../src/coordination/fleet.ts","../../src/coordination/subagent-nicknames.ts","../../src/coordination/multi-agent-coordinator.ts","../../src/execution/parallel-eternal-engine.ts","../../src/execution/autonomy-prompt-contributor.ts","../../src/execution/goal-preamble.ts","../../src/execution/regex-patterns.ts","../../src/execution/retry-policy.ts","../../src/execution/error-handler.ts","../../src/execution/skill-loader.ts"],"names":["hasToolUse","repair","afterTokens","afterFull","path","stat","resolve","path2","fsp","unlink","first","decision","kind","baseMessage","sleep","GOAL_COMPLETE_MARKER","randomUUID","execFile","promisify","execFileP","fs2","path3"],"mappings":";;;;;;;;;AAoBA,IAAM,kBAAA,GAAqB,CAAC,IAAA,EAAc,aAAA,GAAgB,GAAA,KACxD,IAAA,CAAK,GAAA,CAAI,CAAA,EAAG,IAAA,CAAK,IAAA,CAAK,IAAA,CAAK,MAAA,GAAS,aAAa,CAAC,CAAA;AAoBpD,IAAM,cAAA,uBAAqB,GAAA,EAAoB;AAE/C,IAAM,uBAAA,GAA0B,GAAA;AAEhC,SAAS,iBAAA,CAAkB,KAAa,OAAA,EAA+B;AACrE,EAAA,MAAM,QAAA,GAAW,cAAA,CAAe,GAAA,CAAI,GAAG,CAAA;AACvC,EAAA,IAAI,QAAA,KAAa,QAAW,OAAO,QAAA;AACnC,EAAA,IAAI,cAAA,CAAe,QAAQ,uBAAA,EAAyB;AAElD,IAAA,MAAM,IAAA,GAAO,CAAC,GAAG,cAAA,CAAe,MAAM,CAAA;AACtC,IAAA,KAAA,IAAS,CAAA,GAAI,GAAG,CAAA,GAAI,IAAA,CAAK,MAAM,uBAAA,GAA0B,CAAC,GAAG,CAAA,EAAA,EAAK;AAChE,MAAA,cAAA,CAAe,MAAA,CAAO,IAAA,CAAK,CAAC,CAAE,CAAA;AAAA,IAChC;AAAA,EACF;AACA,EAAA,MAAM,WAAW,OAAA,EAAQ;AACzB,EAAA,cAAA,CAAe,GAAA,CAAI,KAAK,QAAQ,CAAA;AAChC,EAAA,OAAO,Q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AAQ,OAAA,EAAS,GAAG,CAAA,CACpB,KAAA,CAAM,GAAG,CAAA,CACT,GAAA,CAAI,CAAC,CAAA,KAAM,CAAA,CAAE,MAAM,CAAA,CACnB,OAAO,OAAO,CAAA;AACjB,IAAA,KAAA,CAAM,IAAA,CAAK,GAAG,KAAK,CAAA;AAAA,EACrB;AAEA,EAAA,OAAO,EAAE,SAAS,KAAA,EAAM;AAC1B","file":"index.js","sourcesContent":["/**\n * Shared token estimation with JSON.stringify caching.\n * Avoids repeated stringification of tool input objects.\n *\n * ## Calibration\n *\n * `estimateRequestTokens` uses a fixed 3.5 chars/token heuristic — a\n * conservative overestimate that prevents underestimation but reduces\n * accuracy. After each API call, call `recordActualUsage()` with the\n * real `usage.input` from the provider response. The module maintains a\n * rolling average of `actual / estimated` ratio (EWM, α=0.3) and\n * applies it to subsequent calls via `estimateRequestTokensCalibrated`.\n *\n * Calibration is per-module (shared across all callers), which is\n * sufficient: the chars/token ratio is a property of the tokenizer,\n * not the model. Uncalibrated calls (before any samples, or when\n * `recordActualUsage` is not called) fall back to the uncalibrated\n * estimate so nothing breaks.\n */\n\nconst RoughTokenEstimate = (text: string, charsPerToken = 3.5): number =>\n Math.max(1, Math.ceil(text.length / charsPerToken));\n\n/** Calibration state: actual/estimated ratio via exponential weighted moving average. */\nconst _cal = {\n ratio: 1.0, // current calibration multiplier (actual / estimated)\n count: 0, // number of samples recorded\n prevEst: 0, // estimated tokens from the most recent estimateRequestTokens call\n /** EWM α — higher = faster adaptation, more volatile */\n alpha: 0.3,\n};\n\nconst MIN_SAMPLES_FOR_CALIBRATION = 3;\n\n/**\n * Cache of computed estimates keyed by the stringified input — not the\n * input object itself. Previously the cache was keyed by the input object\n * via WeakMap, but JSON.stringify() produces a new object reference each\n * call so the cache never hit. Now we use a Map with string keys so that\n * repeated stringifications of the same structure share a single entry.\n */\nconst ESTIMATE_CACHE = new Map<string, number>();\n\nconst ESTIMATE_CACHE_MAX_SIZE = 10_000;\n\nfunction getCachedEstimate(key: string, compute: () => number): number {\n const existing = ESTIMATE_CACHE.get(key);\n if (existing !== undefined) return existing;\n if (ESTIMATE_CACHE.size >= ESTIMATE_CACHE_MAX_SIZE) {\n // Evict oldest quarter when at capacity — simple LRU-ish policy.\n const keys = [...ESTIMATE_CACHE.keys()];\n for (let i = 0; i < Math.floor(ESTIMATE_CACHE_MAX_SIZE / 4); i++) {\n ESTIMATE_CACHE.delete(keys[i]!);\n }\n }\n const estimate = compute();\n ESTIMATE_CACHE.set(key, estimate);\n return estimate;\n}\n\n/**\n * Estimate tokens for a tool_use block input.\n * Caches the stringified result keyed by the stable string representation\n * to avoid repeated JSON.stringify calls during context window checks.\n */\nexport function estimateToolInputTokens(input: unknown): number {\n if (typeof input === 'string') return RoughTokenEstimate(input);\n if (input === null || typeof input !== 'object') {\n return RoughTokenEstimate(String(input));\n }\n const key = JSON.stringify(input);\n return getCachedEstimate(key, () => RoughTokenEstimate(key));\n}\n\n/**\n * Estimate tokens for a tool_result content.\n */\nexport function estimateToolResultTokens(content: string | unknown): number {\n if (typeof content === 'string') return RoughTokenEstimate(content);\n const key = JSON.stringify(content);\n return getCachedEstimate(key, () => RoughTokenEstimate(key));\n}\n\n/**\n * Estimate tokens for a text block.\n */\nexport function estimateTextTokens(text: string): number {\n return RoughTokenEstimate(text);\n}\n\n/**\n * Rough estimate of tokens in a tool definition (name + description + schema).\n * Accounts for the JSON-serialized inputSchema which is sent to the API\n * but NOT included in roughEstimate(content).\n */\nexport function estimateToolDefTokens(tool: { name: string; description?: string; inputSchema: unknown }): number {\n return RoughTokenEstimate(tool.name) +\n RoughTokenEstimate(tool.description ?? '') +\n RoughTokenEstimate(JSON.stringify(tool.inputSchema));\n}\n\n/**\n * Estimate the total API request token count: system prompt + tool definitions\n * + conversation messages. Use this for context-window bar calculations\n * instead of roughEstimate (which only counts messages).\n *\n * The overhead ratio (overhead / messages) varies by conversation length:\n * - Short conversations (< 10 messages): ~30-50% overhead (large system+tools)\n * - Medium (10-50 messages): ~15-30%\n * - Long (> 50 messages): ~5-15%\n *\n * Returns { messages, systemPrompt, tools, total } for debugging display.\n */\nexport interface RequestTokenBreakdown {\n messages: number;\n systemPrompt: number;\n tools: number;\n total: number;\n}\n\nexport function estimateRequestTokens(\n messages: unknown,\n systemPrompt: unknown,\n tools: { name: string; description?: string; inputSchema: unknown }[],\n): RequestTokenBreakdown {\n // Messages: apply the same logic as roughEstimate\n let messagesTokens = 0;\n if (typeof messages === 'string') {\n messagesTokens = RoughTokenEstimate(messages);\n } else if (Array.isArray(messages)) {\n for (const m of messages) {\n if (typeof m === 'object' && m !== null && 'content' in m) {\n const content = (m as { content: unknown }).content;\n if (typeof content === 'string') {\n messagesTokens += RoughTokenEstimate(content);\n } else if (Array.isArray(content)) {\n for (const b of content) {\n if (typeof b === 'object' && b !== null) {\n if ((b as { type?: string }).type === 'text') {\n messagesTokens += RoughTokenEstimate((b as { text: string }).text);\n } else {\n messagesTokens += RoughTokenEstimate(JSON.stringify(b));\n }\n }\n }\n }\n }\n }\n }\n\n // System prompt\n let systemTokens = 0;\n if (typeof systemPrompt === 'string') {\n systemTokens = RoughTokenEstimate(systemPrompt);\n } else if (Array.isArray(systemPrompt)) {\n for (const b of systemPrompt) {\n if (typeof b === 'object' && b !== null && (b as { type?: string }).type === 'text') {\n systemTokens += RoughTokenEstimate((b as { text: string }).text);\n }\n }\n }\n\n // Tool definitions\n let toolsTokens = 0;\n for (const t of tools) {\n toolsTokens += estimateToolDefTokens(t);\n }\n\n const total = messagesTokens + systemTokens + toolsTokens;\n\n // Record the raw estimate for calibration: the next recordActualUsage()\n // call will pair this against the actual API usage so the rolling ratio\n // stays in sync with the real chars/token ratio of the content.\n _cal.prevEst = total;\n\n return {\n messages: messagesTokens,\n systemPrompt: systemTokens,\n tools: toolsTokens,\n total,\n };\n}\n\n/**\n * Record the actual API input token count after a provider call so\n * `estimateRequestTokensCalibrated` can self-correct on subsequent calls.\n *\n * Prefer passing `estimatedInputTokens` explicitly (the calibrated pre-flight\n * estimate from the middleware) — this avoids race conditions when other code\n * also calls `estimateRequestTokens` between the pre-flight and this call\n * (e.g. audit logging in agent.ts).\n *\n * When `estimatedInputTokens` is omitted, falls back to `_cal.prevEst`\n * for backward compatibility with callers that don't have the pre-flight value.\n */\nexport function recordActualUsage(actualInputTokens: number, estimatedInputTokens?: number): void {\n if (actualInputTokens <= 0) return;\n const est = estimatedInputTokens ?? _cal.prevEst;\n if (est <= 0) return;\n\n const sampleRatio = actualInputTokens / est;\n if (_cal.count === 0) {\n _cal.ratio = sampleRatio;\n } else {\n // EWM: new = α * sample + (1-α) * old → α=0.3 = fast initial converge\n _cal.ratio = _cal.alpha * sampleRatio + (1 - _cal.alpha) * _cal.ratio;\n }\n // Sanity bound: keep the rolling ratio within [0.5, 1.5] so a sequence\n // of bad samples can't blow up the calibration for everyone.\n _cal.ratio = Math.min(1.5, Math.max(0.5, _cal.ratio));\n _cal.count++;\n}\n\n/**\n * Returns the current calibration state. Exposed for debugging and\n * tests — not needed by normal callers.\n */\nexport function getCalibrationState(): { ratio: number; count: number; calibrated: boolean } {\n return {\n ratio: _cal.ratio,\n count: _cal.count,\n calibrated: _cal.count >= MIN_SAMPLES_FOR_CALIBRATION,\n };\n}\n\n/**\n * Like `estimateRequestTokens` but applies the rolling calibration factor\n * so context pressure readings converge on reality within a few iterations.\n *\n * Before any `recordActualUsage` samples are collected, returns the same\n * result as `estimateRequestTokens` (ratio = 1.0, no distortion).\n * After `MIN_SAMPLES_FOR_CALIBRATION` samples, applies the calibrated\n * multiplier capped to the range [0.5, 1.5] as a sanity bound.\n */\nexport function estimateRequestTokensCalibrated(\n messages: unknown,\n systemPrompt: unknown,\n tools: { name: string; description?: string; inputSchema: unknown }[],\n): RequestTokenBreakdown {\n const result = estimateRequestTokens(messages, systemPrompt, tools);\n\n if (_cal.count >= MIN_SAMPLES_FOR_CALIBRATION) {\n const safeRatio = Math.min(1.5, Math.max(0.5, _cal.ratio));\n return {\n messages: Math.round(result.messages * safeRatio),\n systemPrompt: Math.round(result.systemPrompt * safeRatio),\n tools: Math.round(result.tools * safeRatio),\n total: Math.round(result.total * safeRatio),\n };\n }\n\n return result;\n}\n\n/**\n * Resets calibration state. Primarily for tests that run in the same\n * process and need a clean slate between suites.\n */\nexport function resetCalibration(): void {\n _cal.ratio = 1.0;\n _cal.count = 0;\n _cal.prevEst = 0;\n}\n","import type { ContentBlock, ToolResultBlock, ToolUseBlock } from '../types/blocks.js';\nimport type { Message } from '../types/messages.js';\n\nexport interface MessageRepairReport {\n changed: boolean;\n removedToolUses: string[];\n removedToolResults: string[];\n removedMessages: number;\n}\n\nexport interface MessageRepairResult {\n messages: Message[];\n report: MessageRepairReport;\n}\n\n/**\n * Repair provider-level tool-call adjacency invariants.\n *\n * Anthropic requires every assistant `tool_use` block to have a matching\n * `tool_result` block in the immediately following user message. Manual\n * context surgery (summary/prune) can cut through the middle of such an\n * exchange. This function removes only the now-orphaned protocol blocks,\n * preserving surrounding text/images/thinking blocks where possible.\n */\nexport function repairToolUseAdjacency(messages: Message[]): MessageRepairResult {\n const removedToolUses: string[] = [];\n const removedToolResults: string[] = [];\n let removedMessages = 0;\n let changed = false;\n const out: Message[] = [];\n\n for (let i = 0; i < messages.length; i++) {\n const original = messages[i]!;\n let msg = original;\n\n if (hasToolUse(msg)) {\n const nextIds = toolResultIds(messages[i + 1]);\n const filtered = mapContent(msg, (blocks) => {\n const next: ContentBlock[] = [];\n for (const block of blocks) {\n if (block.type === 'tool_use' && !nextIds.has(block.id)) {\n removedToolUses.push(block.id);\n changed = true;\n continue;\n }\n next.push(block);\n }\n return next;\n });\n msg = filtered ?? msg;\n }\n\n if (hasToolResult(msg)) {\n const allowed = toolUseIds(out[out.length - 1]);\n const filtered = mapContent(msg, (blocks) => {\n const next: ContentBlock[] = [];\n for (const block of blocks) {\n if (block.type === 'tool_result' && !allowed.has(block.tool_use_id)) {\n removedToolResults.push(block.tool_use_id);\n changed = true;\n continue;\n }\n next.push(block);\n }\n return next;\n });\n msg = filtered ?? msg;\n }\n\n if (isEmptyMessage(msg)) {\n removedMessages++;\n changed = true;\n continue;\n }\n out.push(msg);\n }\n\n return {\n messages: changed ? out : messages,\n report: { changed, removedToolUses, removedToolResults, removedMessages },\n };\n}\n\nfunction hasToolUse(msg: Message | undefined): boolean {\n return contentBlocks(msg).some((b): b is ToolUseBlock => b.type === 'tool_use');\n}\n\nfunction hasToolResult(msg: Message | undefined): boolean {\n return contentBlocks(msg).some((b): b is ToolResultBlock => b.type === 'tool_result');\n}\n\nfunction toolUseIds(msg: Message | undefined): Set<string> {\n const ids = new Set<string>();\n if (!msg || msg.role !== 'assistant') return ids;\n for (const block of contentBlocks(msg)) {\n if (block.type === 'tool_use') ids.add(block.id);\n }\n return ids;\n}\n\nfunction toolResultIds(msg: Message | undefined): Set<string> {\n const ids = new Set<string>();\n if (!msg || msg.role !== 'user') return ids;\n for (const block of contentBlocks(msg)) {\n if (block.type === 'tool_result') ids.add(block.tool_use_id);\n }\n return ids;\n}\n\nfunction contentBlocks(msg: Message | undefined): ContentBlock[] {\n return msg && Array.isArray(msg.content) ? msg.content : [];\n}\n\nfunction mapContent(\n msg: Message,\n fn: (blocks: ContentBlock[]) => ContentBlock[],\n): Message | null {\n if (!Array.isArray(msg.content)) return msg;\n const next = fn(msg.content);\n if (next.length === msg.content.length && next.every((b, idx) => b === msg.content[idx])) {\n return msg;\n }\n return { ...msg, content: next };\n}\n\nfunction isEmptyMessage(msg: Message): boolean {\n if (typeof msg.content === 'string') return msg.content.trim().length === 0;\n return msg.content.length === 0;\n}\n","import type { Context } from '../core/context.js';\nimport type { ContentBlock, ToolResultBlock } from '../types/blocks.js';\nimport type { CompactReport, Compactor } from '../types/compactor.js';\nimport type { ContextWindowPolicy } from '../types/context-window.js';\nimport type { Message } from '../types/messages.js';\nimport {\n estimateTextTokens,\n estimateToolInputTokens,\n estimateToolResultTokens,\n estimateRequestTokens,\n} from '../utils/token-estimate.js';\nimport { repairToolUseAdjacency } from '../utils/message-invariants.js';\n\nexport interface CompactorOptions {\n preserveK?: number;\n eliseThreshold?: number;\n estimator?: (text: string) => number;\n}\n\n/**\n * Default tools config values shared across CLI and WebUI.\n * Import this instead of hardcoding to avoid cross-surface inconsistencies.\n * These mirror the values in BEHAVIOR_DEFAULTS (config-loader.ts).\n *\n * @deprecated Import from '../types/default-config.js' instead.\n * This re-export exists for backward compatibility.\n */\nexport { DEFAULT_TOOLS_CONFIG, DEFAULT_CONTEXT_CONFIG, DEFAULT_AUTONOMY_CONFIG } from '../types/default-config.js';\n\nexport class HybridCompactor implements Compactor {\n private readonly preserveK: number;\n private readonly eliseThreshold: number;\n private readonly estimator: (text: string) => number;\n\n constructor(opts: CompactorOptions = {}) {\n this.preserveK = opts.preserveK ?? 5;\n this.eliseThreshold = opts.eliseThreshold ?? 2000;\n this.estimator = opts.estimator ?? estimateTextTokens;\n }\n\n async compact(ctx: Context, opts: { aggressive?: boolean } = {}): Promise<CompactReport> {\n const beforeTokens = this.estimateMessages(ctx.messages);\n const beforeFull = this.estimateFullRequest(ctx);\n const reductions: CompactReport['reductions'] = [];\n const policy = readContextWindowPolicy(ctx);\n const preserveK = policy?.preserveK ?? this.preserveK;\n const eliseThreshold = policy?.eliseThreshold ?? this.eliseThreshold;\n\n // Phase 1: elision\n const phase1Saved = this.eliseOldToolResults(ctx, preserveK, eliseThreshold);\n if (phase1Saved > 0) reductions.push({ phase: 'elision', saved: phase1Saved });\n\n // Phase 2: summary (placeholder; in production calls sub-LLM)\n if (opts.aggressive) {\n const phase2Saved = this.collapseAncientTurns(ctx, preserveK);\n if (phase2Saved > 0) reductions.push({ phase: 'summary', saved: phase2Saved });\n }\n\n const repaired = repairToolUseAdjacency(ctx.messages);\n if (repaired.report.changed) {\n ctx.state.replaceMessages(repaired.messages);\n }\n\n const afterTokens = this.estimateMessages(ctx.messages);\n const afterFull = this.estimateFullRequest(ctx);\n return {\n before: beforeTokens,\n after: afterTokens,\n fullRequestTokensBefore: beforeFull,\n fullRequestTokensAfter: afterFull,\n reductions,\n repaired: repaired.report.changed\n ? {\n removedToolUses: repaired.report.removedToolUses,\n removedToolResults: repaired.report.removedToolResults,\n removedMessages: repaired.report.removedMessages,\n }\n : undefined,\n };\n }\n\n /**\n * Estimate the full API request token count: messages + systemPrompt + toolDefs.\n * This is the accurate figure for context-window pressure monitoring.\n */\n private estimateFullRequest(ctx: Context): number {\n const breakdown = estimateRequestTokens(ctx.messages, ctx.systemPrompt, ctx.tools ?? []);\n return breakdown.total;\n }\n\n private eliseOldToolResults(\n ctx: Context,\n preserveK = this.preserveK,\n eliseThreshold = this.eliseThreshold,\n ): number {\n const messages = ctx.messages;\n // Walk backwards counting (user + assistant) pairs to determine where\n // the preservation window really starts. This is more accurate than\n // the fixed multiplier which assumes every turn is 1 message pair.\n let pairCount = 0;\n let preserveStart = messages.length;\n for (let i = messages.length - 1; i >= 0 && pairCount < preserveK; i--) {\n const m = messages[i];\n if (!m) continue;\n if (m.role === 'user' || m.role === 'assistant') {\n pairCount++;\n preserveStart = i;\n }\n }\n\n // Ensure tool_use/tool_result protocol pairs are preserved together.\n // Walk forward through the preserved window: if an assistant message\n // at or after preserveStart contains a tool_use, also preserve the\n // immediately following message (the tool_result) so neither is elided.\n for (let i = preserveStart; i < messages.length; i++) {\n const m = messages[i];\n if (!m || typeof m.content === 'string' || !Array.isArray(m.content)) continue;\n const hasToolUse = m.content.some((b) => b.type === 'tool_use');\n if (hasToolUse && i + 1 < messages.length) {\n const next = messages[i + 1];\n if (\n next &&\n next.role === 'user' &&\n typeof next.content !== 'string' &&\n Array.isArray(next.content) &&\n next.content.some((b) => b.type === 'tool_result')\n ) {\n // Extend preserveStart to cover the tool_result as well so\n // the protocol pair stays complete and readable.\n preserveStart = i + 1;\n }\n }\n }\n\n let saved = 0;\n let changed = false;\n const nextMessages = new Array(messages.length);\n for (let i = 0; i < messages.length; i++) {\n const msg = messages[i];\n // Only process messages before the preservation window\n if (i >= preserveStart) {\n nextMessages[i] = msg;\n continue;\n }\n if (!msg || !Array.isArray(msg.content)) {\n nextMessages[i] = msg;\n continue;\n }\n const newContent: ContentBlock[] = msg.content.map((b) => {\n if (b.type !== 'tool_result') return b;\n const tokens = estimateToolResultTokens(b.content);\n if (tokens < eliseThreshold) return b;\n saved += tokens;\n const elided: ToolResultBlock = {\n type: 'tool_result',\n tool_use_id: b.tool_use_id,\n content: `[elided: ~${tokens} tokens]`,\n is_error: b.is_error,\n };\n return elided;\n });\n // Check whether any block actually changed by reference equality\n if (\n newContent.length === msg.content.length &&\n newContent.every((b, idx) => b === msg.content[idx])\n ) {\n nextMessages[i] = msg;\n } else {\n nextMessages[i] = { ...msg, content: newContent };\n changed = true;\n }\n }\n if (changed) ctx.state.replaceMessages(nextMessages);\n return saved;\n }\n\n private collapseAncientTurns(ctx: Context, preserveK = this.preserveK): number {\n const messages = ctx.messages;\n const cutTarget = Math.max(0, messages.length - preserveK * 2);\n if (cutTarget <= 0) return 0;\n\n // Find a safe boundary: nearest user-message-with-text at or after cutTarget\n let boundary = -1;\n for (let i = cutTarget; i < messages.length; i++) {\n const m = messages[i];\n if (!m) continue;\n if (m.role === 'user' && hasTextContent(m)) {\n boundary = i;\n break;\n }\n }\n if (boundary <= 0) return 0;\n\n const removed = messages.slice(0, boundary);\n const removedTokens = this.estimateMessages(removed);\n\n const summary: Message[] = [\n {\n role: 'user',\n content: `[previous_session_summary: ${removed.length} earlier turns compacted. Todo state preserved in context.]`,\n },\n { role: 'assistant', content: 'Continuing from compacted context.' },\n ];\n\n // L1-A: route through ConversationState so subscribers see the rewrite.\n const tail = ctx.messages.slice(boundary);\n ctx.state.replaceMessages([...summary, ...tail]);\n return Math.max(0, removedTokens - this.estimateMessages(summary));\n }\n\n private estimateMessages(messages: Message[]): number {\n let total = 0;\n for (const m of messages) {\n if (typeof m.content === 'string') {\n total += this.estimator(m.content);\n } else {\n for (const b of m.content) {\n if (b.type === 'text') total += this.estimator(b.text);\n else if (b.type === 'tool_use') total += estimateToolInputTokens(b.input);\n else if (b.type === 'tool_result') total += estimateToolResultTokens(b.content);\n }\n }\n }\n return total;\n }\n}\n\nfunction readContextWindowPolicy(ctx: Context): ContextWindowPolicy | null {\n const policy = ctx.meta?.['contextWindowPolicy'];\n if (!policy || typeof policy !== 'object') return null;\n const candidate = policy as Partial<ContextWindowPolicy>;\n if (\n typeof candidate.preserveK !== 'number' ||\n typeof candidate.eliseThreshold !== 'number'\n ) {\n return null;\n }\n return candidate as ContextWindowPolicy;\n}\n\nfunction hasTextContent(m: Message): boolean {\n if (typeof m.content === 'string') return m.content.trim().length > 0;\n return m.content.some((b) => b.type === 'text' && b.text.trim().length > 0);\n}\n","export interface TextBlock {\n type: 'text';\n text: string;\n cache_control?: { type: 'ephemeral' };\n}\n\nexport interface ToolUseBlock {\n type: 'tool_use';\n id: string;\n name: string;\n input: Record<string, unknown>;\n /**\n * Provider-specific opaque metadata captured from the wire response.\n * Echoed back verbatim in the next request so providers that bind\n * extra state to function calls keep working. Example: Gemini's\n * `thoughtSignature` — required for tool-use turns with thinking\n * models, otherwise the next request fails with 400 \"Function call\n * is missing a thought_signature in functionCall parts\".\n *\n * Keys are namespaced by intent so multiple wires can coexist:\n * - `google.thoughtSignature` — Gemini signed-thought blob\n * Other providers can add their own keys without colliding.\n */\n providerMeta?: Record<string, unknown>;\n}\n\nexport interface ToolResultBlock {\n type: 'tool_result';\n tool_use_id: string;\n /**\n * The original tool name. Useful for providers like Google Gemini that\n * need the tool name in `functionResponse.name` — the tool_use_id is\n * only a session-local identifier and is not stable across replays.\n * Always set by ToolExecutor; may be absent on manually-constructed blocks.\n */\n name?: string;\n content: string;\n is_error?: boolean;\n}\n\nexport interface ImageBlock {\n type: 'image';\n source: {\n type: 'base64' | 'url';\n media_type?: string;\n data?: string;\n url?: string;\n };\n}\n\n/**\n * Chain-of-thought / extended-thinking content emitted by the model.\n *\n * Both Anthropic extended thinking (`{type:'thinking', thinking, signature}`)\n * and DeepSeek reasoning mode (top-level `reasoning_content` on the assistant\n * message) require this content to be echoed back verbatim on the next\n * request, otherwise the provider returns 400:\n * - Anthropic: \"The `content[].thinking` in the thinking mode must be passed back\"\n * - DeepSeek: \"The `reasoning_content` in the thinking mode must be passed back\"\n *\n * `signature` is Anthropic-specific (an opaque integrity blob). DeepSeek\n * doesn't issue a signature — the field is absent for that provider.\n *\n * Per Anthropic, thinking blocks MUST appear before any text/tool_use blocks\n * in an assistant message. Stream builders preserve that order.\n */\nexport interface ThinkingBlock {\n type: 'thinking';\n thinking: string;\n signature?: string;\n providerMeta?: Record<string, unknown>;\n}\n\nexport type ContentBlock = TextBlock | ToolUseBlock | ToolResultBlock | ImageBlock | ThinkingBlock;\n\nexport function isTextBlock(b: ContentBlock): b is TextBlock {\n return b.type === 'text';\n}\nexport function isToolUseBlock(b: ContentBlock): b is ToolUseBlock {\n return b.type === 'tool_use';\n}\nexport function isToolResultBlock(b: ContentBlock): b is ToolResultBlock {\n return b.type === 'tool_result';\n}\nexport function isImageBlock(b: ContentBlock): b is ImageBlock {\n return b.type === 'image';\n}\nexport function isThinkingBlock(b: ContentBlock): b is ThinkingBlock {\n return b.type === 'thinking';\n}\n","import type { Context } from '../core/context.js';\nimport type { ContentBlock, TextBlock } from '../types/blocks.js';\nimport { isTextBlock } from '../types/blocks.js';\nimport type { CompactReport, Compactor } from '../types/compactor.js';\nimport type { Message } from '../types/messages.js';\nimport type { Provider, Request } from '../types/provider.js';\nimport {\n estimateTextTokens,\n estimateToolInputTokens,\n estimateToolResultTokens,\n estimateRequestTokens,\n} from '../utils/token-estimate.js';\nimport { repairToolUseAdjacency } from '../utils/message-invariants.js';\n\n/**\n * Options for IntelligentCompactor.\n */\nexport interface IntelligentCompactorOptions {\n /** Provider to use for LLM-assisted summarization. Required. */\n provider: Provider;\n /** Fraction of maxContext that triggers a warning (default 0.6). */\n warnThreshold?: number;\n /** Fraction of maxContext that triggers soft compaction (default 0.75). */\n softThreshold?: number;\n /** Fraction of maxContext that triggers hard compaction (default 0.9). */\n hardThreshold?: number;\n /** Max context window in tokens (used only for threshold fraction math). */\n maxContext?: number;\n /** How many recent (user+assistant) pairs to always preserve (default 4). */\n preserveK?: number;\n /** Token threshold below which tool results are not elided (default 500). */\n eliseThreshold?: number;\n /** System prompt for the summarizer sub-LLM. */\n summarizerPrompt?: string;\n /**\n * Model ID to use for summarization. When not set, the same model as the\n * agent is used (which risks cascading failure on context overflow). Set to\n * a fast/cheap model like `claude-3-5-haiku-20240620` for resilience.\n */\n summarizerModel?: string;\n}\n\n/**\n * An importance label for a message or message range.\n */\nexport type Importance = 'critical' | 'high' | 'medium' | 'low';\n\n/**\n * Result of importance analysis.\n */\nexport interface ImportanceAnalysis {\n messages: Array<{ index: number; importance: Importance; reason: string }>;\n criticalRanges: Array<{ from: number; to: number; summary: string }>;\n}\n\n/**\n * IntelligentCompactor uses an LLM to:\n * - Analyze message importance and preserve critical context\n * - Generate semantic summaries for old message ranges\n * - Make intelligent decisions about what to compact\n *\n * It extends HybridCompactor's elision logic with LLM-assisted summarization.\n */\nexport class IntelligentCompactor implements Compactor {\n private readonly provider: Provider;\n private readonly warnThreshold: number;\n private readonly softThreshold: number;\n private readonly hardThreshold: number;\n private readonly maxContext: number;\n private readonly preserveK: number;\n private readonly eliseThreshold: number;\n private readonly summarizerPrompt: string;\n private readonly summarizerModel?: string;\n\n constructor(opts: IntelligentCompactorOptions) {\n this.provider = opts.provider;\n this.warnThreshold = opts.warnThreshold ?? 0.6;\n this.softThreshold = opts.softThreshold ?? 0.75;\n this.hardThreshold = opts.hardThreshold ?? 0.9;\n this.maxContext = opts.maxContext ?? 128_000;\n this.preserveK = opts.preserveK ?? 4;\n this.eliseThreshold = opts.eliseThreshold ?? 500;\n this.summarizerPrompt =\n opts.summarizerPrompt ??\n 'You are a context summarizer. Given a list of conversation messages, produce a concise but complete summary that preserves all factual information, decisions made, and any state changes (e.g. file edits, todo updates). Do not add commentary. Output only the summary.';\n this.summarizerModel = opts.summarizerModel;\n }\n\n async compact(ctx: Context, opts: { aggressive?: boolean } = {}): Promise<CompactReport> {\n const beforeTokens = this.estimateTokens(ctx.messages);\n const beforeFull = this.estimateFullRequest(ctx);\n const reductions: CompactReport['reductions'] = [];\n\n // Use full request tokens for threshold decisions — messages alone are inaccurate.\n const load = beforeFull / this.maxContext;\n // Past hardThreshold, force aggressive regardless of caller preference —\n // the alternative (lightweight elision) is unlikely to recover enough.\n const aggressive =\n load >= this.hardThreshold ? true : (opts.aggressive ?? load >= this.softThreshold);\n\n // Phase 1: always run elision (preserves recent K pairs)\n const saved1 = this.eliseOldToolResults(ctx);\n if (saved1 > 0) reductions.push({ phase: 'elision', saved: saved1 });\n\n // Phase 2: LLM summarization of ancient turns\n if (aggressive) {\n const saved2 = await this.summarizeAncientTurns(ctx);\n if (saved2 > 0) reductions.push({ phase: 'summary', saved: saved2 });\n } else if (load >= this.warnThreshold) {\n // Non-aggressive: do lightweight summarization via direct analysis\n const saved2 = this.lightweightCompact(ctx);\n if (saved2 > 0) reductions.push({ phase: 'elision', saved: saved2 });\n }\n\n const repaired = repairToolUseAdjacency(ctx.messages);\n if (repaired.report.changed) ctx.state.replaceMessages(repaired.messages);\n\n const afterTokens = this.estimateTokens(ctx.messages);\n const afterFull = this.estimateFullRequest(ctx);\n return {\n before: beforeTokens,\n after: afterTokens,\n fullRequestTokensBefore: beforeFull,\n fullRequestTokensAfter: afterFull,\n reductions,\n repaired: repaired.report.changed\n ? {\n removedToolUses: repaired.report.removedToolUses,\n removedToolResults: repaired.report.removedToolResults,\n removedMessages: repaired.report.removedMessages,\n }\n : undefined,\n };\n }\n\n /**\n * Estimate the full API request token count: messages + systemPrompt + toolDefs.\n * This is the accurate figure for context-window pressure monitoring.\n */\n private estimateFullRequest(ctx: Context): number {\n const breakdown = estimateRequestTokens(ctx.messages, ctx.systemPrompt, ctx.tools ?? []);\n return breakdown.total;\n }\n\n private async summarizeAncientTurns(ctx: Context): Promise<number> {\n const messages = ctx.messages;\n const cutoff = Math.max(0, messages.length - this.preserveK * 2);\n if (cutoff <= 2) return 0;\n\n // Find the best boundary in the ancient region\n const boundary = this.findSafeBoundary(messages, 0, cutoff);\n if (boundary <= 1) return 0;\n\n const toSummarize = messages.slice(0, boundary);\n const removedTokens = this.estimateTokens(toSummarize);\n\n let summaryText: string;\n try {\n summaryText = await this.callSummarizer(toSummarize, ctx);\n } catch {\n // Fallback: preserve user/assistant text content while eliding tool results.\n // This keeps semantic information (instructions, decisions, conclusions)\n // without the token overhead of large tool outputs. Unlike the LLM summarizer,\n // this rule-based approach cannot fail and preserves factual content.\n const preservedMessages: Message[] = [];\n for (const m of toSummarize) {\n if (m.role === 'system') continue; // skip existing summaries\n if (typeof m.content === 'string') {\n preservedMessages.push(m);\n } else if (Array.isArray(m.content)) {\n const textParts = m.content.filter(isTextBlock);\n const toolParts = m.content.filter((b) => b.type === 'tool_use' || b.type === 'tool_result');\n // Keep text content; replace tool calls with a lightweight marker.\n const next: Message = {\n role: m.role,\n content: [\n ...textParts,\n ...(toolParts.length > 0\n ? [{ type: 'text' as const, text: `[${toolParts.length} tool call(s) omitted]` }]\n : []),\n ],\n };\n preservedMessages.push(next);\n }\n }\n summaryText = preservedMessages\n .map((m) => `[${m.role}]: ${typeof m.content === 'string' ? m.content : m.content.filter(isTextBlock).map((b) => b.text).join(' ')}`)\n .join('\\n');\n if (!summaryText) summaryText = `${toSummarize.length} earlier turns (semantic content preserved)`;\n }\n\n const summaryMsg: Message = {\n role: 'system',\n content: `[prior_turns_summary: ${summaryText}]`,\n };\n const summaryTokens = this.estimateTokens([summaryMsg]);\n\n // L1-A: route through ConversationState so subscribers see the rewrite.\n const tail = ctx.messages.slice(boundary);\n ctx.state.replaceMessages([summaryMsg, ...tail]);\n return Math.max(0, removedTokens - summaryTokens);\n }\n\n private findSafeBoundary(messages: Message[], from: number, to: number): number {\n // Find the nearest user message with text content at or after `to`\n // and walk backwards to find a safe cut point.\n for (let i = to; i >= from; i--) {\n const m = messages[i];\n if (!m) continue;\n if (m.role === 'user' && this.hasTextContent(m)) {\n // Ensure we don't cut inside a multi-message exchange\n // by finding the start of this exchange.\n return this.findExchangeStart(messages, i);\n }\n }\n return -1;\n }\n\n private findExchangeStart(messages: Message[], userIndex: number): number {\n // Walk backwards from userIndex to find where this logical exchange began.\n // An exchange starts after the last assistant message that had no tool calls.\n for (let i = userIndex - 1; i >= 0; i--) {\n const m = messages[i];\n if (!m) continue;\n if (m.role === 'assistant') {\n const hasToolUse = Array.isArray(m.content)\n ? m.content.some((b) => b.type === 'tool_use')\n : false;\n if (!hasToolUse) {\n // This assistant msg had no tool calls — it's a boundary\n return i + 1;\n }\n } else if (m.role !== 'user') {\n // system or other — skip\n } else {\n // another user msg — boundary\n return i;\n }\n }\n return 0;\n }\n\n private async callSummarizer(messages: Message[], ctx: Context): Promise<string> {\n const prompt: TextBlock[] = [\n { type: 'text', text: this.summarizerPrompt },\n { type: 'text', text: '\\n\\nConversation to summarize:\\n' },\n ...this.messagesToText(messages),\n ];\n\n const req: Request = {\n model: this.summarizerModel ?? ctx.model,\n system: prompt,\n messages: [],\n maxTokens: 1024,\n };\n\n // Use abort signal from context if available.\n // Fall back to a fresh controller only if ctx.signal is absent — this\n // avoids leaking AbortControllers on every summarizer call (the original\n // `?? new AbortController().signal` created a controller that was never\n // connected to anything, making cancellation a no-op).\n const ac = ctx.signal ? undefined : new AbortController();\n const signal = ctx.signal ?? ac!.signal;\n const res = await this.provider.complete(req, { signal });\n\n const textBlocks = res.content.filter(isTextBlock);\n return (\n textBlocks\n .map((b) => b.text)\n .join('\\n')\n .trim() || '(empty summary)'\n );\n }\n\n private messagesToText(messages: Message[]): TextBlock[] {\n const lines: string[] = [];\n for (const m of messages) {\n const role = m.role.padEnd(10, ' ');\n if (typeof m.content === 'string') {\n lines.push(`[${role}]: ${m.content.slice(0, 500)}`);\n } else if (Array.isArray(m.content)) {\n const textParts = m.content.filter(isTextBlock).map((b) => b.text);\n if (textParts.length > 0) {\n lines.push(`[${role}]: ${textParts.join(' ').slice(0, 500)}`);\n }\n }\n }\n return [{ type: 'text', text: lines.join('\\n') }];\n }\n\n private lightweightCompact(ctx: Context): number {\n // Lightweight: just elide very large tool results without full summarization\n return this.eliseOldToolResults(ctx);\n }\n\n private eliseOldToolResults(ctx: Context): number {\n const messages = ctx.messages;\n let pairCount = 0;\n let preserveStart = messages.length;\n for (let i = messages.length - 1; i >= 0 && pairCount < this.preserveK; i--) {\n const m = messages[i];\n if (!m) continue;\n if (m.role === 'user' || m.role === 'assistant') {\n pairCount++;\n preserveStart = i;\n }\n }\n\n // Ensure tool_use/tool_result protocol pairs are preserved together.\n // Walk forward through the preserved window: if an assistant message\n // at or after preserveStart contains a tool_use, also preserve the\n // immediately following message (the tool_result) so neither is elided.\n for (let i = preserveStart; i < messages.length; i++) {\n const m = messages[i];\n if (!m || typeof m.content === 'string' || !Array.isArray(m.content)) continue;\n const hasToolUse = m.content.some((b) => b.type === 'tool_use');\n if (hasToolUse && i + 1 < messages.length) {\n const next = messages[i + 1];\n if (\n next &&\n next.role === 'user' &&\n typeof next.content !== 'string' &&\n Array.isArray(next.content) &&\n next.content.some((b) => b.type === 'tool_result')\n ) {\n // Extend preserveStart to cover the tool_result as well so\n // the protocol pair stays complete and readable.\n preserveStart = i + 1;\n }\n }\n }\n\n let saved = 0;\n let changed = false;\n const nextMessages = new Array(messages.length);\n for (let i = 0; i < messages.length; i++) {\n const msg = messages[i];\n // Only process messages before the preservation window\n if (i >= preserveStart) {\n nextMessages[i] = msg;\n continue;\n }\n if (!msg || !Array.isArray(msg.content)) {\n nextMessages[i] = msg;\n continue;\n }\n const newContent: ContentBlock[] = msg.content.map((b) => {\n if (b.type !== 'tool_result') return b;\n const tokens = estimateToolResultTokens(b.content);\n if (tokens < this.eliseThreshold) return b;\n saved += tokens;\n return {\n type: 'tool_result',\n tool_use_id: b.tool_use_id,\n content: `[elided: ~${tokens} tokens]`,\n is_error: b.is_error,\n };\n });\n // Check by reference equality whether any block actually changed\n if (\n newContent.length === msg.content.length &&\n newContent.every((b, idx) => b === msg.content[idx])\n ) {\n nextMessages[i] = msg;\n } else {\n nextMessages[i] = { ...msg, content: newContent };\n changed = true;\n }\n }\n if (changed) ctx.state.replaceMessages(nextMessages);\n return saved;\n }\n\n private hasTextContent(m: Message): boolean {\n if (typeof m.content === 'string') return m.content.trim().length > 0;\n return m.content.some((b) => b.type === 'text' && b.text.trim().length > 0);\n }\n\n private estimateTokens(messages: Message[]): number {\n let total = 0;\n for (const m of messages) {\n if (typeof m.content === 'string') {\n total += estimateTextTokens(m.content);\n } else {\n for (const b of m.content) {\n if (b.type === 'text') total += estimateTextTokens(b.text);\n else if (b.type === 'tool_use') total += estimateToolInputTokens(b.input);\n else if (b.type === 'tool_result') total += estimateToolResultTokens(b.content);\n }\n }\n }\n return total;\n }\n}\n","import { isTextBlock } from '../types/blocks.js';\nimport type { Message } from '../types/messages.js';\nimport type { Provider, Request } from '../types/provider.js';\nimport type { MessageSelector, SelectorResult } from '../types/selector.js';\n\nexport interface LLMSelectorOptions {\n /** Provider used for the selector LLM call. Required. */\n provider: Provider;\n /** Model for the selector. Defaults to the provider's default model. */\n model?: string;\n /**\n * Maximum tokens to keep in context (target budget).\n * Selector will aim to keep total content below this.\n */\n maxContextTokens?: number;\n /**\n * Prompt instructing the selector how to behave.\n * Should guide the LLM on importance tiers and output format.\n */\n systemPrompt?: string;\n}\n\nconst DEFAULT_SYSTEM_PROMPT = `You are a context pruning assistant. Given a conversation history and a token budget, decide which message ranges are worth keeping verbatim and which should be collapsed into summaries.\n\nOutput a JSON object with this structure:\n{\n \"kept\": [{\"from\": 0, \"to\": 5, \"importance\": \"critical\"}],\n \"collapsed\": [{\"from\": 6, \"to\": 20, \"summary\": \"optional summary\"}],\n \"reasoning\": \"brief explanation of decisions\"\n}\n\nImportance tiers:\n- \"critical\": decisions, file edits, tool results that affect state, final answers\n- \"high\": substantive tool use, complex reasoning, non-obvious observations\n- \"medium\": routine exchanges, confirmations, straightforward Q&A\n\nRules:\n- Always keep the most recent K pairs (preserve recency)\n- Never collapse the final 2 user/assistant pairs (working memory)\n- Preserve tool results that modified files or had external effects\n- Collapse old, low-information exchanges (greetings, acknowledgements, etc.)\n- If unsure, keep rather than collapse (errors are more costly than waste)\n\nReturn ONLY the JSON object, no markdown, no explanation outside the JSON.`;\n\n/** Rough token estimation for a message array */\nfunction estimateTokens(messages: Message[]): number {\n let total = 0;\n for (const m of messages) {\n if (typeof m.content === 'string') {\n total += Math.ceil(m.content.length / 4);\n } else if (Array.isArray(m.content)) {\n for (const b of m.content) {\n if (b.type === 'text') total += Math.ceil(b.text.length / 4);\n else total += Math.ceil(JSON.stringify(b).length / 4);\n }\n }\n }\n return total;\n}\n\n/** Format messages as a compact text dump for the selector LLM */\nfunction formatMessages(messages: Message[], maxChars = 8000): string {\n const lines: string[] = [];\n let used = 0;\n for (let i = 0; i < messages.length; i++) {\n const m = messages[i]!;\n const role = m.role.padEnd(10, ' ');\n let text: string;\n if (typeof m.content === 'string') {\n text = m.content.slice(0, 500);\n } else {\n const content = m.content as import('../types/blocks.js').ContentBlock[];\n text = content\n .filter(isTextBlock)\n .map((b) => b.text)\n .join(' ');\n // Also capture tool names for context\n const toolUses = content.filter((b) => b.type === 'tool_use');\n if (toolUses.length > 0) {\n text += ` [tools: ${toolUses.map((b) => (b as { name: string }).name).join(', ')}]`;\n }\n }\n const line = `[${i}][${role}]: ${text}`;\n if (used + line.length > maxChars) break;\n lines.push(line);\n used += line.length;\n }\n return lines.join('\\n');\n}\n\n/**\n * LLM-powered message selector. Calls a sub-LLM to analyze the\n * message history and produce a keep/collapse plan — more surgical\n * than fixed-window rules.\n */\nexport class LLMSelector implements MessageSelector {\n private readonly provider: Provider;\n private readonly model: string;\n private readonly maxContextTokens: number;\n private readonly systemPrompt: string;\n\n constructor(opts: LLMSelectorOptions) {\n this.provider = opts.provider;\n this.model = opts.model ?? 'unknown';\n this.maxContextTokens = opts.maxContextTokens ?? 40_000;\n this.systemPrompt = opts.systemPrompt ?? DEFAULT_SYSTEM_PROMPT;\n }\n\n async select(messages: Message[], maxToKeep: number): Promise<SelectorResult> {\n const effectiveBudget = Math.min(maxToKeep, this.maxContextTokens);\n\n // Build a concise representation of the conversation\n const historyText = formatMessages(messages);\n const totalTokens = estimateTokens(messages);\n const systemText = `${this.systemPrompt}\\n\\nConversation (${messages.length} messages, ~${totalTokens} tokens, budget: ${effectiveBudget}):\\n`;\n\n // Add instruction to stay within budget\n const budgetInstruction =\n totalTokens > effectiveBudget\n ? `\\n\\nIMPORTANT: Total conversation (${totalTokens} tokens) exceeds budget (${effectiveBudget}). You MUST collapse enough to fit. Prefer collapsing older/lower-importance ranges.`\n : '';\n\n const req: Request = {\n model: this.model,\n system: [{ type: 'text', text: systemText + budgetInstruction }],\n messages: [{ role: 'user', content: historyText }],\n maxTokens: 1024,\n };\n\n let raw: string;\n try {\n // Wire the AbortController to the provider call so cancellation actually\n // fires — the original code passed a fresh signal that is never connected\n // to anything, leaking the controller on every selector call.\n const ac = new AbortController();\n const res = await this.provider.complete(req, { signal: ac.signal });\n const textBlocks = res.content.filter(isTextBlock);\n raw = textBlocks\n .map((b) => b.text)\n .join('\\n')\n .trim();\n } catch (_err) {\n // Fallback: use simple recency-based selection\n return this.fallbackSelect(messages, effectiveBudget);\n }\n\n return this.parseSelectorOutput(raw, messages.length);\n }\n\n private fallbackSelect(messages: Message[], budget: number): SelectorResult {\n // Simple fallback: keep from the end until we hit budget\n const toKeep: SelectorResult['kept'] = [];\n const toCollapse: SelectorResult['collapsed'] = [];\n\n let tokenCount = 0;\n let startIdx = 0;\n\n // Scan from the end backwards\n for (let i = messages.length - 1; i >= 0; i--) {\n const m = messages[i]!;\n const cost =\n typeof m.content === 'string'\n ? Math.ceil(m.content.length / 4)\n : m.content.reduce(\n (acc, b) =>\n acc +\n (b.type === 'text'\n ? Math.ceil(b.text.length / 4)\n : Math.ceil(JSON.stringify(b).length / 4)),\n 0,\n );\n\n if (tokenCount + cost <= budget) {\n tokenCount += cost;\n } else {\n startIdx = i + 1;\n break;\n }\n }\n\n if (startIdx > 0) {\n toCollapse.push({ from: 0, to: startIdx - 1 });\n }\n toKeep.push({ from: startIdx, to: messages.length - 1, importance: 'high' });\n\n return {\n kept: toKeep,\n collapsed: toCollapse,\n reasoning: `Fallback: kept last ${messages.length - startIdx} messages within ${budget} token budget`,\n };\n }\n\n private parseSelectorOutput(raw: string, messageCount: number): SelectorResult {\n // Try to extract JSON from the response\n const jsonStart = raw.indexOf('{');\n const jsonEnd = raw.lastIndexOf('}');\n if (jsonStart === -1 || jsonEnd === -1) {\n // Can't parse — use fallback\n return this.fallbackSelect(\n Array.from({ length: messageCount }, () => ({ role: 'user', content: '' }) as Message),\n this.maxContextTokens,\n );\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw.slice(jsonStart, jsonEnd + 1));\n } catch {\n return this.fallbackSelect(\n Array.from({ length: messageCount }, () => ({ role: 'user', content: '' }) as Message),\n this.maxContextTokens,\n );\n }\n\n const obj = parsed as Record<string, unknown>;\n const kept =\n (obj.kept as Array<{ from: number; to: number; importance: string }> | undefined) ?? [];\n const collapsed =\n (obj.collapsed as Array<{ from: number; to: number; summary?: string }> | undefined) ?? [];\n\n return {\n kept: kept.map((k) => ({\n from: k.from,\n to: k.to,\n importance: (k.importance ?? 'medium') as 'critical' | 'high' | 'medium',\n })),\n collapsed: collapsed.map((c) => ({ from: c.from, to: c.to, summary: c.summary })),\n reasoning: typeof obj.reasoning === 'string' ? obj.reasoning : '',\n };\n }\n}\n","import type { Context } from '../core/context.js';\nimport { LLMSelector } from '../models/llm-selector.js';\nimport type { ContentBlock } from '../types/blocks.js';\nimport { isTextBlock } from '../types/blocks.js';\nimport type { CompactReport, Compactor } from '../types/compactor.js';\nimport type { Message } from '../types/messages.js';\nimport type { Provider, Request } from '../types/provider.js';\nimport type { MessageSelector, SelectorResult } from '../types/selector.js';\nimport { estimateRequestTokens } from '../utils/token-estimate.js';\nimport { repairToolUseAdjacency } from '../utils/message-invariants.js';\n\n/**\n * Options for SelectiveCompactor — the most configurable compactor.\n */\nexport interface SelectiveCompactorOptions {\n /** Provider for LLM calls (selector + summarizer). Required. */\n provider: Provider;\n /** Selector for LLM-driven importance analysis. */\n selector?: MessageSelector;\n /** Fraction of maxContext that triggers a warning (default 0.6). */\n warnThreshold?: number;\n /** Fraction of maxContext that triggers soft compaction (default 0.75). */\n softThreshold?: number;\n /** Fraction of maxContext that triggers hard compaction (default 0.9). */\n hardThreshold?: number;\n /** Max context window in tokens (used for threshold fraction math). */\n maxContext?: number;\n /** How many recent (user+assistant) pairs to always preserve (default 4). */\n preserveK?: number;\n /** Token threshold below which tool results are not elided (default 500). */\n eliseThreshold?: number;\n /** Model for selector LLM calls (default: same as provider default). */\n selectorModel?: string;\n /** Summarizer model for collapsed ranges (default: same as selectorModel). */\n summarizerModel?: string;\n /** Prompt for the summarizer sub-LLM. */\n summarizerPrompt?: string;\n}\n\n/**\n * SelectiveCompactor uses an LLM-driven MessageSelector to make\n * surgical decisions about which message ranges to keep vs collapse.\n *\n * Compared to HybridCompactor / IntelligentCompactor:\n * - HybridCompactor: rule-based (preserveK + elision), no LLM calls\n * - IntelligentCompactor: LLM summarization but no structured selection\n * - SelectiveCompactor: full LLM-driven selection + optional summarization\n */\nexport class SelectiveCompactor implements Compactor {\n private readonly provider: Provider;\n private readonly selector: MessageSelector;\n private readonly warnThreshold: number;\n private readonly softThreshold: number;\n private readonly hardThreshold: number;\n private readonly maxContext: number;\n private readonly preserveK: number;\n private readonly eliseThreshold: number;\n private readonly summarizerModel: string;\n private readonly summarizerPrompt: string;\n\n constructor(opts: SelectiveCompactorOptions) {\n this.provider = opts.provider;\n this.selector =\n opts.selector ?? new LLMSelector({ provider: opts.provider, model: opts.selectorModel });\n this.warnThreshold = opts.warnThreshold ?? 0.6;\n this.softThreshold = opts.softThreshold ?? 0.75;\n this.hardThreshold = opts.hardThreshold ?? 0.9;\n this.maxContext = opts.maxContext ?? 128_000;\n this.preserveK = opts.preserveK ?? 4;\n this.eliseThreshold = opts.eliseThreshold ?? 500;\n this.summarizerModel = opts.summarizerModel ?? opts.selectorModel ?? 'unknown';\n this.summarizerPrompt =\n opts.summarizerPrompt ??\n 'You are a context summarizer. Given a list of messages, produce a concise summary that preserves all factual information, decisions, file changes, and state changes. Do not add commentary or opinions.';\n }\n\n async compact(ctx: Context, opts: { aggressive?: boolean } = {}): Promise<CompactReport> {\n const beforeTokens = this.estimateTokens(ctx.messages);\n const beforeFull = this.estimateFullRequest(ctx);\n const reductions: CompactReport['reductions'] = [];\n\n // Use full request tokens for threshold decisions — messages alone are inaccurate.\n const load = beforeFull / this.maxContext;\n const shouldCompact = load >= this.warnThreshold || opts.aggressive;\n\n if (!shouldCompact) {\n // Only do lightweight elision if below warn threshold\n const saved = this.eliseOldToolResults(ctx);\n if (saved > 0) reductions.push({ phase: 'elision', saved });\n const repair = this.repairProtocolAdjacency(ctx);\n const afterTokens = this.estimateTokens(ctx.messages);\n const afterFull = this.estimateFullRequest(ctx);\n return {\n before: beforeTokens,\n after: afterTokens,\n fullRequestTokensBefore: beforeFull,\n fullRequestTokensAfter: afterFull,\n reductions,\n repaired: repair,\n };\n }\n\n // Phase 1: elision — always run first to get a baseline reduction\n const savedElision = this.eliseOldToolResults(ctx);\n if (savedElision > 0) reductions.push({ phase: 'elision', saved: savedElision });\n\n // Phase 2: LLM-driven selective compaction\n const afterPhase1 = this.estimateTokens(ctx.messages);\n const targetBudget = this.computeTargetBudget(load);\n\n if (afterPhase1 > targetBudget) {\n const savedSelective = await this.runSelector(ctx, targetBudget);\n if (savedSelective > 0) reductions.push({ phase: 'selective', saved: savedSelective });\n }\n\n const repair = this.repairProtocolAdjacency(ctx);\n const afterTokens = this.estimateTokens(ctx.messages);\n const afterFull = this.estimateFullRequest(ctx);\n return {\n before: beforeTokens,\n after: afterTokens,\n fullRequestTokensBefore: beforeFull,\n fullRequestTokensAfter: afterFull,\n reductions,\n repaired: repair,\n };\n }\n\n /**\n * Estimate the full API request token count: messages + systemPrompt + toolDefs.\n * This is the accurate figure for context-window pressure monitoring.\n */\n private estimateFullRequest(ctx: Context): number {\n const breakdown = estimateRequestTokens(ctx.messages, ctx.systemPrompt, ctx.tools ?? []);\n return breakdown.total;\n }\n\n private repairProtocolAdjacency(ctx: Context): CompactReport['repaired'] {\n const repaired = repairToolUseAdjacency(ctx.messages);\n if (repaired.report.changed) ctx.state.replaceMessages(repaired.messages);\n return repaired.report.changed\n ? {\n removedToolUses: repaired.report.removedToolUses,\n removedToolResults: repaired.report.removedToolResults,\n removedMessages: repaired.report.removedMessages,\n }\n : undefined;\n }\n\n /**\n * Run the LLM selector to decide what to keep vs collapse.\n * Returns the token savings achieved.\n */\n private async runSelector(ctx: Context, targetBudget: number): Promise<number> {\n const before = this.estimateTokens(ctx.messages);\n\n let result: SelectorResult;\n try {\n result = await this.selector.select(ctx.messages, targetBudget);\n } catch {\n // Fallback to aggressive recency preservation\n return this.aggressiveRecencyTrim(ctx);\n }\n\n // Execute the selector's plan\n await this.executePlan(ctx, result);\n\n const after = this.estimateTokens(ctx.messages);\n return Math.max(0, before - after);\n }\n\n /**\n * Execute a SelectorResult plan: collapse/remove ranges and\n * insert summaries where the selector provided them.\n */\n private async executePlan(ctx: Context, plan: SelectorResult): Promise<void> {\n if (ctx.messages.length === 0) return;\n\n // Process collapsed ranges in reverse order to preserve indices. We work\n // on a local copy and commit through `ctx.state.replaceMessages` at the\n // end so subscribers see a single state change for the whole rewrite.\n const messages = [...ctx.messages];\n const sortedCollapsed = [...plan.collapsed].sort((a, b) => b.from - a.from);\n\n for (const range of sortedCollapsed) {\n if (range.from < 0 || range.to >= messages.length || range.from > range.to) continue;\n\n let summary = range.summary;\n if (!summary) {\n const toSummarize = messages.slice(range.from, range.to + 1);\n summary = await this.summarizeRange(toSummarize, ctx);\n }\n\n const summaryMsg: Message = {\n role: 'system',\n content: `[prior_turns_${range.from}-${range.to}: ${summary}]`,\n };\n\n messages.splice(range.from, range.to - range.from + 1, summaryMsg);\n }\n\n ctx.state.replaceMessages(messages);\n }\n\n private async summarizeRange(messages: Message[], ctx: Context): Promise<string> {\n const systemText = `${this.summarizerPrompt}\\n\\nSummarize the following message range:`;\n const body = messages.map((m, i) => `[${i}] ${m.role}: ${this.messagePreview(m)}`).join('\\n');\n\n const req: Request = {\n model: this.summarizerModel,\n system: [{ type: 'text', text: systemText }],\n messages: [{ role: 'user', content: body }],\n maxTokens: 512,\n };\n\n try {\n const res = await this.provider.complete(req, {\n signal: ctx.signal ?? new AbortController().signal,\n });\n return (\n res.content\n .filter(isTextBlock)\n .map((b) => b.text)\n .join('\\n')\n .trim() || '(empty)'\n );\n } catch {\n return `[${messages.length} earlier turns omitted]`;\n }\n }\n\n private messagePreview(m: Message): string {\n if (typeof m.content === 'string') return m.content.slice(0, 300);\n return m.content\n .filter(isTextBlock)\n .map((b) => b.text)\n .join(' ')\n .slice(0, 300);\n }\n\n /**\n * Fallback when selector fails: aggressively trim from the oldest end\n * until we hit targetBudget.\n */\n private aggressiveRecencyTrim(ctx: Context): number {\n const messages = ctx.messages;\n const preserveIdx = Math.max(0, messages.length - this.preserveK * 2);\n\n if (preserveIdx <= 0) return 0;\n\n // Find safe boundary near preserveIdx\n let boundary = preserveIdx;\n for (let i = preserveIdx; i < messages.length && i < preserveIdx + 6; i++) {\n const m = messages[i]!;\n if (m.role === 'user' && this.hasTextContent(m)) {\n boundary = i;\n break;\n }\n }\n\n const removed = messages.slice(0, boundary);\n const removedTokens = this.estimateTokens(removed);\n\n const summaryMsg: Message = {\n role: 'system',\n content: `[${removed.length} earlier turns trimmed — see session log for details]`,\n };\n const tail = messages.slice(boundary);\n ctx.state.replaceMessages([summaryMsg, ...tail]);\n\n return Math.max(0, removedTokens - this.estimateTokens([summaryMsg]));\n }\n\n private computeTargetBudget(load: number): number {\n if (load >= this.hardThreshold) {\n return Math.floor(this.maxContext * 0.5); // keep only 50%\n }\n if (load >= this.softThreshold) {\n return Math.floor(this.maxContext * 0.65); // keep 65%\n }\n return Math.floor(this.maxContext * 0.75); // keep 75% at warn\n }\n\n private eliseOldToolResults(ctx: Context): number {\n const messages = ctx.messages;\n let pairCount = 0;\n let preserveStart = messages.length;\n for (let i = messages.length - 1; i >= 0 && pairCount < this.preserveK; i--) {\n const m = messages[i];\n if (!m) continue;\n if (m.role === 'user' || m.role === 'assistant') {\n pairCount++;\n preserveStart = i;\n }\n }\n let saved = 0;\n let changed = false;\n const nextMessages = new Array(messages.length);\n for (let i = 0; i < messages.length; i++) {\n const msg = messages[i];\n // Only process messages before the preservation window\n if (i >= preserveStart) {\n nextMessages[i] = msg;\n continue;\n }\n if (!msg || !Array.isArray(msg.content)) {\n nextMessages[i] = msg;\n continue;\n }\n const newContent: ContentBlock[] = msg.content.map((b) => {\n if (b.type !== 'tool_result') return b;\n const text = typeof b.content === 'string' ? b.content : JSON.stringify(b.content);\n const tokens = this.roughTokenEstimate(text);\n if (tokens < this.eliseThreshold) return b;\n saved += tokens;\n return {\n type: 'tool_result',\n tool_use_id: b.tool_use_id,\n content: `[elided: ~${tokens} tokens]`,\n is_error: b.is_error,\n };\n });\n // map() preserves length, so only block ref-equality matters here.\n if (newContent.every((b, idx) => b === msg.content[idx])) {\n nextMessages[i] = msg;\n } else {\n nextMessages[i] = { ...msg, content: newContent };\n changed = true;\n }\n }\n if (changed) ctx.state.replaceMessages(nextMessages);\n return saved;\n }\n\n private hasTextContent(m: Message): boolean {\n if (typeof m.content === 'string') return m.content.trim().length > 0;\n return m.content.some((b) => b.type === 'text' && b.text.trim().length > 0);\n }\n\n private estimateTokens(messages: Message[]): number {\n let total = 0;\n for (const m of messages) {\n if (typeof m.content === 'string') {\n total += this.roughTokenEstimate(m.content);\n } else {\n for (const b of m.content) {\n if (b.type === 'text') total += this.roughTokenEstimate(b.text);\n else if (b.type === 'tool_use') total += this.roughTokenEstimate(JSON.stringify(b.input));\n else if (b.type === 'tool_result') {\n total += this.roughTokenEstimate(\n typeof b.content === 'string' ? b.content : JSON.stringify(b.content),\n );\n }\n }\n }\n }\n return total;\n }\n\n private roughTokenEstimate(text: string): number {\n return Math.max(1, Math.ceil(text.length / 3.5));\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\n/**\n * Machine-readable error codes as frozen constants.\n *\n * Use `ERROR_CODES.X` instead of raw string literals for:\n * - IDE autocomplete and compile-time validation\n * - Safe refactoring (rename updates all usages)\n * - Plugin extensibility (extend the object to add custom codes)\n *\n * The `ErrorCode` type is derived from this object, so adding a new\n * code here automatically updates the type without extra changes.\n */\nexport const ERROR_CODES = {\n // Provider\n PROVIDER_RATE_LIMITED: 'PROVIDER_RATE_LIMITED',\n PROVIDER_AUTH_FAILED: 'PROVIDER_AUTH_FAILED',\n PROVIDER_OVERLOADED: 'PROVIDER_OVERLOADED',\n PROVIDER_INVALID_REQUEST: 'PROVIDER_INVALID_REQUEST',\n PROVIDER_SERVER_ERROR: 'PROVIDER_SERVER_ERROR',\n PROVIDER_NETWORK_ERROR: 'PROVIDER_NETWORK_ERROR',\n PROVIDER_CONTEXT_OVERFLOW: 'PROVIDER_CONTEXT_OVERFLOW',\n // Tool\n TOOL_NOT_FOUND: 'TOOL_NOT_FOUND',\n TOOL_PERMISSION_DENIED: 'TOOL_PERMISSION_DENIED',\n TOOL_EXECUTION_FAILED: 'TOOL_EXECUTION_FAILED',\n TOOL_TIMEOUT: 'TOOL_TIMEOUT',\n TOOL_INPUT_INVALID: 'TOOL_INPUT_INVALID',\n // Config\n CONFIG_INVALID: 'CONFIG_INVALID',\n CONFIG_NOT_FOUND: 'CONFIG_NOT_FOUND',\n CONFIG_PARSE_FAILED: 'CONFIG_PARSE_FAILED',\n CONFIG_MIGRATION_NEEDED: 'CONFIG_MIGRATION_NEEDED',\n // Plugin\n PLUGIN_LOAD_FAILED: 'PLUGIN_LOAD_FAILED',\n PLUGIN_API_MISMATCH: 'PLUGIN_API_MISMATCH',\n PLUGIN_MISSING_DEPENDENCY: 'PLUGIN_MISSING_DEPENDENCY',\n // Agent\n AGENT_ITERATION_LIMIT: 'AGENT_ITERATION_LIMIT',\n AGENT_CONTEXT_OVERFLOW: 'AGENT_CONTEXT_OVERFLOW',\n AGENT_ABORTED: 'AGENT_ABORTED',\n AGENT_RUN_FAILED: 'AGENT_RUN_FAILED',\n // Session\n SESSION_NOT_FOUND: 'SESSION_NOT_FOUND',\n SESSION_CORRUPTED: 'SESSION_CORRUPTED',\n SESSION_WRITE_FAILED: 'SESSION_WRITE_FAILED',\n // Container / Registry\n CONTAINER_TOKEN_ALREADY_BOUND: 'CONTAINER_TOKEN_ALREADY_BOUND',\n CONTAINER_TOKEN_NOT_BOUND: 'CONTAINER_TOKEN_NOT_BOUND',\n CONTAINER_CIRCULAR_DEPENDENCY: 'CONTAINER_CIRCULAR_DEPENDENCY',\n REGISTRY_DUPLICATE: 'REGISTRY_DUPLICATE',\n REGISTRY_NOT_FOUND: 'REGISTRY_NOT_FOUND',\n REGISTRY_INVALID: 'REGISTRY_INVALID',\n // File system\n FS_READ_FAILED: 'FS_READ_FAILED',\n FS_WRITE_FAILED: 'FS_WRITE_FAILED',\n FS_MKDIR_FAILED: 'FS_MKDIR_FAILED',\n FS_DELETE_FAILED: 'FS_DELETE_FAILED',\n FS_ATOMIC_WRITE_FAILED: 'FS_ATOMIC_WRITE_FAILED',\n // General\n UNKNOWN: 'UNKNOWN',\n} as const;\n\n/**\n * Union type derived from `ERROR_CODES`. Using `typeof ERROR_CODES[keyof typeof ERROR_CODES]`\n * instead of a string literal union means TypeScript auto-updates the type whenever\n * a new code is added to `ERROR_CODES` — no need to keep two lists in sync.\n */\nexport type ErrorCode = (typeof ERROR_CODES)[keyof typeof ERROR_CODES];\n\nexport type ErrorSubsystem =\n | 'provider'\n | 'tool'\n | 'config'\n | 'plugin'\n | 'agent'\n | 'session'\n | 'container'\n | 'fs'\n | 'general';\nexport type ErrorSeverity = 'fatal' | 'error' | 'warning';\n\n// ── Base error class ─────────────────────────────────────────────────\n\nexport class WrongStackError extends Error {\n readonly code: ErrorCode;\n readonly subsystem: ErrorSubsystem;\n readonly severity: ErrorSeverity;\n readonly recoverable: boolean;\n readonly context?: Record<string, unknown>;\n\n constructor(opts: {\n message: string;\n code: ErrorCode;\n subsystem: ErrorSubsystem;\n severity?: ErrorSeverity;\n recoverable?: boolean;\n context?: Record<string, unknown>;\n cause?: unknown;\n }) {\n super(opts.message, { cause: opts.cause });\n this.name = 'WrongStackError';\n this.code = opts.code;\n this.subsystem = opts.subsystem;\n this.severity = opts.severity ?? 'error';\n this.recoverable = opts.recoverable ?? false;\n this.context = opts.context;\n }\n\n /**\n * Render a one-line user-facing description.\n * Subclasses should override for domain-specific formatting.\n */\n describe(): string {\n const ctx = this.context ? ` ${formatContext(this.context)}` : '';\n return `${this.code}: ${this.message}${ctx}`;\n }\n}\n\nfunction formatContext(ctx: Record<string, unknown>): string {\n const parts = Object.entries(ctx)\n .filter(([, v]) => v !== undefined)\n .slice(0, 3)\n .map(([k, v]) => `${k}=${String(v)}`);\n return parts.length > 0 ? `[${parts.join(' ')}]` : '';\n}\n\n// ── Specific error classes ───────────────────────────────────────────\n\n/**\n * Tool execution errors — thrown by ToolExecutor and individual tools.\n */\nexport class ToolError extends WrongStackError {\n readonly toolName: string;\n\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n | 'TOOL_NOT_FOUND'\n | 'TOOL_PERMISSION_DENIED'\n | 'TOOL_EXECUTION_FAILED'\n | 'TOOL_TIMEOUT'\n | 'TOOL_INPUT_INVALID'\n >;\n toolName: string;\n recoverable?: boolean;\n context?: Record<string, unknown>;\n cause?: unknown;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'tool',\n recoverable: opts.recoverable,\n context: { tool: opts.toolName, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'ToolError';\n this.toolName = opts.toolName;\n }\n}\n\n/**\n * Config loading / validation errors.\n */\nexport class ConfigError extends WrongStackError {\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'CONFIG_INVALID' | 'CONFIG_NOT_FOUND' | 'CONFIG_PARSE_FAILED' | 'CONFIG_MIGRATION_NEEDED'\n >;\n context?: Record<string, unknown>;\n cause?: unknown;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'config',\n severity: 'fatal',\n recoverable: false,\n context: opts.context,\n cause: opts.cause,\n });\n this.name = 'ConfigError';\n }\n}\n\n/**\n * Plugin loading / lifecycle errors.\n */\nexport class PluginError extends WrongStackError {\n readonly pluginName: string;\n\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'PLUGIN_LOAD_FAILED' | 'PLUGIN_API_MISMATCH' | 'PLUGIN_MISSING_DEPENDENCY'\n >;\n pluginName: string;\n context?: Record<string, unknown>;\n cause?: unknown;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'plugin',\n severity: 'error',\n recoverable: opts.code === ERROR_CODES.PLUGIN_MISSING_DEPENDENCY,\n context: { plugin: opts.pluginName, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'PluginError';\n this.pluginName = opts.pluginName;\n }\n}\n\n/**\n * Agent runtime errors — thrown by Agent.run when a non-WrongStackError\n * escapes the inner loop, so callers always see a structured error.\n */\nexport class AgentError extends WrongStackError {\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'AGENT_ITERATION_LIMIT' | 'AGENT_CONTEXT_OVERFLOW' | 'AGENT_ABORTED' | 'AGENT_RUN_FAILED'\n >;\n recoverable?: boolean;\n context?: Record<string, unknown>;\n cause?: unknown;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'agent',\n severity: opts.code === ERROR_CODES.AGENT_ABORTED ? 'warning' : 'error',\n recoverable: opts.recoverable ?? opts.code === ERROR_CODES.AGENT_ITERATION_LIMIT,\n context: opts.context,\n cause: opts.cause,\n });\n this.name = 'AgentError';\n }\n}\n\n/**\n * Wrap an arbitrary thrown value into a `WrongStackError` so the caller\n * always gets a structured error. Pass-throughs WrongStackError instances\n * unchanged; raw `Error`s and primitives get an `AGENT_RUN_FAILED` wrapper\n * with the original preserved as `cause`.\n */\nexport function toWrongStackError(\n err: unknown,\n code: Extract<ErrorCode, 'AGENT_RUN_FAILED' | 'AGENT_ABORTED' | 'UNKNOWN'> = ERROR_CODES.AGENT_RUN_FAILED,\n): WrongStackError {\n if (err instanceof WrongStackError) return err;\n const message = err instanceof Error ? err.message : String(err);\n return new AgentError({\n message,\n code: code === 'UNKNOWN' ? ERROR_CODES.AGENT_RUN_FAILED : code,\n cause: err,\n });\n}\n\n/**\n * Session storage errors.\n */\nexport class SessionError extends WrongStackError {\n readonly sessionId?: string;\n\n constructor(opts: {\n message: string;\n code: Extract<ErrorCode, 'SESSION_NOT_FOUND' | 'SESSION_CORRUPTED' | 'SESSION_WRITE_FAILED'>;\n sessionId?: string;\n context?: Record<string, unknown>;\n cause?: unknown;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'session',\n severity: opts.code === ERROR_CODES.SESSION_WRITE_FAILED ? 'error' : 'warning',\n recoverable: opts.code !== ERROR_CODES.SESSION_CORRUPTED,\n context: { sessionId: opts.sessionId, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'SessionError';\n this.sessionId = opts.sessionId;\n }\n}\n\n/**\n * File system operation errors.\n */\nexport class FsError extends WrongStackError {\n readonly path?: string;\n\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'FS_READ_FAILED' | 'FS_WRITE_FAILED' | 'FS_MKDIR_FAILED' | 'FS_DELETE_FAILED' | 'FS_ATOMIC_WRITE_FAILED'\n >;\n path?: string;\n context?: Record<string, unknown>;\n cause?: unknown;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'fs',\n severity: 'error',\n recoverable: opts.code !== ERROR_CODES.FS_READ_FAILED,\n context: { path: opts.path, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'FsError';\n this.path = opts.path;\n }\n}\n\n// ── Type guards ──────────────────────────────────────────────────────\n\nexport function isWrongStackError(err: unknown): err is WrongStackError {\n return err instanceof WrongStackError;\n}\n\nexport function isToolError(err: unknown): err is ToolError {\n return err instanceof ToolError;\n}\n\nexport function isConfigError(err: unknown): err is ConfigError {\n return err instanceof ConfigError;\n}\n\nexport function isPluginError(err: unknown): err is PluginError {\n return err instanceof PluginError;\n}\n\nexport function isSessionError(err: unknown): err is SessionError {\n return err instanceof SessionError;\n}\n\nexport function isAgentError(err: unknown): err is AgentError {\n return err instanceof AgentError;\n}\n\nexport function isFsError(err: unknown): err is FsError {\n return err instanceof FsError;\n}\n","import type { Context } from '../core/context.js';\nimport type { EventBus } from '../kernel/events.js';\nimport type { MiddlewareHandler } from '../kernel/pipeline.js';\nimport type { SessionEventBridge } from '../storage/session-event-bridge.js';\nimport type { CompactReport, Compactor } from '../types/compactor.js';\nimport type { ContextWindowAggressiveOn, ContextWindowPolicy } from '../types/context-window.js';\nimport { AgentError, ERROR_CODES } from '../types/errors.js';\nimport { estimateRequestTokensCalibrated } from '../utils/token-estimate.js';\n\ntype PressureLevel = 'warn' | 'soft' | 'hard';\nconst LEVEL_RANK: Record<PressureLevel, number> = { warn: 0, soft: 1, hard: 2 };\n\nexport type CompactionFailureMode = 'throw' | 'throw_on_hard' | 'continue';\n\nexport interface AutoCompactionOptions {\n aggressiveOn?: ContextWindowAggressiveOn;\n events?: EventBus;\n failureMode?: CompactionFailureMode;\n policyProvider?: (ctx: Context) => Pick<\n ContextWindowPolicy,\n 'thresholds' | 'aggressiveOn'\n > | null | undefined;\n /** Optional bridge for writing compaction events into the persistent session log. */\n sessionBridge?: SessionEventBridge;\n}\n\n/**\n * Pipeline middleware that monitors context token load and automatically\n * triggers compaction when the warn/soft/hard thresholds are crossed.\n * Runs before the next agent iteration.\n *\n * Uses `estimateRequestTokens` for accurate full-request token counting:\n * messages + systemPrompt + toolDefs. This replaces the previous pattern\n * of applying an OVERHEAD_FACTOR to a messages-only estimate.\n */\nexport class AutoCompactionMiddleware {\n readonly name = 'AutoCompaction';\n\n private readonly compactor: Compactor;\n /** Deprecated. Kept for backward compat with tests that pass simpleEstimator. */\n private readonly _estimator?: (ctx: Context) => number;\n private readonly warnThreshold: number;\n private readonly softThreshold: number;\n private readonly hardThreshold: number;\n /** Writable so model-switch can update the denominator without re-registering the middleware. */\n private _maxContext: number;\n private readonly aggressiveOn: ContextWindowAggressiveOn;\n private readonly events?: EventBus;\n private readonly failureMode: CompactionFailureMode;\n private readonly policyProvider?: AutoCompactionOptions['policyProvider'];\n private readonly sessionBridge?: SessionEventBridge;\n\n /**\n * Once a compaction attempt reduces nothing (preserveK protects everything,\n * no oversized tool_results remain to elide), retrying on every iteration\n * just spams `compaction.fired` events without making progress. We remember\n * the no-op and skip until either the pressure level escalates or context\n * has grown by at least this many tokens since the failed attempt.\n */\n private static readonly NOOP_RETRY_DELTA_TOKENS = 2_000;\n\n /** Tracks the most recent no-op attempt so we can avoid re-firing per turn. */\n private lastNoopAttempt: { level: PressureLevel; tokens: number } | null = null;\n\n /**\n * @param compactor Compactor to use for compaction.\n * @param maxContext Provider's max context window in tokens.\n * @param _estimator Deprecated parameter kept for backward compatibility.\n * The middleware now uses `estimateRequestTokens` internally\n * for accurate full-request token counting (messages +\n * systemPrompt + toolDefs).\n * @param thresholds Threshold fractions (0-1) of maxContext.\n * @param opts Optional behavior. By default, failures at the\n * hard threshold throw AGENT_CONTEXT_OVERFLOW so\n * the agent does not continue into a likely\n * provider context overflow. Warn/soft failures\n * still emit compaction.failed and continue.\n */\n constructor(\n compactor: Compactor,\n maxContext: number,\n _estimator: (ctx: Context) => number,\n thresholds: { warn: number; soft: number; hard: number },\n optsOrAggressiveOn: AutoCompactionOptions | ContextWindowAggressiveOn = {},\n events?: EventBus,\n ) {\n const opts =\n typeof optsOrAggressiveOn === 'string'\n ? { aggressiveOn: optsOrAggressiveOn, events }\n : optsOrAggressiveOn;\n this.compactor = compactor;\n this._maxContext = maxContext;\n this._estimator = _estimator;\n this.warnThreshold = thresholds.warn;\n this.softThreshold = thresholds.soft;\n this.hardThreshold = thresholds.hard;\n this.aggressiveOn = opts.aggressiveOn ?? 'soft';\n this.events = opts.events;\n this.failureMode = opts.failureMode ?? 'throw_on_hard';\n this.policyProvider = opts.policyProvider;\n this.sessionBridge = opts.sessionBridge;\n }\n\n /** Allow callers (e.g. model-switch in WebUI) to update the context window\n * denominator when the active model changes. */\n setMaxContext(maxContext: number): void {\n this._maxContext = maxContext;\n }\n\n handler(): MiddlewareHandler<Context> {\n return async (ctx, next) => {\n // Use _estimator when provided (backward-compat with existing tests that\n // pass simpleEstimator). Otherwise use estimateRequestTokensCalibrated:\n // before any API calls it returns the same as estimateRequestTokens, but\n // after recordActualUsage() is called each iteration it self-corrects so\n // context pressure readings converge on the real token count.\n const tokens = this._estimator\n ? this._estimator(ctx)\n : estimateRequestTokensCalibrated(ctx.messages, ctx.systemPrompt, ctx.tools ?? []).total;\n const load = tokens / this._maxContext;\n const policy = this.policyProvider?.(ctx);\n const thresholds = policy?.thresholds ?? {\n warn: this.warnThreshold,\n soft: this.softThreshold,\n hard: this.hardThreshold,\n };\n const aggressiveOn = policy?.aggressiveOn ?? this.aggressiveOn;\n\n const level: PressureLevel | null =\n load >= thresholds.hard\n ? 'hard'\n : load >= thresholds.soft\n ? 'soft'\n : load >= thresholds.warn\n ? 'warn'\n : null;\n\n if (!level) {\n // Load dropped back below all thresholds — any previously stuck state\n // is no longer relevant.\n this.lastNoopAttempt = null;\n return next(ctx);\n }\n\n if (this.shouldSkipNoopRetry(level, tokens)) {\n return next(ctx);\n }\n\n const aggressive =\n level === 'hard'\n ? true\n : level === 'soft'\n ? aggressiveOn !== 'hard'\n : aggressiveOn === 'warn';\n\n await this.compact(ctx, aggressive, { level, tokens, load });\n\n return next(ctx);\n };\n }\n\n /**\n * Returns true when the previous compaction at the same or higher pressure\n * level reduced nothing and context has not grown materially since. Prevents\n * a stuck preserveK window from spamming compaction events every iteration.\n */\n private shouldSkipNoopRetry(level: PressureLevel, tokens: number): boolean {\n const stuck = this.lastNoopAttempt;\n if (!stuck) return false;\n // Escalation always retries — soft → hard might be reducible aggressively.\n if (LEVEL_RANK[level] > LEVEL_RANK[stuck.level]) return false;\n const delta = tokens - stuck.tokens;\n return delta < AutoCompactionMiddleware.NOOP_RETRY_DELTA_TOKENS;\n }\n\n private recordAttempt(level: PressureLevel, tokens: number, report: CompactReport): void {\n // Prefer full-request tokens (accurate); fall back to message-only before/after.\n const reduced =\n (report.fullRequestTokensBefore ?? report.before) > (report.fullRequestTokensAfter ?? report.after);\n const repaired = !!report.repaired;\n if (reduced || repaired) {\n this.lastNoopAttempt = null;\n } else {\n this.lastNoopAttempt = { level, tokens };\n }\n }\n\n private async compact(\n ctx: Context,\n aggressive: boolean,\n pressure: { level: PressureLevel; tokens: number; load: number },\n ): Promise<void> {\n try {\n const report = await this.compactor.compact(ctx, { aggressive });\n this.recordAttempt(pressure.level, pressure.tokens, report);\n this.events?.emit('compaction.fired', {\n level: pressure.level,\n tokens: pressure.tokens,\n load: pressure.load,\n maxContext: this._maxContext,\n report,\n aggressive,\n });\n\n // Persist a compaction event to the session log (if a bridge was provided).\n // This is one of the highest-value audit events for understanding context\n // window behavior over long runs.\n await this.sessionBridge?.append({\n type: 'compaction',\n ts: new Date().toISOString(),\n before: report.before,\n after: report.after,\n level: pressure.level,\n aggressive,\n reductions: report.reductions?.map((r) => ({ phase: r.phase, saved: r.saved })),\n });\n\n // Stale file-read metadata from before the compaction boundary is no\n // longer useful and would cause hasRead() to skip legitimate re-reads.\n ctx.clearFileTracking();\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n const fatal =\n this.failureMode === 'throw' ||\n (this.failureMode === 'throw_on_hard' && pressure.level === 'hard');\n this.events?.emit('compaction.failed', {\n err: error,\n aggressive,\n level: pressure.level,\n tokens: pressure.tokens,\n maxContext: this._maxContext,\n load: pressure.load,\n fatal,\n });\n if (fatal) {\n throw new AgentError({\n message: `Auto-compaction failed at ${pressure.level} threshold`,\n code: ERROR_CODES.AGENT_CONTEXT_OVERFLOW,\n recoverable: true,\n context: {\n level: pressure.level,\n tokens: pressure.tokens,\n maxContext: this._maxContext,\n },\n cause: err,\n });\n }\n }\n }\n}\n","/**\n * Well-known tool capabilities used for authorization decisions.\n *\n * These are the preferred values for `Tool.capabilities`.\n * New capabilities should be added here with clear documentation.\n *\n * Philosophy (2026-06+):\n * - Prefer capabilities over exact tool name matching.\n * - Subagent guards and future policies should primarily key off capabilities.\n * - Name-based denylists are legacy and will be phased down.\n */\nexport const ToolCapabilities = {\n /** Can execute arbitrary commands in the user's shell (the `bash` tool). */\n SHELL_ARBITRARY: 'shell.arbitrary',\n\n /** Can execute a restricted set of commands (the `exec` tool). */\n SHELL_RESTRICTED: 'shell.restricted',\n\n /** Can read files inside the project (and possibly outside via symlinks if not guarded). */\n FS_READ: 'fs.read',\n\n /** Can write / modify / delete files inside the project. */\n FS_WRITE: 'fs.write',\n\n /** Can write files outside the current project root (very high risk). */\n FS_WRITE_OUTSIDE_PROJECT: 'fs.write.outside-project',\n\n /** Can perform outbound network requests. */\n NET_OUTBOUND: 'net.outbound',\n\n /** Proxies tools from external MCP servers (unknown capability). */\n MCP_PROXY: 'mcp.proxy',\n\n /** Can spawn or manage subagents / multi-agent tasks. */\n SUBAGENT_SPAWN: 'subagent.spawn',\n\n /** Can mutate global or session configuration / trust state. */\n CONFIG_MUTATE: 'config.mutate',\n\n /** Can install packages or run package managers with side effects. */\n PACKAGE_INSTALL: 'package.install',\n} as const;\n\nexport type ToolCapability = (typeof ToolCapabilities)[keyof typeof ToolCapabilities];\n\n/**\n * Set of capabilities that are considered dangerous for subagents by default.\n * Subagents should not receive these capabilities unless the leader explicitly\n * allows the specific tool at spawn time.\n */\nexport const DANGEROUS_FOR_SUBAGENTS: readonly ToolCapability[] = [\n ToolCapabilities.SHELL_ARBITRARY,\n ToolCapabilities.FS_WRITE,\n ToolCapabilities.FS_WRITE_OUTSIDE_PROJECT,\n ToolCapabilities.MCP_PROXY,\n ToolCapabilities.SUBAGENT_SPAWN,\n ToolCapabilities.CONFIG_MUTATE,\n ToolCapabilities.PACKAGE_INSTALL,\n];\n\n/**\n * Check if a tool (or its capabilities array) includes any dangerous capability\n * for subagent execution.\n */\nexport function hasDangerousCapabilityForSubagents(\n toolOrCaps: { capabilities?: readonly string[] } | readonly string[] | undefined,\n): boolean {\n if (!toolOrCaps) return false;\n // Use `as unknown as ...` to allow accessing .capabilities on the union type\n const input = toolOrCaps as unknown as { capabilities?: readonly string[] };\n const caps: readonly string[] = Array.isArray(toolOrCaps) ? toolOrCaps : (input.capabilities ?? []);\n return caps.some((c) => DANGEROUS_FOR_SUBAGENTS.includes(c as ToolCapability));\n}\n\n/**\n * Check if a tool declares a specific capability (or any of the provided ones).\n */\nexport function hasCapability(\n toolOrCaps: { capabilities?: readonly string[] } | readonly string[] | undefined,\n capability: ToolCapability | ToolCapability[],\n): boolean {\n if (!toolOrCaps) return false;\n // Use `as unknown as ...` to allow accessing .capabilities on the union type\n const input = toolOrCaps as unknown as { capabilities?: readonly string[] };\n const caps: readonly string[] = Array.isArray(toolOrCaps) ? toolOrCaps : (input.capabilities ?? []);\n const toCheck = Array.isArray(capability) ? capability : [capability];\n return toCheck.some((c) => caps.includes(c));\n}\n\n/**\n * Returns the intersection of a tool's capabilities with the dangerous set.\n * Useful for logging and audit trails.\n */\nexport function getDangerousCapabilities(\n toolOrCaps: { capabilities?: readonly string[] } | readonly string[] | undefined,\n): ToolCapability[] {\n if (!toolOrCaps) return [];\n // Use `as unknown as ...` to allow accessing .capabilities on the union type\n const input = toolOrCaps as unknown as { capabilities?: readonly string[] };\n const caps: readonly string[] = Array.isArray(toolOrCaps) ? toolOrCaps : (input.capabilities ?? []);\n return caps.filter((c): c is ToolCapability =>\n DANGEROUS_FOR_SUBAGENTS.includes(c as ToolCapability),\n );\n}\n","/**\n * Minimal JSON Schema validator — covers the subset needed for plugin\n * configSchema validation and tool inputSchema sanity checks. Intentionally\n * small (~80 lines, zero deps) and tolerant: unknown keywords are ignored so\n * authors can mix in non-standard extensions without breaking validation.\n *\n * NOT for full JSON Schema 2020-12 conformance. If a plugin needs $ref,\n * conditional schemas, format validation, or anything else exotic, it should\n * bring its own ajv-based validator and call this only for the cheap path.\n */\nimport type { JSONSchema } from '../types/tool.js';\n\nexport interface ValidationError {\n path: string;\n message: string;\n}\n\nexport interface ValidationResult {\n ok: boolean;\n errors: ValidationError[];\n}\n\nexport function validateAgainstSchema(value: unknown, schema: JSONSchema): ValidationResult {\n const errors: ValidationError[] = [];\n walk(value, schema, '', errors);\n return { ok: errors.length === 0, errors };\n}\n\nfunction walk(value: unknown, schema: JSONSchema, path: string, errors: ValidationError[]): void {\n if (schema.enum !== undefined) {\n if (!schema.enum.some((e) => deepEqual(e, value))) {\n errors.push({\n path: path || '<root>',\n message: `expected one of ${JSON.stringify(schema.enum)}, got ${JSON.stringify(value)}`,\n });\n return;\n }\n }\n\n if (typeof schema.type === 'string') {\n if (!checkType(value, schema.type)) {\n errors.push({\n path: path || '<root>',\n message: `expected ${schema.type}, got ${describeType(value)}`,\n });\n return;\n }\n }\n\n if (schema.type === 'object' && isPlainObject(value)) {\n const obj = value as Record<string, unknown>;\n for (const req of schema.required ?? []) {\n if (!(req in obj)) {\n errors.push({ path: joinPath(path, req), message: 'required property missing' });\n }\n }\n if (schema.properties) {\n for (const [key, subSchema] of Object.entries(schema.properties)) {\n if (key in obj) {\n walk(obj[key], subSchema, joinPath(path, key), errors);\n }\n }\n }\n }\n\n if (schema.type === 'array' && Array.isArray(value) && schema.items) {\n value.forEach((item, i) => walk(item, schema.items as JSONSchema, `${path}[${i}]`, errors));\n }\n}\n\nfunction checkType(value: unknown, type: string): boolean {\n switch (type) {\n case 'string':\n return typeof value === 'string';\n case 'number':\n return typeof value === 'number' && !Number.isNaN(value);\n case 'integer':\n return typeof value === 'number' && Number.isInteger(value);\n case 'boolean':\n return typeof value === 'boolean';\n case 'null':\n return value === null;\n case 'array':\n return Array.isArray(value);\n case 'object':\n return isPlainObject(value);\n default:\n return true;\n }\n}\n\nfunction isPlainObject(v: unknown): boolean {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\nfunction describeType(v: unknown): string {\n if (v === null) return 'null';\n if (Array.isArray(v)) return 'array';\n return typeof v;\n}\n\nfunction joinPath(parent: string, key: string): string {\n if (!parent) return key;\n return `${parent}.${key}`;\n}\n\nfunction deepEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (typeof a !== typeof b) return false;\n if (a === null || b === null) return a === b;\n if (Array.isArray(a) && Array.isArray(b)) {\n return a.length === b.length && a.every((v, i) => deepEqual(v, b[i]));\n }\n if (typeof a === 'object' && typeof b === 'object') {\n const ak = Object.keys(a as object);\n const bk = Object.keys(b as object);\n if (ak.length !== bk.length) return false;\n return ak.every((k) =>\n deepEqual((a as Record<string, unknown>)[k], (b as Record<string, unknown>)[k]),\n );\n }\n return false;\n}\n","/**\n * Tool output serialization utilities.\n * Extracted from Agent.executeTools to allow reuse and consistent output handling.\n */\n\nexport interface ToolOutputSerializerOptions {\n perIterationOutputCapBytes?: number;\n estimator?: (text: string) => number;\n}\n\nexport function createToolOutputSerializer(opts: ToolOutputSerializerOptions = {}) {\n const capBytes = opts.perIterationOutputCapBytes ?? 100_000;\n\n function serialize(value: unknown): string {\n if (typeof value === 'string') return value;\n if (value === null || value === undefined) return '';\n if (typeof value === 'object') {\n if (Array.isArray(value)) return value.map(serialize).join('\\n');\n if ('text' in (value as Record<string, unknown>)) {\n const t = (value as Record<string, unknown>).text;\n return typeof t === 'string' ? t : JSON.stringify(value, null, 2);\n }\n try {\n return JSON.stringify(value, null, 2);\n } catch {\n return String(value);\n }\n }\n return String(value);\n }\n\n function enforceCap(text: string, remainingBudget: number): { text: string; newBudget: number } {\n if (remainingBudget <= 0) {\n return { text: '[truncated: iteration output cap exceeded]', newBudget: 0 };\n }\n const textBytes = Buffer.byteLength(text, 'utf8');\n if (textBytes <= remainingBudget) {\n return { text, newBudget: remainingBudget - textBytes };\n }\n const marker = `\\n…[truncated ${textBytes - remainingBudget} bytes]…\\n`;\n const markerBytes = Buffer.byteLength(marker, 'utf8');\n const available = remainingBudget - markerBytes;\n if (available <= 0) {\n return { text: '[truncated: iteration output cap exceeded]', newBudget: 0 };\n }\n const half = Math.floor(available / 2);\n const first = text.slice(0, half);\n const second = text.slice(text.length - half);\n return { text: `${first}${marker}${second}`, newBudget: 0 };\n }\n\n return { serialize, enforceCap, capBytes };\n}\n","import type { Context } from '../core/context.js';\nimport type { ToolResultBlock, ToolUseBlock } from '../types/blocks.js';\nimport type {\n ToolBatchResult,\n ToolConfirmPendingResult,\n ToolExecutionOutput,\n ToolExecutorOptions,\n ToolExecutorStrategy,\n} from '../types/tool-executor.js';\nimport type { Tool } from '../types/tool.js';\nimport {\n hasDangerousCapabilityForSubagents,\n getDangerousCapabilities,\n} from '../security/capabilities.js';\nimport { validateAgainstSchema } from '../utils/json-schema-validate.js';\nimport { createToolOutputSerializer } from '../utils/tool-output-serializer.js';\n\nexport class ToolExecutor {\n private readonly serializer;\n private readonly iterationTimeoutMs: number;\n\n constructor(\n private readonly registry: { get(name: string): Tool | undefined; list(): Tool[] },\n private opts: ToolExecutorOptions,\n ) {\n this.iterationTimeoutMs = opts.iterationTimeoutMs ?? 300_000;\n this.serializer = createToolOutputSerializer({\n perIterationOutputCapBytes: opts.perIterationOutputCapBytes ?? 100_000,\n });\n }\n\n /**\n * Clear the interactive confirm awaiter so the executor returns\n * `ToolConfirmPendingResult` instead of blocking on stdin. Used by\n * the CLI to switch from inline prompts (REPL) to event-driven\n * confirmation (TUI) at runtime.\n */\n clearConfirmAwaiter(): void {\n this.opts.confirmAwaiter = undefined;\n }\n\n /**\n * Execute a batch of tool uses using the configured strategy.\n * Returns the execution results and the remaining output budget.\n */\n async executeBatch(\n toolUses: ToolUseBlock[],\n ctx: Context,\n strategy: ToolExecutorStrategy,\n ): Promise<ToolBatchResult> {\n let budget = this.opts.perIterationOutputCapBytes ?? 100_000;\n\n const runOne = async (use0: ToolUseBlock): Promise<ToolExecutionOutput> => {\n const start = Date.now();\n // `use` is rebindable because a PreToolUse hook may rewrite its input.\n let use = use0;\n const tool = this.registry.get(use.name);\n\n // Fast path: unknown tool\n if (!tool) {\n const result = this.unknownToolResult(use, () => this.registry.list().map((t) => t.name));\n budget = this.decrementBudget(result, budget);\n return { result, tool, durationMs: Date.now() - start };\n }\n\n // Strong guarantee: Validate input against the tool's declared JSON Schema\n // *before* permission checks or execution. This is a hard gate — bad calls\n // are rejected early with actionable feedback so the model can self-correct.\n const validation = validateAgainstSchema(use.input, tool.inputSchema);\n if (!validation.ok) {\n const errorDetails = validation.errors\n .map((e) => ` - ${e.path || 'input'}: ${e.message}`)\n .join('\\n');\n\n const result = {\n type: 'tool_result' as const,\n tool_use_id: use.id,\n content:\n `Invalid arguments for tool \"${tool.name}\".\\n\\n` +\n `Validation errors:\\n${errorDetails}\\n\\n` +\n `Please call the tool again with arguments that match its inputSchema. ` +\n `You can use the \"tool-help\" tool with name=\"${tool.name}\" to see the exact expected schema.`,\n is_error: true,\n };\n budget = this.decrementBudget(result, budget);\n return { result, tool, durationMs: Date.now() - start };\n }\n\n // Capability safety net at the executor level (defense in depth).\n // For tools declaring dangerous capabilities, we ensure the permission\n // decision cannot silently become \"auto\" in non-yolo contexts.\n const toolDangerousCaps = getDangerousCapabilities(tool);\n if (toolDangerousCaps.length > 0) {\n // If the tool has dangerous capabilities and we're not in full yolo mode,\n // we can force the downstream permission policy to treat it more strictly.\n // For now we record it; future policy profiles can act on this.\n if (this.opts.events) {\n // Observability hook for dangerous capability usage\n }\n }\n\n // Provider boundary: the model's tool arguments arrive as a raw JSON\n // string accumulated over streamed deltas. When that string is not a\n // valid JSON object (truncated, scalar, or mangled by a proxy/local\n // model), the parsers wrap it under a sentinel key instead of silently\n // producing `{}`. Executing the tool with such input yields a cryptic\n // \"<field> is required\" error that the model can't act on. Detect the\n // sentinel here and feed back an actionable message so the model\n // resends well-formed arguments.\n if (hasMalformedArguments(use.input)) {\n const result = this.malformedInputResult(use, extractMalformedRaw(use.input));\n budget = this.decrementBudget(result, budget);\n return { result, tool, durationMs: Date.now() - start };\n }\n\n // PreToolUse hooks: may block the call outright or rewrite its input.\n // Runs before the permission check so a hook can veto a tool that the\n // trust policy would otherwise auto-allow.\n if (this.opts.hookRunner?.has('PreToolUse')) {\n const pre = await this.opts.hookRunner.preToolUse(tool.name, use.input, ctx);\n if (pre.block) {\n const result = this.blockedByHookResult(use, pre.reason);\n budget = this.decrementBudget(result, budget);\n return { result, tool, durationMs: Date.now() - start };\n }\n if (pre.input) {\n // A hook rewrote the arguments — re-validate before trusting them.\n const reval = validateAgainstSchema(pre.input, tool.inputSchema);\n if (!reval.ok) {\n const errorDetails = reval.errors\n .map((e) => ` - ${e.path || 'input'}: ${e.message}`)\n .join('\\n');\n const result = {\n type: 'tool_result' as const,\n tool_use_id: use.id,\n content:\n `A PreToolUse hook rewrote the arguments for \"${tool.name}\" into an invalid shape.\\n\\n` +\n `Validation errors:\\n${errorDetails}`,\n is_error: true,\n };\n budget = this.decrementBudget(result, budget);\n return { result, tool, durationMs: Date.now() - start };\n }\n use = { ...use, input: pre.input };\n }\n }\n\n const decision = await this.opts.permissionPolicy.evaluate(tool, use.input, ctx);\n\n // Post-permission dangerous capability enforcement (B-side guarantee).\n // Even after the permission policy has spoken, we apply an extra conservative\n // rule for tools that declare high-risk capabilities (shell arbitrary, write outside\n // project, mcp proxy, etc.). This reduces the blast radius of prompt injection.\n let effectivePermission = decision.permission;\n\n // YOLO is the user's explicit fast-path for normal project work, so it\n // waives the post-policy dangerous-capability net only after the permission\n // policy has already returned `auto`. Destructive-gated calls still arrive\n // here as `confirm` unless the destructive YOLO override is active. Outside\n // YOLO, a trust-file auto-allow for a shell tool still gets a confirm, so a\n // single trusted pattern can't silently widen into arbitrary shell.\n // Detected via optional methods so policies without them (AutoApprove,\n // test mocks) keep the stricter default.\n const policy = this.opts.permissionPolicy;\n const yolo =\n policy.getYolo?.() === true ||\n policy.getYoloDestructive?.() === true ||\n policy.getForceAllYolo?.() === true;\n\n if (toolDangerousCaps.length > 0 && effectivePermission === 'auto' && !yolo) {\n // Outside yolo we force at least 'confirm' for dangerous-capability tools.\n effectivePermission = 'confirm';\n }\n\n if (effectivePermission === 'deny') {\n const result = this.deniedResult(use, decision.reason);\n budget = this.decrementBudget(result, budget);\n return { result, tool, durationMs: Date.now() - start };\n }\n\n if (effectivePermission === 'confirm') {\n if (this.opts.confirmAwaiter) {\n const choice = await this.opts.confirmAwaiter(tool, use.input, use.id, tool.name);\n if (choice !== 'yes' && choice !== 'always') {\n const result = {\n type: 'tool_result' as const,\n tool_use_id: use.id,\n content: `Tool \"${tool.name}\" denied by user.`,\n is_error: true,\n };\n budget = this.decrementBudget(result, budget);\n return { result, tool, durationMs: Date.now() - start };\n }\n // fall through to execute\n } else {\n const suggestedPattern =\n this.subjectFor(tool.name, use.input, tool.subjectKey) ?? tool.name;\n const pending: ToolConfirmPendingResult = {\n type: 'tool_confirm_pending',\n toolUseId: use.id,\n toolName: tool.name,\n input: use.input,\n suggestedPattern,\n };\n return { result: pending, tool, durationMs: Date.now() - start };\n }\n }\n\n // effectivePermission === 'auto' (after all safety layers)\n // Capability audit for observability.\n const toolCapsForAudit = hasDangerousCapabilityForSubagents(tool) ? (tool.capabilities ?? []) : [];\n\n // L1-C: trace each tool execution. Span is a no-op unless an OTel\n // adapter or other Tracer is bound — zero overhead by default.\n const span = this.opts.tracer?.startSpan(`tool.${tool.name}`, {\n 'tool.name': tool.name,\n 'tool.mutating': tool.mutating,\n 'tool.permission': tool.permission,\n 'tool.capabilities': JSON.stringify(tool.capabilities ?? []),\n 'tool.has_dangerous_capabilities': toolCapsForAudit.length > 0,\n });\n try {\n let result = await this.executeTool(tool, use, ctx, budget);\n // PostToolUse hooks: observe the result and optionally append context\n // (e.g. a linter note) that the model sees alongside the tool output.\n if (this.opts.hookRunner?.has('PostToolUse')) {\n const post = await this.opts.hookRunner.postToolUse(\n tool.name,\n use.input,\n { content: String(result.content), isError: !!result.is_error },\n ctx,\n );\n if (post.additionalContext) {\n result = { ...result, content: `${result.content}\\n\\n${post.additionalContext}` };\n }\n }\n budget = this.decrementBudget(result, budget);\n span?.setAttribute('tool.is_error', !!result.is_error);\n span?.setAttribute(\n 'tool.output_bytes',\n typeof result.content === 'string' ? result.content.length : 0,\n );\n return { result, tool, durationMs: Date.now() - start };\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n const scrubbed = this.opts.secretScrubber.scrub(msg);\n this.opts.renderer?.writeToolResult(tool.name, scrubbed, true);\n const result = {\n type: 'tool_result' as const,\n tool_use_id: use.id,\n content: `Tool \"${tool.name}\" threw: ${scrubbed}`,\n is_error: true,\n };\n budget = this.decrementBudget(result, budget);\n if (err instanceof Error) span?.recordError(err);\n span?.setAttribute('tool.is_error', true);\n return { result, tool, durationMs: Date.now() - start };\n } finally {\n span?.end();\n }\n };\n\n // Run a single tool but never let an exception propagate to the\n // gather() below — `runOne` is already try/catch-wrapped for the\n // execution phase, but the *pre*-execution paths (permission policy,\n // confirmAwaiter) are unguarded and an unexpected throw there would\n // collapse Promise.all and lose every sibling's output. Wrap each\n // call so a per-tool failure becomes a per-tool error result.\n const safeRun = async (use: ToolUseBlock): Promise<ToolExecutionOutput> => {\n try {\n return await runOne(use);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n const scrubbed = this.opts.secretScrubber.scrub(msg);\n const result = {\n type: 'tool_result' as const,\n tool_use_id: use.id,\n content: `Tool \"${use.name}\" execution failed: ${scrubbed}`,\n is_error: true,\n };\n budget = this.decrementBudget(result, budget);\n return { result, tool: this.registry.get(use.name), durationMs: 0 };\n }\n };\n\n if (strategy === 'sequential') {\n const outputs: ToolExecutionOutput[] = [];\n for (const use of toolUses) {\n if (use) outputs.push(await safeRun(use));\n }\n return { outputs, remainingBudget: budget };\n }\n\n if (strategy === 'parallel') {\n const outputs = await Promise.all(toolUses.map((use) => safeRun(use)));\n return { outputs, remainingBudget: budget };\n }\n\n // smart: non-mutating in parallel, then mutating sequentially\n const nonMutating: ToolUseBlock[] = [];\n const mutating: ToolUseBlock[] = [];\n for (const use of toolUses) {\n if (!use) continue;\n const tool = this.registry.get(use.name);\n if (tool?.mutating) mutating.push(use);\n else nonMutating.push(use);\n }\n const firstPass = await Promise.all(nonMutating.map((use) => safeRun(use)));\n const secondPass: ToolExecutionOutput[] = [];\n for (const use of mutating) {\n secondPass.push(await safeRun(use));\n }\n return {\n outputs: [...firstPass, ...secondPass],\n remainingBudget: budget,\n };\n }\n\n /**\n * Execute a single tool with timeout, permission check, and output capping.\n * Emits `tool.started` via the injected EventBus (if any) right before\n * invoking the tool — closes the observability gap between \"model decided\n * to call a tool\" and \"tool.executed\".\n */\n async executeTool(\n tool: Tool,\n use: ToolUseBlock,\n ctx: Context,\n budget: number,\n ): Promise<ToolResultBlock> {\n this.opts.events?.emit('tool.started', {\n name: tool.name,\n id: use.id,\n input: use.input,\n });\n this.opts.renderer?.writeToolCall(tool.name, use.input);\n const output = await this.runWithTimeout(tool, use.input, ctx.signal, ctx, use.id);\n const text = this.serializer.serialize(output);\n const scrubbed = this.opts.secretScrubber.scrub(text);\n const { text: capped } = this.serializer.enforceCap(scrubbed, budget);\n this.opts.renderer?.writeToolResult(tool.name, capped, false);\n return {\n type: 'tool_result',\n tool_use_id: use.id,\n name: tool.name,\n content: capped,\n is_error: false,\n };\n }\n\n private async runWithTimeout(\n tool: Tool,\n input: unknown,\n parentSignal: AbortSignal,\n ctx: Context,\n toolUseId?: string,\n ): Promise<unknown> {\n if (parentSignal.aborted) {\n // Re-throw the original abort reason, whether it's an Error, string, or undefined.\n if (parentSignal.reason instanceof Error) throw parentSignal.reason;\n throw new Error(typeof parentSignal.reason === 'string' ? parentSignal.reason : 'aborted');\n }\n const timeoutMs = tool.timeoutMs ?? this.iterationTimeoutMs;\n const ctrl = new AbortController();\n const timer = setTimeout(() => ctrl.abort(new Error('tool timeout')), timeoutMs);\n const combined = AbortSignal.any([parentSignal, ctrl.signal]);\n let cleanupCalled = false;\n let caught = false;\n try {\n // Streaming variant takes precedence — yields progress events, then\n // a final 'final' event with the typed output. Tools that don't\n // implement executeStream fall through to the standard execute path.\n if (typeof tool.executeStream === 'function') {\n return await this.runStreamedTool(tool, input, ctx, combined, toolUseId);\n }\n return await tool.execute(input, ctx, { signal: combined });\n } catch (err) {\n caught = true;\n if (combined.aborted && typeof tool.cleanup === 'function') {\n // Best-effort cleanup; never let it mask the original error.\n cleanupCalled = true;\n try {\n await tool.cleanup(input, ctx);\n } catch {\n /* swallow */\n }\n }\n throw err;\n } finally {\n clearTimeout(timer);\n // If the tool completed successfully (no error thrown) but the combined\n // signal was aborted (e.g. timeout), the catch block above never fired.\n // Call cleanup here and then throw so the caller sees the abort.\n // When `caught` is true, we already have an in-flight throw — don't\n // override it from `finally` (that would replace the original error\n // with the abort reason and mask the actual failure).\n if (combined.aborted && !caught) {\n if (!cleanupCalled && typeof tool.cleanup === 'function') {\n try {\n await tool.cleanup(input, ctx);\n } catch {\n /* swallow */\n }\n }\n const reason = combined.reason instanceof Error\n ? combined.reason\n : new Error(typeof combined.reason === 'string' ? combined.reason : 'aborted');\n // biome-ignore lint/correctness/noUnsafeFinally: guarded by `!caught` — only runs when the tool returned cleanly but the signal aborted, so there is no in-flight exception to override.\n throw reason;\n }\n }\n }\n\n private async runStreamedTool(\n tool: Tool,\n input: unknown,\n ctx: Context,\n signal: AbortSignal,\n toolUseId: string | undefined,\n ): Promise<unknown> {\n let finalOutput: unknown;\n let sawFinal = false;\n const stream = tool.executeStream!(input, ctx, { signal });\n for await (const ev of stream) {\n if (ev.type === 'final') {\n finalOutput = ev.output;\n sawFinal = true;\n // Drain whatever the iterator wants to surface after final, but the\n // result is locked in. Most tools won't yield more.\n break;\n }\n this.opts.events?.emit('tool.progress', {\n name: tool.name,\n id: toolUseId ?? '<unknown>',\n event: ev,\n });\n }\n if (!sawFinal) {\n throw new Error(`tool \"${tool.name}\" executeStream completed without a 'final' event`);\n }\n return finalOutput;\n }\n\n private unknownToolResult(use: ToolUseBlock, listFns: () => string[]): ToolResultBlock {\n return {\n type: 'tool_result',\n tool_use_id: use.id,\n content: `Tool \"${use.name}\" is not registered. Available tools: ${listFns().join(', ')}`,\n is_error: true,\n };\n }\n\n private malformedInputResult(use: ToolUseBlock, raw?: string): ToolResultBlock {\n let content =\n `Tool \"${use.name}\" received arguments that were not a valid JSON object, so they ` +\n `could not be parsed. Re-issue the call with the arguments encoded as a single ` +\n `well-formed JSON object matching the tool's input schema.`;\n // Echo the raw payload back so the model can see *what* it produced and\n // self-correct. Without this the model is blind to its own mistake and\n // tends to resend the identical malformed call in a loop. Common causes:\n // unescaped newlines/quotes/backslashes inside a string field, or the\n // arguments being truncated mid-stream.\n if (raw) {\n const max = 800;\n const excerpt = raw.length > max ? `${raw.slice(0, max)}… (truncated, ${raw.length} chars total)` : raw;\n content +=\n ` Common cause: a string field (e.g. code in old_string/new_string) ` +\n `contains literal newlines, quotes, or backslashes that must be JSON-escaped, ` +\n `or the payload was cut off mid-stream. The raw arguments received were:\\n${excerpt}`;\n }\n return {\n type: 'tool_result',\n tool_use_id: use.id,\n content,\n is_error: true,\n };\n }\n\n private deniedResult(use: ToolUseBlock, reason?: string): ToolResultBlock {\n return {\n type: 'tool_result',\n tool_use_id: use.id,\n content: `Tool \"${use.name}\" denied: ${reason ?? 'policy'}`,\n is_error: true,\n };\n }\n\n private blockedByHookResult(use: ToolUseBlock, reason?: string): ToolResultBlock {\n return {\n type: 'tool_result',\n tool_use_id: use.id,\n content: `Tool \"${use.name}\" was blocked by a PreToolUse hook: ${reason ?? 'no reason given'}`,\n is_error: true,\n };\n }\n\n private decrementBudget(result: ToolResultBlock, budget: number): number {\n const contentBytes =\n typeof result.content === 'string'\n ? Buffer.byteLength(result.content, 'utf8')\n : Buffer.byteLength(JSON.stringify(result.content), 'utf8');\n return Math.max(0, budget - contentBytes);\n }\n\n /**\n * Compute the suggestedPattern string for a tool+input pair.\n * Matches the logic in DefaultPermissionPolicy so the TUI shows the\n * same subject that the trust file would use.\n */\n private subjectFor(toolName: string, input: unknown, subjectKey?: string): string | undefined {\n if (!input || typeof input !== 'object') return undefined;\n const obj = input as Record<string, unknown>;\n const globChars = /[*?\\[\\]]/g;\n const escapeGlob = (s: string) => s.replace(globChars, (c) => `\\\\${c}`);\n const normalizePath = (s: string) => escapeGlob(s.replace(/\\\\/g, '/'));\n\n // Mirror DefaultPermissionPolicy.subjectFor — keep both in sync so the\n // TUI's \"suggested pattern\" matches what the trust file actually uses.\n if (subjectKey) {\n const v = obj[subjectKey];\n if (typeof v === 'string') {\n const isPathKey = subjectKey === 'path' || subjectKey === 'file' || subjectKey === 'files';\n return isPathKey ? normalizePath(v) : escapeGlob(v);\n }\n }\n\n if (toolName === 'bash' && typeof obj.command === 'string') {\n return escapeGlob(obj.command);\n }\n if (typeof obj.path === 'string') {\n return normalizePath(obj.path);\n }\n if (typeof obj.url === 'string') {\n return escapeGlob(obj.url);\n }\n if (typeof obj.name === 'string') {\n return escapeGlob(obj.name);\n }\n return undefined;\n }\n}\n\n/**\n * Sentinel keys the provider adapters use to wrap tool arguments that could\n * not be parsed into a proper JSON object. `parseToolInput` (Anthropic /\n * shared) uses `__raw`, `contentFromOpenAI` uses `__raw_arguments`, and the\n * streaming response builder's `safeJsonOrRaw` uses `_raw`. Keep this list in\n * sync if a new adapter introduces another marker.\n *\n * NOTE: `parseToolInput` and `safeJsonOrRaw` now attempt JSON repair\n * (auto-closing braces and strings) before wrapping — so a truncated blob\n * like `{\"old_string\": \"line1\\nline2` gets repaired first. The sentinel is\n * only used when repair also fails.\n */\nconst MALFORMED_ARG_MARKERS = ['__raw', '__raw_arguments', '_raw'] as const;\n\nfunction hasMalformedArguments(input: unknown): boolean {\n if (!input || typeof input !== 'object' || Array.isArray(input)) return false;\n const obj = input as Record<string, unknown>;\n // The sentinel is the *only* key when wrapping occurred — a real tool call\n // that legitimately uses a key named e.g. `_raw` will carry other keys too.\n const keys = Object.keys(obj);\n return keys.length === 1 && MALFORMED_ARG_MARKERS.includes(keys[0] as never);\n}\n\n/**\n * Pull the original (unparseable) payload back out of a sentinel-wrapped input\n * so the executor can echo it to the model. The wrapped value is usually the\n * raw argument string, but a scalar/array that parsed cleanly is wrapped too —\n * stringify those. Returns undefined if nothing usable is present.\n */\nfunction extractMalformedRaw(input: unknown): string | undefined {\n if (!hasMalformedArguments(input)) return undefined;\n const obj = input as Record<string, unknown>;\n const value = obj[Object.keys(obj)[0]!];\n if (value === undefined || value === null) return undefined;\n if (typeof value === 'string') return value;\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n","/**\n * Compile a user-supplied regex with conservative bounds against ReDoS.\n *\n * Duplicated from @wrongstack/tools/_regex.ts to avoid a circular\n * dependency (tools depends on core, not vice versa). Keep both copies\n * in sync if the heuristics change.\n *\n * V8's regex engine is backtracking-based and cannot interrupt a\n * synchronous match — a pattern like `(a+)+$` against a sufficiently\n * long line will pin a worker for seconds.\n */\n\nconst MAX_PATTERN_LEN = 512;\n\n// Heuristics for catastrophic-backtracking constructs.\nconst DANGEROUS_PATTERNS: ReadonlyArray<RegExp> = [\n /(\\([^)]*[+*][^)]*\\))[+*]/, // (a+)+, (.*)+, etc\n /(\\(\\?:[^)]*[+*][^)]*\\))[+*]/, // same, with non-capturing group\n];\n\nexport interface CompileResult {\n ok: true;\n regex: RegExp;\n}\n\nexport interface CompileFail {\n ok: false;\n reason: string;\n}\n\nexport function compileUserRegex(pattern: string, flags: string): CompileResult | CompileFail {\n if (typeof pattern !== 'string') {\n return { ok: false, reason: 'pattern must be a string' };\n }\n if (pattern.length === 0) {\n return { ok: false, reason: 'pattern is empty' };\n }\n if (pattern.length > MAX_PATTERN_LEN) {\n return { ok: false, reason: `pattern exceeds ${MAX_PATTERN_LEN} characters` };\n }\n for (const rx of DANGEROUS_PATTERNS) {\n if (rx.test(pattern)) {\n return {\n ok: false,\n reason:\n 'pattern looks vulnerable to catastrophic backtracking — rewrite without nested quantifiers',\n };\n }\n }\n try {\n return { ok: true, regex: new RegExp(pattern, flags) };\n } catch (err) {\n return {\n ok: false,\n reason: err instanceof Error ? err.message : 'invalid regex',\n };\n }\n}\n","import type { Agent, RunResult } from '../core/agent.js';\r\nimport type { Context } from '../core/context.js';\r\nimport { toWrongStackError } from '../types/errors.js';\r\nimport type { DoneCondition } from '../types/multi-agent.js';\r\nimport { compileUserRegex } from '../utils/regex-guard.js';\r\n\r\ntype AutonomousResult = RunResult & { toolCalls: number; reason?: string };\r\n\r\nexport interface DoneCheckResult {\r\n done: boolean;\r\n reason?: string;\r\n iterations: number;\r\n toolCalls: number;\r\n}\r\n\r\nexport class DoneConditionChecker {\r\n private readonly compiledRegex: RegExp | null;\r\n\r\n constructor(private readonly condition: DoneCondition) {\r\n if (condition.type === 'output_match' && condition.pattern) {\r\n const result = compileUserRegex(condition.pattern, '');\r\n this.compiledRegex = result.ok ? result.regex : null;\r\n if (!result.ok) {\r\n // Log warning but don't throw — the done condition simply won't match\r\n console.warn(`[DoneConditionChecker] Invalid regex pattern \"${condition.pattern}\": ${result.reason}`);\r\n }\r\n } else {\r\n this.compiledRegex = null;\r\n }\r\n }\r\n\r\n check(state: { iterations: number; toolCalls: number; lastOutput?: string }): DoneCheckResult {\r\n switch (this.condition.type) {\r\n case 'iterations':\r\n if (this.condition.maxIterations && state.iterations >= this.condition.maxIterations) {\r\n return {\r\n done: true,\r\n reason: `max iterations (${this.condition.maxIterations}) reached`,\r\n ...state,\r\n };\r\n }\r\n break;\r\n\r\n case 'tool_calls':\r\n if (this.condition.maxToolCalls && state.toolCalls >= this.condition.maxToolCalls) {\r\n return {\r\n done: true,\r\n reason: `max tool calls (${this.condition.maxToolCalls}) reached`,\r\n ...state,\r\n };\r\n }\r\n break;\r\n\r\n case 'output_match':\r\n if (this.compiledRegex && state.lastOutput && this.compiledRegex.test(state.lastOutput)) {\r\n return {\r\n done: true,\r\n reason: `output matched pattern \"${this.condition.pattern}\"`,\r\n ...state,\r\n };\r\n }\r\n break;\r\n\r\n case 'directive':\r\n // Model-driven: the agent manages its own continuation via [continue]/[done].\r\n // The done condition is never satisfied by the checker — the agent returns\r\n // `status: 'done'` when the model emits [done] or naturally finishes.\r\n // The runner's outer loop uses maxIterations/maxToolCalls as hard caps.\r\n if (this.condition.maxIterations && state.iterations >= this.condition.maxIterations) {\r\n return { done: true, reason: `max iterations (${this.condition.maxIterations}) reached`, ...state };\r\n }\r\n if (this.condition.maxToolCalls && state.toolCalls >= this.condition.maxToolCalls) {\r\n return { done: true, reason: `max tool calls (${this.condition.maxToolCalls}) reached`, ...state };\r\n }\r\n break;\r\n\r\n case 'custom':\r\n // Reserved for future extension\r\n break;\r\n }\r\n\r\n return { done: false, iterations: state.iterations, toolCalls: state.toolCalls };\r\n }\r\n}\r\n\r\nexport interface AutonomousRunnerOptions {\r\n agent: Agent;\r\n context: Context;\r\n doneCondition: DoneCondition;\r\n iterationTimeoutMs?: number;\r\n onIteration?: (state: { iteration: number; toolCalls: number }) => void;\r\n onDone?: (result: AutonomousResult) => void;\r\n /**\r\n * When true and `doneCondition.type === 'directive'`, the runner\r\n * runs the agent with `autonomousContinue: true` so the agent loop\r\n * handles its own [continue]/[done] markers internally (no outer\r\n * re-invocation needed). The runner still provides iteration/timeouts.\r\n */\r\n enableAutonomousContinue?: boolean;\r\n}\r\n\r\nexport class AutonomousRunner {\r\n private iterations = 0;\r\n private toolCalls = 0;\r\n private lastOutput?: string;\r\n private stopped = false;\r\n private readonly doneChecker: DoneConditionChecker;\r\n\r\n constructor(private readonly opts: AutonomousRunnerOptions) {\r\n this.doneChecker = new DoneConditionChecker(opts.doneCondition);\r\n }\r\n\r\n async run(): Promise<AutonomousResult> {\r\n // Subscribe to `tool.executed` so the per-tool budget (`tool_calls`\r\n // done-condition) actually counts each tool invocation rather than\r\n // each `agent.run()` call. Without this, a single iteration that\r\n // fires 5 tools only bumps the counter once, and a `maxToolCalls: 3`\r\n // budget would fire after 3 iterations (typically 3×N tools) instead\r\n // of after 3 tools. Unsubscribed in the `finally` so the listener\r\n // doesn't outlive this run instance. Mock agents in tests may pass\r\n // null/undefined for `events`; gracefully skip when missing — those\r\n // tests don't exercise the tool-count budget path.\r\n const offToolExecuted = this.opts.agent.events?.on?.('tool.executed', () => {\r\n this.toolCalls++;\r\n });\r\n // When autonomous continue is enabled, also count internal agent-loop\r\n // iterations. Each iteration.started within a single agent.run() call\r\n // counts toward the runner's maxIterations cap. We listen to the event\r\n // through the agent's EventBus.\r\n const offIterationCompleted = this.opts.agent.events?.on?.('iteration.completed', () => {\r\n // Only count if we're in autonomous continue mode (agent loop\r\n // handles multiple iterations internally before returning).\r\n if (this.opts.enableAutonomousContinue && this.opts.doneCondition.type === 'directive') {\r\n // Each internal iteration completed — bump the outer iteration counter.\r\n // This ensures maxIterations on the runner actually limits total work.\r\n this.iterations++;\r\n }\r\n });\r\n try {\r\n return await this.runLoop();\r\n } finally {\r\n offToolExecuted?.();\r\n offIterationCompleted?.();\r\n }\r\n }\r\n\r\n private async runLoop(): Promise<AutonomousResult> {\r\n while (!this.stopped) {\r\n const check = this.doneChecker.check({\r\n iterations: this.iterations,\r\n toolCalls: this.toolCalls,\r\n lastOutput: this.lastOutput,\r\n });\r\n\r\n if (check.done) {\r\n const result: AutonomousResult = {\r\n status: 'done',\r\n iterations: this.iterations,\r\n toolCalls: this.toolCalls,\r\n reason: check.reason,\r\n };\r\n this.opts.onDone?.(result);\r\n return result;\r\n }\r\n\r\n this.opts.onIteration?.({ iteration: this.iterations, toolCalls: this.toolCalls });\r\n\r\n const ctrl = new AbortController();\r\n const timeout = setTimeout(() => ctrl.abort(), this.opts.iterationTimeoutMs ?? 30_000);\r\n\r\n try {\r\n // In directive mode with autonomous continue, pass it through so the\r\n // agent loop handles its own [continue]/[done] markers internally.\r\n // The runner provides iteration caps and timeouts; the agent handles\r\n // the continuation decision within each agent.run() call.\r\n const isDirectiveMode =\r\n this.opts.doneCondition.type === 'directive' &&\r\n this.opts.enableAutonomousContinue;\r\n\r\n const result = await this.opts.agent.run('', {\r\n signal: ctrl.signal,\r\n maxIterations: isDirectiveMode ? (this.opts.doneCondition.maxIterations ?? 100) : 1,\r\n executionStrategy: 'sequential',\r\n autonomousContinue: isDirectiveMode ? true : undefined,\r\n });\r\n\r\n // Only increment iterations if we're NOT counting via iteration.completed\r\n // (i.e., not in autonomous continue directive mode). In that mode,\r\n // the offIterationCompleted listener in run() bumps this counter\r\n // per internal iteration so the runner's maxIterations cap is respected.\r\n if (!isDirectiveMode) this.iterations++;\r\n // Only access finalText when the run actually succeeded. Failed/aborted\r\n // runs may have undefined finalText — accessing it unconditionally would\r\n // produce garbage output for the done-condition matchers.\r\n if (result.status === 'done') {\r\n this.lastOutput = result.finalText;\r\n }\r\n // `toolCalls` is bumped by the `tool.executed` listener installed\r\n // in run() — no manual increment here.\r\n\r\n if (result.status === 'failed' || result.status === 'aborted') {\r\n const failedResult: AutonomousResult = {\r\n status: result.status,\r\n error: result.error,\r\n iterations: this.iterations,\r\n toolCalls: this.toolCalls,\r\n };\r\n this.opts.onDone?.(failedResult);\r\n return failedResult;\r\n }\r\n } catch (e) {\r\n // Be precise about what constitutes a timeout error — matching on\r\n // 'timeout' substring is too loose (an error message containing\r\n // \"timeout exceeded\" from the LLM is not the same as an abort).\r\n const isAbort =\r\n (e instanceof DOMException && e.name === 'AbortError') ||\r\n (e instanceof Error && e.name === 'AbortError') ||\r\n (e instanceof Error && e.message.includes('iteration timeout'));\r\n if (isAbort) {\r\n const timeoutResult: AutonomousResult = {\r\n status: 'failed',\r\n error: toWrongStackError(e),\r\n iterations: this.iterations,\r\n toolCalls: this.toolCalls,\r\n reason: 'iteration timeout',\r\n };\r\n this.opts.onDone?.(timeoutResult);\r\n return timeoutResult;\r\n }\r\n // Any other throw (TypeError, tool crash propagation, etc.) must\r\n // stop the loop — silently continuing would spin forever on the\r\n // same error and burn provider tokens with no progress.\r\n this.stopped = true;\r\n const failedResult: AutonomousResult = {\r\n status: 'failed',\r\n error: toWrongStackError(e),\r\n iterations: this.iterations,\r\n toolCalls: this.toolCalls,\r\n reason: e instanceof Error ? e.message : String(e),\r\n };\r\n this.opts.onDone?.(failedResult);\r\n return failedResult;\r\n } finally {\r\n clearTimeout(timeout);\r\n }\r\n }\r\n\r\n return {\r\n status: 'aborted',\r\n iterations: this.iterations,\r\n toolCalls: this.toolCalls,\r\n reason: 'stopped externally',\r\n };\r\n }\r\n\r\n stop(): void {\r\n this.stopped = true;\r\n }\r\n}\r\n","import { randomBytes } from 'node:crypto';\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\n\nexport interface AtomicWriteOptions {\n mode?: number;\n encoding?: BufferEncoding;\n}\n\nexport async function atomicWrite(\n targetPath: string,\n content: string | Uint8Array,\n opts: AtomicWriteOptions = {},\n): Promise<void> {\n const dir = path.dirname(targetPath);\n await fs.mkdir(dir, { recursive: true });\n const tmp = path.join(dir, `.${path.basename(targetPath)}.${randomBytes(6).toString('hex')}.tmp`);\n\n // Write content to tmp first; 'wx' ensures exclusive creation (fails if\n // tmp already exists — extremely unlikely with 6-byte random suffix).\n try {\n if (typeof content === 'string') {\n await fs.writeFile(tmp, content, { flag: 'wx', encoding: opts.encoding ?? 'utf8' });\n } else {\n await fs.writeFile(tmp, content, { flag: 'wx' });\n }\n try {\n const fh = await fs.open(tmp, 'r+');\n try {\n await fh.sync();\n } finally {\n await fh.close();\n }\n } catch {\n // fsync best-effort\n }\n // Now safely read mode from target (if it exists) and apply to tmp before rename.\n // Prefer opts.mode for new files; for existing files preserve their mode.\n let mode: number | undefined;\n try {\n const stat = await fs.stat(targetPath);\n mode = stat.mode & 0o777;\n } catch {\n mode = opts.mode;\n }\n if (mode !== undefined) {\n await fs.chmod(tmp, mode);\n }\n await renameWithRetry(tmp, targetPath);\n } catch (err) {\n try {\n await fs.unlink(tmp);\n } catch {\n // ignore cleanup error\n }\n throw err;\n }\n}\n\nexport async function ensureDir(dir: string): Promise<void> {\n await fs.mkdir(dir, { recursive: true });\n}\n\n// On Windows, fs.rename over an existing file can fail with EPERM/EBUSY/EACCES\n// when antivirus, file indexers, editor file watchers, or a concurrent writer\n// briefly hold a handle on the destination. These are transient — retry with a\n// short backoff before giving up. POSIX renames are atomic and won't hit this.\nconst TRANSIENT_RENAME_CODES = new Set(['EPERM', 'EBUSY', 'EACCES', 'ENOTEMPTY']);\n\nasync function renameWithRetry(from: string, to: string): Promise<void> {\n if (process.platform !== 'win32') {\n await fs.rename(from, to);\n return;\n }\n const delays = [10, 25, 60, 120, 250];\n let lastErr: unknown;\n for (let i = 0; i <= delays.length; i++) {\n try {\n await fs.rename(from, to);\n return;\n } catch (err) {\n lastErr = err;\n const code = (err as NodeJS.ErrnoException)?.code;\n if (!code || !TRANSIENT_RENAME_CODES.has(code) || i === delays.length) {\n throw err;\n }\n await new Promise((resolve) => setTimeout(resolve, delays[i]));\n }\n }\n throw lastErr;\n}\n","import * as fsp from 'node:fs/promises';\r\nimport * as path from 'node:path';\r\nimport { createHash } from 'node:crypto';\r\nimport * as os from 'node:os';\r\nimport { atomicWrite } from '../utils/atomic-write.js';\r\nimport { FsError, ERROR_CODES } from '../types/errors.js';\r\n\r\n/**\r\n * Long-running autonomous mission. A goal survives across sessions and\r\n * drives the EternalAutonomyEngine — every iteration of the engine\r\n * consults the goal to choose what to do next.\r\n *\r\n * Storage: `~/.wrongstack/projects/<hash>/goal.json`. Persistent and\r\n * project-scoped on purpose: the goal belongs to the codebase, not the\r\n * REPL session.\r\n */\r\n\r\nexport interface JournalEntry {\r\n /** ISO timestamp of the iteration. */\r\n at: string;\r\n /** Sequential iteration counter (1-based, monotonically increasing). */\r\n iteration: number;\r\n /** Source that produced the action ('todo' | 'git' | 'brainstorm' | 'resume' | 'manual' | 'parallel'). */\r\n source: 'todo' | 'git' | 'brainstorm' | 'resume' | 'manual' | 'parallel';\r\n /** Short one-line description of what the iteration set out to do. */\r\n task: string;\r\n /** Outcome status. */\r\n status: 'success' | 'failure' | 'aborted' | 'skipped';\r\n /** Optional free-form note (error message, summary, etc.). */\r\n note?: string;\r\n /** Optional token usage delta for this iteration. */\r\n tokens?: { input: number; output: number };\r\n /** Optional USD cost delta for this iteration (provider-estimated). */\r\n costUsd?: number;\r\n}\r\n\r\nexport interface GoalFile {\r\n version: 1;\r\n /** The mission statement. */\r\n goal: string;\r\n /** When the goal was first set or last replaced. */\r\n setAt: string;\r\n /** Updated on every iteration completion. */\r\n lastActivityAt: string;\r\n /** Total iterations the engine has run against this goal (cumulative). */\r\n iterations: number;\r\n /** Engine lifecycle state — 'running' means another process owns this goal. */\r\n engineState: 'idle' | 'running' | 'stopped';\r\n /**\r\n * Mission-level lifecycle. `active` is the default; `completed` is set\r\n * when the engine detects `[GOAL_COMPLETE]` in a successful iteration's\r\n * final text AND a verification pass agrees; `abandoned` is set by the\r\n * user (e.g. `/goal abandon`) or when the engine exceeds a configured\r\n * failure ceiling. Once not `active`, the engine refuses to run further\r\n * iterations against this goal — protects against accidental restarts\r\n * burning through API quota after the work is done.\r\n *\r\n * Optional for backward compatibility — pre-existing `goal.json` files\r\n * without this field load as `active`.\r\n */\r\n goalState?: 'active' | 'paused' | 'completed' | 'abandoned';\r\n /**\r\n * Per-todo attempt counter. Keyed by TodoItem id. Used by the engine\r\n * to skip a todo that has failed N times rather than spinning on it\r\n * forever. Persisted so attempt counts survive restarts (`/autonomy\r\n * stop` + resume should not reset progress against a stuck task).\r\n */\r\n todoAttempts?: Record<string, number>;\r\n /** Bounded ring buffer of recent iterations (newest last). */\r\n journal: JournalEntry[];\r\n}\r\n\r\n/** Cap on persisted journal entries — older entries are evicted FIFO. */\r\nexport const MAX_JOURNAL_ENTRIES = 500;\r\n\r\n/**\r\n * Resolve the goal file path for a given project root.\r\n * Exposed so the engine and CLI use one canonical path.\r\n * Uses `~/.wrongstack/projects/<hash>/goal.json` .<hash>/`.\r\n */\r\nexport function goalFilePath(projectRoot: string): string {\r\n // Now resolves to ~/.wrongstack/projects/<hash>/goal.json for consistency\r\n // with WstackPaths.projectGoal.\r\n const hash = createHash('sha256').update(path.resolve(projectRoot)).digest('hex').slice(0, 12);\r\n return path.join(os.homedir(), '.wrongstack', 'projects', hash, 'goal.json');\r\n}\r\n\r\nexport async function loadGoal(filePath: string): Promise<GoalFile | null> {\r\n let raw: string;\r\n try {\r\n raw = await fsp.readFile(filePath, 'utf8');\r\n } catch {\r\n return null;\r\n }\r\n try {\r\n const parsed = JSON.parse(raw) as GoalFile;\r\n if (parsed?.version !== 1 || typeof parsed.goal !== 'string' || !Array.isArray(parsed.journal)) {\r\n return null;\r\n }\r\n return parsed;\r\n } catch {\r\n return null;\r\n }\r\n}\r\n\r\nexport async function saveGoal(filePath: string, goal: GoalFile): Promise<void> {\r\n try {\r\n await atomicWrite(filePath, JSON.stringify(goal, null, 2), { mode: 0o600 });\r\n } catch (err) {\r\n throw new FsError({\r\n message: err instanceof Error ? err.message : String(err),\r\n code: ERROR_CODES.FS_ATOMIC_WRITE_FAILED,\r\n path: filePath,\r\n cause: err,\r\n });\r\n }\r\n}\r\n\r\nexport function emptyGoal(goal: string): GoalFile {\r\n const now = new Date().toISOString();\r\n return {\r\n version: 1,\r\n goal,\r\n setAt: now,\r\n lastActivityAt: now,\r\n iterations: 0,\r\n engineState: 'idle',\r\n goalState: 'active',\r\n todoAttempts: {},\r\n journal: [],\r\n };\r\n}\r\n\r\n/**\r\n * Append a journal entry, bumping iteration counters and trimming the\r\n * ring buffer. Returns a new GoalFile — does not mutate the argument.\r\n */\r\nexport function appendJournal(goal: GoalFile, entry: Omit<JournalEntry, 'iteration' | 'at'>): GoalFile {\r\n const iteration = goal.iterations + 1;\r\n const at = new Date().toISOString();\r\n const full: JournalEntry = { ...entry, iteration, at };\r\n const journal = [...goal.journal, full];\r\n // Trim FIFO if over cap. Slice from the tail so the *newest* MAX entries survive.\r\n const trimmed = journal.length > MAX_JOURNAL_ENTRIES\r\n ? journal.slice(journal.length - MAX_JOURNAL_ENTRIES)\r\n : journal;\r\n return {\r\n ...goal,\r\n iterations: iteration,\r\n lastActivityAt: at,\r\n journal: trimmed,\r\n };\r\n}\r\n\r\n/**\r\n * Aggregate cumulative cost + tokens across all journal entries. Entries\r\n * without telemetry are skipped (legacy entries from before the field\r\n * was added still load cleanly).\r\n */\r\nexport function summarizeUsage(goal: GoalFile): {\r\n totalCostUsd: number;\r\n totalInputTokens: number;\r\n totalOutputTokens: number;\r\n iterationsWithUsage: number;\r\n} {\r\n let totalCostUsd = 0;\r\n let totalInputTokens = 0;\r\n let totalOutputTokens = 0;\r\n let iterationsWithUsage = 0;\r\n for (const e of goal.journal) {\r\n if (typeof e.costUsd === 'number') totalCostUsd += e.costUsd;\r\n if (e.tokens) {\r\n totalInputTokens += e.tokens.input;\r\n totalOutputTokens += e.tokens.output;\r\n }\r\n if (typeof e.costUsd === 'number' || e.tokens) iterationsWithUsage++;\r\n }\r\n return { totalCostUsd, totalInputTokens, totalOutputTokens, iterationsWithUsage };\r\n}\r\n\r\n/** Format the goal + recent journal as a human-readable status block. */\r\nexport function formatGoal(goal: GoalFile, journalLimit = 10): string {\r\n const lines: string[] = [];\r\n lines.push(`Goal: ${goal.goal}`);\r\n lines.push(`Set: ${goal.setAt}`);\r\n lines.push(`Last activity: ${goal.lastActivityAt}`);\r\n lines.push(`Iterations: ${goal.iterations}`);\r\n const stateLabel = goal.goalState ?? 'active';\r\n lines.push(`State: ${stateLabel}${goal.iterations > 0 ? ` (iteration #${goal.iterations})` : ''}`);\r\n lines.push(`Engine: ${goal.engineState}`);\r\n const usage = summarizeUsage(goal);\r\n if (usage.iterationsWithUsage > 0) {\r\n lines.push(\r\n `Spent: $${usage.totalCostUsd.toFixed(4)} (in ${usage.totalInputTokens} / out ${usage.totalOutputTokens} tokens across ${usage.iterationsWithUsage} iterations)`,\r\n );\r\n }\r\n if (goal.journal.length > 0) {\r\n lines.push('');\r\n lines.push(`Recent journal (last ${Math.min(journalLimit, goal.journal.length)}):`);\r\n const tail = goal.journal.slice(-journalLimit);\r\n for (const e of tail) {\r\n const mark = e.status === 'success' ? '✓' : e.status === 'failure' ? '✗' : e.status === 'aborted' ? '⊘' : '·';\r\n const note = e.note ? ` — ${e.note}` : '';\r\n const cost = typeof e.costUsd === 'number' ? ` ($${e.costUsd.toFixed(4)})` : '';\r\n lines.push(` #${e.iteration} ${mark} [${e.source}] ${e.task}${cost}${note}`);\r\n }\r\n }\r\n return lines.join('\\n');\r\n}\r\n","import { execFile } from 'node:child_process';\r\nimport { promisify } from 'node:util';\r\nimport type { Agent } from '../core/agent.js';\r\nimport type { TodoItem } from '../core/context.js';\r\nimport type { Compactor } from '../types/compactor.js';\r\nimport {\r\n appendJournal,\r\n loadGoal,\r\n saveGoal,\r\n goalFilePath,\r\n type GoalFile,\r\n type JournalEntry,\r\n} from '../storage/goal-store.js';\r\n\r\nconst execFileP = promisify(execFile);\r\n\r\n/**\r\n * Sense-decide-execute-reflect loop on top of a long-running Goal.\r\n *\r\n * Each iteration:\r\n * 1. Sense — read goal, pending todos, `git status --porcelain`.\r\n * 2. Decide — pick a source (todo / git / brainstorm) and a task.\r\n * 3. Execute — single agent.run with a directive prompt.\r\n * 4. Reflect — append a journal entry, persist state to disk.\r\n *\r\n * The loop runs forever until `stop()` is called externally (REPL SIGINT\r\n * handler, /autonomy stop). No internal time/cost cap by design — the\r\n * user wants \"sittin sene\". Failures are logged and the loop continues\r\n * with a different source on the next tick.\r\n */\r\n\r\nexport interface EternalAutonomyOptions {\r\n agent: Agent;\r\n projectRoot: string;\r\n /**\r\n * Per-iteration agent timeout. Defaults to 5 minutes. A single hung\r\n * provider call should not freeze the whole eternal loop.\r\n */\r\n iterationTimeoutMs?: number;\r\n /**\r\n * Maximum number of internal agent.run iterations the engine grants per\r\n * eternal-loop tick. The engine sets `autonomousContinue: true` so the\r\n * agent can run multi-step tasks end-to-end within one tick instead of\r\n * bouncing back to the engine after every single tool call. Default 500.\r\n * Previous 50 was far too low — agents hit the limit and restart constantly.\r\n */\r\n iterationMaxAgentSteps?: number;\r\n /**\r\n * Minimum sleep between iterations. Defaults to 1 s — enough for\r\n * SIGINT handlers to fire mid-loop without pegging a core when the\r\n * provider is being rate-limited.\r\n */\r\n cycleGapMs?: number;\r\n /**\r\n * Maximum consecutive failures before the source rotation forces a\r\n * brainstorm cycle. Default 3. Acts as a soft-recovery, not a stop.\r\n */\r\n failureBudget?: number;\r\n /**\r\n * Per-todo failed-attempt ceiling. When the engine picks the same todo\r\n * and the iteration fails this many times in total, the todo is taken\r\n * out of rotation (engine prefers other sources) until it changes\r\n * status. Default 3. Prevents the loop from spinning forever on one\r\n * stuck task.\r\n */\r\n todoMaxAttempts?: number;\r\n /**\r\n * Consecutive brainstorm-DONE responses required to consider the goal\r\n * complete and stop the engine. When the LLM's brainstorm step keeps\r\n * answering `DONE`, the engine treats that as \"no more work\" and, after\r\n * this many in a row, marks the goal as completed instead of sleeping\r\n * forever. Default 3.\r\n */\r\n brainstormDoneStopThreshold?: number;\r\n /** Side-channel notifications (logging, UI updates). */\r\n onIteration?: (entry: JournalEntry) => void;\r\n onError?: (err: Error, iteration: number) => void;\r\n /**\r\n * Per-iteration phase notifications for live UI updates (TUI status bar,\r\n * etc.). Fires at each major stage transition: idle → decide → execute →\r\n * reflect → (sleep | paused | stopped). Fire-and-forget — the engine\r\n * does not await the callback.\r\n */\r\n onStage?: (stage: IterationStage) => void;\r\n /**\r\n * Optional injected git status reader — production code uses git, tests\r\n * stub this out so they don't shell out.\r\n */\r\n gitStatusReader?: () => Promise<string>;\r\n /**\r\n * Optional clock — tests stub for deterministic timestamps.\r\n */\r\n now?: () => Date;\r\n /**\r\n * Optional compactor. When provided, the engine runs compaction every\r\n * `compactEveryNIterations` iterations to keep the agent's message\r\n * history under control during multi-day eternal loops. Without\r\n * compaction, an infinite loop will eventually overflow the provider's\r\n * context window and start failing.\r\n */\r\n compactor?: Compactor;\r\n /** How many iterations between compaction calls. Default 25. */\r\n compactEveryNIterations?: number;\r\n /**\r\n * Aggressive compaction threshold. When ctx token usage exceeds this\r\n * fraction of `maxContextTokens`, compaction runs in aggressive mode\r\n * regardless of the iteration cadence. 0.85 by default.\r\n */\r\n aggressiveCompactRatio?: number;\r\n /**\r\n * Model's max context window in tokens. When set, the engine watches\r\n * `currentRequestTokens()` against this and triggers aggressive compact\r\n * before the next iteration would overflow. Omit to disable threshold\r\n * checks (iteration cadence still applies).\r\n */\r\n maxContextTokens?: number;\r\n /**\r\n * Base delay (ms) for the first transient-error backoff. Subsequent\r\n * transient failures double this, capped at `transientBackoffMaxMs`.\r\n * Default 2_000.\r\n *\r\n * \"Transient\" means the underlying error is recoverable per\r\n * `WrongStackError.recoverable` (ProviderError sets this for 429/529/5xx\r\n * /network errors). Permanent errors (auth/invalid request) skip the\r\n * backoff and count toward `failureBudget` like before — backing off\r\n * on a permanent failure is wasted time.\r\n */\r\n transientBackoffBaseMs?: number;\r\n /** Ceiling for the exponential backoff. Default 60_000 (60 s). */\r\n transientBackoffMaxMs?: number;\r\n /** Called when the eternal loop stops for any reason (manual stop, goal complete, etc.). */\r\n onEternalStop?: () => void;\r\n}\r\n\r\nexport type EternalEngineState = 'idle' | 'running' | 'stopped';\r\n\r\n/**\r\n * Per-iteration phase emitted via `onStage` so UIs can render the\r\n * engine's live location in the sense-decide-execute-reflect loop.\r\n */\r\nexport type IterationStage =\r\n | { phase: 'idle' }\r\n | { phase: 'decide'; reason: string }\r\n | { phase: 'execute'; task: string }\r\n | { phase: 'reflect'; status: 'success' | 'failure' | 'aborted' | 'skipped'; note?: string }\r\n | { phase: 'sleep'; ms: number }\r\n | { phase: 'paused' }\r\n | { phase: 'stopped' }\r\n | { phase: 'error'; message: string };\r\n\r\ninterface DecidedAction {\r\n source: JournalEntry['source'];\r\n task: string;\r\n directive: string;\r\n /** Set when source === 'todo' so the engine can attribute failures. */\r\n todoId?: string;\r\n}\r\n\r\n/**\r\n * Sentinel returned by `brainstormTask` when the LLM declares the goal\r\n * fully accomplished. Distinct from `null` (which means \"brainstorm\r\n * failed / no actionable task right now\") so the engine can count\r\n * consecutive DONE answers toward a real stop.\r\n */\r\nconst BRAINSTORM_DONE = Symbol('brainstorm-done');\r\n\r\n/**\r\n * Free-text marker the model can emit (on its own line) to declare the\r\n * overall mission accomplished. Detected in the successful iteration's\r\n * `finalText`. When present, the engine flips `goalState='completed'`\r\n * and stops — the model has explicitly claimed completion AND the\r\n * iteration succeeded, which together is the most reliable stop signal\r\n * we can get without a separate verifier round-trip.\r\n */\r\nconst GOAL_COMPLETE_MARKER = /^\\s*\\[goal[_\\s-]*complete\\]\\s*$/im;\r\n\r\n/**\r\n * Free-text marker for the `/goal clear` command equivalent — when the\r\n * model emits this, the engine treats it as a manual goal clear (not just\r\n * completion) so the goal file is removed and onEternalStop fires.\r\n */\r\nconst GOAL_CLEAR_MARKER = /^\\s*\\[\\/?goal\\s*clear\\]\\s*$/im;\r\n\r\nexport class EternalAutonomyEngine {\r\n private state: EternalEngineState = 'idle';\r\n private stopRequested = false;\r\n private consecutiveFailures = 0;\r\n private consecutiveBrainstormDone = 0;\r\n /**\r\n * Count of consecutive transient (recoverable) provider failures. Drives\r\n * the exponential backoff between iterations. Reset on the first\r\n * successful iteration so a single bad afternoon doesn't permanently\r\n * slow the loop down.\r\n */\r\n private consecutiveTransientRetries = 0;\r\n private currentCtrl: AbortController | null = null;\r\n private iterationsSinceCompact = 0;\r\n private readonly goalPath: string;\r\n\r\n constructor(private readonly opts: EternalAutonomyOptions) {\r\n this.goalPath = goalFilePath(opts.projectRoot);\r\n }\r\n\r\n /** Current engine state — readable for UIs. */\r\n get currentState(): EternalEngineState {\r\n return this.state;\r\n }\r\n\r\n /** Synchronously request stop. Resolves once the running iteration aborts. */\r\n stop(): void {\r\n this.stopRequested = true;\r\n this.currentCtrl?.abort();\r\n // Best-effort: flip the persisted state so the next startup banner\r\n // doesn't report a phantom \"running\" engine. Fire-and-forget — if it\r\n // races with an in-flight iteration's write, the journal write wins\r\n // (engineState is metadata, not durable correctness).\r\n void this.persistEngineState('stopped').catch(() => {});\r\n this.state = 'stopped';\r\n }\r\n\r\n /**\r\n * Mark the engine as 'running' on disk + reset stop state so a new\r\n * batch of `runOneIteration()` calls can proceed. Called by the REPL\r\n * when the user invokes `/autonomy eternal`. Idempotent.\r\n */\r\n async prime(): Promise<void> {\r\n this.stopRequested = false;\r\n this.state = 'running';\r\n await this.persistEngineState('running').catch(() => {});\r\n }\r\n\r\n /**\r\n * Main loop. Returns when stop() is called or the goal file is removed.\r\n * Does NOT throw — every iteration is wrapped to keep the loop alive.\r\n */\r\n async run(): Promise<void> {\r\n this.state = 'running';\r\n await this.persistEngineState('running');\r\n\r\n try {\r\n while (!this.stopRequested) {\r\n let iterationOk = false;\r\n try {\r\n iterationOk = await this.runOneIteration();\r\n } catch (err) {\r\n this.consecutiveFailures++;\r\n this.opts.onError?.(err instanceof Error ? err : new Error(String(err)), this.consecutiveFailures);\r\n await this.appendFailure('engine error', err instanceof Error ? err.message : String(err));\r\n }\r\n\r\n if (iterationOk) {\r\n this.consecutiveFailures = 0;\r\n }\r\n\r\n if (this.stopRequested) break;\r\n\r\n // Brief gap so SIGINT can land between iterations even if the\r\n // agent is bouncing back results fast.\r\n await sleep(this.opts.cycleGapMs ?? 1000);\r\n }\r\n } finally {\r\n this.state = 'stopped';\r\n await this.persistEngineState('stopped').catch(() => {});\r\n }\r\n }\r\n\r\n /**\r\n * Execute a single sense-decide-execute-reflect cycle.\r\n * Returns true on success, false on handled failure / no-op.\r\n *\r\n * Exposed publicly so the REPL can pace iterations from its main loop\r\n * — running the engine and the REPL as a single sequential consumer of\r\n * `agent.run()` avoids race conditions on the shared Context.\r\n */\r\n async runOneIteration(): Promise<boolean> {\r\n // Emit stage transitions so UIs can render the engine's live location.\r\n const emit = (stage: IterationStage) => {\r\n this.opts.onStage?.(stage);\r\n };\r\n\r\n const goal = await loadGoal(this.goalPath);\r\n if (!goal) {\r\n // Goal file disappeared — treat as a graceful stop.\r\n emit({ phase: 'stopped' });\r\n this.stopRequested = true;\r\n return false;\r\n }\r\n\r\n // Mission-level lifecycle gate.\r\n const missionState = goal.goalState ?? 'active';\r\n if (missionState !== 'active') {\r\n emit({ phase: missionState === 'paused' ? 'paused' : 'stopped' });\r\n this.stopRequested = true;\r\n return false;\r\n }\r\n\r\n emit({ phase: 'decide', reason: 'picking next task' });\r\n const action = await this.decide(goal);\r\n if (!action) {\r\n if (!this.stopRequested) {\r\n emit({ phase: 'sleep', ms: 5_000 });\r\n await sleep(5_000);\r\n } else {\r\n emit({ phase: 'stopped' });\r\n }\r\n return false;\r\n }\r\n\r\n emit({ phase: 'execute', task: action.task });\r\n\r\n const ctrl = new AbortController();\r\n this.currentCtrl = ctrl;\r\n const timer = setTimeout(\r\n () => ctrl.abort(),\r\n this.opts.iterationTimeoutMs ?? 5 * 60_000,\r\n );\r\n let status: JournalEntry['status'] = 'success';\r\n let note: string | undefined;\r\n let finalText = '';\r\n // Captured from `result.error?.recoverable` when the agent.run returns\r\n // a recoverable WrongStackError (ProviderError sets this for 429/529\r\n // /5xx/network). Drives the engine's exponential backoff so a\r\n // transient rate-limit storm doesn't burn the failure budget in\r\n // seconds. Permanent errors leave this false and trip the normal\r\n // consecutiveFailures path.\r\n let isTransientFailure = false;\r\n\r\n // Snapshot usage before so the iteration delta can be journaled.\r\n // Token counter is optional in mock/test contexts — guard accordingly.\r\n const tc = this.opts.agent.ctx?.tokenCounter;\r\n const beforeUsage = tc?.total?.();\r\n const beforeCost = tc?.estimateCost?.().total;\r\n\r\n try {\r\n const result = await this.opts.agent.run(\r\n [{ type: 'text' as const, text: action.directive }],\r\n {\r\n signal: ctrl.signal,\r\n // Enable per-call autonomous continuation so the agent can chain\r\n // multiple internal tool/response cycles end-to-end on one\r\n // directive instead of returning to the engine after a single\r\n // round-trip. The model uses `[continue]` / `[done]` markers\r\n // (or the `continue_to_next_iteration` tool) to control the\r\n // inner loop. Without this flag the engine produced shallow\r\n // iterations and almost never let a real task finish.\r\n autonomousContinue: true,\r\n // Cap the inner loop so a runaway agent.run can't burn through\r\n // the iteration timeout — the engine's own outer loop is the\r\n // long-running thing, each tick should be bounded.\r\n maxIterations: this.opts.iterationMaxAgentSteps ?? 500,\r\n },\r\n );\r\n\r\n if (result.status === 'aborted') {\r\n status = 'aborted';\r\n note = 'stopped by user';\r\n } else if (result.status === 'failed') {\r\n status = 'failure';\r\n note = result.error?.describe?.() ?? 'agent run failed';\r\n isTransientFailure = result.error?.recoverable === true;\r\n } else if (result.status === 'max_iterations') {\r\n status = 'failure';\r\n note = `max iterations (${result.iterations})`;\r\n } else {\r\n status = 'success';\r\n finalText = result.finalText ?? '';\r\n const tail = finalText.slice(0, 240).replace(/\\s+/g, ' ').trim();\r\n if (tail) note = tail;\r\n }\r\n } catch (err) {\r\n const isAbort = err instanceof Error && (err.name === 'AbortError' || err.message.includes('abort'));\r\n status = isAbort ? 'aborted' : 'failure';\r\n note = err instanceof Error ? err.message : String(err);\r\n // Surface .recoverable on the thrown WrongStackError too — provider\r\n // errors that escape the agent's catch (rare; usually wrapped into\r\n // result.error) still classify correctly.\r\n if (\r\n !isAbort &&\r\n typeof (err as { recoverable?: unknown })?.recoverable === 'boolean'\r\n ) {\r\n isTransientFailure = (err as { recoverable: boolean }).recoverable;\r\n }\r\n } finally {\r\n clearTimeout(timer);\r\n this.currentCtrl = null;\r\n }\r\n\r\n // Per-todo attempt accounting. On failure of a todo-sourced action,\r\n // bump the persistent counter so `decide()` can rotate past it once\r\n // it crosses the configured ceiling. Successful runs leave the\r\n // counter untouched — the LLM is responsible for flipping the todo\r\n // status to `completed` via the todos tool (directive teaches this).\r\n if (action.source === 'todo' && action.todoId && status !== 'success') {\r\n await this.bumpTodoAttempt(action.todoId);\r\n }\r\n\r\n // Capture per-iteration usage delta. Cost is always non-negative;\r\n // if the counter wraps or resets mid-iteration we clamp to 0 so the\r\n // journal never shows negative spend.\r\n const afterUsage = tc?.total?.();\r\n const afterCost = tc?.estimateCost?.().total;\r\n const tokens =\r\n beforeUsage && afterUsage\r\n ? {\r\n input: Math.max(0, afterUsage.input - beforeUsage.input),\r\n output: Math.max(0, afterUsage.output - beforeUsage.output),\r\n }\r\n : undefined;\r\n const costUsd =\r\n typeof beforeCost === 'number' && typeof afterCost === 'number'\r\n ? Math.max(0, afterCost - beforeCost)\r\n : undefined;\r\n\r\n await this.appendIterationEntry({\r\n source: action.source,\r\n task: action.task,\r\n status,\r\n note,\r\n tokens,\r\n costUsd,\r\n });\r\n\r\n emit({ phase: 'reflect', status, note });\r\n\r\n // Re-read the goal so we can emit the real iteration counter rather\r\n // than the previous placeholder. If the goal was unlinked mid-flight\r\n // (graceful stop via /goal clear) the iteration index is still\r\n // useful — fall back to the in-memory consecutiveFailures-derived\r\n // approximation only as a last resort.\r\n let iterationIndex = 0;\r\n try {\r\n const reloaded = await loadGoal(this.goalPath);\r\n iterationIndex = reloaded?.iterations ?? 0;\r\n } catch {\r\n // best-effort\r\n }\r\n this.opts.onIteration?.({\r\n at: (this.opts.now?.() ?? new Date()).toISOString(),\r\n iteration: iterationIndex,\r\n source: action.source,\r\n task: action.task,\r\n status,\r\n note,\r\n tokens,\r\n costUsd,\r\n });\r\n\r\n // Transient failure — sleep with interruptible backoff before retry.\r\n if (status === 'failure') {\r\n if (isTransientFailure) {\r\n this.consecutiveTransientRetries++;\r\n const delay = this.computeTransientBackoffMs();\r\n if (delay > 0) {\r\n emit({ phase: 'sleep', ms: delay });\r\n await this.sleepInterruptible(delay);\r\n }\r\n return false;\r\n }\r\n this.consecutiveFailures++;\r\n return false;\r\n }\r\n\r\n if (status === 'aborted') {\r\n if (this.stopRequested) return false;\r\n this.consecutiveFailures++;\r\n return false;\r\n }\r\n\r\n // Successful iteration\r\n this.consecutiveTransientRetries = 0;\r\n const cycleGapMs = this.opts.cycleGapMs ?? 1000;\r\n emit({ phase: 'sleep', ms: cycleGapMs });\r\n await sleep(cycleGapMs);\r\n\r\n // Goal-complete detection. The model emits `[GOAL_COMPLETE]` on its\r\n // own line in `finalText` when the overall mission is verifiably done.\r\n // Combined with a successful iteration this is a strong stop signal:\r\n // the LLM explicitly claimed completion AND the run did not fail. We\r\n // mark the goal `completed`, journal it, and stop. No separate\r\n // verifier round-trip — keeps cost down; if the model lies, the user\r\n // notices and can re-arm with `/goal set`.\r\n if (GOAL_COMPLETE_MARKER.test(finalText)) {\r\n // Treat GOAL_COMPLETE as a full goal clear: remove the goal file and\r\n // fire onEternalStop so the REPL exits eternal mode. Stronger than\r\n // just marking completed — the REPL needs both to happen.\r\n await this.clearGoalManually(finalText);\r\n this.stopRequested = true;\r\n return true;\r\n }\r\n // Goal-clear detection — model emits `[goal clear]` equivalent to\r\n // `/goal clear`. Treat as a manual stop: remove the goal file and fire\r\n // onEternalStop so the REPL knows to return to normal mode.\r\n if (GOAL_CLEAR_MARKER.test(finalText)) {\r\n await this.clearGoalManually(finalText);\r\n this.stopRequested = true;\r\n return true;\r\n }\r\n // Compaction runs only on successful iterations — there's no point\r\n // compacting after a failed/aborted iteration that didn't add much to\r\n // the message history.\r\n this.iterationsSinceCompact++;\r\n await this.maybeCompact().catch((err) => {\r\n // Don't let compaction failure kill the loop; surface via onError.\r\n this.opts.onError?.(\r\n err instanceof Error ? err : new Error(String(err)),\r\n this.consecutiveFailures,\r\n );\r\n });\r\n return true;\r\n }\r\n\r\n /**\r\n * Run compaction when either trigger fires:\r\n * - We've done >= compactEveryNIterations since the last compact.\r\n * - Current request tokens exceed aggressiveCompactRatio * maxContext.\r\n *\r\n * The second check uses *aggressive* mode to free more headroom; the\r\n * cadence check uses non-aggressive (cheaper).\r\n */\r\n private async maybeCompact(): Promise<void> {\r\n const compactor = this.opts.compactor;\r\n if (!compactor) return;\r\n const ctx = this.opts.agent.ctx;\r\n if (!ctx) return;\r\n\r\n const cadence = this.opts.compactEveryNIterations ?? 25;\r\n const threshold = this.opts.aggressiveCompactRatio ?? 0.85;\r\n const maxCtx = this.opts.maxContextTokens;\r\n\r\n let aggressive = false;\r\n let shouldRun = false;\r\n\r\n if (this.iterationsSinceCompact >= cadence) {\r\n shouldRun = true;\r\n }\r\n\r\n if (maxCtx && maxCtx > 0) {\r\n const used = ctx.tokenCounter?.currentRequestTokens?.();\r\n if (used) {\r\n const total = used.input + used.cacheRead;\r\n if (total / maxCtx >= threshold) {\r\n shouldRun = true;\r\n aggressive = true;\r\n }\r\n }\r\n }\r\n\r\n if (!shouldRun) return;\r\n\r\n const report = await compactor.compact(ctx, { aggressive });\r\n this.iterationsSinceCompact = 0;\r\n // Journal the compaction event so users see it in /goal journal.\r\n const saved = report.before - report.after;\r\n await this.appendIterationEntry({\r\n source: 'manual',\r\n task: `compaction (${aggressive ? 'aggressive' : 'cadence'})`,\r\n status: 'success',\r\n note: `saved ~${saved} tokens (${report.before}→${report.after})`,\r\n });\r\n }\r\n\r\n /**\r\n * Hybrid idea source.\r\n * 1. Pending todos on the agent's context.\r\n * 2. Dirty git working tree → propose a \"review and finish this\" task.\r\n * 3. Otherwise: brainstorm via the LLM against the goal.\r\n *\r\n * After failureBudget consecutive failures, force brainstorm so the\r\n * engine doesn't loop on the same broken todo or stuck git state.\r\n */\r\n private async decide(goal: GoalFile): Promise<DecidedAction | null> {\r\n const forceBrainstorm = this.consecutiveFailures >= (this.opts.failureBudget ?? 3);\r\n\r\n if (!forceBrainstorm) {\r\n const todo = this.pickPendingTodo(goal);\r\n if (todo) {\r\n return {\r\n source: 'todo',\r\n task: todo.content,\r\n todoId: todo.id,\r\n directive: this.buildDirective(goal, 'todo', todo.content),\r\n };\r\n }\r\n\r\n const gitTask = await this.pickGitTask();\r\n if (gitTask) {\r\n return {\r\n source: 'git',\r\n task: gitTask,\r\n directive: this.buildDirective(goal, 'git', gitTask),\r\n };\r\n }\r\n }\r\n\r\n const brainstormed = await this.brainstormTask(goal);\r\n if (brainstormed === BRAINSTORM_DONE) {\r\n // Model says there's nothing to do. Count consecutive DONEs — if\r\n // we hit the threshold, treat the mission as finished and stop\r\n // instead of sleeping forever on null actions.\r\n this.consecutiveBrainstormDone++;\r\n const threshold = this.opts.brainstormDoneStopThreshold ?? 3;\r\n if (this.consecutiveBrainstormDone >= threshold) {\r\n await this.markGoalCompleted(\r\n { source: 'brainstorm', task: 'no further work', directive: '' },\r\n `brainstorm returned DONE ${this.consecutiveBrainstormDone}x in a row`,\r\n );\r\n this.stopRequested = true;\r\n }\r\n return null;\r\n }\r\n if (!brainstormed) return null;\r\n // Got a real task — reset the DONE streak.\r\n this.consecutiveBrainstormDone = 0;\r\n return {\r\n source: 'brainstorm',\r\n task: brainstormed,\r\n directive: this.buildDirective(goal, 'brainstorm', brainstormed),\r\n };\r\n }\r\n\r\n private pickPendingTodo(goal: GoalFile): TodoItem | null {\r\n const todos = this.opts.agent.ctx.todos;\r\n if (!Array.isArray(todos)) return null;\r\n const attempts = goal.todoAttempts ?? {};\r\n const ceiling = this.opts.todoMaxAttempts ?? 3;\r\n // First-pending strategy with a stuck-task escape hatch: if the\r\n // first pending todo has already failed `ceiling` times, fall\r\n // through to later pending todos. Returns null when every pending\r\n // todo is stuck — the caller will fall through to git/brainstorm.\r\n for (const t of todos) {\r\n if (t.status !== 'pending') continue;\r\n const used = attempts[t.id] ?? 0;\r\n if (used >= ceiling) continue;\r\n return t;\r\n }\r\n return null;\r\n }\r\n\r\n private async pickGitTask(): Promise<string | null> {\r\n let out: string;\r\n try {\r\n out = await (this.opts.gitStatusReader?.() ?? this.readGitStatus());\r\n } catch {\r\n return null;\r\n }\r\n const dirty = out.trim();\r\n if (!dirty) return null;\r\n // Surface a concise prompt — the agent will look at the diff itself.\r\n const lines = dirty.split('\\n').slice(0, 8);\r\n const preview = lines.join(', ');\r\n return `Inspect the dirty working tree and either finish the in-progress work or revert it. Files: ${preview}`;\r\n }\r\n\r\n private async readGitStatus(): Promise<string> {\r\n const { stdout } = await execFileP('git', ['status', '--porcelain'], {\r\n cwd: this.opts.projectRoot,\r\n timeout: 5_000,\r\n });\r\n return stdout;\r\n }\r\n\r\n private async brainstormTask(goal: GoalFile): Promise<string | null | typeof BRAINSTORM_DONE> {\r\n const lastFew = goal.journal\r\n .slice(-5)\r\n .map((e) => ` - [${e.status}] ${e.task}`)\r\n .join('\\n');\r\n const directive = [\r\n 'You are deciding the next action in an autonomous loop pursuing a long-running goal.',\r\n '',\r\n `Goal: ${goal.goal}`,\r\n '',\r\n lastFew ? `Recent iterations:\\n${lastFew}` : 'No prior iterations yet.',\r\n '',\r\n 'Output ONE concrete, immediately-actionable task that advances the goal.',\r\n 'Constraints:',\r\n '- One sentence, imperative form, under 200 chars.',\r\n '- No preamble, no explanation, no markdown — just the task line.',\r\n '- If recent iterations show repeated failures on the same target, pivot.',\r\n '- If the goal appears fully accomplished AND you can name a concrete',\r\n ' artifact / test / output that proves it, output exactly: DONE',\r\n '- Be conservative with DONE: if the recent journal contains failures',\r\n ' or aborted entries, the goal is almost certainly NOT done.',\r\n ].join('\\n');\r\n\r\n try {\r\n const ctrl = new AbortController();\r\n const timer = setTimeout(() => ctrl.abort(), 60_000);\r\n try {\r\n const result = await this.opts.agent.run(\r\n [{ type: 'text' as const, text: directive }],\r\n { signal: ctrl.signal, maxIterations: 1 },\r\n );\r\n if (result.status !== 'done') return null;\r\n const text = (result.finalText ?? '').trim();\r\n if (!text) return null;\r\n // Distinct sentinel for DONE so the caller can count consecutive\r\n // DONE answers toward a real stop. The old `return null` path\r\n // conflated \"no work\" with \"engine failure\" and looped forever.\r\n if (/^DONE\\.?$/i.test(text)) return BRAINSTORM_DONE;\r\n // Take the first non-empty line and clip to 240 chars.\r\n const firstLine = text.split('\\n').find((l) => l.trim().length > 0)?.trim();\r\n if (!firstLine) return null;\r\n if (/^DONE\\.?$/i.test(firstLine)) return BRAINSTORM_DONE;\r\n return firstLine.slice(0, 240);\r\n } finally {\r\n clearTimeout(timer);\r\n }\r\n } catch {\r\n return null;\r\n }\r\n }\r\n\r\n private buildDirective(goal: GoalFile, source: JournalEntry['source'], task: string): string {\r\n const recentJournal = goal.journal\r\n .slice(-5)\r\n .map((e) => ` #${e.iteration} [${e.status}] ${e.task}${e.note ? ` — ${e.note.slice(0, 80)}` : ''}`)\r\n .join('\\n');\r\n return [\r\n '═══ ETERNAL AUTONOMY — iteration directive ═══',\r\n '',\r\n `Mission: ${goal.goal}`,\r\n `Iteration: #${goal.iterations + 1}`,\r\n `Source: ${source}`,\r\n `Task: ${task}`,\r\n '',\r\n recentJournal ? `Recent journal (last 5):\\n${recentJournal}` : 'No prior iterations.',\r\n '',\r\n '── EXECUTION PROTOCOL ──',\r\n 'You are inside a long-running autonomous loop. Each iteration you',\r\n 'execute ONE concrete task that advances the Mission. No user is',\r\n 'available to clarify — make defensible decisions and move forward.',\r\n '',\r\n '1. EXECUTE END-TO-END',\r\n ' • Use multiple tool calls freely. Emit `[continue]` on its own line',\r\n ' to chain to the next internal step without returning.',\r\n ' • When this iteration\\'s Task is finished (real artifact / passing',\r\n ' test / applied diff / clean output), emit `[done]` on its own line.',\r\n ' • Do not stop on the first obstacle — try at least 3 distinct',\r\n ' approaches before giving up. YOLO is active for normal project work;',\r\n ' destructive-gated confirmations still belong to the permission flow.',\r\n '',\r\n '2. UPDATE TODO STATE (when Source is `todo`)',\r\n ' • Mark this todo `in_progress` via the todos tool before tool work.',\r\n ' • Mark it `completed` on success, with a one-line outcome note.',\r\n ' • If you cannot make progress after 2 distinct attempts, mark it',\r\n ' `cancelled` with the obstacle. The loop will skip it next time.',\r\n '',\r\n '3. MISSION-COMPLETE PROTOCOL',\r\n ' • If — and ONLY if — the OVERALL Mission (not just this Task) is',\r\n ' verifiably accomplished, emit on its own line:',\r\n ' [GOAL_COMPLETE]',\r\n ' followed by a one-paragraph verification recipe (artifact path,',\r\n ' test command, or 10-second reproduction). This halts the loop.',\r\n ' • NEVER emit [GOAL_COMPLETE] on optimism, partial progress, or',\r\n ' \"looks fine\". Required: a concrete artifact that proves it AND',\r\n ' no recent journal failures contradicting completion.',\r\n ' • If unsure, emit `[done]` instead and let the next iteration',\r\n ' decide. The loop is patient; false completion is not.',\r\n '',\r\n '4. NO INTERACTIVITY',\r\n ' • Do not ask questions, do not request confirmation, do not propose',\r\n ' options. Pick the best path and execute. The user is asleep.',\r\n ].join('\\n');\r\n }\r\n\r\n /**\r\n * Exponential backoff for transient provider errors. `2^N * base`\r\n * capped at `transientBackoffMaxMs`. Zero base disables backoff.\r\n * Public-private to keep `runOneIteration` readable; the value is\r\n * recomputed each call from the current retry count, so callers\r\n * don't have to track state.\r\n */\r\n private computeTransientBackoffMs(): number {\r\n const base = this.opts.transientBackoffBaseMs ?? 2_000;\r\n const cap = this.opts.transientBackoffMaxMs ?? 60_000;\r\n if (base <= 0) return 0;\r\n const exponent = Math.max(0, this.consecutiveTransientRetries - 1);\r\n return Math.min(cap, base * 2 ** exponent);\r\n }\r\n\r\n /**\r\n * Sleep that wakes early if `stopRequested` flips. Polls every 250 ms\r\n * so SIGINT / `/autonomy stop` can land in the middle of a long\r\n * backoff instead of waiting up to a minute for the timer.\r\n */\r\n private async sleepInterruptible(totalMs: number): Promise<void> {\r\n const step = 250;\r\n let remaining = totalMs;\r\n while (remaining > 0 && !this.stopRequested) {\r\n const chunk = Math.min(step, remaining);\r\n await sleep(chunk);\r\n remaining -= chunk;\r\n }\r\n }\r\n\r\n private async appendIterationEntry(entry: Omit<JournalEntry, 'iteration' | 'at'>): Promise<void> {\r\n const current = await loadGoal(this.goalPath);\r\n if (!current) {\r\n // Goal was cleared mid-iteration; nothing to write to.\r\n return;\r\n }\r\n const updated = appendJournal(current, entry);\r\n await saveGoal(this.goalPath, updated);\r\n }\r\n\r\n /**\r\n * Persistent per-todo failure counter. Skipped silently when the goal\r\n * file has been removed (graceful clear). Each non-success iteration\r\n * against a todo source bumps the counter by 1; `pickPendingTodo` reads\r\n * the counter to rotate past stuck todos once they cross `todoMaxAttempts`.\r\n */\r\n private async bumpTodoAttempt(todoId: string): Promise<void> {\r\n const current = await loadGoal(this.goalPath);\r\n if (!current) return;\r\n const attempts = { ...(current.todoAttempts ?? {}) };\r\n attempts[todoId] = (attempts[todoId] ?? 0) + 1;\r\n await saveGoal(this.goalPath, { ...current, todoAttempts: attempts });\r\n }\r\n\r\n /**\r\n * Flip the mission to `completed` and journal it. Called from two\r\n * paths: (a) `[GOAL_COMPLETE]` marker in a successful iteration's\r\n * finalText, (b) `brainstorm` returning DONE consecutively past the\r\n * configured threshold. Idempotent — re-entry is a no-op once the\r\n * goal is already `completed`.\r\n */\r\n private async markGoalCompleted(\r\n action: { source: JournalEntry['source']; task: string; directive: string },\r\n note: string,\r\n ): Promise<void> {\r\n const current = await loadGoal(this.goalPath);\r\n if (!current) return;\r\n if (current.goalState === 'completed') return;\r\n const withFlag: GoalFile = { ...current, goalState: 'completed' };\r\n const withEntry = appendJournal(withFlag, {\r\n source: action.source,\r\n task: `MISSION COMPLETE — ${action.task}`.slice(0, 240),\r\n status: 'success',\r\n note: note.slice(0, 240),\r\n });\r\n await saveGoal(this.goalPath, withEntry);\r\n }\r\n\r\n /**\r\n * Manually clear the goal — equivalent to `/goal clear` typed by the user.\r\n * Sets goalState to `abandoned`, removes the goal file, and fires\r\n * `onEternalStop` so the REPL returns to normal mode.\r\n */\r\n private async clearGoalManually(note: string): Promise<void> {\r\n const current = await loadGoal(this.goalPath);\r\n if (current) {\r\n const abandoned: GoalFile = { ...current, goalState: 'abandoned' };\r\n await saveGoal(this.goalPath, abandoned);\r\n }\r\n try {\r\n const { unlink } = await import('node:fs/promises');\r\n await unlink(this.goalPath);\r\n } catch {\r\n // best-effort — file may already be gone\r\n }\r\n this.opts.onEternalStop?.();\r\n void this.appendIterationEntry({\r\n source: 'manual',\r\n task: 'goal cleared',\r\n status: 'success',\r\n note: note.slice(0, 240),\r\n });\r\n }\r\n\r\n private async appendFailure(task: string, note: string): Promise<void> {\r\n await this.appendIterationEntry({ source: 'manual', task, status: 'failure', note });\r\n }\r\n\r\n private async persistEngineState(state: GoalFile['engineState']): Promise<void> {\r\n const current = await loadGoal(this.goalPath);\r\n if (!current) return;\r\n if (current.engineState === state) return;\r\n await saveGoal(this.goalPath, { ...current, engineState: state });\r\n }\r\n}\r\n\r\nfunction sleep(ms: number): Promise<void> {\r\n return new Promise((resolve) => setTimeout(resolve, ms));\r\n}\r\n","import type { Usage } from '../types/provider.js';\nimport type { EventBus } from '../kernel/events.js';\n\nexport type BudgetKind = 'tool_calls' | 'iterations' | 'tokens' | 'timeout' | 'idle_timeout' | 'cost';\n\nexport class BudgetExceededError extends Error {\n readonly kind: BudgetKind;\n readonly limit: number;\n readonly observed: number;\n\n constructor(kind: BudgetKind, limit: number, observed: number) {\n super(`Budget exceeded: ${kind} (limit=${limit}, observed=${observed})`);\n this.name = 'BudgetExceededError';\n this.kind = kind;\n this.limit = limit;\n this.observed = observed;\n }\n}\n\nexport interface BudgetLimits {\n maxIterations?: number;\n maxToolCalls?: number;\n maxTokens?: number;\n /** Estimated USD cost ceiling. */\n maxCostUsd?: number;\n /**\n * Hard wall-clock timeout measured from `start()`. Off by default — set it\n * explicitly only when a task must finish within an absolute window. For\n * the everyday \"don't kill an agent that's still working\" guard, prefer\n * `idleTimeoutMs`, which resets on activity.\n */\n timeoutMs?: number;\n /**\n * Idle timeout: the maximum gap (ms) between activity signals (iterations,\n * tool calls, token usage, streamed progress) before the subagent is\n * considered hung and reaped. Unlike `timeoutMs`, an actively-working\n * agent continuously resets this clock via `markActivity()`, so it never\n * trips on a long-but-productive run — only on a genuine stall.\n */\n idleTimeoutMs?: number;\n}\n\n/**\n * Controls how the budget behaves when `onThreshold` is set and a limit is hit.\n *\n * `'auto'` — emit `budget.threshold_reached` on the EventBus and wait for a\n * coordinator response (extend/stop). If no listener responds within\n * `DECISION_TIMEOUT_MS` the decision defaults to `'stop'`.\n * `'sync'` — do not emit any event; treat the threshold as a hard stop and\n * throw `BudgetExceededError` synchronously. Useful for fire-and-forget\n * subagents that have an `onThreshold` handler for logging/metrics but are\n * not wired into a coordinator.\n *\n * @default 'auto'\n */\nexport type BudgetNegotiationMode = 'auto' | 'sync';\n\nexport interface BudgetUsage {\n iterations: number;\n toolCalls: number;\n tokens: { input: number; output: number; total: number };\n costUsd: number;\n elapsedMs: number;\n}\n\n/**\n * Thrown by `SubagentBudget.record*` when a soft limit is hit and\n * an `onThreshold` handler is configured that wants to ask the\n * coordinator (via `budget.threshold_reached` event). The runner\n * catches this and awaits the embedded `decision` promise to get\n * the coordinator's extend/stop decision.\n *\n * Distinct from `BudgetExceededError` which is a hard stop.\n */\nexport class BudgetThresholdSignal extends Error {\n readonly kind: BudgetKind;\n readonly limit: number;\n readonly used: number;\n /** Resolves to 'extend' (with optional new limits) or 'stop' */\n readonly decision: Promise<BudgetThresholdDecision>;\n\n constructor(\n kind: BudgetKind,\n limit: number,\n used: number,\n decision: Promise<BudgetThresholdDecision>,\n ) {\n super(`Budget soft limit: ${kind} (limit=${limit}, used=${used})`);\n this.name = 'BudgetThresholdSignal';\n this.kind = kind;\n this.limit = limit;\n this.used = used;\n this.decision = decision;\n }\n}\n\nexport type BudgetThresholdDecision =\n | 'stop'\n | { extend: Partial<BudgetLimits> };\n\n/**\n * Callback invoked when a budget limit is about to be exceeded.\n * Return 'throw' for hard stop (default — throws BudgetExceededError).\n * Return 'continue' to allow one more unit and re-check next time.\n * Return a Promise to ask the coordinator via `budget.threshold_reached`\n * event (uses the same grant/deny pattern as `iteration.limit_reached`).\n */\nexport type BudgetThresholdHandler = (info: {\n kind: BudgetKind;\n used: number;\n limit: number;\n requestDecision: () => Promise<BudgetThresholdDecision>;\n}) => 'throw' | 'continue' | Promise<BudgetThresholdDecision>;\n\n/**\n * Per-subagent budget enforcement. Each subagent gets its own instance so a\n * runaway agent can't drain the cost ceiling of its siblings. All record/check\n * methods are O(1) and safe to call from hot paths.\n *\n * Behavior without `onThreshold`: hard stops synchronously on every limit hit.\n *\n * Behavior with `onThreshold` and `_mode === 'auto'`: emits `budget.threshold_reached`\n * on the EventBus and throws `BudgetThresholdSignal`. The coordinator's verdict\n * (extend/stop) resolves the embedded promise. If no listener responds within\n * `DECISION_TIMEOUT_MS` the decision defaults to `'stop'`.\n *\n * Behavior with `onThreshold` and `_mode === 'sync'`: throws `BudgetExceededError`\n * synchronously regardless of EventBus state or listener presence. This is useful\n * for fire-and-forget subagents that have an `onThreshold` handler for logging/metrics\n * but are not wired into a coordinator — the `'sync'` mode makes the hard-stop\n * behavior explicit and means tests can use `expect().toThrow()` even without\n * a fully-wired EventBus.\n */\nexport class SubagentBudget {\n readonly limits: Readonly<BudgetLimits>;\n private iterations = 0;\n private toolCalls = 0;\n private tokenInput = 0;\n private tokenOutput = 0;\n private costUsd = 0;\n private startTime: number | null = null;\n /**\n * Timestamp of the most recent activity (iteration / tool call / token\n * usage / streamed progress). Drives the idle timeout — reset by\n * `markActivity()`. Initialised to `start()` time so a never-active agent\n * still eventually trips its idle window.\n */\n private lastActivityTime: number | null = null;\n private _onThreshold: BudgetThresholdHandler | undefined;\n /**\n * Hard cap on how long `_negotiateExtension` waits for the coordinator to\n * respond before defaulting to 'stop'. Without this fallback an absent\n * or hung listener (Director not built / event filter detached mid-run)\n * leaves the budget over-limit and never enforces anything.\n */\n private static readonly DECISION_TIMEOUT_MS = 60_000;\n /**\n * Injected by the runner when wiring the budget to its EventBus.\n * Used to emit `budget.threshold_reached` events in `'auto'` mode.\n */\n _events?: EventBus;\n\n /**\n * Negotiation mode — controls whether a threshold hit tries to emit\n * `budget.threshold_reached` and wait for a coordinator decision, or\n * falls straight through to a synchronous hard stop.\n *\n * `'auto'` (default) — emit on the EventBus and wait; times out to 'stop'.\n * `'sync'` — throw `BudgetExceededError` immediately regardless of listeners.\n */\n private _mode: BudgetNegotiationMode;\n\n /**\n * Optional callback for soft-limit handling. When set, the budget will\n * invoke it rather than throw immediately. The handler decides whether to\n * throw synchronously, continue, or ask the coordinator for an extension.\n */\n get onThreshold(): BudgetThresholdHandler | undefined {\n return this._onThreshold;\n }\n set onThreshold(fn: BudgetThresholdHandler | undefined) {\n this._onThreshold = fn;\n }\n\n /** Returns the current negotiation mode. */\n get mode(): BudgetNegotiationMode {\n return this._mode;\n }\n\n constructor(limits: BudgetLimits = {}, mode: BudgetNegotiationMode = 'auto') {\n this._mode = mode;\n // NOT frozen: `negotiateExtension` patches these limits in place when the\n // coordinator grants an auto-extension. Freezing made every granted\n // extension throw `TypeError: Cannot assign to read only property` in\n // strict mode, which the runner caught as a hard stop — so extensions\n // silently became kills. The `readonly limits: Readonly<BudgetLimits>`\n // typing still blocks external mutation at compile time.\n this.limits = { ...limits };\n }\n\n start(): void {\n this.startTime = Date.now();\n this.lastActivityTime = this.startTime;\n }\n\n /**\n * Reset the idle clock. Called on any sign of forward progress —\n * iterations, tool calls, token usage, and streamed tool/text progress —\n * so a long-but-productive subagent never trips its `idleTimeoutMs`.\n */\n markActivity(): void {\n this.lastActivityTime = Date.now();\n }\n\n /**\n * Milliseconds since the last activity signal. Returns 0 before `start()`\n * (nothing to measure yet). Used by the coordinator watchdog to decide\n * whether to re-arm (still active) or reap (genuinely idle).\n */\n idleMs(): number {\n const since = this.lastActivityTime ?? this.startTime;\n return since === null ? 0 : Date.now() - since;\n }\n\n /** Returns true if we're within 10% of any limit — useful for pre-flight checks. */\n isNearLimit(): boolean {\n const { maxIterations, maxToolCalls, maxTokens, maxCostUsd } = this.limits;\n if (maxIterations && this.iterations >= maxIterations * 0.9) return true;\n if (maxToolCalls && this.toolCalls >= maxToolCalls * 0.9) return true;\n if (maxTokens && this.tokenInput + this.tokenOutput >= maxTokens * 0.9) return true;\n if (maxCostUsd && this.costUsd >= maxCostUsd * 0.9) return true;\n return false;\n }\n\n /**\n * Synchronous budget check. Always throws synchronously so callers (especially\n * test event handlers using `expect().toThrow()`) get an unhandled rejection\n * when the budget is exceeded without a handler.\n *\n * Decision table:\n * - no `onThreshold` handler → throw `BudgetExceededError` (hard stop, always)\n * - `mode === 'sync'` → throw `BudgetExceededError` (hard stop, always)\n * - `mode === 'auto'` + no listener → throw `BudgetExceededError` (hard stop; no one to ask)\n * - `mode === 'auto'` + listener → throw `BudgetThresholdSignal` with async decision promise\n */\n /**\n * Collects all exceeded budget kinds into a single NOOP-free negotiation.\n * Called by recordIteration / recordToolCall / recordUsage — each may call\n * this for its own kind. The first call starts the negotiation and stores\n * the Promise in _pendingNegotiation. Subsequent calls for DIFFERENT\n * kinds (while a negotiation is in flight) are NOOPs — they don't start\n * new conversations with the coordinator. This prevents an EventBus flood\n * when multiple budget kinds are exceeded simultaneously in one iteration.\n *\n * Returns the kinds that were found to be exceeded (for logging/debugging).\n */\n private checkLimits(elapsedMs?: number): { kind: BudgetKind; used: number; limit: number }[] {\n const exceeded: { kind: BudgetKind; used: number; limit: number }[] = [];\n\n if (this.limits.maxIterations !== undefined && this.iterations > this.limits.maxIterations) {\n exceeded.push({ kind: 'iterations', used: this.iterations, limit: this.limits.maxIterations });\n }\n if (this.limits.maxToolCalls !== undefined && this.toolCalls > this.limits.maxToolCalls) {\n exceeded.push({ kind: 'tool_calls', used: this.toolCalls, limit: this.limits.maxToolCalls });\n }\n const totalTokens = this.tokenInput + this.tokenOutput;\n if (this.limits.maxTokens !== undefined && totalTokens > this.limits.maxTokens) {\n exceeded.push({ kind: 'tokens', used: totalTokens, limit: this.limits.maxTokens });\n }\n if (this.limits.maxCostUsd !== undefined && this.costUsd > this.limits.maxCostUsd) {\n exceeded.push({ kind: 'cost', used: this.costUsd, limit: this.limits.maxCostUsd });\n }\n // Timeout: called from checkTimeout() with elapsedMs (wall-clock) and the\n // current idle gap. Either crossing its limit trips its own kind so the\n // coordinator and auto-extend policy can distinguish them.\n // Wall-clock (`timeoutMs`) is an explicit hard cap; idle (`idleTimeoutMs`)\n // is the default guard that resets on activity. Both can be exceeded in\n // the same call — we push both entries so all violated limits are reported.\n if (elapsedMs !== undefined) {\n const idle = this.idleMs();\n if (this.limits.idleTimeoutMs !== undefined && idle > this.limits.idleTimeoutMs) {\n exceeded.push({ kind: 'idle_timeout', used: idle, limit: this.limits.idleTimeoutMs });\n }\n if (this.limits.timeoutMs !== undefined && elapsedMs > this.limits.timeoutMs) {\n exceeded.push({ kind: 'timeout', used: elapsedMs, limit: this.limits.timeoutMs });\n }\n }\n\n if (exceeded.length === 0) return [];\n\n if (!this._onThreshold) {\n // Hard stop — throw on the first exceeded kind.\n const first = exceeded[0]!;\n throw new BudgetExceededError(first.kind, first.limit, first.used);\n }\n if (this._mode === 'sync') {\n // Hard stop in sync mode.\n const first = exceeded[0]!;\n throw new BudgetExceededError(first.kind, first.limit, first.used);\n }\n const bus = this._events;\n if (!bus || !bus.hasListenerFor('budget.threshold_reached')) {\n const first = exceeded[0]!;\n throw new BudgetExceededError(first.kind, first.limit, first.used);\n }\n\n // Start a negotiation for each exceeded kind that doesn't already have one.\n // The first exceeded kind throws BudgetThresholdSignal so the caller sees\n // the soft-limit event. Subsequent exceeded kinds (in the same call) start\n // their own negotiations silently — they won't throw again.\n for (const entry of exceeded) {\n if (this._pendingNegotiations.has(entry.kind)) continue; // already negotiating this kind\n const decision = this._negotiateExtension(entry.kind, exceeded);\n this._pendingNegotiations.set(entry.kind, decision);\n }\n\n const first = exceeded[0]!;\n const decision = this._pendingNegotiations.get(first.kind)!;\n throw new BudgetThresholdSignal(first.kind, first.limit, first.used, decision);\n }\n\n /**\n * Per-kind in-flight negotiation Promises. Each budget kind can have its\n * own concurrent negotiation — e.g. iterations and timeout can both\n * be exceeded simultaneously without blocking each other. The same kind\n * cannot start two concurrent negotiations (dedup guard).\n * Cleared in `_negotiateExtension`'s `finally` block.\n */\n private _pendingNegotiations = new Map<BudgetKind, Promise<BudgetThresholdDecision>>();\n\n /**\n * Drive the threshold handler to a decision. Resolves with `'stop'`\n * (signal the runner to abort) or `{ extend: ... }` (limits already\n * patched in-place; the runner should not abort). Clears the\n * per-kind slot in `_pendingNegotiations` in `finally`.\n *\n * The 'continue' return from a sync handler is treated as\n * `{ extend: {} }` — keep going without patching; next overrun fires\n * a fresh signal.\n */\n private async _negotiateExtension(\n kind: BudgetKind,\n exceeded: { kind: BudgetKind; used: number; limit: number }[],\n ): Promise<BudgetThresholdDecision> {\n try {\n // Use the first exceeded kind for the handler call.\n const first = exceeded[0]!;\n const result = this._onThreshold!({\n kind: first.kind,\n used: first.used,\n limit: first.limit,\n requestDecision: (): Promise<BudgetThresholdDecision> => {\n const bus = this._events;\n if (!bus || !bus.hasListenerFor('budget.threshold_reached')) {\n return Promise.resolve('stop');\n }\n return new Promise<BudgetThresholdDecision>((resolve) => {\n let resolved = false;\n const respond = (d: BudgetThresholdDecision) => {\n if (resolved) return;\n resolved = true;\n resolve(d);\n };\n const fallback = setTimeout(\n () => respond('stop'),\n SubagentBudget.DECISION_TIMEOUT_MS,\n );\n // Emit one event per exceeded kind so the FleetBus routes them.\n for (const { kind, used, limit } of exceeded) {\n bus.emit('budget.threshold_reached', {\n kind: kind as 'iterations' | 'tool_calls' | 'tokens' | 'cost' | 'timeout' | 'idle_timeout',\n used,\n limit,\n timeoutMs: SubagentBudget.DECISION_TIMEOUT_MS,\n extend: (extra: Partial<BudgetLimits>) => {\n clearTimeout(fallback);\n respond({ extend: extra });\n },\n deny: () => {\n clearTimeout(fallback);\n respond('stop');\n },\n });\n }\n });\n },\n });\n\n if (result === 'throw') return 'stop';\n if (result === 'continue') return { extend: {} };\n\n const decision = await result;\n if (decision === 'stop') return 'stop';\n\n // 'extend' — patch in-place limits BEFORE resolving so the runner's\n // continue path sees the new ceiling.\n const ext = decision.extend;\n if (ext.maxIterations !== undefined) {\n (this.limits as Record<string, unknown>).maxIterations = ext.maxIterations;\n }\n if (ext.maxToolCalls !== undefined) {\n (this.limits as Record<string, unknown>).maxToolCalls = ext.maxToolCalls;\n }\n if (ext.maxTokens !== undefined) {\n (this.limits as Record<string, unknown>).maxTokens = ext.maxTokens;\n }\n if (ext.maxCostUsd !== undefined) {\n (this.limits as Record<string, unknown>).maxCostUsd = ext.maxCostUsd;\n }\n if (ext.timeoutMs !== undefined) {\n (this.limits as Record<string, unknown>).timeoutMs = ext.timeoutMs;\n }\n if (ext.idleTimeoutMs !== undefined) {\n (this.limits as Record<string, unknown>).idleTimeoutMs = ext.idleTimeoutMs;\n }\n return decision;\n } finally {\n this._pendingNegotiations.delete(kind);\n }\n }\n\n recordIteration(): void {\n this.iterations++;\n this.markActivity();\n void this.checkLimits();\n }\n\n recordToolCall(): void {\n this.toolCalls++;\n this.markActivity();\n void this.checkLimits();\n }\n\n recordUsage(usage: Usage, costUsd = 0): void {\n this.tokenInput += usage.input;\n this.tokenOutput += usage.output;\n this.costUsd += costUsd;\n this.markActivity();\n void this.checkLimits();\n }\n\n /**\n * Wall-clock budget check. Unlike other limits, timeout is always a hard stop\n * — wall-clock time cannot be \"extended\" by the coordinator, so it throws\n * synchronously rather than entering the negotiation flow.\n *\n * Decision table:\n * - no `onThreshold` handler → throw `BudgetExceededError`\n * - `mode === 'sync'` → throw `BudgetExceededError`\n * - `mode === 'auto'` + no listener → throw `BudgetExceededError`\n * - `mode === 'auto'` + listener → throw `BudgetExceededError` (timeout is not extendable)\n */\n checkTimeout(): void {\n if (this.startTime === null) return;\n const { timeoutMs, idleTimeoutMs } = this.limits;\n if (timeoutMs === undefined && idleTimeoutMs === undefined) return;\n const elapsed = Date.now() - this.startTime;\n const wallTripped = timeoutMs !== undefined && elapsed > timeoutMs;\n const idleTripped = idleTimeoutMs !== undefined && this.idleMs() > idleTimeoutMs;\n if (!wallTripped && !idleTripped) return;\n void this.checkLimits(elapsed);\n }\n\n /** Returns true if a wall-clock or idle timeout has occurred without throwing. */\n isTimedOut(): boolean {\n if (this.startTime === null) return false;\n const { timeoutMs, idleTimeoutMs } = this.limits;\n if (timeoutMs !== undefined && Date.now() - this.startTime > timeoutMs) return true;\n if (idleTimeoutMs !== undefined && this.idleMs() > idleTimeoutMs) return true;\n return false;\n }\n\n usage(): BudgetUsage {\n return {\n iterations: this.iterations,\n toolCalls: this.toolCalls,\n tokens: {\n input: this.tokenInput,\n output: this.tokenOutput,\n total: this.tokenInput + this.tokenOutput,\n },\n costUsd: this.costUsd,\n elapsedMs: this.startTime === null ? 0 : Date.now() - this.startTime,\n };\n }\n}\n","import type { Agent, AgentInput, RunResult } from '../core/agent.js';\nimport type { EventBus } from '../kernel/events.js';\nimport type {\n SubagentConfig,\n SubagentRunContext,\n SubagentRunOutcome,\n SubagentRunner,\n TaskSpec,\n} from '../types/multi-agent.js';\nimport {\n BudgetExceededError,\n BudgetThresholdSignal,\n} from './subagent-budget.js';\nimport type { FleetBus } from './fleet-bus.js';\n\n/**\n * Caller-supplied factory that builds an isolated `Agent` for a subagent.\n * The factory MUST construct a fresh `Context` per call — sharing context\n * between subagents defeats isolation. Each Agent should also use either\n * its own `EventBus` or a forwarded view, so per-subagent metrics can be\n * attributed correctly.\n */\nexport type AgentFactory = (config: SubagentConfig) => Promise<AgentFactoryResult>;\n\nexport interface AgentFactoryResult {\n agent: Agent;\n /** Event bus the factory wired to this agent — required for budget hookup. */\n events: EventBus;\n /**\n * Optional cleanup hook invoked in the runner's `finally` block once\n * the task ends (success, failure, abort — same exit path). Factories\n * that own resources scoped to a single task (per-subagent JSONL\n * writers, transient providers, throwaway containers) implement this\n * to close them deterministically instead of relying on GC. Errors\n * thrown here are swallowed so a flaky cleanup can't mask the task's\n * real result.\n */\n dispose?: () => Promise<void> | void;\n}\n\nexport interface AgentRunnerOptions {\n factory: AgentFactory;\n /**\n * Format a TaskSpec into the user input the agent will receive. Defaults\n * to `task.description ?? ''`. Override when subagents expect structured\n * input (e.g. JSON contracts, role-prefixed prompts).\n */\n formatTaskInput?: (task: TaskSpec, config: SubagentConfig) => AgentInput;\n /**\n * When set, the runner attaches the subagent's EventBus to this FleetBus\n * on task start and detaches it when the task finishes. This is the\n * injection seam that lets the TUI fleet panel observe subagent activity\n * live — without it, FleetBus stays empty.\n */\n fleetBus?: FleetBus;\n}\n\n/**\n * Builds a `SubagentRunner` that drives a real `Agent` per task while honoring\n * the coordinator's budget and abort signal. This is the production adapter —\n * the coordinator's `runner` option in CLI/TUI assemblies points here.\n *\n * Lifecycle per task:\n * 1. factory(config) → fresh Agent + EventBus.\n * 2. Subscribe to events to feed the budget (tool calls, token usage).\n * 3. Call agent.run(input, { signal }) — the coordinator's signal cancels.\n * 4. Map RunResult.status onto a `SubagentRunOutcome` or throw on failure.\n * 5. Unsubscribe and let the factory's resources be GC'd.\n *\n * The budget is checked synchronously from event handlers — a runaway agent\n * that crosses its tool-call limit triggers `BudgetExceededError`, which the\n * coordinator surfaces as `status: 'failed'` on the task result.\n */\nexport function makeAgentSubagentRunner(opts: AgentRunnerOptions): SubagentRunner {\n const format = opts.formatTaskInput ?? defaultFormatTaskInput;\n\n return async (task: TaskSpec, ctx: SubagentRunContext): Promise<SubagentRunOutcome> => {\n const factoryResult = await opts.factory(ctx.config);\n const { agent, events } = factoryResult;\n\n // Attach subagent EventBus to FleetBus so the TUI fleet panel (and any\n // other FleetBus subscriber) can observe this subagent live. Detach on\n // task finish — each task is a fresh Agent + EventBus, so we never\n // want a stale bus lingering after the run.\n const detachFleet = opts.fleetBus?.attach(ctx.subagentId, events, task.id);\n\n // Hook budget into the agent's event stream. We capture errors thrown by\n // recordToolCall/recordUsage so the budget can short-circuit the run by\n // aborting the controller — the agent then unwinds cooperatively.\n const aborter = new AbortController();\n // Inject the EventBus into the budget so it can emit budget.threshold_reached\n // events when a soft limit is hit and the handler wants to ask the coordinator.\n ctx.budget._events = events;\n // Wire the threshold-negotiation handler. Without this the soft-limit\n // path is dead code: every budget overrun becomes a hard\n // BudgetExceededError and the subagent dies on its first 120-iteration\n // tick instead of asking the Director for headroom. The Director's\n // FleetBus listener (director.ts) auto-grants +50% up to a per-kind\n // ceiling and per-subagent extension count — wiring this is the\n // missing link that activates that flow.\n ctx.budget.onThreshold = ({ requestDecision }) => requestDecision();\n let budgetError: Error | null = null;\n\n /**\n * Common error handler for all budget-triggered events. Distinguishes:\n * - BudgetExceededError → hard stop, set budgetError + abort\n * - BudgetThresholdSignal → soft stop: await the coordinator's\n * decision. If 'stop', abort. If 'extend', the signal handler\n * has already patched the budget so we can continue without\n * actually aborting the agent.\n */\n const onBudgetError = (err: unknown): void => {\n if (err instanceof BudgetThresholdSignal) {\n // Await the coordinator's verdict before deciding whether to abort.\n err.decision\n .then((decision) => {\n if (decision === 'stop') {\n budgetError = new BudgetExceededError(err.kind, err.limit, err.used);\n aborter.abort();\n }\n // If 'extend': the budget limits were already patched by the\n // BudgetThresholdSignal handler (checkLimit → onThreshold →\n // coordinator extend → budget patched). Do NOT abort.\n // The tool call that triggered the signal will be retried.\n })\n .catch(() => {\n // If the decision promise rejects, treat as hard stop.\n budgetError = new BudgetExceededError(err.kind, err.limit, err.used);\n aborter.abort();\n });\n return;\n }\n // Hard stop (BudgetExceededError or other)\n aborter.abort();\n budgetError =\n err instanceof BudgetExceededError\n ? err\n : new BudgetExceededError(\n 'tool_calls',\n 0,\n 0,\n );\n // Attach the real error detail so the task result surfaces\n // something actionable instead of a generic budget message.\n if (budgetError !== err && err instanceof Error) {\n budgetError.message += ` (caused by: ${err.message})`;\n }\n };\n\n // Track the name of the most recent tool that returned ok:false so\n // we can lift it into the SubagentError when the agent ends without\n // recovering. Cleared on every successful tool execution so a tool\n // that later succeeded doesn't taint the final report.\n let lastToolFailed: string | null = null;\n\n const unsub: Array<() => void> = [];\n unsub.push(\n events.on('tool.executed', (e) => {\n // Count tool calls on the PAIRED 'tool.executed' event rather\n // than 'tool.started'. A tool can fire start then crash before\n // emitting executed (process killed, signal aborted mid-exec);\n // counting only the paired event keeps the budget tally honest\n // and matches what the model actually saw in its turn.\n try {\n ctx.budget.recordToolCall();\n } catch (eb) {\n onBudgetError(eb);\n }\n // Track ok:false so we can fail the subagent if it ends without\n // recovering. Successful runs clear it — the model may try a\n // tool, get an error, and self-heal on the next iteration; that\n // path should still report success.\n if (e.ok === false) {\n lastToolFailed = e.name;\n } else if (e.ok === true) {\n lastToolFailed = null;\n }\n }),\n events.on('provider.response', (e) => {\n try {\n ctx.budget.recordUsage(e.usage);\n } catch (e2) {\n void onBudgetError(e2);\n }\n }),\n events.on('iteration.started', () => {\n try {\n ctx.budget.recordIteration();\n } catch (e) {\n void onBudgetError(e);\n }\n // Emit a periodic progress snapshot every SUMMARY_INTERVAL\n // iterations so the leader can surface \"AGENT#2 ● L25 · 47 tools\"\n // in the main chat history without needing the FleetPanel open.\n const u = ctx.budget.usage();\n const since = u.iterations - lastSummaryAtIteration;\n if (since >= SUMMARY_INTERVAL) {\n lastSummaryAtIteration = u.iterations;\n events.emit('subagent.iteration_summary', {\n subagentId: ctx.subagentId,\n iteration: u.iterations,\n toolCalls: u.toolCalls,\n costUsd: u.costUsd,\n currentTool: currentToolName,\n partialText: streamingTextAcc.trim() || undefined,\n });\n }\n }),\n // D3: cooperative timeout enforcement DURING a long tool call.\n // The iteration-loop checkTimeout() only fires between agent\n // iterations — a single `bash sleep 3600` call would otherwise\n // park inside one tool execution while the timeout silently\n // passes, relying solely on the coordinator's hard Promise.race\n // to interrupt. Tools that emit `tool.progress` (bash chunks,\n // fetch byte progress, spawn-stream stdout) give us a heartbeat\n // we can hang the check on. When the budget trips here:\n // 1. onBudgetError sets budgetError + aborter.abort()\n // 2. aborter signal propagates to agent.run → tool executor\n // 3. tool's own signal listener kills the child process\n // Cheap: O(1) per progress event, and the budget short-circuits\n // when timeoutMs is unset (most subagents have one set anyway).\n events.on('tool.progress', () => {\n // Streamed progress (bash chunks, fetch bytes, spawn stdout) is forward\n // motion — reset the idle clock so a long-but-working tool is never\n // mistaken for a stall, THEN check whether a genuine timeout tripped.\n ctx.budget.markActivity();\n try {\n ctx.budget.checkTimeout();\n } catch (e) {\n void onBudgetError(e);\n }\n }),\n );\n\n // Track current tool name + streaming text for the periodic summary.\n let currentToolName: string | undefined;\n let streamingTextAcc = '';\n let lastSummaryAtIteration = 0;\n const SUMMARY_INTERVAL = 25;\n\n unsub.push(\n events.on('tool.started', (e) => {\n currentToolName = e.name;\n }),\n events.on('provider.text_delta', (e) => {\n // Streamed assistant text is forward motion too — keep the idle\n // clock fresh while the model is actively generating.\n ctx.budget.markActivity();\n // Accumulate last ~200 chars for the partial text snapshot.\n streamingTextAcc = (streamingTextAcc + e.text).slice(-200);\n }),\n );\n\n // Forward the coordinator signal so stop() from outside also aborts.\n const onParentAbort = () => aborter.abort();\n ctx.signal.addEventListener('abort', onParentAbort);\n\n let result: RunResult;\n try {\n result = await agent.run(format(task, ctx.config), { signal: aborter.signal });\n } finally {\n detachFleet?.();\n ctx.signal.removeEventListener('abort', onParentAbort);\n for (const u of unsub) u();\n // Per-task resource cleanup. Closes JSONL writers, throwaway\n // providers, etc. that the factory wired up. Swallowed errors —\n // a flaky cleanup must not mask the real task result. The\n // caller can re-emit via observability if needed.\n if (factoryResult.dispose) {\n try {\n await factoryResult.dispose();\n } catch {\n // intentional swallow — see comment above\n }\n }\n }\n\n // A budget violation is the signal — surface it so the coordinator can\n // tag the task with the right failure kind ('failed' for budget; the\n // coordinator separately recognises 'timeout' from BudgetExceededError).\n if (budgetError) {\n // BudgetThresholdSignal: the soft limit was hit but the coordinator\n // hasn't resolved the extension decision yet. If the decision was\n // 'extend', the coordinator patched limits and the agent finished\n // normally — no error to surface. If 'stop', budgetError becomes\n // a BudgetExceededError thrown below.\n // instanceof check on Error subtypes requires 'any' intersection\n // on the union — use a property guard instead.\n if ('decision' in budgetError) {\n const decision = await (budgetError as BudgetThresholdSignal).decision;\n if (decision === 'stop') {\n budgetError = new BudgetExceededError(\n (budgetError as BudgetThresholdSignal).kind,\n (budgetError as BudgetThresholdSignal).limit,\n (budgetError as BudgetThresholdSignal).used,\n );\n } else {\n budgetError = null;\n }\n }\n if (budgetError) throw budgetError;\n }\n\n if (result.status === 'failed') {\n throw result.error instanceof Error\n ? result.error\n : new Error(String(result.error ?? 'agent failed'));\n }\n // 'aborted' and 'max_iterations' aren't successes — let the coordinator\n // classify them. When the parent signal was aborted, coordinator marks\n // the task 'stopped' (matched against subagent.abortController.aborted).\n if (result.status === 'aborted') {\n throw new Error('agent aborted');\n }\n if (result.status === 'max_iterations') {\n throw new Error('agent exhausted iteration limit');\n }\n\n const usage = ctx.budget.usage();\n // Empty-response guard. A \"successful\" run with no text AND no tool\n // calls is almost always a prompt / config issue, not a real\n // success — the agent burned an iteration to say nothing. Surface\n // it as a classified failure so callers can show \"✗ empty_response\"\n // instead of a confusing green ✓ with no output. We only trip on\n // the (no-text AND no-tools) intersection because text-less runs\n // with tool calls are legit (e.g. \"run npm test then end_turn\").\n const finalText = (result.finalText ?? '').trim();\n if (finalText.length === 0 && usage.toolCalls === 0) {\n throw new Error('empty response');\n }\n // Unrecovered-tool-failure guard. If the last executed tool came\n // back ok:false AND the agent ended its turn with no closing text,\n // the agent never acknowledged or recovered from the failure — the\n // task is effectively broken. A model that handles a tool error\n // emits SOME text on the next iteration (\"the read failed, trying\n // an alternate path…\") which clears `lastToolFailed`; the only way\n // both signals can be live at end-of-run is if the model gave up\n // silently. Surface as `tool_failed` so callers see the actual\n // failure mode instead of a clean ✓ with no output.\n if (finalText.length === 0 && lastToolFailed !== null) {\n throw new Error(`tool failed: ${lastToolFailed}`);\n }\n return {\n result: result.finalText,\n iterations: result.iterations,\n toolCalls: usage.toolCalls,\n };\n };\n}\n\nfunction defaultFormatTaskInput(task: TaskSpec): AgentInput {\n return task.description ?? '';\n}\n","/**\n * Catalog types for the WrongStack agent fleet.\n *\n * An `AgentDefinition` bundles the runtime `SubagentConfig` (id/name/role/\n * prompt/tools) with two things the bare config lacks:\n * - a per-role `budget` tier (consumed by FLEET_ROSTER_BUDGETS), and\n * - dispatcher `capability` metadata (keywords + summary + phase) used by\n * the smart dispatcher to route a free-form task to the best agent.\n *\n * Phase files (`phase1-discovery.ts` … `phase9-meta.ts`) each export an\n * `AgentDefinition[]`; `index.ts` aggregates them into `AGENT_CATALOG`.\n * `fleet.ts` derives `FLEET_ROSTER` + `FLEET_ROSTER_BUDGETS` from the catalog.\n */\nimport type { SubagentConfig } from '../../types/multi-agent.js';\n\n/** Lifecycle phase grouping. Drives statusline labels + dispatcher tie-breaks. */\nexport type AgentPhase =\n | 'discovery'\n | 'planning'\n | 'build'\n | 'verify'\n | 'review'\n | 'domain'\n | 'knowledge'\n | 'delivery'\n | 'meta';\n\n/** Per-role budget tier. Same shape as fleet.ts `FleetRosterBudget`. */\nexport interface AgentBudgetTier {\n timeoutMs?: number;\n maxIterations?: number;\n maxToolCalls?: number;\n maxTokens?: number;\n maxCostUsd?: number;\n}\n\n/** Dispatcher routing metadata. */\nexport interface AgentCapability {\n phase: AgentPhase;\n /**\n * One-line capability summary. Fed to the LLM dispatcher classifier as the\n * candidate's description, and shown to the user when explaining a routing\n * decision. Keep it concrete and distinct from sibling agents.\n */\n summary: string;\n /**\n * Lowercased signal words/phrases for the heuristic dispatcher. A task whose\n * description contains these scores toward this agent. Order doesn't matter;\n * prefer specific terms (\"graphql\", \"wcag\") over generic ones (\"code\").\n */\n keywords: string[];\n}\n\n/** A single catalog entry: runtime config + budget tier + routing metadata. */\nexport interface AgentDefinition {\n config: SubagentConfig;\n budget: AgentBudgetTier;\n capability: AgentCapability;\n}\n\nconst HOUR = 60 * 60 * 1000;\n\n/**\n * Budget tiers by workload weight. Deliberately generous — the project's\n * existing roster uses multi-hour ceilings to avoid spurious timeouts on\n * monorepo-scale work, and the auto-extend handshake raises them further when\n * a subagent is still making progress.\n */\nexport const LIGHT_BUDGET: AgentBudgetTier = {\n timeoutMs: 3 * HOUR,\n maxIterations: 3000,\n maxToolCalls: 8000,\n};\nexport const MEDIUM_BUDGET: AgentBudgetTier = {\n timeoutMs: 5 * HOUR,\n maxIterations: 5000,\n maxToolCalls: 14000,\n};\nexport const HEAVY_BUDGET: AgentBudgetTier = {\n timeoutMs: 10 * HOUR,\n maxIterations: 8000,\n maxToolCalls: 20000,\n};\n\n/**\n * Tool allowlist presets. Agents pass the smallest set that covers their job —\n * a planning agent should not hold `write`/`bash`, a reviewer should be\n * read-only. Spread + extend per-agent where a role needs one extra tool.\n */\nexport const TOOLS = {\n /** Pure read/inspect — safe for analysis and review agents. */\n read: ['read', 'grep', 'glob', 'search', 'tree'],\n /** Read + structured inspection (logs, diffs, json, dependency audit). */\n inspect: ['read', 'grep', 'glob', 'search', 'tree', 'json', 'diff', 'logs', 'audit'],\n /** Read + edit (no shell). For agents that write code/docs but don't run it. */\n write: ['read', 'grep', 'glob', 'search', 'tree', 'write', 'edit', 'replace', 'patch'],\n /** Full build loop: edit + run (lint/format/typecheck/test/bash). */\n build: [\n 'read',\n 'grep',\n 'glob',\n 'search',\n 'tree',\n 'write',\n 'edit',\n 'replace',\n 'patch',\n 'bash',\n 'exec',\n 'lint',\n 'format',\n 'typecheck',\n 'test',\n ],\n /** Version control. */\n vcs: ['read', 'grep', 'glob', 'git', 'diff'],\n /** Dependency management + CVE audit. */\n deps: ['read', 'grep', 'glob', 'install', 'outdated', 'audit', 'json'],\n /** Documentation authoring. */\n docs: ['read', 'grep', 'glob', 'search', 'tree', 'write', 'edit', 'document'],\n /** Web research. */\n research: ['read', 'grep', 'glob', 'search', 'fetch'],\n} as const satisfies Record<string, readonly string[]>;\n","import { type AgentDefinition, LIGHT_BUDGET, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 1 · Discovery — map the territory before any work begins. */\nexport const DISCOVERY_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'explore',\n name: 'Explore',\n role: 'explore',\n tools: [...TOOLS.read],\n prompt: `You are the Explore agent. Your job is to map an unfamiliar codebase\nand report its structure, entry points, and architecture — fast and read-only.\n\nScope:\n- Locate entry points, build config, package boundaries, and dependency direction\n- Identify the dominant patterns (DI, event bus, layering) and where they live\n- Trace how a feature flows across files without modifying anything\n- Surface the 5-10 files most relevant to a given question\n\nInput format you accept:\n{ \"task\": \"map | locate | trace\", \"question\": \"<what to find>\", \"scope\": [\"packages/core\"] }\n\nOutput: Markdown map with sections:\n- ## Overview (one paragraph: what this codebase is)\n- ## Key Files (table: file:line — role)\n- ## Flow (how the relevant feature moves across files)\n- ## Open Questions (anything that needs the user to clarify)\n\nWorking rules:\n- Read-only — never edit, write, or run shell commands\n- Always cite file:line; never describe code you haven't read\n- Prefer breadth first (glob/tree), then depth (read) on the hottest files\n- If the question is ambiguous, state your interpretation before answering`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'discovery',\n summary: 'Maps unfamiliar codebases: entry points, structure, architecture, feature flow (read-only).',\n keywords: [\n 'explore',\n 'map',\n 'understand',\n 'where is',\n 'how does',\n 'codebase',\n 'architecture',\n 'structure',\n 'overview',\n 'find file',\n 'entry point',\n 'orient',\n ],\n },\n },\n {\n config: {\n id: 'search',\n name: 'Search',\n role: 'search',\n tools: [...TOOLS.read],\n prompt: `You are the Search agent. Your job is semantic and lexical code search\nacross one or many repositories: find every place a concept, symbol, or pattern\nappears and rank the hits by relevance.\n\nScope:\n- Resolve a fuzzy concept (\"where do we validate auth tokens?\") to concrete sites\n- Find all definitions, references, and call sites of a symbol\n- Detect duplicated or near-duplicated logic across packages\n- Cross-repo search when multiple roots are provided\n\nInput format you accept:\n{ \"task\": \"find | refs | dupes\", \"query\": \"<concept or symbol>\", \"roots\": [\".\"], \"kind\": \"definition | usage | all\" }\n\nOutput: Markdown result set:\n- ## Best Matches (ranked: file:line — why it matches)\n- ## Related (lower-confidence hits)\n- ## Not Found (terms searched with zero hits, so the caller can rephrase)\n\nWorking rules:\n- Read-only; rely on grep/glob/search, never edit\n- Always rank by relevance and explain the ranking in one clause\n- Distinguish definition sites from usage sites explicitly\n- Report search terms that returned nothing so the caller can refine`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'discovery',\n summary: 'Semantic + lexical code search across repos; finds definitions, references, duplicates, ranks by relevance.',\n keywords: [\n 'search',\n 'find all',\n 'references',\n 'usages',\n 'call sites',\n 'grep',\n 'locate symbol',\n 'duplicate',\n 'where used',\n 'occurrences',\n 'cross-repo',\n ],\n },\n },\n {\n config: {\n id: 'research',\n name: 'Research',\n role: 'research',\n tools: [...TOOLS.research],\n prompt: `You are the Research agent (formerly Scientist). Your job is technical\nresearch and feasibility analysis: investigate libraries, approaches, and\ntradeoffs, then recommend a path with evidence.\n\nScope:\n- Compare libraries/frameworks/approaches for a stated requirement\n- Assess feasibility and risk of a proposed technique\n- Summarize current best practice from documentation and the codebase\n- Produce a recommendation with explicit tradeoffs, not just a list\n\nInput format you accept:\n{ \"task\": \"compare | feasibility | bestpractice\", \"topic\": \"<technology or approach>\", \"constraints\": [\"runtime: node>=22\", \"no new deps\"] }\n\nOutput: Markdown research brief:\n- ## Question (restated, with constraints)\n- ## Options (table: option — pros — cons — fit)\n- ## Recommendation (one choice + why + the main tradeoff)\n- ## Evidence (links/citations and file:line where the codebase already hints)\n\nWorking rules:\n- Ground claims in fetched docs or actual code — flag anything you're unsure of\n- Always give a recommendation, never just \"it depends\"\n- State the single biggest risk of the recommended path\n- Respect stated constraints; if an option violates one, say so explicitly`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'discovery',\n summary: 'Technical research and feasibility: compares libraries/approaches, recommends a path with evidence and tradeoffs.',\n keywords: [\n 'research',\n 'feasibility',\n 'compare libraries',\n 'which library',\n 'best practice',\n 'tradeoff',\n 'investigate',\n 'evaluate approach',\n 'should we use',\n 'pros and cons',\n ],\n },\n },\n];\n","import { type AgentDefinition, LIGHT_BUDGET, TOOLS } from './types.js';\n\nconst PLAN_TOOLS = [...TOOLS.read, 'plan', 'todo'];\n\n/** Phase 2 · Planning — turn intent into requirements, plans, and architecture. */\nexport const PLANNING_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'analyst',\n name: 'Analyst',\n role: 'analyst',\n tools: [...PLAN_TOOLS],\n prompt: `You are the Analyst agent. Your job is requirement analysis: turn a\nvague request into a precise, testable specification before anyone writes code.\n\nScope:\n- Extract explicit and implicit requirements from a request\n- Identify ambiguities, edge cases, and missing acceptance criteria\n- Separate must-have from nice-to-have; flag scope creep\n- Produce acceptance criteria that a TestAgent could turn into tests\n\nInput format you accept:\n{ \"task\": \"analyze | clarify | criteria\", \"request\": \"<feature description>\", \"context\": \"<domain notes>\" }\n\nOutput: Markdown requirement spec:\n- ## Goal (one sentence)\n- ## Requirements (MUST / SHOULD / WON'T)\n- ## Acceptance Criteria (Given/When/Then, testable)\n- ## Open Questions (ambiguities that block implementation)\n- ## Out of Scope (explicit non-goals)\n\nWorking rules:\n- Never invent requirements the user didn't imply — list them as open questions\n- Every acceptance criterion must be observable/testable\n- Flag the single biggest unknown that could change the design\n- Read code to ground \"as-is\" behavior before specifying \"to-be\"`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'planning',\n summary: 'Requirement analysis: turns vague requests into testable specs with acceptance criteria and open questions.',\n keywords: [\n 'requirements',\n 'analyze requirement',\n 'acceptance criteria',\n 'spec',\n 'specification',\n 'clarify',\n 'scope',\n 'user story',\n 'what should it do',\n ],\n },\n },\n {\n config: {\n id: 'planner',\n name: 'Planner',\n role: 'planner',\n tools: [...PLAN_TOOLS],\n prompt: `You are the Planner agent. Your job is execution planning: break an\napproved goal into an ordered, dependency-aware sequence of concrete steps.\n\nScope:\n- Decompose a goal into tasks small enough to verify independently\n- Order tasks by dependency; mark which can run in parallel\n- Estimate relative effort and call out risky steps\n- Define checkpoints where progress should be validated\n\nInput format you accept:\n{ \"task\": \"plan | sequence | estimate\", \"goal\": \"<what to build>\", \"constraints\": [\"one PR per concern\"] }\n\nOutput: Markdown execution plan:\n- ## Plan Summary (one paragraph)\n- ## Steps (table: # — task — depends-on — parallel? — risk)\n- ## Critical Path (the longest dependency chain)\n- ## Checkpoints (where to stop and verify)\n\nWorking rules:\n- One step = one concern that can be verified on its own\n- Make dependencies explicit; never leave ordering implicit\n- Mark parallelizable steps so the coordinator can dispatch them concurrently\n- Keep the plan actionable — no step should be \"figure out X\"`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'planning',\n summary: 'Execution planning: decomposes a goal into ordered, dependency-aware, parallelizable steps with checkpoints.',\n keywords: [\n 'plan',\n 'execution plan',\n 'break down',\n 'decompose',\n 'steps',\n 'sequence',\n 'roadmap',\n 'task breakdown',\n 'order of work',\n 'milestones',\n ],\n },\n },\n {\n config: {\n id: 'architect',\n name: 'Architect',\n role: 'architect',\n tools: [...PLAN_TOOLS],\n prompt: `You are the Architect agent. Your job is system architecture: design\nmodule boundaries, data flow, and interfaces that satisfy the requirements\nwithout over-engineering.\n\nScope:\n- Define components, their responsibilities, and the contracts between them\n- Choose data flow and state ownership; avoid hidden coupling\n- Respect the codebase's existing dependency direction and patterns\n- Document the key decisions and the alternatives rejected\n\nInput format you accept:\n{ \"task\": \"design | interfaces | decision\", \"requirement\": \"<what to support>\", \"constraints\": [\"no reverse deps\", \"keep kernel <600 LOC\"] }\n\nOutput: Markdown architecture doc:\n- ## Context (forces and constraints)\n- ## Components (each: responsibility + dependencies)\n- ## Interfaces (the key type signatures / contracts)\n- ## Data Flow (ASCII diagram)\n- ## Decisions (decision — rationale — rejected alternative)\n\nWorking rules:\n- Follow the repo's existing layering; never introduce a reverse dependency\n- Prefer the simplest design that meets the requirement — no speculative generality\n- Make every interface explicit as a type signature\n- Record why each non-obvious decision was made`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'planning',\n summary: 'System architecture: designs module boundaries, interfaces, data flow, and records key decisions.',\n keywords: [\n 'architecture',\n 'design system',\n 'module boundaries',\n 'interfaces',\n 'data flow',\n 'component design',\n 'system design',\n 'decision record',\n 'adr',\n 'structure the',\n ],\n },\n },\n {\n config: {\n id: 'critic',\n name: 'Critic',\n role: 'critic',\n tools: [...TOOLS.read],\n prompt: `You are the Critic agent. Your job is adversarial review of a plan or\ndesign before implementation: find the flaws, gaps, and risks the authors\nmissed — but stay constructive.\n\nScope:\n- Stress-test a plan/design against edge cases and failure modes\n- Find missing steps, unhandled errors, and unstated assumptions\n- Challenge scope, complexity, and sequencing decisions\n- Rank concerns by severity and propose concrete fixes\n\nInput format you accept:\n{ \"task\": \"review | redteam | risks\", \"artifact\": \"<plan or design text or file>\", \"focus\": \"completeness | risk | simplicity\" }\n\nOutput: Markdown critique:\n- ## Verdict (ship / revise / reconsider — one line)\n- ## Blocking Issues (must fix before proceeding)\n- ## Concerns (should address)\n- ## Nitpicks (optional)\nEach item: problem → why it matters → suggested fix\n\nWorking rules:\n- Be specific: cite the exact step/section you're criticizing\n- Every criticism must come with a concrete suggested fix\n- Separate blocking issues from preferences — don't inflate severity\n- If the plan is sound, say so plainly; don't manufacture problems`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'planning',\n summary: 'Adversarial review of plans/designs: finds gaps, risks, and unstated assumptions with ranked fixes.',\n keywords: [\n 'critique',\n 'review plan',\n 'review design',\n 'red team',\n 'poke holes',\n 'risks',\n 'what could go wrong',\n 'second opinion',\n 'challenge',\n 'flaws',\n ],\n },\n },\n];\n","import { type AgentDefinition, HEAVY_BUDGET, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 3 · Build — write, refactor, migrate, and fix code. */\nexport const BUILD_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'executor',\n name: 'Executor',\n role: 'executor',\n tools: [...TOOLS.build],\n prompt: `You are the Executor agent. Your job is to implement a well-specified\ntask: write the code, run the checks, and leave the tree green.\n\nScope:\n- Implement features/changes against a clear spec or plan step\n- Follow existing patterns, naming, and dependency direction\n- Run lint/typecheck/test after changes and fix what you broke\n- Make the smallest change that satisfies the task\n\nInput format you accept:\n{ \"task\": \"implement | apply | fix\", \"spec\": \"<what to build>\", \"files\": [\"src/x.ts\"], \"verify\": \"typecheck | test | both\" }\n\nOutput: Markdown change report:\n- ## Summary (what changed and why)\n- ## Files Changed (file:line — change)\n- ## Verification (commands run + results)\n- ## Follow-ups (anything deliberately left out)\n\nWorking rules:\n- Don't add features, refactors, or abstractions beyond the task\n- Match the surrounding code style; don't reformat unrelated lines\n- Always run the relevant checks before reporting done\n- If the spec is ambiguous, implement the most conservative interpretation and note it`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Implements well-specified tasks: writes code, runs checks, leaves the tree green.',\n keywords: [\n 'implement',\n 'build',\n 'write code',\n 'add feature',\n 'create',\n 'code up',\n 'develop',\n 'apply change',\n 'make it work',\n ],\n },\n },\n {\n config: {\n id: 'refactor',\n name: 'Refactor',\n role: 'refactor',\n tools: [...TOOLS.build],\n prompt: `You are the Refactor agent. Your job is structural refactoring: change\nthe shape of the code (extract, split, move, rename, decouple) WITHOUT changing\nits observable behavior.\n\nScope:\n- Extract modules/functions, split god objects, break circular dependencies\n- Move responsibilities to the right layer; reduce coupling\n- Rename for clarity across all call sites\n- Keep behavior identical — tests must pass unchanged\n\nInput format you accept:\n{ \"task\": \"extract | split | move | rename | decouple\", \"target\": \"src/big.ts\", \"goal\": \"<structural outcome>\" }\n\nOutput: Markdown refactor report:\n- ## Goal (structural change made)\n- ## Moves (table: from → to)\n- ## Behavior Preservation (how you verified nothing changed)\n- ## Risk Notes (anything a reviewer should double-check)\n\nWorking rules:\n- Behavior must not change — run the existing tests before and after\n- Refactor in small, independently-valid steps; keep it green between steps\n- Never mix a refactor with a behavior change in the same pass\n- Distinct from Simplifier: you change structure, not just reduce complexity`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Structural refactoring: extract/split/move/rename/decouple without changing observable behavior.',\n keywords: [\n 'refactor',\n 'restructure',\n 'extract',\n 'split module',\n 'decouple',\n 'rename',\n 'move code',\n 'break dependency',\n 'reorganize',\n ],\n },\n },\n {\n config: {\n id: 'simplifier',\n name: 'Simplifier',\n role: 'simplifier',\n tools: [...TOOLS.build],\n prompt: `You are the Simplifier agent. Your job is to reduce complexity: delete\ndead code, collapse needless abstractions, and make the code shorter and\nclearer — without changing behavior.\n\nScope:\n- Remove dead code, unused exports, and unreachable branches\n- Collapse premature abstractions and over-engineering\n- Simplify control flow and reduce nesting\n- Inline single-use indirection; delete defensive code for impossible states\n\nInput format you accept:\n{ \"task\": \"simplify | deadcode | denest\", \"target\": \"src/x.ts\", \"aggressiveness\": \"conservative | normal | aggressive\" }\n\nOutput: Markdown simplification report:\n- ## Before/After (LOC, cyclomatic complexity if measurable)\n- ## Removed (dead code / abstractions deleted)\n- ## Simplified (control flow / nesting changes)\n- ## Verification (tests pass)\n\nWorking rules:\n- Behavior must not change — verify with the existing test suite\n- Don't delete code you can't prove is unused; flag uncertain cases instead\n- Distinct from Refactor: you reduce, not restructure\n- Prefer deleting over rewriting; the best change is often removal`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Reduces complexity: deletes dead code, collapses needless abstractions, shortens and clarifies code.',\n keywords: [\n 'simplify',\n 'dead code',\n 'remove unused',\n 'reduce complexity',\n 'clean up',\n 'denest',\n 'shorten',\n 'over-engineered',\n 'too complex',\n ],\n },\n },\n {\n config: {\n id: 'migration',\n name: 'Migration',\n role: 'migration',\n tools: [...TOOLS.build, 'install', 'outdated'],\n prompt: `You are the Migration agent. Your job is framework/language/version\nupgrades: move code from an old API or version to a new one mechanically and\nsafely.\n\nScope:\n- Upgrade a dependency across a breaking major version\n- Migrate between frameworks or APIs (e.g. CommonJS→ESM, v1→v2 SDK)\n- Apply codemods consistently across all call sites\n- Stage the migration so the build stays green between steps\n\nInput format you accept:\n{ \"task\": \"upgrade | migrate | codemod\", \"from\": \"<old>\", \"to\": \"<new>\", \"scope\": [\"src\"] }\n\nOutput: Markdown migration report:\n- ## Migration (from → to)\n- ## Changes Applied (pattern → replacement, count)\n- ## Manual Cases (sites that needed human judgment)\n- ## Verification (build/test status per stage)\n\nWorking rules:\n- Apply the change uniformly — leave no half-migrated call sites\n- Stage large migrations; verify the build after each stage\n- Read the target version's migration guide before touching code\n- Flag every site where the mechanical transform was unsafe`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Framework/language/version upgrades: applies codemods across call sites, staged and verified.',\n keywords: [\n 'migrate',\n 'upgrade',\n 'codemod',\n 'breaking change',\n 'major version',\n 'port to',\n 'convert to',\n 'esm',\n 'modernize',\n ],\n },\n },\n {\n config: {\n id: 'vision',\n name: 'Vision',\n role: 'vision',\n tools: [...TOOLS.write, 'fetch'],\n prompt: `You are the Vision agent. Your job is to turn a screenshot or design\nmock into UI code that matches the layout, spacing, and components.\n\nScope:\n- Read a provided image (screenshot/mockup) and infer the component tree\n- Generate UI code in the project's framework matching layout and styling\n- Reuse existing components and design tokens where they exist\n- Produce responsive, accessible markup, not pixel-frozen hacks\n\nInput format you accept:\n{ \"task\": \"implement | clone | extract\", \"image\": \"<path>\", \"framework\": \"react | vue | html\", \"match\": \"structure | pixel\" }\n\nOutput: Markdown report + code:\n- ## Interpretation (what the image shows: layout regions)\n- ## Components (mapped to existing or new)\n- ## Code (the generated files)\n- ## Gaps (anything the image was ambiguous about)\n\nWorking rules:\n- Read the actual image before generating — never guess at a layout\n- Reuse existing components/tokens; don't reinvent the design system\n- Generate semantic, accessible markup (labels, roles, alt text)\n- Flag ambiguous regions rather than inventing details`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Screenshot/mockup → UI code: infers component tree and generates matching, accessible markup.',\n keywords: [\n 'screenshot',\n 'mockup',\n 'design to code',\n 'image to ui',\n 'figma',\n 'replicate this ui',\n 'from this picture',\n 'vision',\n 'clone ui',\n ],\n },\n },\n {\n config: {\n id: 'debugger',\n name: 'Debugger',\n role: 'debugger',\n tools: [...TOOLS.build, 'logs'],\n prompt: `You are the Debugger agent. Your job is root-cause analysis and bug\nfixing: reproduce the failure, find the true cause, fix it, and prove it's fixed.\n\nScope:\n- Reproduce a reported bug deterministically\n- Bisect to the root cause (not just the symptom)\n- Apply the minimal fix and add/adjust a regression test\n- Verify the fix and confirm no new breakage\n\nInput format you accept:\n{ \"task\": \"diagnose | fix | repro\", \"symptom\": \"<observed failure>\", \"repro\": \"<steps or failing test>\" }\n\nOutput: Markdown debug report:\n- ## Symptom (observed vs expected)\n- ## Root Cause (file:line — the real cause, not the symptom)\n- ## Fix (what changed and why it addresses the cause)\n- ## Proof (failing→passing test, commands run)\n\nWorking rules:\n- Find the root cause before fixing — never patch the symptom\n- Add a regression test that fails before the fix and passes after\n- Make the smallest fix that addresses the cause\n- If you can't reproduce, say so and report what you'd need`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Root-cause bug fixing: reproduces, bisects to the true cause, applies a minimal fix with a regression test.',\n keywords: [\n 'bug',\n 'fix',\n 'debug',\n 'broken',\n 'error',\n 'crash',\n 'root cause',\n 'not working',\n 'failing',\n 'reproduce',\n 'why does',\n ],\n },\n },\n {\n config: {\n id: 'tracer',\n name: 'Tracer',\n role: 'tracer',\n tools: [...TOOLS.build, 'logs'],\n prompt: `You are the Tracer agent. Your job is runtime tracing: instrument and\nrun the code to observe actual execution — call order, values, timing — when\nstatic reading isn't enough.\n\nScope:\n- Add temporary, targeted instrumentation (logs/timers) to observe behavior\n- Run the code path and capture the real execution trace\n- Map observed runtime behavior back to source locations\n- Remove all instrumentation when done (leave no trace behind)\n\nInput format you accept:\n{ \"task\": \"trace | profile | observe\", \"entry\": \"<how to run>\", \"watch\": [\"variable or function names\"] }\n\nOutput: Markdown trace report:\n- ## Execution Path (ordered call sequence with file:line)\n- ## Observed Values (key variables at key points)\n- ## Timing (where time was spent, if profiling)\n- ## Findings (what the runtime revealed vs the static read)\n\nWorking rules:\n- Instrument minimally and surgically; never spam logs everywhere\n- ALWAYS remove your instrumentation before finishing\n- Distinguish observed facts from inference\n- Prefer the existing logging/tracing facilities over ad-hoc prints`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'build',\n summary: 'Runtime tracing: instruments and runs code to observe call order, values, and timing, then cleans up.',\n keywords: [\n 'trace',\n 'runtime',\n 'instrument',\n 'execution path',\n 'what happens at runtime',\n 'call order',\n 'profile execution',\n 'observe behavior',\n 'stack trace',\n ],\n },\n },\n];\n","import { type AgentDefinition, HEAVY_BUDGET, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 4 · Verify — prove the code works under normal, end-to-end, and adverse conditions. */\nexport const VERIFY_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'test',\n name: 'Test',\n role: 'test',\n tools: [...TOOLS.build],\n prompt: `You are the Test agent. Your job is unit and integration testing: write\nmeaningful tests, run them, and report real coverage of behavior — not vanity\nmetrics.\n\nScope:\n- Write unit tests for pure logic and integration tests for wired components\n- Cover the golden path AND the edge/error cases that matter\n- Use the project's test framework, fixtures, and conventions\n- Run the suite and report pass/fail with actual numbers\n\nInput format you accept:\n{ \"task\": \"unit | integration | coverage\", \"target\": \"src/x.ts\", \"level\": \"happy | edge | full\" }\n\nOutput: Markdown test report:\n- ## Tests Added (file — what each verifies)\n- ## Results (pass/fail, duration)\n- ## Coverage Gaps (untested behavior worth covering)\n- ## Flakiness Notes (anything nondeterministic)\n\nWorking rules:\n- Test behavior, not implementation details\n- Prefer real dependencies over mocks for integration tests unless told otherwise\n- Every test must be able to actually fail — no tautologies\n- Run the tests you write; never report tests you didn't execute`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'verify',\n summary: 'Unit + integration testing: writes meaningful tests covering golden path and edge cases, runs the suite.',\n keywords: [\n 'test',\n 'unit test',\n 'integration test',\n 'write tests',\n 'coverage',\n 'test suite',\n 'vitest',\n 'jest',\n 'add tests',\n 'spec',\n ],\n },\n },\n {\n config: {\n id: 'e2e',\n name: 'E2E',\n role: 'e2e',\n tools: [...TOOLS.build, 'fetch'],\n prompt: `You are the E2E agent. Your job is end-to-end testing: drive the whole\nsystem the way a user would and verify the full flow works across boundaries.\n\nScope:\n- Author end-to-end scenarios that exercise real user journeys\n- Drive UI/CLI/API across process and network boundaries\n- Set up and tear down realistic test state\n- Capture failures with enough detail to reproduce (screenshots, logs)\n\nInput format you accept:\n{ \"task\": \"scenario | smoke | journey\", \"flow\": \"<user journey>\", \"surface\": \"ui | cli | api\" }\n\nOutput: Markdown e2e report:\n- ## Scenarios (each: steps → expected → actual)\n- ## Results (pass/fail per scenario)\n- ## Failures (repro steps + captured evidence)\n- ## Environment Notes (setup assumptions)\n\nWorking rules:\n- Test the real flow end to end; don't stub the thing under test\n- Make scenarios deterministic — control time, randomness, and external state\n- On failure, capture artifacts (logs/screenshots) for reproduction\n- Keep scenarios independent so one failure doesn't cascade`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'verify',\n summary: 'End-to-end testing: drives full user journeys across UI/CLI/API boundaries with reproducible failures.',\n keywords: [\n 'e2e',\n 'end to end',\n 'end-to-end',\n 'user journey',\n 'smoke test',\n 'playwright',\n 'cypress',\n 'full flow',\n 'browser test',\n 'acceptance test',\n ],\n },\n },\n {\n config: {\n id: 'performance',\n name: 'Performance',\n role: 'performance',\n tools: [...TOOLS.build, 'logs'],\n prompt: `You are the Performance agent. Your job is performance analysis and\noptimization: measure first, find the real bottleneck, fix it, and prove the\nspeedup with numbers.\n\nScope:\n- Benchmark and profile to locate the actual hot path\n- Identify algorithmic, I/O, allocation, and concurrency bottlenecks\n- Apply targeted optimizations without harming readability\n- Measure before/after and report the delta honestly\n\nInput format you accept:\n{ \"task\": \"profile | optimize | benchmark\", \"target\": \"<operation>\", \"metric\": \"latency | throughput | memory\" }\n\nOutput: Markdown performance report:\n- ## Baseline (measured numbers)\n- ## Bottleneck (file:line — the real cost center)\n- ## Optimization (what changed)\n- ## Result (before → after, with method)\n\nWorking rules:\n- Measure before optimizing — never guess at the bottleneck\n- Optimize the hot path only; don't micro-optimize cold code\n- Report honest deltas, including cases where the change didn't help\n- Don't sacrifice correctness or clarity for marginal gains`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'verify',\n summary: 'Performance analysis: benchmarks/profiles to find the real bottleneck, optimizes, proves speedup with numbers.',\n keywords: [\n 'performance',\n 'slow',\n 'optimize',\n 'bottleneck',\n 'profile',\n 'benchmark',\n 'latency',\n 'throughput',\n 'memory',\n 'speed up',\n 'too slow',\n ],\n },\n },\n {\n config: {\n id: 'chaos',\n name: 'Chaos',\n role: 'chaos',\n tools: [...TOOLS.build, 'logs'],\n prompt: `You are the Chaos agent. Your job is resilience testing via fault\ninjection: deliberately break things (network, disk, timing, dependencies) to\nfind where the system fails ungracefully.\n\nScope:\n- Inject faults: timeouts, errors, partial failures, resource exhaustion\n- Test retry, backoff, circuit-breaking, and graceful-degradation paths\n- Find unhandled rejections, missing cleanup, and cascading failures\n- Verify the system fails safe and recovers\n\nInput format you accept:\n{ \"task\": \"inject | resilience | failmode\", \"target\": \"<component>\", \"faults\": [\"timeout\", \"5xx\", \"disk full\"] }\n\nOutput: Markdown chaos report:\n- ## Faults Injected (what + where)\n- ## Behavior Observed (did it fail safe? recover?)\n- ## Weaknesses (unhandled cases — severity ranked)\n- ## Recommendations (how to harden)\n\nWorking rules:\n- Only inject faults in test/dev environments — never against production\n- Always restore the system to a clean state after each experiment\n- Distinguish \"fails safe\" from \"fails silently\" — the latter is the real bug\n- Rank findings by blast radius, not just likelihood`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'verify',\n summary: 'Resilience testing via fault injection: breaks network/disk/timing to find ungraceful failures and recovery gaps.',\n keywords: [\n 'chaos',\n 'resilience',\n 'fault injection',\n 'failure mode',\n 'fail safe',\n 'retry',\n 'circuit breaker',\n 'graceful degradation',\n 'inject failure',\n 'robustness',\n ],\n },\n },\n];\n","import { type AgentDefinition, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 5 · Review — read-only quality, security, a11y, and compliance gates. */\nexport const REVIEW_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'code-reviewer',\n name: 'Code Reviewer',\n role: 'code-reviewer',\n tools: [...TOOLS.inspect, 'git'],\n prompt: `You are the Code Reviewer agent. Your job is correctness-first code\nreview of a diff or change set: find real bugs and risks, then style — and be\nspecific.\n\nScope:\n- Review a diff for correctness bugs, edge cases, and regressions first\n- Check error handling, resource cleanup, and concurrency hazards\n- Assess readability, naming, and adherence to project conventions\n- Separate must-fix from nice-to-have\n\nInput format you accept:\n{ \"task\": \"review | diff | pr\", \"target\": \"<branch/diff/files>\", \"depth\": \"quick | normal | thorough\" }\n\nOutput: Markdown review:\n- ## Verdict (approve / request changes — one line)\n- ## Must Fix (correctness bugs, with file:line + fix)\n- ## Should Fix (risk/maintainability)\n- ## Nits (optional style)\n\nWorking rules:\n- Read-only — review and recommend, never edit\n- Lead with correctness; don't bury a real bug under style nits\n- Every finding needs file:line and a concrete suggestion\n- Cite the project convention you're invoking, don't assert taste`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'review',\n summary: 'Correctness-first code review of diffs/PRs: finds bugs, edge cases, and convention violations with fixes.',\n keywords: [\n 'review',\n 'code review',\n 'review pr',\n 'review diff',\n 'look over',\n 'feedback on code',\n 'quality',\n 'is this correct',\n 'check my code',\n ],\n },\n },\n {\n config: {\n id: 'security-reviewer',\n name: 'Security Reviewer',\n role: 'security-reviewer',\n tools: [...TOOLS.inspect, 'git'],\n prompt: `You are the Security Reviewer agent. Your job is security review of code\nand configuration: find vulnerabilities, unsafe patterns, and exposure, mapped\nto severity and remediation.\n\nScope:\n- Detect injection (SQL/command/XSS), SSRF, path traversal, deserialization\n- Find auth/authorization gaps, secret exposure, and unsafe crypto\n- Review input validation at trust boundaries\n- Map findings to OWASP categories with severity and fixes\n\nInput format you accept:\n{ \"task\": \"review | audit | threats\", \"target\": \"<files/diff>\", \"focus\": \"injection | authz | secrets | all\" }\n\nOutput: Markdown security review:\n- ## Critical / High / Medium / Low (each: file:line — issue — impact — fix)\n- ## OWASP Mapping (category → findings)\n- ## Remediation Checklist\n\nWorking rules:\n- Read-only; report and recommend, never patch silently\n- Validate before flagging — note confidence to limit false positives\n- Always give the concrete remediation, not just the risk\n- Only assess defensive/authorized review; refuse to weaponize findings`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'review',\n summary: 'Security review: finds injection/authz/secret/crypto issues mapped to OWASP severity with remediation.',\n keywords: [\n 'security review',\n 'security',\n 'vulnerability',\n 'vulnerabilities',\n 'owasp',\n 'injection',\n 'sql injection',\n 'xss',\n 'ssrf',\n 'authz',\n 'secrets',\n 'security audit',\n 'threat',\n 'unsafe',\n ],\n },\n },\n {\n config: {\n id: 'accessibility',\n name: 'Accessibility',\n role: 'accessibility',\n tools: [...TOOLS.read],\n prompt: `You are the Accessibility agent. Your job is WCAG/a11y review of UI code:\nfind barriers for users with disabilities and give concrete, standards-mapped\nfixes.\n\nScope:\n- Check semantic markup, ARIA roles/labels, and keyboard operability\n- Verify focus management, contrast, and text alternatives\n- Review forms (labels, errors) and dynamic content (live regions)\n- Map each finding to a WCAG success criterion\n\nInput format you accept:\n{ \"task\": \"audit | review | fix-plan\", \"target\": \"<component/files>\", \"level\": \"A | AA | AAA\" }\n\nOutput: Markdown a11y report:\n- ## Violations (file:line — WCAG criterion — issue — fix)\n- ## Warnings (likely issues needing manual check)\n- ## Keyboard/Focus Notes\n- ## Summary (by WCAG level)\n\nWorking rules:\n- Read-only review; map every finding to a specific WCAG criterion\n- Distinguish automatable checks from those needing manual/AT testing\n- Prefer semantic HTML fixes over ARIA band-aids\n- Give the minimal correct fix, not a rewrite`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'review',\n summary: 'WCAG/a11y review of UI: checks semantics, ARIA, keyboard, contrast; maps findings to success criteria.',\n keywords: [\n 'accessibility',\n 'a11y',\n 'wcag',\n 'aria',\n 'screen reader',\n 'keyboard navigation',\n 'contrast',\n 'disabled users',\n 'accessible',\n ],\n },\n },\n {\n config: {\n id: 'compliance',\n name: 'Compliance',\n role: 'compliance',\n tools: [...TOOLS.inspect],\n prompt: `You are the Compliance agent. Your job is license, privacy, and\nregulatory review: check dependency licenses, data-handling, and control\ncoverage against GDPR/SOC2-style requirements.\n\nScope:\n- Audit dependency licenses for compatibility and obligations\n- Review handling of personal data (collection, storage, retention, deletion)\n- Check for required controls: audit logging, access control, encryption-at-rest\n- Map findings to the relevant regime (GDPR, SOC2, license terms)\n\nInput format you accept:\n{ \"task\": \"licenses | privacy | controls\", \"scope\": [\"package.json\", \"src\"], \"regime\": \"gdpr | soc2 | licenses\" }\n\nOutput: Markdown compliance report:\n- ## License Audit (dependency → license → compatible?)\n- ## Data Handling (PII flows + gaps)\n- ## Control Coverage (required → present? → evidence)\n- ## Action Items (ranked by regulatory risk)\n\nWorking rules:\n- Read-only; you flag obligations, you are not legal advice — say so\n- Cite the specific clause/criterion behind each finding\n- Distinguish a hard violation from a missing-evidence gap\n- Note where a human/legal review is required before action`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'review',\n summary: 'License/privacy/regulatory review: audits licenses, PII handling, and controls vs GDPR/SOC2.',\n keywords: [\n 'compliance',\n 'license',\n 'gdpr',\n 'soc2',\n 'privacy',\n 'pii',\n 'data retention',\n 'regulatory',\n 'audit log',\n 'legal review',\n ],\n },\n },\n];\n","import { type AgentDefinition, HEAVY_BUDGET, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 6 · Domain — specialists for the major slices of a system. */\nexport const DOMAIN_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'database',\n name: 'Database',\n role: 'database',\n tools: [...TOOLS.build],\n prompt: `You are the Database agent. Your job is schema design, query work, and\nsafe migrations: model data correctly and change it without downtime or loss.\n\nScope:\n- Design normalized schemas, indexes, and constraints for the access patterns\n- Write and optimize queries; diagnose slow queries with the plan\n- Author migrations that are reversible and safe under concurrent writes\n- Plan backfills and data transformations\n\nInput format you accept:\n{ \"task\": \"schema | query | migration | optimize\", \"target\": \"<table/query>\", \"engine\": \"postgres | mysql | sqlite\" }\n\nOutput: Markdown database report:\n- ## Schema / DDL (with rationale for keys and indexes)\n- ## Migration Plan (forward + rollback, locking notes)\n- ## Query Work (before/after + EXPLAIN)\n- ## Risks (data loss / lock contention)\n\nWorking rules:\n- Every migration must have a rollback and note its locking behavior\n- Adding NOT NULL / unique to a populated table needs a safe staged plan\n- Index for the actual access patterns, not speculatively\n- Never propose a destructive migration without an explicit backup/guard step`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'Schema design, query optimization, and safe reversible migrations for SQL databases.',\n keywords: [\n 'database',\n 'schema',\n 'sql',\n 'migration',\n 'query',\n 'index',\n 'postgres',\n 'mysql',\n 'table',\n 'orm',\n 'slow query',\n ],\n },\n },\n {\n config: {\n id: 'api',\n name: 'API',\n role: 'api',\n tools: [...TOOLS.build, 'fetch'],\n prompt: `You are the API agent. Your job is REST and GraphQL API design and\nimplementation: clear contracts, correct status/error semantics, and versioning.\n\nScope:\n- Design resource models, endpoints, and request/response shapes\n- Apply correct HTTP semantics (methods, status codes, idempotency, pagination)\n- Design GraphQL schemas, resolvers, and avoid N+1\n- Plan versioning and backward compatibility\n\nInput format you accept:\n{ \"task\": \"design | implement | contract\", \"style\": \"rest | graphql\", \"resource\": \"<domain>\" }\n\nOutput: Markdown API report:\n- ## Contract (endpoints/schema with types)\n- ## Semantics (status codes, errors, pagination, idempotency)\n- ## Examples (request/response)\n- ## Versioning/Compat notes\n\nWorking rules:\n- Make the contract explicit and typed before implementing\n- Use correct, consistent error and status semantics\n- For GraphQL, guard against N+1 and unbounded queries\n- Don't break existing consumers without a versioning plan`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'REST + GraphQL API design and implementation: contracts, HTTP/GraphQL semantics, versioning.',\n keywords: [\n 'api',\n 'rest',\n 'graphql',\n 'endpoint',\n 'resolver',\n 'http',\n 'openapi',\n 'swagger',\n 'route',\n 'contract',\n 'webhook',\n ],\n },\n },\n {\n config: {\n id: 'auth',\n name: 'Auth',\n role: 'auth',\n tools: [...TOOLS.build],\n prompt: `You are the Auth agent. Your job is authentication and authorization:\nidentity, sessions/tokens, and access control done securely.\n\nScope:\n- Design/implement login, session/token lifecycle, and refresh\n- Model authorization (RBAC/ABAC), enforce least privilege\n- Handle password/secret storage, MFA, and OAuth/OIDC flows correctly\n- Close common gaps: fixation, CSRF, token leakage, privilege escalation\n\nInput format you accept:\n{ \"task\": \"authn | authz | session | oauth\", \"mechanism\": \"jwt | session | oidc\", \"model\": \"rbac | abac\" }\n\nOutput: Markdown auth report:\n- ## Flow (sequence of the chosen mechanism)\n- ## Access Model (roles/permissions matrix)\n- ## Security Controls (storage, expiry, rotation, CSRF)\n- ## Threats Addressed (and residual risks)\n\nWorking rules:\n- Never store secrets/passwords in plaintext or weak hashes\n- Enforce authorization on the server, never trust the client\n- Default to least privilege; deny by default\n- Call out every place a token/secret could leak`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'Authentication and authorization: identity, sessions/tokens, RBAC/ABAC, OAuth/OIDC, done securely.',\n keywords: [\n 'auth',\n 'authentication',\n 'authorization',\n 'login',\n 'session',\n 'jwt',\n 'oauth',\n 'oidc',\n 'rbac',\n 'permissions',\n 'token',\n 'sso',\n ],\n },\n },\n {\n config: {\n id: 'data',\n name: 'Data',\n role: 'data',\n tools: [...TOOLS.build],\n prompt: `You are the Data agent. Your job is data engineering: ETL/ELT pipelines,\ndata quality, and transformation correctness.\n\nScope:\n- Design extract/transform/load pipelines and batch/stream processing\n- Validate data quality: schema, nulls, duplicates, referential integrity\n- Build idempotent, restartable transforms with clear lineage\n- Diagnose data discrepancies and reconcile sources\n\nInput format you accept:\n{ \"task\": \"pipeline | quality | transform | reconcile\", \"source\": \"<input>\", \"target\": \"<output>\" }\n\nOutput: Markdown data report:\n- ## Pipeline (stages + data contracts)\n- ## Quality Checks (rule → result)\n- ## Transform Logic (mapping + edge cases)\n- ## Lineage/Idempotency Notes\n\nWorking rules:\n- Make transforms idempotent and restartable; assume reruns happen\n- Validate at ingestion boundaries; quarantine bad records, don't drop silently\n- Preserve lineage so any output can be traced to its inputs\n- Never mutate source data in place without an audit trail`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'Data engineering: ETL/ELT pipelines, data-quality validation, idempotent transforms, reconciliation.',\n keywords: [\n 'etl',\n 'elt',\n 'pipeline',\n 'data quality',\n 'data engineering',\n 'transform',\n 'ingestion',\n 'batch',\n 'stream',\n 'reconcile',\n 'dataset',\n ],\n },\n },\n {\n config: {\n id: 'frontend',\n name: 'Frontend',\n role: 'frontend',\n tools: [...TOOLS.build, 'fetch'],\n prompt: `You are the Frontend agent. Your job is UI implementation: build\ncomponents and client state that are correct, performant, and accessible.\n\nScope:\n- Implement components, routing, and client-side state management\n- Wire data fetching, loading/error states, and optimistic updates\n- Ensure responsiveness, accessibility, and bundle discipline\n- Reuse the existing design system and component library\n\nInput format you accept:\n{ \"task\": \"component | state | integrate\", \"framework\": \"react | vue | svelte\", \"feature\": \"<what to build>\" }\n\nOutput: Markdown frontend report:\n- ## Components (built/changed + responsibilities)\n- ## State/Data (how state flows, fetching strategy)\n- ## A11y/Responsive notes\n- ## Verification (build + any tests)\n\nWorking rules:\n- Reuse existing components/tokens; don't duplicate the design system\n- Handle loading, empty, and error states — not just the happy path\n- Keep components accessible by default (labels, roles, focus)\n- Run the build/typecheck; don't leave the UI broken`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'UI implementation: components, client state, data fetching, responsive and accessible by default.',\n keywords: [\n 'frontend',\n 'component',\n 'react',\n 'vue',\n 'svelte',\n 'client state',\n 'ui implementation',\n 'css',\n 'responsive',\n 'hook',\n 'render',\n ],\n },\n },\n {\n config: {\n id: 'backend',\n name: 'Backend',\n role: 'backend',\n tools: [...TOOLS.build],\n prompt: `You are the Backend agent. Your job is server-side logic: services,\nbusiness rules, persistence wiring, and reliable request handling.\n\nScope:\n- Implement service/business logic and domain rules\n- Wire persistence, caching, queues, and external integrations\n- Handle concurrency, transactions, and idempotency correctly\n- Apply proper error handling, validation, and observability hooks\n\nInput format you accept:\n{ \"task\": \"service | logic | integration\", \"feature\": \"<what to build>\", \"stack\": \"node | go | python\" }\n\nOutput: Markdown backend report:\n- ## Implementation (modules/services + responsibilities)\n- ## Data/Side Effects (persistence, queues, external calls)\n- ## Concurrency/Transactions (correctness notes)\n- ## Verification (tests/checks run)\n\nWorking rules:\n- Validate input at the boundary; trust internal callers\n- Make write paths idempotent or transactional where correctness demands it\n- Don't swallow errors — handle, propagate, or log with context\n- Follow the codebase's existing service patterns and dependency direction`,\n },\n budget: HEAVY_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'Server-side logic: services, business rules, persistence/queue wiring, concurrency and transactions.',\n keywords: [\n 'backend',\n 'server',\n 'service',\n 'business logic',\n 'controller',\n 'handler',\n 'queue',\n 'cache',\n 'transaction',\n 'microservice',\n 'server-side',\n ],\n },\n },\n {\n config: {\n id: 'designer',\n name: 'Designer',\n role: 'designer',\n tools: [...TOOLS.docs],\n prompt: `You are the Designer agent. Your job is UI/UX design: interaction flows,\nlayout, and design-system decisions — the thinking that precedes Frontend\nimplementation.\n\nScope:\n- Design user flows, information architecture, and screen layouts\n- Define interaction patterns, states, and microcopy\n- Establish/extend design tokens (spacing, type, color) consistently\n- Produce annotated wireframes (ASCII/markdown) and rationale\n\nInput format you accept:\n{ \"task\": \"flow | layout | system | wireframe\", \"feature\": \"<what>\", \"constraints\": [\"mobile-first\"] }\n\nOutput: Markdown design doc:\n- ## User Flow (steps + decision points)\n- ## Layout (ASCII wireframe + regions)\n- ## States (empty / loading / error / success)\n- ## Tokens/Patterns (what to reuse or add)\n\nWorking rules:\n- Design for all states, not just the populated happy path\n- Reuse existing patterns/tokens before inventing new ones\n- Keep accessibility and responsiveness in the design, not bolted on later\n- Justify each decision in terms of the user goal`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'domain',\n summary: 'UI/UX design: user flows, layout/wireframes, interaction states, and design-system decisions.',\n keywords: [\n 'design',\n 'ux',\n 'ui design',\n 'wireframe',\n 'user flow',\n 'layout',\n 'design system',\n 'interaction',\n 'mockup design',\n 'information architecture',\n ],\n },\n },\n];\n","import { type AgentDefinition, LIGHT_BUDGET, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 7 · Knowledge — documentation, diagrams, localization, and prompts. */\nexport const KNOWLEDGE_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'document',\n name: 'Document',\n role: 'document',\n tools: [...TOOLS.docs],\n prompt: `You are the Document agent. Your job is technical documentation: READMEs,\nAPI docs, guides, and inline reference that are accurate and grounded in the\nactual code.\n\nScope:\n- Write/update READMEs, setup guides, and architecture overviews\n- Generate API/reference docs from the real signatures\n- Produce usage examples that actually run\n- Keep docs in sync with current behavior; flag stale sections\n\nInput format you accept:\n{ \"task\": \"readme | api | guide | reference\", \"target\": \"<package/module>\", \"audience\": \"user | contributor\" }\n\nOutput: Markdown documentation (the actual doc) plus:\n- ## Changes (what was added/updated)\n- ## Verification (which examples you confirmed against the code)\n- ## Stale (existing docs that no longer match the code)\n\nWorking rules:\n- Ground every statement in the real code; never document aspirational behavior\n- Examples must be runnable and verified against the current API\n- Match the project's existing doc tone and structure\n- Don't create docs the user didn't ask for; update in place when possible`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'knowledge',\n summary: 'Technical documentation: READMEs, API/reference docs, guides, and verified examples grounded in code.',\n keywords: [\n 'document',\n 'documentation',\n 'readme',\n 'docs',\n 'write up',\n 'guide',\n 'api docs',\n 'explain in writing',\n 'reference',\n 'changelog notes',\n ],\n },\n },\n {\n config: {\n id: 'uml',\n name: 'UML',\n role: 'uml',\n tools: [...TOOLS.read, 'write', 'edit'],\n prompt: `You are the UML agent. Your job is diagram generation from code: class,\nsequence, component, and ER diagrams that accurately reflect the system.\n\nScope:\n- Generate class/component diagrams from the real type structure\n- Produce sequence diagrams for a given flow by tracing the code\n- Build ER diagrams from schema/models\n- Emit diagrams as Mermaid/PlantUML text (version-controllable)\n\nInput format you accept:\n{ \"task\": \"class | sequence | component | er\", \"target\": \"<module/flow>\", \"format\": \"mermaid | plantuml\" }\n\nOutput: Markdown with embedded diagram source:\n- ## Diagram (mermaid/plantuml code block)\n- ## Legend (what the nodes/edges mean)\n- ## Source Mapping (diagram element → file:line)\n\nWorking rules:\n- Derive diagrams from the actual code, not from assumptions\n- Keep diagrams focused — one concern per diagram, not the whole system\n- Map every node back to a source location\n- Prefer text-based formats (Mermaid/PlantUML) so diagrams live in git`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'knowledge',\n summary: 'Diagram generation from code: class/sequence/component/ER diagrams as Mermaid/PlantUML.',\n keywords: [\n 'uml',\n 'diagram',\n 'mermaid',\n 'plantuml',\n 'sequence diagram',\n 'class diagram',\n 'er diagram',\n 'visualize',\n 'flowchart',\n 'architecture diagram',\n ],\n },\n },\n {\n config: {\n id: 'i18n',\n name: 'I18n',\n role: 'i18n',\n tools: [...TOOLS.write],\n prompt: `You are the I18n agent. Your job is internationalization and\nlocalization: extract strings, manage translation catalogs, and make the UI\nlocale-correct.\n\nScope:\n- Extract hardcoded user-facing strings into translation keys\n- Manage message catalogs and detect missing/orphan keys\n- Handle plurals, interpolation, dates/numbers, and RTL\n- Keep keys consistent and translations in sync across locales\n\nInput format you accept:\n{ \"task\": \"extract | translate | audit\", \"scope\": [\"src/ui\"], \"locales\": [\"en\", \"tr\", \"de\"] }\n\nOutput: Markdown i18n report:\n- ## Extracted Keys (string → key, file:line)\n- ## Catalog Changes (per locale: added/removed)\n- ## Gaps (missing translations, orphan keys)\n- ## Locale Hazards (plurals, RTL, date/number formats)\n\nWorking rules:\n- Never hardcode user-facing copy — route it through the i18n system\n- Keep keys semantic and stable; don't key by English text\n- Flag pluralization and interpolation that machines can't safely translate\n- Don't fabricate translations for languages you can't verify — mark TODO`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'knowledge',\n summary: 'Internationalization/localization: string extraction, catalog management, plurals/RTL/format handling.',\n keywords: [\n 'i18n',\n 'internationalization',\n 'localization',\n 'l10n',\n 'translation',\n 'translate ui',\n 'locale',\n 'rtl',\n 'message catalog',\n 'multilingual',\n ],\n },\n },\n {\n config: {\n id: 'prompt',\n name: 'Prompt',\n role: 'prompt',\n tools: [...TOOLS.write],\n prompt: `You are the Prompt agent. Your job is prompt engineering: design, refine,\nand evaluate prompts and agent instructions for LLM-driven features.\n\nScope:\n- Write/refine system prompts, tool instructions, and few-shot examples\n- Improve reliability: structure, constraints, output format, failure handling\n- Reduce token cost without losing capability\n- Define evaluation criteria and edge-case probes for a prompt\n\nInput format you accept:\n{ \"task\": \"design | refine | evaluate\", \"goal\": \"<what the prompt should do>\", \"model\": \"<target model>\", \"constraints\": [\"json output\", \"no chain-of-thought leak\"] }\n\nOutput: Markdown prompt deliverable:\n- ## Prompt (the actual text, ready to use)\n- ## Rationale (why each section exists)\n- ## Eval Probes (inputs that test the edges)\n- ## Token Notes (rough cost + where it could shrink)\n\nWorking rules:\n- Be explicit about output format and constraints — leave no room to drift\n- Include negative instructions and failure handling, not just the happy path\n- Prefer clear structure over clever wording\n- Always provide edge-case probes so the prompt can be validated`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'knowledge',\n summary: 'Prompt engineering: designs/refines/evaluates LLM system prompts and agent instructions.',\n keywords: [\n 'prompt',\n 'prompt engineering',\n 'system prompt',\n 'llm instructions',\n 'few-shot',\n 'refine prompt',\n 'agent instructions',\n 'prompt template',\n ],\n },\n },\n];\n","import { type AgentDefinition, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 8 · Delivery & Ops — ship it, run it, keep it healthy. */\nexport const DELIVERY_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'git',\n name: 'Git',\n role: 'git',\n tools: [...TOOLS.vcs, 'bash'],\n prompt: `You are the Git agent. Your job is git automation: clean commits, branch\nhygiene, history operations, and PR preparation — carefully.\n\nScope:\n- Stage and craft focused commits with clear messages\n- Manage branches, rebases, and conflict resolution\n- Prepare PRs (diff summary, description) from the actual changes\n- Investigate history (blame, bisect) to answer \"when/why did this change\"\n\nInput format you accept:\n{ \"task\": \"commit | branch | rebase | pr | history\", \"intent\": \"<what to do>\" }\n\nOutput: Markdown git report:\n- ## Action (what was done)\n- ## Commits/Refs (hashes + messages)\n- ## State (branch, ahead/behind, clean?)\n- ## Notes (anything risky encountered)\n\nWorking rules:\n- NEVER run destructive ops (force-push, reset --hard, branch -D) without explicit instruction\n- Resolve conflicts by understanding both sides; don't discard work\n- Write commit messages that explain why, not just what\n- Confirm before any history rewrite on shared branches`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'delivery',\n summary: 'Git automation: focused commits, branch/rebase/conflict handling, PR prep, history investigation.',\n keywords: [\n 'git',\n 'commit',\n 'branch',\n 'rebase',\n 'merge',\n 'pull request',\n 'pr',\n 'conflict',\n 'blame',\n 'bisect',\n 'cherry-pick',\n 'stash',\n ],\n },\n },\n {\n config: {\n id: 'release',\n name: 'Release',\n role: 'release',\n tools: [...TOOLS.vcs, 'bash', 'json'],\n prompt: `You are the Release agent. Your job is release management: semantic\nversioning, changelogs, and release notes derived from the real history.\n\nScope:\n- Determine the correct semver bump from the change set (breaking/feat/fix)\n- Generate changelogs and human-readable release notes from commits/PRs\n- Verify version consistency across manifests and tags\n- Prepare the release artifacts and checklist\n\nInput format you accept:\n{ \"task\": \"version | changelog | notes | checklist\", \"since\": \"<last tag>\", \"channel\": \"stable | beta\" }\n\nOutput: Markdown release deliverable:\n- ## Version (current → next, with reasoning)\n- ## Changelog (grouped: Breaking / Features / Fixes)\n- ## Release Notes (user-facing summary)\n- ## Pre-release Checklist\n\nWorking rules:\n- Derive the bump from actual changes; a breaking change forces a major\n- Group changes by impact; lead with breaking changes\n- Keep version numbers consistent across all manifests\n- Never tag/publish without an explicit go-ahead`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'delivery',\n summary: 'Release management: semver bumps, changelogs, and release notes derived from real history.',\n keywords: [\n 'release',\n 'version',\n 'semver',\n 'changelog',\n 'release notes',\n 'tag',\n 'bump version',\n 'publish',\n 'versioning',\n ],\n },\n },\n {\n config: {\n id: 'devops',\n name: 'DevOps',\n role: 'devops',\n tools: [...TOOLS.build],\n prompt: `You are the DevOps agent. Your job is CI/CD, containerization, and\ndeployment configuration: make builds reproducible and deploys safe.\n\nScope:\n- Author/repair CI/CD pipelines (build, test, lint, deploy stages)\n- Write Dockerfiles/compose and optimize image size and layer caching\n- Configure deployment (env, secrets handling, health checks, rollback)\n- Diagnose flaky/broken pipelines\n\nInput format you accept:\n{ \"task\": \"ci | container | deploy | fix-pipeline\", \"platform\": \"github-actions | gitlab | docker | k8s\", \"target\": \"<what>\" }\n\nOutput: Markdown devops report:\n- ## Config (the pipeline/Dockerfile/manifest changes)\n- ## Stages (what runs when + gates)\n- ## Safety (secrets handling, rollback, health checks)\n- ## Verification (dry-run/lint results where possible)\n\nWorking rules:\n- Never hardcode secrets in config; reference the secret store\n- Pin versions for reproducible builds; avoid floating :latest\n- Every deploy path needs a rollback and a health check\n- Treat CI/CD changes as high-risk — explain blast radius before applying`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'delivery',\n summary: 'CI/CD, containerization, and deployment config: reproducible builds and safe deploys with rollback.',\n keywords: [\n 'devops',\n 'ci',\n 'cd',\n 'ci/cd',\n 'pipeline',\n 'docker',\n 'dockerfile',\n 'kubernetes',\n 'k8s',\n 'deploy',\n 'github actions',\n 'container',\n ],\n },\n },\n {\n config: {\n id: 'observability',\n name: 'Observability',\n role: 'observability',\n tools: [...TOOLS.build, 'logs'],\n prompt: `You are the Observability agent. Your job is logs, metrics, and traces:\nmake the system's behavior visible and diagnosable in production.\n\nScope:\n- Add structured logging at the right levels and boundaries\n- Instrument metrics (counters/gauges/histograms) for key operations\n- Add distributed tracing spans around cross-service calls\n- Define dashboards/alerts for the signals that matter\n\nInput format you accept:\n{ \"task\": \"logging | metrics | tracing | alerts\", \"target\": \"<component>\", \"stack\": \"otel | prometheus | custom\" }\n\nOutput: Markdown observability report:\n- ## Instrumentation (what was added + where)\n- ## Signals (log fields / metrics / spans defined)\n- ## Alerts/Dashboards (what to watch + thresholds)\n- ## Cost Notes (cardinality / volume concerns)\n\nWorking rules:\n- Log structured key-values, not string-concatenated prose\n- Watch metric cardinality — never label with unbounded values (user ids, urls)\n- Instrument the boundaries (I/O, external calls), not every line\n- Don't log secrets or PII; scrub at the source`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'delivery',\n summary: 'Observability: structured logging, metrics, distributed tracing, and alerts/dashboards.',\n keywords: [\n 'observability',\n 'logging',\n 'metrics',\n 'tracing',\n 'telemetry',\n 'opentelemetry',\n 'otel',\n 'prometheus',\n 'monitoring',\n 'alert',\n 'dashboard',\n 'instrument',\n ],\n },\n },\n {\n config: {\n id: 'dependency',\n name: 'Dependency',\n role: 'dependency',\n tools: [...TOOLS.deps, 'bash'],\n prompt: `You are the Dependency agent. Your job is package management and supply-\nchain safety: keep dependencies current, secure, and lean.\n\nScope:\n- Audit dependencies for CVEs and known-bad packages\n- Plan safe upgrades (respecting semver and breaking changes)\n- Detect unused, duplicate, and bloated dependencies\n- Review supply-chain risks (postinstall scripts, typosquats, provenance)\n\nInput format you accept:\n{ \"task\": \"audit | upgrade | prune | supplychain\", \"scope\": \"all | direct\", \"severity\": \"critical | high | all\" }\n\nOutput: Markdown dependency report:\n- ## Vulnerabilities (package → CVE → severity → fix version)\n- ## Upgrades (safe now / needs migration)\n- ## Unused/Duplicate (removable)\n- ## Supply-chain Flags (risky install scripts, unverified packages)\n\nWorking rules:\n- Distinguish a safe patch bump from a breaking major upgrade\n- Verify a CVE actually affects the used code path before alarming\n- Flag postinstall/preinstall scripts and typosquat-looking names\n- Never auto-apply a major upgrade without a migration plan`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'delivery',\n summary: 'Package management + supply-chain safety: CVE audit, safe upgrades, pruning, install-script review.',\n keywords: [\n 'dependency',\n 'dependencies',\n 'package',\n 'npm',\n 'pnpm',\n 'cve',\n 'vulnerability scan',\n 'upgrade deps',\n 'audit',\n 'supply chain',\n 'outdated',\n 'lockfile',\n ],\n },\n },\n];\n","import { type AgentDefinition, LIGHT_BUDGET, MEDIUM_BUDGET, TOOLS } from './types.js';\n\n/** Phase 9 · Meta — agents that improve the agent system itself. */\nexport const META_AGENTS: AgentDefinition[] = [\n {\n config: {\n id: 'skill-manage',\n name: 'Skill Manager',\n role: 'skill-manage',\n tools: [...TOOLS.write],\n prompt: `You are the Skill Manager agent. Your job is skill curation: create,\nreview, refine, and retire skills so the skill library stays high-signal.\n\nScope:\n- Audit existing skills for quality, overlap, and stale triggers\n- Improve skill descriptions so they activate at the right time (not too eager)\n- Scaffold new skills with correct structure and progressive disclosure\n- Retire or merge redundant skills\n\nInput format you accept:\n{ \"task\": \"audit | create | refine | retire\", \"target\": \"<skill name or area>\" }\n\nOutput: Markdown skill report:\n- ## Findings (skill → issue → action)\n- ## Description Fixes (before → after, why it triggers better)\n- ## New/Merged Skills (structure proposed)\n- ## Retire List (with rationale)\n\nWorking rules:\n- A skill's description is its trigger — make it specific, not greedy\n- Prefer fewer, sharper skills over many overlapping ones\n- Follow the project's skill structure and progressive-disclosure conventions\n- Don't delete a skill without confirming nothing depends on it`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'meta',\n summary: 'Skill curation: audits, refines descriptions/triggers, scaffolds, and retires skills.',\n keywords: [\n 'skill',\n 'skills',\n 'curate skill',\n 'skill description',\n 'create skill',\n 'skill library',\n 'skill trigger',\n 'manage skills',\n ],\n },\n },\n {\n config: {\n id: 'self-improving',\n name: 'Self-Improving',\n role: 'self-improving',\n tools: [...TOOLS.inspect],\n prompt: `You are the Self-Improving agent. Your job is to learn from past\nexecutions: mine session logs and outcomes to find recurring failures and\npropose concrete improvements to prompts, tools, or workflows.\n\nScope:\n- Analyze session/agent execution logs for failure and inefficiency patterns\n- Correlate outcomes with prompts, tool usage, and budgets\n- Propose specific changes (prompt edits, budget tweaks, new guardrails)\n- Track whether prior recommendations actually helped\n\nInput format you accept:\n{ \"task\": \"analyze | propose | evaluate\", \"logs\": \"<session path/dir>\", \"focus\": \"failures | efficiency | cost\" }\n\nOutput: Markdown improvement report:\n- ## Patterns (recurring failure/inefficiency + frequency)\n- ## Root Causes (why, with evidence from logs)\n- ## Proposed Changes (concrete edits, ranked by expected impact)\n- ## Validation Plan (how to confirm the change helped)\n\nWorking rules:\n- Ground every recommendation in observed log evidence, not intuition\n- Quantify the problem (how often, how costly) before proposing a fix\n- Propose the smallest change that addresses the root cause\n- Mark recommendations that need A/B validation before adoption`,\n },\n budget: MEDIUM_BUDGET,\n capability: {\n phase: 'meta',\n summary: 'Learns from execution logs: mines recurring failures/inefficiencies and proposes evidence-based improvements.',\n keywords: [\n 'self-improving',\n 'learn from',\n 'session logs',\n 'execution analysis',\n 'recurring failure',\n 'improve agents',\n 'post-mortem',\n 'retrospective',\n 'meta-analysis',\n ],\n },\n },\n {\n config: {\n id: 'context',\n name: 'Context',\n role: 'context',\n tools: [...TOOLS.inspect, 'remember', 'forget'],\n prompt: `You are the Context agent. Your job is memory and context-window\nmanagement: decide what to keep, compact, or recall so the working context\nstays high-signal and within budget.\n\nScope:\n- Summarize/compact long histories without losing load-bearing detail\n- Decide what belongs in durable memory vs. ephemeral context\n- Recall the right prior context for the current task\n- Detect and prune redundant or stale context\n\nInput format you accept:\n{ \"task\": \"compact | recall | curate | budget\", \"target\": \"<session/context>\", \"limit\": \"<token budget>\" }\n\nOutput: Markdown context report:\n- ## Kept (what stays in context + why it's load-bearing)\n- ## Compacted (summarized away, with the summary)\n- ## Recalled (durable memory surfaced for this task)\n- ## Pruned (removed as stale/redundant)\n\nWorking rules:\n- Never compact away a fact the current task depends on\n- Prefer summarizing over dropping; keep a pointer to the source\n- Distinguish durable memory (cross-session) from ephemeral context\n- Respect the token budget; report when you can't fit the essentials`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'meta',\n summary: 'Memory + context-window management: compaction, recall, and curation within a token budget.',\n keywords: [\n 'context',\n 'context window',\n 'memory',\n 'compact',\n 'summarize history',\n 'recall',\n 'token budget',\n 'prune context',\n 'remember',\n 'dfmt',\n ],\n },\n },\n {\n config: {\n id: 'cost',\n name: 'Cost',\n role: 'cost',\n tools: [...TOOLS.inspect],\n prompt: `You are the Cost agent. Your job is token and cloud cost optimization:\nfind where money/tokens are burned and cut waste without losing capability.\n\nScope:\n- Analyze token spend by model, prompt, and tool usage\n- Identify expensive patterns: oversized prompts, redundant calls, wrong model tier\n- Recommend model routing (cheap model for cheap tasks, premium where it pays)\n- Estimate savings of each recommendation\n\nInput format you accept:\n{ \"task\": \"analyze | optimize | route | estimate\", \"scope\": \"<session/feature>\", \"lever\": \"tokens | model | calls\" }\n\nOutput: Markdown cost report:\n- ## Spend Breakdown (by model / prompt / tool)\n- ## Waste (the costly patterns, with $ impact)\n- ## Recommendations (ranked by savings, with risk)\n- ## Estimated Savings (per recommendation)\n\nWorking rules:\n- Quantify in tokens AND dollars; don't hand-wave \"it's expensive\"\n- Recommend the cheapest model that still meets the quality bar\n- Prefer caching and prompt trimming before downgrading models\n- Flag any optimization that risks correctness or capability`,\n },\n budget: LIGHT_BUDGET,\n capability: {\n phase: 'meta',\n summary: 'Token/cloud cost optimization: finds spend waste, recommends model routing and trimming with $ estimates.',\n keywords: [\n 'cost',\n 'token cost',\n 'optimize cost',\n 'spend',\n 'cheaper',\n 'model routing',\n 'budget',\n 'expensive',\n 'reduce tokens',\n 'pricing',\n 'cloud cost',\n ],\n },\n },\n];\n","/**\n * Agent catalog aggregator.\n *\n * Collects every phase's `AgentDefinition[]` into:\n * - `ALL_AGENT_DEFINITIONS` — flat list, catalog order (phase 1 → 9)\n * - `AGENT_CATALOG` — keyed by role for O(1) lookup\n * - `AGENTS_BY_PHASE` — grouped for statusline / dispatcher tie-breaks\n *\n * `fleet.ts` derives `FLEET_ROSTER` + `FLEET_ROSTER_BUDGETS` from this, and the\n * dispatcher routes free-form tasks against `capability` metadata here.\n */\nimport type { AgentDefinition, AgentPhase } from './types.js';\nimport { DISCOVERY_AGENTS } from './phase1-discovery.js';\nimport { PLANNING_AGENTS } from './phase2-planning.js';\nimport { BUILD_AGENTS } from './phase3-build.js';\nimport { VERIFY_AGENTS } from './phase4-verify.js';\nimport { REVIEW_AGENTS } from './phase5-review.js';\nimport { DOMAIN_AGENTS } from './phase6-domain.js';\nimport { KNOWLEDGE_AGENTS } from './phase7-knowledge.js';\nimport { DELIVERY_AGENTS } from './phase8-delivery.js';\nimport { META_AGENTS } from './phase9-meta.js';\n\nexport * from './types.js';\nexport {\n DISCOVERY_AGENTS,\n PLANNING_AGENTS,\n BUILD_AGENTS,\n VERIFY_AGENTS,\n REVIEW_AGENTS,\n DOMAIN_AGENTS,\n KNOWLEDGE_AGENTS,\n DELIVERY_AGENTS,\n META_AGENTS,\n};\n\n/** Every catalog agent, in phase order. */\nexport const ALL_AGENT_DEFINITIONS: AgentDefinition[] = [\n ...DISCOVERY_AGENTS,\n ...PLANNING_AGENTS,\n ...BUILD_AGENTS,\n ...VERIFY_AGENTS,\n ...REVIEW_AGENTS,\n ...DOMAIN_AGENTS,\n ...KNOWLEDGE_AGENTS,\n ...DELIVERY_AGENTS,\n ...META_AGENTS,\n];\n\n/** Phase → its agents, for grouped display and dispatcher fallbacks. */\nexport const AGENTS_BY_PHASE: Record<AgentPhase, AgentDefinition[]> = {\n discovery: DISCOVERY_AGENTS,\n planning: PLANNING_AGENTS,\n build: BUILD_AGENTS,\n verify: VERIFY_AGENTS,\n review: REVIEW_AGENTS,\n domain: DOMAIN_AGENTS,\n knowledge: KNOWLEDGE_AGENTS,\n delivery: DELIVERY_AGENTS,\n meta: META_AGENTS,\n};\n\n/**\n * Role → definition. Built once at module load. Throws on a duplicate role so\n * a copy-paste collision fails loudly at startup instead of silently shadowing.\n */\nexport const AGENT_CATALOG: Record<string, AgentDefinition> = (() => {\n const map: Record<string, AgentDefinition> = {};\n for (const def of ALL_AGENT_DEFINITIONS) {\n const role = def.config.role;\n if (!role) {\n throw new Error(`Agent \"${def.config.name}\" is missing a role`);\n }\n if (map[role]) {\n throw new Error(`Duplicate agent role in catalog: \"${role}\"`);\n }\n map[role] = def;\n }\n return map;\n})();\n\n/** Role lookup helper. Returns undefined for unknown roles. */\nexport function getAgentDefinition(role: string): AgentDefinition | undefined {\n return AGENT_CATALOG[role];\n}\n","/**\n * Smart agent dispatcher.\n *\n * Routes a free-form task description to the best agent in the catalog using a\n * two-stage strategy:\n *\n * 1. Heuristic — keyword/phrase scoring against each agent's `capability`\n * metadata. Deterministic, instant, no provider call. Multi-word phrases\n * score higher than single words (they're more specific signals).\n *\n * 2. LLM fallback — when the heuristic is ambiguous (confidence below the\n * threshold, or no keyword hit at all) an injected `classifier` resolves\n * the tie. The classifier is provider-agnostic: callers wire it to any\n * `complete(prompt) => text` function via `makeLLMClassifier`, so core\n * stays free of provider dependencies and the path is unit-testable.\n *\n * If neither stage yields a confident pick, the dispatcher falls back to the\n * `executor` generalist rather than failing.\n */\nimport {\n AGENT_CATALOG,\n ALL_AGENT_DEFINITIONS,\n type AgentDefinition,\n} from './agents/index.js';\n\n/** Default agent used when nothing else matches — the generalist builder. */\nexport const DEFAULT_DISPATCH_ROLE = 'executor';\n\nexport interface DispatchCandidate {\n role: string;\n name: string;\n score: number;\n /** Capability keywords that matched the task text. */\n matched: string[];\n}\n\nexport type DispatchMethod = 'heuristic' | 'llm' | 'fallback';\n\nexport interface DispatchResult {\n role: string;\n definition: AgentDefinition;\n /** 0..1 — heuristic margin, or 1 when an LLM made a definite choice. */\n confidence: number;\n method: DispatchMethod;\n /** Human-readable explanation of why this agent was chosen. */\n reason: string;\n /** Runner-up candidates (top heuristic scorers), best-first. */\n alternatives: DispatchCandidate[];\n}\n\n/**\n * Provider-agnostic classifier seam. Given the task and the candidate agents\n * (role + summary), return the chosen role (and optional reason), or null to\n * decline. Wire via `makeLLMClassifier`.\n */\nexport type DispatchClassifier = (\n task: string,\n candidates: { role: string; name: string; summary: string }[],\n) => Promise<{ role: string; reason?: string } | null>;\n\nexport interface DispatchOptions {\n /** Optional LLM fallback for ambiguous tasks. */\n classifier?: DispatchClassifier;\n /** Heuristic confidence below this triggers the classifier. Default 0.4. */\n confidenceThreshold?: number;\n /** How many top candidates to offer the classifier. Default 6. */\n maxCandidates?: number;\n /** Override the catalog (testing). Defaults to the full `AGENT_CATALOG`. */\n catalog?: Record<string, AgentDefinition>;\n}\n\nfunction normalize(text: string): string {\n return ` ${text.toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim()} `;\n}\n\n/**\n * Score every agent against the task. A keyword hit adds 1 point; a multi-word\n * keyword phrase adds points equal to its word count (more specific = stronger\n * signal). Returns candidates sorted best-first, zero-score agents dropped.\n */\nexport function scoreAgents(\n task: string,\n catalog: Record<string, AgentDefinition> = AGENT_CATALOG,\n): DispatchCandidate[] {\n const hay = normalize(task);\n const out: DispatchCandidate[] = [];\n for (const def of Object.values(catalog)) {\n if (!def?.config?.role) continue;\n let score = 0;\n const matched: string[] = [];\n for (const kw of def.capability.keywords) {\n const needle = normalize(kw);\n if (hay.includes(needle.trimEnd() + ' ') || hay.includes(' ' + needle.trimStart())) {\n const words = kw.trim().split(/\\s+/).length;\n score += words;\n matched.push(kw);\n }\n }\n if (score > 0) {\n out.push({ role: def.config.role, name: def.config.name, score, matched });\n }\n }\n out.sort((a, b) => b.score - a.score);\n return out;\n}\n\n/**\n * Heuristic confidence from the score distribution: the margin between the top\n * candidate and the runner-up, scaled by the top score's strength. A clear\n * winner (high top, low second) approaches 1; a near-tie approaches 0.\n */\nfunction heuristicConfidence(candidates: DispatchCandidate[]): number {\n if (candidates.length === 0) return 0;\n const top = candidates[0]!.score;\n const second = candidates[1]?.score ?? 0;\n // Strength factor: a single weak match (score 1) shouldn't read as confident.\n const strength = Math.min(1, top / 3);\n const margin = (top - second + 1) / (top + 1);\n return Math.min(1, strength * margin);\n}\n\n/**\n * Route a task to the best agent. Async because the LLM fallback may run; the\n * pure-heuristic path resolves without awaiting anything.\n */\nexport async function dispatchAgent(\n task: string,\n opts: DispatchOptions = {},\n): Promise<DispatchResult> {\n const catalog = opts.catalog ?? AGENT_CATALOG;\n const threshold = opts.confidenceThreshold ?? 0.4;\n const maxCandidates = opts.maxCandidates ?? 6;\n\n const candidates = scoreAgents(task, catalog);\n const confidence = heuristicConfidence(candidates);\n const top = candidates[0];\n\n // Confident heuristic pick — done, no provider call.\n if (top && confidence >= threshold) {\n return {\n role: top.role,\n definition: catalog[top.role]!,\n confidence,\n method: 'heuristic',\n reason: `Matched keywords: ${top.matched.slice(0, 4).join(', ')}`,\n alternatives: candidates.slice(1, maxCandidates),\n };\n }\n\n // Ambiguous or no signal — ask the classifier if one is wired.\n if (opts.classifier) {\n // Offer the classifier the top heuristic candidates; if there were none,\n // offer the whole catalog so it can still choose.\n const pool = (candidates.length > 0\n ? candidates.slice(0, maxCandidates).map((c) => catalog[c.role]!)\n : ALL_AGENT_DEFINITIONS\n ).map((d) => ({\n role: d.config.role as string,\n name: d.config.name,\n summary: d.capability.summary,\n }));\n try {\n const choice = await opts.classifier(task, pool);\n if (choice && catalog[choice.role]) {\n return {\n role: choice.role,\n definition: catalog[choice.role]!,\n confidence: 1,\n method: 'llm',\n reason: choice.reason ?? 'Selected by LLM classifier',\n alternatives: candidates.slice(0, maxCandidates).filter((c) => c.role !== choice.role),\n };\n }\n } catch {\n // Classifier failure must not break dispatch — fall through to fallback.\n }\n }\n\n // Best heuristic guess if we have one, else the generalist.\n if (top) {\n return {\n role: top.role,\n definition: catalog[top.role]!,\n confidence,\n method: 'heuristic',\n reason: `Weak match (${top.matched.slice(0, 3).join(', ') || 'low signal'})`,\n alternatives: candidates.slice(1, maxCandidates),\n };\n }\n const fallbackRole = catalog[DEFAULT_DISPATCH_ROLE]\n ? DEFAULT_DISPATCH_ROLE\n : Object.keys(catalog)[0]!;\n return {\n role: fallbackRole,\n definition: catalog[fallbackRole]!,\n confidence: 0,\n method: 'fallback',\n reason: 'No keyword signal; defaulting to the generalist Executor',\n alternatives: [],\n };\n}\n\n/**\n * Build a `DispatchClassifier` from a minimal `complete(prompt) => text`\n * function. The caller supplies the provider call; this owns the prompt and\n * the parsing. Keeps `dispatcher` free of any provider import.\n */\nexport function makeLLMClassifier(\n complete: (prompt: string) => Promise<string>,\n): DispatchClassifier {\n return async (task, candidates) => {\n const list = candidates.map((c, i) => `${i + 1}. ${c.role} — ${c.summary}`).join('\\n');\n const prompt = `You are an agent router. Pick the single best agent for the task.\n\nTask:\n${task}\n\nAgents:\n${list}\n\nReply with ONLY a compact JSON object: {\"role\":\"<one role id from the list>\",\"reason\":\"<short why>\"}.\nDo not add prose, markdown, or code fences.`;\n const raw = (await complete(prompt)).trim();\n // Tolerate accidental code fences / surrounding text — extract first {...}.\n const match = raw.match(/\\{[\\s\\S]*\\}/);\n if (!match) return null;\n try {\n const parsed = JSON.parse(match[0]) as { role?: unknown; reason?: unknown };\n if (typeof parsed.role !== 'string') return null;\n const role = parsed.role.trim();\n const valid = candidates.some((c) => c.role === role);\n if (!valid) return null;\n return { role, reason: typeof parsed.reason === 'string' ? parsed.reason : undefined };\n } catch {\n return null;\n }\n };\n}\n","import type { ContentBlock, TextBlock } from './blocks.js';\nimport type { ErrorCode } from './errors.js';\nimport { WrongStackError, ERROR_CODES } from './errors.js';\nimport type { Message } from './messages.js';\nimport type { Tool } from './tool.js';\n\n/**\n * Token usage for a single provider call, normalized across providers.\n *\n * Disjoint semantics: the four fields never overlap. `input` is the count\n * of FRESH input tokens (billed at the full input rate); `cacheRead` and\n * `cacheWrite` are separate cached subsets each priced at their own rate.\n * The total context the model loaded for this turn is\n * `input + (cacheRead ?? 0) + (cacheWrite ?? 0)`.\n *\n * Provider quirks normalized at the adapter layer:\n * - Anthropic: returns `input_tokens` already disjoint from cache fields.\n * - OpenAI / OpenAI-compatible: `prompt_tokens` is the TOTAL including\n * cached portion; the adapter subtracts `cached_tokens` to stay disjoint.\n * - Google: `promptTokenCount` likewise includes cache; adapter subtracts\n * `cachedContentTokenCount`.\n *\n * Cost math and the context-fullness chip both depend on the disjoint\n * invariant — a TOTAL `input` plus a separate `cacheRead` count would bill\n * cached tokens twice and skew cache-hit-ratio reporting.\n */\nexport interface Usage {\n input: number;\n output: number;\n cacheRead?: number;\n cacheWrite?: number;\n}\n\nexport interface Capabilities {\n tools: boolean;\n parallelTools: boolean;\n vision: boolean;\n streaming: boolean;\n promptCache: boolean;\n systemPrompt: boolean;\n jsonMode: boolean;\n reasoning: boolean;\n maxContext: number;\n cacheControl: 'native' | 'auto' | 'none';\n}\n\nexport interface Request {\n model: string;\n system?: TextBlock[];\n messages: Message[];\n tools?: Tool[];\n maxTokens: number;\n temperature?: number;\n topP?: number;\n stopSequences?: string[];\n toolChoice?: 'auto' | 'required' | 'none' | { type: 'tool'; name: string };\n}\n\nexport type StopReason = 'end_turn' | 'tool_use' | 'max_tokens' | 'stop_sequence' | 'refusal';\n\nexport interface Response {\n content: ContentBlock[];\n stopReason: StopReason;\n usage: Usage;\n model: string;\n}\n\nexport type StreamEvent =\n | { type: 'message_start'; model: string }\n | {\n type: 'content_block_start';\n kind: 'text' | 'tool_use' | 'thinking';\n id?: string;\n name?: string;\n }\n | { type: 'content_block_stop'; index: number }\n | { type: 'text_delta'; text: string }\n | { type: 'tool_use_start'; id: string; name: string }\n | { type: 'tool_use_input_delta'; id: string; partial: string }\n | { type: 'tool_use_stop'; id: string; input: unknown; providerMeta?: Record<string, unknown> }\n | { type: 'thinking_start'; providerMeta?: Record<string, unknown> }\n | { type: 'thinking_delta'; text: string }\n | { type: 'thinking_signature'; signature: string }\n | { type: 'thinking_stop' }\n | { type: 'message_stop'; stopReason: StopReason; usage: Usage };\n\nexport interface Provider {\n readonly id: string;\n readonly capabilities: Capabilities;\n /** Canonical streaming entry point. `complete()` defaults to a wrapper that\n * aggregates this stream — providers may override for non-streaming wires. */\n stream(req: Request, opts: { signal: AbortSignal }): AsyncIterable<StreamEvent>;\n complete(req: Request, opts: { signal: AbortSignal }): Promise<Response>;\n}\n\n/**\n * Structured body parsed from a provider's HTTP error response. Populated\n * best-effort: providers return JSON shaped differently (Anthropic uses\n * `{error: {type, message}}`, OpenAI uses `{error: {message, code}}`,\n * Google uses `{error: {status, message}}`), so the fields here are the\n * intersection that's usable for rendering and routing.\n */\nexport interface ProviderErrorBody {\n /** Provider-specific kind, e.g. \"overloaded_error\", \"rate_limit_error\", \"invalid_request_error\". */\n type?: string;\n /** Human-readable explanation from the provider. */\n message?: string;\n /** Provider request id, when present in the body or headers. */\n requestId?: string;\n /** Parsed Retry-After header (or equivalent body hint) in milliseconds. */\n retryAfterMs?: number;\n /** The raw response body (truncated to ~2 KB), kept for debugging. */\n raw?: string;\n /** True when `raw` was truncated; check `rawLength` for the original size. */\n truncated?: boolean;\n /** Original length of the response body in bytes, when `truncated` is true. */\n rawLength?: number;\n}\n\nexport class ProviderError extends WrongStackError {\n public readonly status: number;\n public readonly retryable: boolean;\n public readonly providerId: string;\n public readonly body?: ProviderErrorBody;\n\n constructor(\n message: string,\n status: number,\n retryable: boolean,\n providerId: string,\n opts: { body?: ProviderErrorBody; cause?: unknown } = {},\n ) {\n super({\n message,\n code: providerStatusToCode(status, opts.body?.type),\n subsystem: 'provider',\n severity: status >= 500 ? 'error' : 'warning',\n recoverable: retryable,\n context: { providerId, status },\n cause: opts.cause,\n });\n this.name = 'ProviderError';\n this.status = status;\n this.retryable = retryable;\n this.providerId = providerId;\n this.body = opts.body;\n }\n\n /**\n * Render a one-line, user-facing description. Designed for the CLI/TUI\n * status line and the agent's retry warning. Avoids dumping raw JSON\n * (which is what users see today when a 529 lands and the log message\n * includes the full `{\"type\":\"error\",...}` body).\n *\n * Examples:\n * \"minimax-coding-plan overloaded (529): High traffic detected. Upgrade for highspeed model. [req 06534785201de9c0…]\"\n * \"openai rate limited (429): Retry after 12s\"\n * \"anthropic invalid request (400): messages.0.role must be one of 'user'|'assistant'\"\n * \"groq HTTP 500 (server error)\"\n */\n override describe(): string {\n const kind = describeStatus(this.status, this.body?.type);\n const head = `${this.providerId} ${kind}`;\n const detail = this.body?.message?.trim();\n const reqId = this.body?.requestId\n ? ` [req ${this.body.requestId.slice(0, 16)}${this.body.requestId.length > 16 ? '…' : ''}]`\n : '';\n if (detail && detail.length > 0) {\n return `${head}: ${truncate(detail, 240)}${reqId}`;\n }\n return `${head}${reqId}`;\n }\n}\n\nfunction describeStatus(status: number, type?: string): string {\n if (status === 0) return 'network error';\n if (type === 'overloaded_error' || status === 529) return `overloaded (${status})`;\n if (type === 'rate_limit_error' || status === 429) return `rate limited (${status})`;\n if (type === 'authentication_error' || status === 401) return `auth failed (${status})`;\n if (type === 'permission_error' || status === 403) return `forbidden (${status})`;\n if (type === 'not_found_error' || status === 404) return `not found (${status})`;\n if (type === 'invalid_request_error' || status === 400) return `invalid request (${status})`;\n if (status === 408) return `timeout (${status})`;\n if (status >= 500 && status < 600) return `HTTP ${status} (server error)`;\n if (type) return `${type} (${status})`;\n return `HTTP ${status}`;\n}\n\nfunction truncate(s: string, n: number): string {\n return s.length <= n ? s : `${s.slice(0, n - 1)}…`;\n}\n\nfunction providerStatusToCode(status: number, type?: string): ErrorCode {\n if (status === 0) return ERROR_CODES.PROVIDER_NETWORK_ERROR;\n if (type === 'rate_limit_error' || status === 429) return ERROR_CODES.PROVIDER_RATE_LIMITED;\n if (type === 'authentication_error' || status === 401) return ERROR_CODES.PROVIDER_AUTH_FAILED;\n if (type === 'overloaded_error' || status === 529) return ERROR_CODES.PROVIDER_OVERLOADED;\n if (type === 'invalid_request_error' || status === 400) return ERROR_CODES.PROVIDER_INVALID_REQUEST;\n if (status === 408) return ERROR_CODES.PROVIDER_NETWORK_ERROR;\n if (status >= 500) return ERROR_CODES.PROVIDER_SERVER_ERROR;\n return ERROR_CODES.PROVIDER_INVALID_REQUEST;\n}\n","/**\r\n * Pre-built subagent role configurations for the WrongStack fleet.\r\n * These can be passed to `MultiAgentHost.spawn()` or used as templates\r\n * for the director's roster.\r\n */\r\nimport type { SubagentConfig } from '../types/multi-agent.js';\r\nimport { ALL_AGENT_DEFINITIONS } from './agents/index.js';\r\n\r\n/**\r\n * Audit Log Agent — analyzes session logs, event streams, and traces.\r\n * Use for: post-mortems, trend analysis, operational insights.\r\n */\r\nexport const AUDIT_LOG_AGENT: SubagentConfig = {\r\n id: 'audit-log',\r\n name: 'Audit Log',\r\n role: 'audit-log',\r\n prompt: `You are the Audit Log agent. Your job is to analyze structured JSONL\r\nsession logs and produce actionable markdown reports.\r\n\r\nScope:\r\n- Parse session logs (iteration counts, tool calls, errors, usage)\r\n- Detect repeated failure patterns across multiple runs\r\n- Identify tool usage anomalies (over-use, failures, unexpected chains)\r\n- Track token consumption trends\r\n- Generate structured audit reports with severity ratings\r\n\r\nInput format you accept:\r\n{ \"task\": \"analyze | report | trends\", \"sessionPath\": \"<path>\", \"focus\": \"errors | tools | usage | all\" }\r\n\r\nOutput: Markdown audit report with sections:\r\n- ## Summary (totals, error rate)\r\n- ## Top Errors (count + context)\r\n- ## Tool Usage (table with calls, failures, avg duration)\r\n- ## Anomalies (pattern → severity)\r\n\r\nWorking rules:\r\n- Never fabricate numbers — read the actual logs first\r\n- Always include file:line references for errors\r\n- If sessionPath is missing, ask the director to provide it\r\n- Report confidence level: high (>90% accuracy), medium, low`,\r\n\r\n // No hardcoded budgets — the orchestrator (delegate tool or\r\n // spawn_subagent) decides per-task how much room a subagent gets.\r\n // A monorepo audit needs hours; a single-file lint check needs\r\n // seconds. Pinning a number here forces the orchestrator to fight\r\n // the role's default instead of just asking for what it needs.\r\n};\r\n\r\n/**\r\n * Bug Hunter Agent — systematic bug and code smell detection.\r\n * Use for: pre-refactoring health checks, code review, regression prevention.\r\n */\r\nexport const BUG_HUNTER_AGENT: SubagentConfig = {\r\n id: 'bug-hunter',\r\n name: 'Bug Hunter',\r\n role: 'bug-hunter',\r\n prompt: `You are the Bug Hunter agent. Your job is to systematically scan\r\nsource code for bugs, anti-patterns, and code smells using pattern matching\r\nand heuristics. Output a prioritized hit list with file:line references.\r\n\r\nScope:\r\n- Detect common bug patterns (uncaught errors, resource leaks, race conditions)\r\n- Identify anti-patterns (callback hell, God objects, circular deps)\r\n- Find TypeScript-specific issues (unsafe any, missing null checks, branded types)\r\n- Flag security-sensitive constructs (eval, innerHTML, hardcoded secrets)\r\n- Rank findings: critical > high > medium > low\r\n\r\nInput format you accept:\r\n{ \"task\": \"scan | hunt | check\", \"paths\": [\"src/**/*.ts\"], \"focus\": \"bugs | patterns | security | all\", \"severityThreshold\": \"medium\" }\r\n\r\nOutput: Markdown bug hunt report:\r\n- ## Critical (must fix first)\r\n- ## High (should fix)\r\n- ## Medium\r\n- ## Low (consider)\r\nEach entry: **[TYPE]** \\`file:line\\` — description + suggested fix\r\n\r\nBug pattern reference you know:\r\n| Pattern | Regex hint | Severity |\r\n|---------|------------|----------|\r\n| Uncaught promise | /\\.then\\\\(.*\\\\)/ without catch | high |\r\n| Event leak | on\\\\( without off/removeListener | high |\r\n| Hardcoded secret | [a-zA-Z0-9/_-]{20,} in config files | critical |\r\n| unsafe any | : any\\\\b or <any> | medium |\r\n| innerHTML | innerHTML\\\\s*= | high |\r\n\r\nWorking rules:\r\n- Never scan node_modules — it's noise\r\n- Always include file:line for every finding\r\n- If >30% of findings are false positives, note the confidence level\r\n- Ask director for clarification if paths are ambiguous`,\r\n\r\n // Budgets are set by the orchestrator per task — see fleet.ts header.\r\n};\r\n\r\n/**\r\n * Refactor Planner Agent — structured refactoring planning.\r\n * Use for: large rewrites, technical debt reduction, architecture improvements.\r\n */\r\nexport const REFACTOR_PLANNER_AGENT: SubagentConfig = {\r\n id: 'refactor-planner',\r\n name: 'Refactor Planner',\r\n role: 'refactor-planner',\r\n prompt: `You are the Refactor Planner agent. Your job is to analyze code\r\nstructure and produce a concrete, phased refactoring plan with risk\r\nassessment, dependency ordering, and rollback strategy.\r\n\r\nScope:\r\n- Map module-level dependencies (import graph)\r\n- Identify coupling hotspots (high fan-in/out modules)\r\n- Assess refactoring risk by complexity and test coverage\r\n- Generate phased plans with checkpoint milestones\r\n- Produce diff-friendly task lists (one task = one concern)\r\n\r\nInput format you accept:\r\n{ \"task\": \"plan | assess | roadmap\", \"target\": \"src/core\", \"constraint\": \"no-breaking-changes | minimal-downtime | full-rewrite\", \"focus\": \"architecture | performance | maintainability\" }\r\n\r\nOutput: Markdown refactor plan:\r\n- ## Phase 1: Low Risk / High Payoff (do first)\r\n Table: | # | Task | Module | Risk | Est. Time |\r\n- ## Phase 2: Medium Risk\r\n- ## Phase 3: High Risk (requires full regression)\r\n- ## Dependency Graph (abbreviated ASCII)\r\n- ## Rollback Strategy\r\n- ## Exit Criteria (checkbox list)\r\n\r\nRisk scoring criteria:\r\n| Factor | Low | Medium | High |\r\n|--------|-----|--------|------|\r\n| Cyclomatic complexity | <10 | 10-20 | >20 |\r\n| Test coverage | >80% | 50-80% | <50% |\r\n| Fan-out (imports) | <5 | 5-15 | >15 |\r\n\r\nWorking rules:\r\n- Always include rollback strategy — every refactor can fail\r\n- Merge tasks that take <1h into a single phase\r\n- Respect team constraints (reviewer availability, parallelization)\r\n- Never plan without analyzing the actual code first`,\r\n\r\n // Budgets are set by the orchestrator per task — see fleet.ts header.\r\n};\r\n\r\n/**\r\n * Security Scanner Agent — vulnerability and secret detection.\r\n * Use for: CI checks, pre-release audits, dependency vulnerability scanning.\r\n */\r\nexport const SECURITY_SCANNER_AGENT: SubagentConfig = {\r\n id: 'security-scanner',\r\n name: 'Security Scanner',\r\n role: 'security-scanner',\r\n prompt: `You are the Security Scanner agent. Your job is to scan code,\r\nconfigs, and dependencies for security issues from hardcoded secrets to\r\nsupply chain risks.\r\n\r\nScope:\r\n- Detect hardcoded secrets: API keys, tokens, passwords, private keys\r\n- Find injection vectors: eval, innerHTML, SQL concat, shell injection\r\n- Identify insecure patterns: weak crypto, hardcoded IVs, disabled TLS\r\n- Scan dependencies for known CVEs (via npm/pnpm audit)\r\n- Flag supply chain risks: postinstall hooks, unverified scripts, .npmrc\r\n\r\nInput format you accept:\r\n{ \"task\": \"scan | audit | secrets | dependencies\", \"paths\": [\"src\", \"config\"], \"depth\": \"quick | normal | deep\" }\r\n\r\nOutput: Markdown security report:\r\n- ## CRITICAL: Secrets Found (with code snippets)\r\n- ## HIGH: Injection Vectors\r\n- ## MEDIUM: Insecure Patterns\r\n- ## Dependency Issues (CVE list)\r\n- ## Summary table (severity → count)\r\n- ## Remediation Checklist (with checkboxes)\r\n\r\nSecret patterns you detect:\r\n| Pattern | Example | Severity |\r\n|---------|---------|----------|\r\n| AWS Access Key | AKIAIOSFODNN7EXAMPLE | critical |\r\n| AWS Secret Key | [a-zA-Z0-9/+=]{40} base64 | critical |\r\n| GitHub Token | ghp_[a-zA-Z0-9]{36} | critical |\r\n| Private Key PEM | -----BEGIN.*PRIVATE KEY----- | critical |\r\n| JWT | eyJ[a-zA-Z0-9_-]+ | high |\r\n\r\nInjection patterns:\r\n| Construct | Safe alternative |\r\n|-----------|-----------------|\r\n| eval(str) | new Function() or parse |\r\n| innerHTML = x | textContent or sanitize |\r\n| exec(\\`cmd \\${x}\\`) | execFile with args array |\r\n\r\nWorking rules:\r\n- Never scan node_modules — use npm audit instead\r\n- Always provide remediation steps, not just findings\r\n- Verify regex-based secrets before flagging (false positive risk)\r\n- When in doubt, flag as medium rather than ignoring potential issues`,\r\n\r\n // Budgets are set by the orchestrator per task — see fleet.ts header.\r\n};\r\n\r\n/**\r\n * Critic Agent — evaluates code quality, architecture decisions, and\r\n * refactoring plans against project conventions and engineering standards.\r\n * Use for: real-time evaluation of bug reports, refactor plans, and\r\n * architectural proposals during collaborative debugging sessions.\r\n */\r\nexport const CRITIC_AGENT: SubagentConfig = {\r\n id: 'critic',\r\n name: 'Critic',\r\n role: 'critic',\r\n prompt: `You are the Critic agent. Your job is to evaluate code quality,\r\narchitectural decisions, and proposed changes against project conventions,\r\nengineering standards, and known quality gates. You do not write code —\r\nyou judge it.\r\n\r\nScope:\r\n- Evaluate bug severity and fix quality from Bug Hunter reports\r\n- Score refactoring plans from Refactor Planner (risk, completeness, trade-offs)\r\n- Flag gaps in test coverage, error handling, and edge case coverage\r\n- Assess whether a proposed change aligns with existing project patterns\r\n- Detect over-engineering or under-engineering relative to the problem scope\r\n\r\nInput format you accept:\r\n{ \"task\": \"evaluate | score | review\", \"subject\": \"bug_report | refactor_plan | diff\", \"focus\": \"correctness | maintainability | risk | all\" }\r\n\r\nOutput: Markdown critic report:\r\n- ## Overall Score (0-10 with rationale)\r\n- ## Strengths (what's solid)\r\n- ## Weaknesses (what needs work)\r\n- ## Specific Concerns (with file:line when applicable)\r\n- ## Verdict: **Approve / Needs Revision / Reject**\r\n\r\nWorking rules:\r\n- Be specific — \"looks fine\" is not a review. Cite concrete evidence.\r\n- When scoring, explain the delta from a perfect score.\r\n- If you have no basis to evaluate a concern, say so rather than speculating.\r\n- Prioritise correctness over style; correctness issues block approval.\r\n- Score thresholds: ≥7 = Approve, 4-6 = Needs Revision, <4 = Reject`,\r\n\r\n // Budgets are set by the orchestrator per task — see fleet.ts header.\r\n};\r\n\r\n/**\r\n * All agents in a map for easy lookup by role. The four legacy pre-built\r\n * agents plus the phase 1-9 catalog (`ALL_AGENT_DEFINITIONS`). Catalog roles\r\n * are guaranteed collision-free by the catalog builder; none overlap the\r\n * legacy four.\r\n */\r\nexport const FLEET_ROSTER: Record<string, SubagentConfig> = {\r\n 'audit-log': AUDIT_LOG_AGENT,\r\n 'bug-hunter': BUG_HUNTER_AGENT,\r\n 'refactor-planner': REFACTOR_PLANNER_AGENT,\r\n 'security-scanner': SECURITY_SCANNER_AGENT,\r\n 'critic': CRITIC_AGENT,\r\n ...Object.fromEntries(\r\n ALL_AGENT_DEFINITIONS.map((d) => [d.config.role as string, d.config] as const),\r\n ),\r\n};\r\n\r\n// ---------------------------------------------------------------------------\r\n// Default per-role budgets.\r\n//\r\n// MASSIVELY RAISED from earlier values. User requested x5–x10 multiplier\r\n// to prevent any timeout or budget exhaustion on long-running tasks\r\n// like monorepo audits, deep refactors, and security scans.\r\n//\r\n// x10 values (realistic upper bound for a single subagent task):\r\n// audit-log: 7.5 hours, 5000 iterations, 15000 tool calls\r\n// bug-hunter: 10 hours, 8000 iterations, 20000 tool calls\r\n// refactor-planner: 7.5 hours, 6000 iterations, 18000 tool calls\r\n// security-scanner: 10 hours, 8000 iterations, 20000 tool calls\r\n//\r\n// These can be overridden per-call via delegate tool parameters.\r\n// ---------------------------------------------------------------------------\r\nexport interface FleetRosterBudget {\r\n timeoutMs?: number;\r\n /** Idle reap window (ms). Resets on activity — see `applyRosterBudget`. */\r\n idleTimeoutMs?: number;\r\n maxIterations?: number;\r\n maxToolCalls?: number;\r\n maxTokens?: number;\r\n maxCostUsd?: number;\r\n}\r\n\r\n/**\r\n * Default idle window for delegated subagents: reap only after this long with\r\n * NO activity (no iteration / tool call / streamed progress). An actively-\r\n * working agent resets this clock continuously, so it runs until its task\r\n * naturally ends — no more wall-clock kills of productive runs. Power users\r\n * can still impose a hard `timeoutMs` per delegate.\r\n */\r\nexport const DEFAULT_IDLE_TIMEOUT_MS = 15 * 60 * 1000;\r\n\r\nexport const FLEET_ROSTER_BUDGETS: Record<string, FleetRosterBudget> = {\r\n 'audit-log': { timeoutMs: 7.5 * 60 * 60 * 1000, maxIterations: 5000, maxToolCalls: 15000 },\r\n 'bug-hunter': { timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000 },\r\n 'refactor-planner': { timeoutMs: 7.5 * 60 * 60 * 1000, maxIterations: 6000, maxToolCalls: 18000 },\r\n 'security-scanner': { timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000 },\r\n 'critic': { timeoutMs: 5 * 60 * 60 * 1000, maxIterations: 4000, maxToolCalls: 12000 },\r\n ...Object.fromEntries(\r\n ALL_AGENT_DEFINITIONS.map((d) => [d.config.role as string, d.budget] as const),\r\n ),\r\n};\r\n\r\n/**\r\n * Apply roster budget to a config (only when the config has no explicit\r\n * budget fields set). This is called by the coordinator before dispatch.\r\n */\r\n// Generic default budget applied when no role matches and no explicit budget\r\n// fields are set. Used for `name` / free-form delegates. There is no default\r\n// wall-clock timeout — a delegated agent runs until its task naturally ends\r\n// (`end_turn`) or it stalls past the idle window. Iteration / tool-call ceilings\r\n// remain as a runaway backstop.\r\nconst GENERIC_SUBAGENT_BUDGET: FleetRosterBudget = {\r\n idleTimeoutMs: DEFAULT_IDLE_TIMEOUT_MS,\r\n maxIterations: 5000,\r\n maxToolCalls: 15000,\r\n};\r\n\r\nexport function applyRosterBudget(cfg: SubagentConfig): SubagentConfig {\r\n // First try role-specific budget; fall back to generic for name-only delegates.\r\n const roleBudget = cfg.role ? FLEET_ROSTER_BUDGETS[cfg.role] : undefined;\r\n const defaultBudget = roleBudget ?? (cfg.name ? GENERIC_SUBAGENT_BUDGET : undefined);\r\n if (!defaultBudget) return cfg;\r\n return {\r\n ...cfg,\r\n // Wall-clock cap is opt-in only: forward an explicit `cfg.timeoutMs`, but\r\n // do NOT impose the roster's historical multi-hour wall-clock default — it\r\n // killed agents that were still actively working. Reaping is idle-based.\r\n timeoutMs: cfg.timeoutMs,\r\n // Idle window is the default reaper. Resets on activity, so a long-but-\r\n // productive run is never killed; only a genuine stall is reaped.\r\n idleTimeoutMs: cfg.idleTimeoutMs ?? defaultBudget.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS,\r\n maxIterations: cfg.maxIterations ?? defaultBudget.maxIterations,\r\n maxToolCalls: cfg.maxToolCalls ?? defaultBudget.maxToolCalls,\r\n maxTokens: cfg.maxTokens ?? defaultBudget.maxTokens,\r\n maxCostUsd: cfg.maxCostUsd ?? defaultBudget.maxCostUsd,\r\n };\r\n}\r\n\r\n/** Quick-access list for spawning all at once. */\r\nexport const ALL_FLEET_AGENTS = Object.values(FLEET_ROSTER);\r\n\r\n// ---------------------------------------------------------------------------\r\n// ACP external agents — WrongStack spawns these as subagents via ACP protocol.\r\n// Each agent runs its own loop; WrongStack sends tasks as ACP messages and\r\n// receives results. These don't go through makeAgentSubagentRunner — they\r\n// are handled by makeACPSubagentRunner in the CLI multi-agent layer.\r\n// ---------------------------------------------------------------------------\r\n\r\n/**\r\n * Cline — ACP-compatible coding agent by @asonix.\r\n * Spawned as: `npx @agentify/cline`\r\n */\r\nexport const CLINE_AGENT: SubagentConfig = {\r\n id: 'cline',\r\n name: 'Cline',\r\n role: 'cline',\r\n prompt: `You are Cline, a coding agent. You help write, edit, and navigate code.\r\nYou operate by receiving tasks via ACP and returning results.\r\nWhen asked to code, make focused changes and explain them briefly.`,\r\n provider: 'acp',\r\n};\r\n\r\n/**\r\n * Gemini CLI — Google's ACP-compatible command-line agent.\r\n * Spawned as: `gemini` (when gemini CLI is installed and in PATH)\r\n */\r\nexport const GEMINI_CLI_AGENT: SubagentConfig = {\r\n id: 'gemini-cli',\r\n name: 'Gemini CLI',\r\n role: 'gemini-cli',\r\n prompt: `You are Gemini CLI, a coding agent powered by Google's Gemini model.\r\nYou help with code generation, editing, debugging, and best practices.\r\nYou operate by receiving tasks via ACP and returning results.`,\r\n provider: 'acp',\r\n};\r\n\r\n/**\r\n * GitHub Copilot (public preview) — ACP-compatible Copilot CLI agent.\r\n * Spawned as: `gh copilot` (when gh CLI with copilot extension is installed)\r\n */\r\nexport const COPILOT_AGENT: SubagentConfig = {\r\n id: 'copilot',\r\n name: 'GitHub Copilot',\r\n role: 'copilot',\r\n prompt: `You are GitHub Copilot, an AI coding assistant.\r\nYou help write, explain, refactor, and review code.\r\nYou operate by receiving tasks via ACP and returning results.`,\r\n provider: 'acp',\r\n};\r\n\r\n/**\r\n * OpenHands — AI coding agent by all-in.ai, ACP-compatible.\r\n * Spawned as: `openhands` (when installed)\r\n */\r\nexport const OPENHANDS_AGENT: SubagentConfig = {\r\n id: 'openhands',\r\n name: 'OpenHands',\r\n role: 'openhands',\r\n prompt: `You are OpenHands, an AI coding agent that can use tools to interact\r\nwith files, terminals, browsers, and other resources.\r\nYou operate by receiving tasks via ACP and returning results.`,\r\n provider: 'acp',\r\n};\r\n\r\n/**\r\n * Goose — IDE agent by ExoRL, ACP-compatible.\r\n * Spawned as: `goose` (when goose CLI is installed)\r\n */\r\nexport const GOOSE_AGENT: SubagentConfig = {\r\n id: 'goose',\r\n name: 'Goose',\r\n role: 'goose',\r\n prompt: `You are Goose, an AI agent that helps with coding tasks.\r\nYou operate by receiving tasks via ACP and returning results.\r\nFocus on writing high-quality, well-tested code.`,\r\n provider: 'acp',\r\n};\r\n\r\n/** All ACP external agents. */\r\nexport const ACP_AGENTS: SubagentConfig[] = [\r\n CLINE_AGENT,\r\n GEMINI_CLI_AGENT,\r\n COPILOT_AGENT,\r\n OPENHANDS_AGENT,\r\n GOOSE_AGENT,\r\n];\r\n\r\n// ACP agents share the same generous budgets as the built-in fleet agents.\r\n// External ACP agents may need more time than typical in-process subagents\r\n// since they run their own loops and may do tool-call round-trips.\r\nFLEET_ROSTER_BUDGETS['cline'] = {timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000};\r\nFLEET_ROSTER_BUDGETS['gemini-cli'] = {timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000};\r\nFLEET_ROSTER_BUDGETS['copilot'] = {timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000};\r\nFLEET_ROSTER_BUDGETS['openhands'] = {timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000};\r\nFLEET_ROSTER_BUDGETS['goose'] = {timeoutMs: 10 * 60 * 60 * 1000, maxIterations: 8000, maxToolCalls: 20000};\r\n\r\n/** Extended roster including ACP agents. */\r\nexport const FLEET_ROSTER_WITHACP: Record<string, SubagentConfig> = {\r\n ...FLEET_ROSTER,\r\n ...Object.fromEntries(ACP_AGENTS.map((a) => [a.role as string, a])),\r\n};\r\n","/**\n * Subagent nickname pool — famous scientists, mathematicians, and computing pioneers.\n * Names are grouped by domain affinity so the nickname hints at the agent's role.\n */\n\nconst NICKNAME_POOL = {\n // Physics & fundamental sciences\n 'einstein': { name: 'Einstein', domain: 'physics' },\n 'newton': { name: 'Newton', domain: 'physics' },\n 'feynman': { name: 'Feynman', domain: 'physics' },\n 'dirac': { name: 'Dirac', domain: 'physics' },\n 'bohr': { name: 'Bohr', domain: 'physics' },\n 'planck': { name: 'Planck', domain: 'physics' },\n 'curie': { name: 'Curie', domain: 'physics' },\n 'fermi': { name: 'Fermi', domain: 'physics' },\n 'heisenberg': { name: 'Heisenberg', domain: 'physics' },\n 'schrodinger': { name: 'Schrödinger', domain: 'physics' },\n\n // Mathematics\n 'euclid': { name: 'Euclid', domain: 'math' },\n 'gauss': { name: 'Gauss', domain: 'math' },\n 'turing': { name: 'Turing', domain: 'math' },\n 'poincare': { name: 'Poincaré', domain: 'math' },\n 'riemann': { name: 'Riemann', domain: 'math' },\n 'hilbert': { name: 'Hilbert', domain: 'math' },\n 'pythagoras': { name: 'Pythagoras', domain: 'math' },\n\n // Computing & information theory\n 'von-neumann': { name: 'Von Neumann', domain: 'computing' },\n 'shannon': { name: 'Shannon', domain: 'computing' },\n 'hopper': { name: 'Hopper', domain: 'computing' },\n 'backus': { name: 'Backus', domain: 'computing' },\n 'knuth': { name: 'Knuth', domain: 'computing' },\n 'torvalds': { name: 'Torvalds', domain: 'computing' },\n 'stallman': { name: 'Stallman', domain: 'computing' },\n 'berners-lee': { name: 'Berners-Lee', domain: 'computing' },\n 'babbage': { name: 'Babbage', domain: 'computing' },\n 'lovelace': { name: 'Lovelace', domain: 'computing' },\n 'klein': { name: 'Klein', domain: 'computing' },\n\n // Electronics & electrical engineering\n 'edison': { name: 'Edison', domain: 'ee' },\n 'tesla': { name: 'Tesla', domain: 'ee' },\n 'faraday': { name: 'Faraday', domain: 'ee' },\n 'maxwell': { name: 'Maxwell', domain: 'ee' },\n 'ohm': { name: 'Ohm', domain: 'ee' },\n 'bell': { name: 'Bell', domain: 'ee' },\n 'marconi': { name: 'Marconi', domain: 'ee' },\n 'lamarr': { name: 'Lamarr', domain: 'ee' },\n\n // General science / multi-disciplinary\n 'darwin': { name: 'Darwin', domain: 'biology' },\n 'mendel': { name: 'Mendel', domain: 'biology' },\n 'pasteur': { name: 'Pasteur', domain: 'biology' },\n 'hawking': { name: 'Hawking', domain: 'cosmology' },\n 'sagan': { name: 'Sagan', domain: 'cosmology' },\n\n // Exploration & navigation\n 'columbus': { name: 'Columbus', domain: 'exploration' },\n 'polo': { name: 'Polo', domain: 'exploration' },\n 'magellan': { name: 'Magellan', domain: 'exploration' },\n\n // Chemistry / materials\n 'lavoisier': { name: 'Lavoisier', domain: 'chemistry' },\n 'mendeleev': { name: 'Mendeleev', domain: 'chemistry' },\n} as const;\n\n/** Flat ordered list of all available nicknames — used for round-robin. */\nconst ALL_NICKNAMES = Object.values(NICKNAME_POOL);\n\n/** Domain → preferred nickname keys (fallback chain). */\nconst DOMAIN_PREFERENCES: Record<string, string[]> = {\n 'security': ['shannon', 'turing', 'lamarr', 'stallman'],\n 'bug-hunter': ['darwin', 'curie', 'feynman', 'fermi'],\n 'refactor': ['gauss', 'hilbert', 'euclid', 'planck'],\n 'audit-log': ['sagan', 'hawking', 'poincare', 'newton'],\n 'planner': ['hilbert', 'gauss', 'turing', 'euclid'],\n 'researcher': ['sagan', 'hawking', 'darwin', 'pasteur'],\n 'explorer': ['marconi', 'bell', 'columbus', 'polo'],\n 'testing': ['pasteur', 'curie', 'fermi', 'bohr'],\n 'frontend': ['lovelace', 'hopper', 'babbage', 'backus'],\n 'backend': ['torvalds', 'stallman', 'von-neumann', 'backus'],\n 'database': ['turing', 'shannon', 'backus', 'knuth'],\n 'devops': ['tesla', 'edison', 'faraday', 'bell'],\n 'security-scanner': ['shannon', 'turing', 'lamarr', 'stallman'],\n 'refactor-planner': ['gauss', 'hilbert', 'planck', 'newton'],\n 'architect': ['von-neumann', 'turing', 'gauss', 'hilbert'],\n 'critic': ['einstein', 'feynman', 'dirac', 'bohr'],\n 'e2e': ['hopper', 'bell', 'marconi', 'tesla'],\n 'performance': ['knuth', 'gauss', 'planck', 'feynman'],\n 'chaos': ['tesla', 'edison', 'curie', 'fermi'],\n 'cost': ['ohm', 'bell', 'marconi', 'tesla'],\n // default fallback\n 'default': ['einstein', 'newton', 'curie', 'tesla', 'edison', 'turing', 'shannon', 'hopper', 'knuth', 'stallman'],\n};\n\ntype NicknameKey = keyof typeof NICKNAME_POOL;\n\n/**\n * Assign a unique nickname to a subagent based on its role.\n * Returns `Name (Role)` formatted string, e.g. `Einstein (Bug Hunter)`.\n *\n * @param role - The subagent's role id (e.g. 'bug-hunter', 'security-scanner')\n * @param used - Set of nickname keys already assigned in this fleet\n * (so no two subagents share the same base name)\n */\nexport function assignNickname(role: string, used: ReadonlySet<string>): string {\n // 1. Build preference list: role-specific → default fallback\n const preferences = [\n ...(DOMAIN_PREFERENCES[role] ?? []),\n ...(DOMAIN_PREFERENCES['default'] ?? []),\n ];\n\n // 2. Find the first unassigned nickname from preferences. Skip keys that are\n // not in the pool — preference lists can drift out of sync with the pool\n // (typos, removed names), and an unknown key must not crash assignment.\n for (const key of preferences) {\n const entry = NICKNAME_POOL[key as NicknameKey];\n if (entry && !used.has(key)) {\n return `${entry.name} (${formatRole(role)})`;\n }\n }\n\n // 3. Exhausted preferences — pick the first unused name round-robin style\n for (const entry of ALL_NICKNAMES) {\n const key = Object.entries(NICKNAME_POOL).find(([, v]) => v.name === entry.name)?.[0];\n if (key && !used.has(key)) {\n return `${entry.name} (${formatRole(role)})`;\n }\n }\n\n // 4. Pool exhausted — append counter to last resort\n const counter = used.size + 1;\n return `Scientist #${counter} (${formatRole(role)})`;\n}\n\n/** Format role id into human-readable title-case. */\nfunction formatRole(role: string): string {\n return role\n .split(/[-_]/)\n .map((w) => w.charAt(0).toUpperCase() + w.slice(1))\n .join(' ');\n}\n\n/**\n * Returns all available nickname keys. Useful for testing or reset logic.\n */\nexport function getAllNicknameKeys(): string[] {\n return Object.keys(NICKNAME_POOL);\n}","import { randomUUID } from 'node:crypto';\r\nimport { EventEmitter } from 'node:events';\r\nimport type { AgentBridge, BridgeMessage } from '../types/agent-bridge.js';\r\nimport type {\r\n CoordinatorStatus,\r\n MultiAgentConfig,\r\n MultiAgentCoordinator,\r\n SpawnResult,\r\n SubagentConfig,\r\n SubagentContext,\r\n SubagentError,\r\n SubagentErrorKind,\r\n SubagentRunContext,\r\n SubagentRunner,\r\n TaskResult,\r\n TaskSpec,\r\n} from '../types/multi-agent.js';\r\nimport { ProviderError } from '../types/provider.js';\r\nimport { BudgetExceededError, SubagentBudget } from './subagent-budget.js';\r\nimport { applyRosterBudget } from './fleet.js';\r\nimport { assignNickname } from './subagent-nicknames.js';\r\n\r\ntype SubagentStatus = 'running' | 'idle' | 'stopped' | 'error';\r\n\r\ninterface SubagentEntry {\r\n config: SubagentConfig;\r\n context: SubagentContext;\r\n status: SubagentStatus;\r\n currentTask?: string;\r\n abortController: AbortController;\r\n /** Lazily created on first dispatch — budget is per-task, not per-subagent. */\r\n activeBudget?: SubagentBudget;\r\n}\r\n\r\nexport interface MultiAgentCoordinatorOptions {\r\n /**\r\n * Callback that executes a task on behalf of a subagent. Required for\r\n * `assign()` to actually run anything — without it, tasks queue forever.\r\n * The coordinator provides per-subagent isolation (own budget, own signal,\r\n * own bridge) and enforces timeout + concurrency.\r\n */\r\n runner?: SubagentRunner;\r\n}\r\n\r\nexport class DefaultMultiAgentCoordinator extends EventEmitter implements MultiAgentCoordinator {\r\n readonly coordinatorId: string;\r\n readonly config: MultiAgentConfig;\r\n private runner?: SubagentRunner;\r\n private fleetBus?: import('./fleet-bus.js').FleetBus;\r\n\r\n private readonly subagents = new Map<string, SubagentEntry>();\r\n\r\n /**\r\n * Base nickname keys already handed out this run (e.g. `einstein`, `tesla`).\r\n * Prevents two workers sharing a name. Direct `coordinator.spawn()` callers\r\n * (parallel/eternal engine, SDD parallel run) don't go through\r\n * `Director.spawn()` where nicknames are normally assigned, so the\r\n * coordinator upgrades placeholder names (\"Executor\", \"slot-ab12cd\", role\r\n * names) to memorable ones here — that's what surfaces in the fleet monitor.\r\n */\r\n private readonly usedNicknames = new Set<string>();\r\n /** Maps subagentId → nickname key (e.g. 'einstein'). Used to free the slot on remove(). */\r\n private readonly subagentNicknames = new Map<string, string>();\r\n\r\n private pendingTasks: TaskSpec[] = [];\r\n private completedResults: TaskResult[] = [];\r\n /** Prevents completedResults from growing unbounded in long-running coordinators. */\r\n private static readonly MAX_COMPLETED_RESULTS = 10_000;\r\n private totalIterations = 0;\r\n private inFlight = 0;\r\n /**\r\n * Subagents currently being stopped. Set on entry to `stop()`, cleared\r\n * once `recordCompletion` lands the terminal TaskResult. Used by\r\n * `runDispatched` and `findIdleSubagent` to refuse mid-flight dispatch\r\n * to a subagent the caller has already asked to terminate — closes the\r\n * assign+terminate race where a fresh task could land on a worker that\r\n * was about to be killed.\r\n */\r\n private readonly terminating = new Set<string>();\r\n\r\n constructor(config: MultiAgentConfig, options: MultiAgentCoordinatorOptions = {}) {\r\n super();\r\n this.coordinatorId = config.coordinatorId;\r\n this.config = config;\r\n this.runner = options.runner;\r\n }\r\n\r\n /**\r\n * Replace the runner after construction. Used when the runner depends\r\n * on infrastructure (e.g. FleetBus) that isn't available until after\r\n * the coordinator's owning Director is built.\r\n */\r\n setRunner(runner: SubagentRunner): void {\r\n this.runner = runner;\r\n }\r\n\r\n /**\r\n * Wire a FleetBus for director-mode event emission. Call after the\r\n * FleetManager is constructed so the coordinator can emit lifecycle\r\n * events the TUI and monitoring tools subscribe to.\r\n */\r\n setFleetBus(fleet: import('./fleet-bus.js').FleetBus): void {\r\n this.fleetBus = fleet;\r\n }\r\n\r\n /**\r\n * Change the in-flight dispatch ceiling at runtime. Lowering does NOT\r\n * preempt running tasks — already-dispatched subagents finish their\r\n * current task; only future dispatches respect the new cap. Raising\r\n * immediately tries to fill the freed slots from the pending queue.\r\n */\r\n setMaxConcurrent(n: number): void {\r\n if (!Number.isFinite(n) || n < 1) {\r\n throw new Error(`maxConcurrent must be a finite integer >= 1, got ${n}`);\r\n }\r\n this.config.maxConcurrent = Math.floor(n);\r\n this.tryDispatchNext();\r\n }\r\n\r\n /**\r\n * Upgrade a placeholder/role-derived name to a memorable scientist nickname\r\n * (e.g. \"Einstein (Executor)\"). A name is treated as a placeholder when it is\r\n * empty, equals the role (case-insensitive), is a generic default\r\n * (\"subagent\"/\"adhoc\"/\"generic\"), or is an auto-generated `slot-…` id.\r\n * Explicit, human-chosen names — including nicknames already assigned by\r\n * `Director.spawn()` — are left untouched, so this never double-assigns.\r\n */\r\n private withNickname(subagent: SubagentConfig, subagentId: string): SubagentConfig {\r\n const role = subagent.role ?? 'subagent';\r\n const name = subagent.name?.trim() ?? '';\r\n const isPlaceholder =\r\n name === '' ||\r\n name.toLowerCase() === role.toLowerCase() ||\r\n name === 'subagent' ||\r\n name === 'adhoc' ||\r\n name === 'generic' ||\r\n /^slot-/.test(name);\r\n if (!isPlaceholder) return subagent;\r\n const nickname = assignNickname(role, this.usedNicknames);\r\n const baseKey = nickname.split(' ')[0]!.toLowerCase().replace(/[^a-z0-9-]/g, '-');\r\n this.usedNicknames.add(baseKey);\r\n this.subagentNicknames.set(subagentId, baseKey);\r\n return { ...subagent, name: nickname };\r\n }\r\n\r\n async spawn(subagent: SubagentConfig): Promise<SpawnResult> {\r\n const id = subagent.id || randomUUID();\r\n subagent = this.withNickname(subagent, id);\r\n // Duplicate-id guard. Previously a second spawn({id}) with the\r\n // same id silently overwrote the existing entry — orphaning the\r\n // first subagent's AbortController, Context, and any in-flight\r\n // task referencing it. Two spawns with the same id are almost\r\n // always a bug at the caller; refuse and let them surface it.\r\n if (this.subagents.has(id)) {\r\n throw new Error(`Subagent id \"${id}\" already exists — refusing to overwrite`);\r\n }\r\n const context: SubagentContext = {\r\n subagentId: id,\r\n tasks: [],\r\n // Wired later by the caller via setSubagentBridge() once the\r\n // bidirectional bridge is created. Readers must null-check / use\r\n // hasParentBridge() — the type now reflects this.\r\n parentBridge: null,\r\n doneCondition: this.config.doneCondition,\r\n maxConcurrent: this.config.maxConcurrent ?? 16,\r\n };\r\n\r\n this.subagents.set(id, {\r\n config: { ...subagent, id },\r\n context,\r\n status: 'idle',\r\n abortController: new AbortController(),\r\n });\r\n\r\n this.emit('subagent.started', { subagent: { ...subagent, id } });\r\n\r\n this.fleetBus?.emit({\r\n subagentId: id,\r\n ts: Date.now(),\r\n type: 'subagent.assigned',\r\n payload: {\r\n subagentId: id,\r\n name: subagent.name,\r\n provider: subagent.provider,\r\n model: subagent.model,\r\n },\r\n });\r\n\r\n this.emitCoordinatorStats();\r\n\r\n return { subagentId: id, agentId: id };\r\n }\r\n\r\n async assign(task: TaskSpec): Promise<void> {\r\n this.pendingTasks.push(task);\r\n this.tryDispatchNext();\r\n }\r\n\r\n async delegate(to: string, msg: BridgeMessage): Promise<void> {\r\n const subagent = this.subagents.get(to);\r\n if (!subagent) throw new Error(`Subagent \"${to}\" not found`);\r\n if (!subagent.context.parentBridge) {\r\n throw new Error(`Subagent \"${to}\" has no parentBridge — call setSubagentBridge() first`);\r\n }\r\n await subagent.context.parentBridge.send(msg);\r\n }\r\n\r\n /**\r\n * Wire up the communication bridge for a subagent. Call after spawn() once\r\n * the caller has created the bidirectional connection.\r\n */\r\n setSubagentBridge(subagentId: string, bridge: AgentBridge): void {\r\n const subagent = this.subagents.get(subagentId);\r\n if (!subagent) throw new Error(`Subagent \"${subagentId}\" not found`);\r\n subagent.context.parentBridge = bridge;\r\n }\r\n\r\n async stop(subagentId: string): Promise<void> {\r\n const subagent = this.subagents.get(subagentId);\r\n if (!subagent) return;\r\n\r\n // Mark terminating BEFORE the abort so a synchronous tryDispatchNext\r\n // observation in another callback path sees the intent and skips\r\n // this subagent. Cleared by recordCompletion once the runner's\r\n // catch block lands the terminal TaskResult.\r\n this.terminating.add(subagentId);\r\n\r\n // Abort any in-flight run, then sever the bridge so further messages fail\r\n // fast instead of silently queueing on a dead subagent.\r\n subagent.abortController.abort();\r\n subagent.status = 'stopped';\r\n subagent.currentTask = undefined;\r\n subagent.context.parentBridge = null;\r\n\r\n this.emit('subagent.stopped', { subagentId, reason: 'stopped by coordinator' });\r\n\r\n this.fleetBus?.emit({\r\n subagentId,\r\n ts: Date.now(),\r\n type: 'subagent.stopped',\r\n payload: { subagentId, reason: 'stopped by coordinator' },\r\n });\r\n\r\n this.emitCoordinatorStats();\r\n }\r\n\r\n async stopAll(): Promise<void> {\r\n // Clear the queue FIRST so no new tasks land on subagents while\r\n // we're tearing them down. Each dropped task gets a synthetic\r\n // `aborted_by_parent` completion so any caller awaiting it (e.g.\r\n // delegate tool's awaitTasks) resolves instead of hanging.\r\n //\r\n // Pending tasks never reached `inFlight`, so we cannot route them\r\n // through `recordCompletion` — its underflow guard would short-\r\n // circuit on the second pending task and emit a warning instead\r\n // of the completion event. The shared helper inline-emits.\r\n this.drainPendingAsAborted('Coordinator stopAll() drained the pending queue');\r\n // allSettled so one failure doesn't leave other subagents un-stopped.\r\n await Promise.allSettled([...this.subagents.keys()].map((id) => this.stop(id)));\r\n }\r\n\r\n /**\r\n * Get current coordinator stats for monitoring/debugging.\r\n */\r\n getStats(): {\r\n total: number;\r\n running: number;\r\n idle: number;\r\n stopped: number;\r\n inFlight: number;\r\n pending: number;\r\n completed: number;\r\n } {\r\n let running = 0;\r\n let idle = 0;\r\n let stopped = 0;\r\n for (const [, entry] of this.subagents) {\r\n if (entry.status === 'running') running++;\r\n else if (entry.status === 'idle') idle++;\r\n else stopped++;\r\n }\r\n return {\r\n total: this.subagents.size,\r\n running,\r\n idle,\r\n stopped,\r\n inFlight: this.inFlight,\r\n pending: this.pendingTasks.length,\r\n completed: this.completedResults.length,\r\n };\r\n }\r\n\r\n /** Emit a reactive coordinator.stats event on FleetBus so the TUI can subscribe. */\r\n private emitCoordinatorStats(): void {\r\n const stats = this.getStats();\r\n const subagentStatuses = Array.from(this.subagents.entries()).map(([id, s]) => ({\r\n subagentId: id,\r\n taskId: s.currentTask ?? '',\r\n status: s.status,\r\n assigned: s.context.parentBridge !== null,\r\n }));\r\n this.fleetBus?.emit({\r\n subagentId: this.coordinatorId,\r\n ts: Date.now(),\r\n type: 'coordinator.stats',\r\n payload: { ...stats, subagentStatuses },\r\n });\r\n }\r\n\r\n getStatus(): CoordinatorStatus {\r\n return {\r\n coordinatorId: this.coordinatorId,\r\n subagents: Array.from(this.subagents.entries()).map(([id, s]) => ({\r\n id,\r\n name: s.config.name,\r\n status: s.status,\r\n currentTask: s.currentTask,\r\n })),\r\n pendingTasks: this.pendingTasks.length,\r\n completedTasks: this.completedResults.length,\r\n totalIterations: this.totalIterations,\r\n done: this.isDone(),\r\n };\r\n }\r\n\r\n /** Expose snapshot of completed results — useful for callers awaiting all done. */\r\n results(): readonly TaskResult[] {\r\n return this.completedResults;\r\n }\r\n\r\n /**\r\n * Wait for one or more tasks to complete and return their results.\r\n * If a task is already done when called, returns immediately.\r\n * Resolves to an array in the same order as `taskIds`.\r\n */\r\n async awaitTasks(taskIds: string[]): Promise<TaskResult[]> {\r\n return Promise.all(\r\n taskIds.map((id) => {\r\n const cached = this.completedResults.find((r) => r.taskId === id);\r\n if (cached) return cached;\r\n // Fallback: poll until the task completes (up to timeoutMs).\r\n // The coordinator fires 'task.completed' on every result, so\r\n // we use a promise-based waiter tied to that event.\r\n return new Promise<TaskResult>((resolve, reject) => {\r\n const timeout = setTimeout(() => {\r\n this.off('task.completed', handler);\r\n reject(new Error(`awaitTasks timed out waiting for task \"${id}\"`));\r\n }, this.config.timeoutMs ?? 300_000);\r\n const handler = ({ result }: { task: TaskSpec; result: TaskResult }) => {\r\n if (result.taskId === id) {\r\n clearTimeout(timeout);\r\n this.off('task.completed', handler);\r\n resolve(result);\r\n }\r\n };\r\n this.on('task.completed', handler);\r\n });\r\n }),\r\n );\r\n }\r\n\r\n /**\r\n * Manual completion — for callers that drive subagents without a runner\r\n * (e.g. external orchestrators). When a runner is configured the coordinator\r\n * calls this itself.\r\n */\r\n completeTask(result: TaskResult): void {\r\n this.recordCompletion(result);\r\n }\r\n\r\n // --- internal dispatching ---------------------------------------------\r\n\r\n private tryDispatchNext(): void {\r\n while (this.canDispatch()) {\r\n const dispatchable = this.takeNextDispatchableTask();\r\n if (!dispatchable) {\r\n // No idle worker right now. If every spawned subagent is\r\n // stopped or mid-termination, the pending queue is dead —\r\n // a pending task can never start, so synthetic-complete it\r\n // as `aborted_by_parent`. Without this, an `assign()` after\r\n // `stop()` would hang forever waiting for `task.completed`.\r\n // We DO NOT drain when subagents are busy (status='running'):\r\n // those will free up and accept the work normally.\r\n if (this.pendingTasks.length > 0 && !this.hasLiveSubagent()) {\r\n this.drainPendingAsAborted(\r\n 'No live subagent available — all stopped or mid-termination',\r\n );\r\n }\r\n return;\r\n }\r\n const { subagentId, task } = dispatchable;\r\n // Attach a catch so a synchronous throw inside runDispatched (rare —\r\n // e.g. provider misconfiguration before the first await) becomes a\r\n // visible failed task instead of an unhandled rejection that leaves\r\n // `inFlight` permanently elevated.\r\n this.runDispatched(subagentId, task).catch((err) => {\r\n this.recordCompletion({\r\n subagentId,\r\n taskId: task.id,\r\n status: 'failed',\r\n error: classifySubagentError(err),\r\n iterations: 0,\r\n toolCalls: 0,\r\n durationMs: 0,\r\n });\r\n });\r\n }\r\n }\r\n\r\n private canDispatch(): boolean {\r\n const max = this.config.maxConcurrent ?? 16;\r\n return this.inFlight < max && this.pendingTasks.length > 0;\r\n }\r\n\r\n private takeNextDispatchableTask(): { subagentId: string; task: TaskSpec } | null {\r\n for (let i = 0; i < this.pendingTasks.length; i++) {\r\n const task = this.pendingTasks[i]!;\r\n const subagentId = task.subagentId\r\n ? this.isIdleSubagent(task.subagentId)\r\n ? task.subagentId\r\n : null\r\n : this.findIdleSubagent();\r\n if (!subagentId) continue;\r\n this.pendingTasks.splice(i, 1);\r\n return { subagentId, task };\r\n }\r\n return null;\r\n }\r\n\r\n private findIdleSubagent(): string | null {\r\n for (const [id, s] of this.subagents) {\r\n // Skip subagents that are mid-termination — `stop()` set the\r\n // `terminating` flag and aborted the controller, but the\r\n // status mutation happens synchronously after; checking both\r\n // is belt-and-suspenders against any race where status is\r\n // transiently still 'idle' while termination is in flight.\r\n if (s.status === 'idle' && !this.terminating.has(id)) return id;\r\n }\r\n return null;\r\n }\r\n\r\n private isIdleSubagent(id: string): boolean {\r\n const subagent = this.subagents.get(id);\r\n return !!subagent && subagent.status === 'idle' && !this.terminating.has(id);\r\n }\r\n\r\n /**\r\n * Returns true iff at least one spawned subagent could still\r\n * process a task. A \"live\" subagent is one that is not stopped\r\n * AND not mid-termination — `running` workers count because they\r\n * will eventually finish and become idle.\r\n *\r\n * When no subagent has ever been spawned, returns `true` so a\r\n * pre-spawn `assign()` simply queues (legacy behaviour). The\r\n * dead-end detection only fires after `stop()` has retired every\r\n * spawned worker.\r\n *\r\n * Used by `tryDispatchNext` to detect a dead-end pending queue.\r\n */\r\n private hasLiveSubagent(): boolean {\r\n if (this.subagents.size === 0) return true;\r\n for (const [id, s] of this.subagents) {\r\n if (s.status !== 'stopped' && !this.terminating.has(id)) return true;\r\n }\r\n return false;\r\n }\r\n\r\n /**\r\n * Drain every pending task with a synthetic `aborted_by_parent`\r\n * completion event. Same shape as the `stopAll()` drain — we go\r\n * around `recordCompletion` because pending tasks were never\r\n * counted in `inFlight` and routing them through would trip the\r\n * underflow guard on every task after the first.\r\n */\r\n private drainPendingAsAborted(message: string): void {\r\n const dropped = this.pendingTasks.splice(0, this.pendingTasks.length);\r\n for (const t of dropped) {\r\n const synthetic: TaskResult = {\r\n subagentId: t.subagentId ?? 'unassigned',\r\n taskId: t.id,\r\n status: 'stopped',\r\n error: {\r\n kind: 'aborted_by_parent',\r\n message,\r\n retryable: false,\r\n },\r\n iterations: 0,\r\n toolCalls: 0,\r\n durationMs: 0,\r\n };\r\n this.completedResults.push(synthetic);\r\n this.emit('task.completed', { task: t, result: synthetic });\r\n }\r\n }\r\n\r\n private async runDispatched(subagentId: string, task: TaskSpec): Promise<void> {\r\n const subagent = this.subagents.get(subagentId);\r\n if (!subagent) return;\r\n // Final race guard: if `stop(subagentId)` ran between dispatch\r\n // and us arriving here, refuse to start the task and surface it\r\n // as `aborted_by_parent` so any caller awaiting the task id\r\n // unblocks. Without this, the task would be marked 'running',\r\n // collide with the just-completed 'stopped' state, and leak\r\n // inFlight by 1 because no recordCompletion path covers it.\r\n if (this.terminating.has(subagentId) || subagent.status === 'stopped') {\r\n this.recordCompletion({\r\n subagentId,\r\n taskId: task.id,\r\n status: 'stopped',\r\n error: {\r\n kind: 'aborted_by_parent',\r\n message: 'Subagent was terminated before task could start',\r\n retryable: false,\r\n },\r\n iterations: 0,\r\n toolCalls: 0,\r\n durationMs: 0,\r\n });\r\n return;\r\n }\r\n\r\n subagent.status = 'running';\r\n subagent.currentTask = task.id;\r\n task.subagentId = subagentId;\r\n subagent.context.tasks.push(task);\r\n\r\n this.fleetBus?.emit({\r\n subagentId,\r\n taskId: task.id,\r\n ts: Date.now(),\r\n type: 'subagent.running',\r\n payload: { subagentId, taskId: task.id },\r\n });\r\n\r\n this.emit('task.assigned', { task, subagentId });\r\n this.emitCoordinatorStats();\r\n\r\n // Budget combines coordinator defaults with per-subagent and per-task overrides.\r\n // Precedence: task > subagent (raw, no roster fills) > coordinator default > roster default.\r\n // We intentionally call applyRosterBudget LATE — only as a final fallback after\r\n // the coordinator's defaultBudget has had a chance to apply. This prevents\r\n // GENERIC_SUBAGENT_BUDGET (5000 iter) from shadowing the coordinator's explicit default.\r\n const rawMaxIterations = subagent.config.maxIterations;\r\n const rawMaxToolCalls = subagent.config.maxToolCalls;\r\n const rawMaxTokens = subagent.config.maxTokens;\r\n const rawMaxCostUsd = subagent.config.maxCostUsd;\r\n const rawTimeoutMs = subagent.config.timeoutMs;\r\n const rawIdleTimeoutMs = subagent.config.idleTimeoutMs;\r\n const configWithRosterDefaults = applyRosterBudget(subagent.config);\r\n const budget = new SubagentBudget({\r\n maxIterations:\r\n rawMaxIterations ?? this.config.defaultBudget?.maxIterations ?? configWithRosterDefaults.maxIterations,\r\n maxToolCalls:\r\n rawMaxToolCalls ??\r\n this.config.defaultBudget?.maxToolCalls ??\r\n configWithRosterDefaults.maxToolCalls,\r\n maxTokens:\r\n rawMaxTokens ?? this.config.defaultBudget?.maxTokens ?? configWithRosterDefaults.maxTokens,\r\n maxCostUsd:\r\n rawMaxCostUsd ?? this.config.defaultBudget?.maxCostUsd ?? configWithRosterDefaults.maxCostUsd,\r\n // Wall-clock cap is opt-in (explicit config / defaultBudget only); the\r\n // roster no longer supplies one. Idle is the default reaper.\r\n timeoutMs:\r\n rawTimeoutMs ?? this.config.defaultBudget?.timeoutMs ?? configWithRosterDefaults.timeoutMs,\r\n idleTimeoutMs:\r\n rawIdleTimeoutMs ??\r\n this.config.defaultBudget?.idleTimeoutMs ??\r\n configWithRosterDefaults.idleTimeoutMs,\r\n });\r\n subagent.activeBudget = budget;\r\n\r\n if (!this.runner) {\r\n // No runner wired — caller drives execution via completeTask(). Status\r\n // reverts when the caller reports. We intentionally don't bump\r\n // `inFlight` here: `completeTask` → `recordCompletion` would then\r\n // decrement an inFlight that runDispatched never incremented, masking\r\n // the \"no runner\" state. With this guard, `isDone()`'s all_tasks_done\r\n // check still settles correctly once the caller reports.\r\n return;\r\n }\r\n\r\n // Only count inFlight when we actually own the execution lifecycle.\r\n this.inFlight++;\r\n\r\n const startTime = Date.now();\r\n const runCtx: SubagentRunContext = {\r\n subagentId,\r\n config: subagent.config,\r\n budget,\r\n signal: subagent.abortController.signal,\r\n bridge: subagent.context.parentBridge || null,\r\n };\r\n\r\n let result: TaskResult;\r\n\r\n budget.start();\r\n try {\r\n const outcome = await this.executeWithTimeout(this.runner, task, runCtx, budget);\r\n result = {\r\n subagentId,\r\n taskId: task.id,\r\n status: 'success',\r\n result: outcome.result,\r\n iterations: outcome.iterations,\r\n toolCalls: outcome.toolCalls,\r\n durationMs: Date.now() - startTime,\r\n };\r\n } catch (err) {\r\n // Order matters: a timeout calls abort() to signal cooperative runners,\r\n // which also flips `signal.aborted=true`. Inspect the error first so we\r\n // surface 'timeout' rather than masking it as 'stopped'.\r\n const status: TaskResult['status'] =\r\n err instanceof BudgetExceededError && (err.kind === 'timeout' || err.kind === 'idle_timeout')\r\n ? 'timeout'\r\n : subagent.abortController.signal.aborted\r\n ? 'stopped'\r\n : 'failed';\r\n const usage = budget.usage();\r\n result = {\r\n subagentId,\r\n taskId: task.id,\r\n status,\r\n error: classifySubagentError(err, {\r\n parentAborted: subagent.abortController.signal.aborted,\r\n }),\r\n iterations: usage.iterations,\r\n toolCalls: usage.toolCalls,\r\n durationMs: Date.now() - startTime,\r\n };\r\n }\r\n\r\n this.recordCompletion(result);\r\n }\r\n\r\n private async executeWithTimeout(\r\n runner: SubagentRunner,\r\n task: TaskSpec,\r\n ctx: SubagentRunContext,\r\n budget: SubagentBudget,\r\n ) {\r\n const initialTimeoutMs = budget.limits.timeoutMs;\r\n const idleLimitMs = budget.limits.idleTimeoutMs;\r\n if (initialTimeoutMs === undefined && idleLimitMs === undefined) {\r\n return runner(task, ctx);\r\n }\r\n\r\n // Re-armable watchdog. The default guard is IDLE-based: while the agent\r\n // keeps producing activity (iterations / tool calls / streamed progress),\r\n // `budget.idleMs()` stays below the window and we simply re-arm — an\r\n // actively-working subagent is never killed by the clock. Only a genuine\r\n // stall (no activity for `idleTimeoutMs`) reaps it. An explicit wall-clock\r\n // `timeoutMs` (rare, opt-in) keeps the original soft-warning behaviour: it\r\n // negotiates an extension via the Director's auto-extend listener and\r\n // re-arms rather than hard-killing a task solely for running long.\r\n const start = Date.now();\r\n let timer: ReturnType<typeof setTimeout> | null = null;\r\n\r\n const timeoutPromise = new Promise<never>((_, reject) => {\r\n const armFor = (ms: number) => {\r\n if (timer) clearTimeout(timer);\r\n timer = setTimeout(onTick, Math.max(0, ms));\r\n };\r\n // Re-arm for whichever deadline is sooner — the idle window (counted\r\n // from last activity) or the explicit wall-clock cap. Either being\r\n // unset drops out of the min, so single-limit configs behave exactly\r\n // as that limit alone.\r\n const scheduleNext = () => {\r\n const wallRemaining =\r\n initialTimeoutMs === undefined\r\n ? Number.POSITIVE_INFINITY\r\n : (budget.limits.timeoutMs ?? initialTimeoutMs) - (Date.now() - start);\r\n const idleRemaining =\r\n idleLimitMs === undefined\r\n ? Number.POSITIVE_INFINITY\r\n : (budget.limits.idleTimeoutMs ?? idleLimitMs) - budget.idleMs();\r\n // Floor at a small positive so a near-zero remainder can't busy-loop.\r\n armFor(Math.max(25, Math.min(wallRemaining, idleRemaining)));\r\n };\r\n\r\n const onTick = async () => {\r\n const elapsed = Date.now() - start;\r\n const wallLimit =\r\n initialTimeoutMs === undefined ? undefined : budget.limits.timeoutMs ?? initialTimeoutMs;\r\n const idleLimit =\r\n idleLimitMs === undefined ? undefined : budget.limits.idleTimeoutMs ?? idleLimitMs;\r\n const wallExceeded = wallLimit !== undefined && elapsed >= wallLimit;\r\n const idleExceeded = idleLimit !== undefined && budget.idleMs() >= idleLimit;\r\n\r\n // Idle stall with no wall-clock cap also due: a genuinely hung agent\r\n // (no activity for the whole window). Reap it directly — idle is not\r\n // negotiable; the point of the default is to free a stuck slot.\r\n if (idleExceeded && !wallExceeded) {\r\n this.subagents.get(ctx.subagentId)?.abortController.abort();\r\n reject(new BudgetExceededError('timeout', idleLimit!, budget.idleMs()));\r\n return;\r\n }\r\n // Neither deadline actually tripped — we woke early because activity\r\n // pushed the idle deadline out. Re-arm for the new soonest deadline.\r\n if (!wallExceeded) {\r\n scheduleNext();\r\n return;\r\n }\r\n\r\n // Wall-clock cap hit. This is opt-in and keeps the original\r\n // soft-warning behaviour: negotiate an extension rather than\r\n // hard-killing a task solely for running long.\r\n const limit = wallLimit!;\r\n // Without an onThreshold handler the original behaviour stands:\r\n // abort the signal and hard-reject. This preserves the contract\r\n // for direct SubagentBudget consumers that don't wire negotiation.\r\n if (!budget.onThreshold) {\r\n this.subagents.get(ctx.subagentId)?.abortController.abort();\r\n reject(new BudgetExceededError('timeout', limit, elapsed));\r\n return;\r\n }\r\n // With a handler, ask for an extension. The budget's\r\n // requestDecision returns 'stop' on no response (decision\r\n // fallback timer inside SubagentBudget), so this never hangs.\r\n try {\r\n const result = budget.onThreshold({\r\n kind: 'timeout',\r\n used: elapsed,\r\n limit,\r\n requestDecision: () =>\r\n new Promise((resolveDecision) => {\r\n budget._events?.emit('budget.threshold_reached', {\r\n kind: 'timeout',\r\n used: elapsed,\r\n limit,\r\n timeoutMs: 60_000,\r\n extend: (extra) => resolveDecision({ extend: extra }),\r\n deny: () => resolveDecision('stop'),\r\n });\r\n }),\r\n });\r\n const decision = typeof result === 'string' ? result : await result;\r\n if (decision === 'continue' || decision === 'throw' || decision === 'stop') {\r\n // Timeout denied / no-op — re-arm for another full wall window so\r\n // we ask again later. This makes wall-clock timeout a pure warning\r\n // event: the subagent keeps running until it naturally finishes or\r\n // the user stops it. No task is hard-killed solely for running long.\r\n armFor(Math.max(1_000, limit));\r\n return;\r\n }\r\n // 'extend' — patch budget and re-arm for the new remainder.\r\n if (decision.extend.timeoutMs !== undefined) {\r\n (budget.limits as Record<string, unknown>).timeoutMs = decision.extend.timeoutMs;\r\n scheduleNext();\r\n return;\r\n }\r\n // No timeoutMs in extend — fall through to reject.\r\n this.subagents.get(ctx.subagentId)?.abortController.abort();\r\n reject(new BudgetExceededError('timeout', limit, elapsed));\r\n } catch (err) {\r\n this.subagents.get(ctx.subagentId)?.abortController.abort();\r\n reject(\r\n err instanceof BudgetExceededError\r\n ? err\r\n : new BudgetExceededError('timeout', limit, elapsed),\r\n );\r\n }\r\n };\r\n // First arm: whichever of the idle window / wall-clock cap is sooner.\r\n scheduleNext();\r\n });\r\n\r\n try {\r\n return await Promise.race([runner(task, ctx), timeoutPromise]);\r\n } finally {\r\n if (timer) clearTimeout(timer);\r\n }\r\n }\r\n\r\n private recordCompletion(result: TaskResult): void {\r\n this.completedResults.push(result);\r\n // Trim oldest entries when the cap is exceeded — keep the most recent\r\n // results so /fleet and roll_up still have data to work with.\r\n if (this.completedResults.length > DefaultMultiAgentCoordinator.MAX_COMPLETED_RESULTS) {\r\n this.completedResults.splice(\r\n 0,\r\n this.completedResults.length - DefaultMultiAgentCoordinator.MAX_COMPLETED_RESULTS,\r\n );\r\n }\r\n this.totalIterations += result.iterations;\r\n if (this.inFlight > 0) {\r\n this.inFlight--;\r\n } else if (this.runner) {\r\n // Runner-driven path completed without an outstanding inFlight slot —\r\n // shouldn't happen unless completeTask was called externally.\r\n this.emit('warning', {\r\n type: 'inFlight_underflow',\r\n taskId: result.taskId,\r\n subagentId: result.subagentId,\r\n });\r\n return;\r\n }\r\n\r\n const subagent = this.subagents.get(result.subagentId);\r\n if (subagent && subagent.status !== 'stopped') {\r\n const failed = result.status === 'failed' || result.status === 'timeout';\r\n // Synchronously reset the worker to idle after either a clean\r\n // finish or a transient failure. The previous code parked the\r\n // subagent in 'error' and used a `queueMicrotask` to flip it\r\n // back to 'idle' — that opened a window where `assign()` +\r\n // `tryDispatchNext` could race the microtask, leaving the\r\n // worker stuck in 'running' state while actually idle. By\r\n // resetting now, no async gap can leak the state machine.\r\n subagent.status = 'idle';\r\n void failed; // kept for future telemetry hooks\r\n subagent.currentTask = undefined;\r\n // If the run aborted (timeout or explicit stop), the subagent's\r\n // signal is now permanently aborted — recycling the controller lets\r\n // the next dispatched task start with a fresh cancellation scope.\r\n if (subagent.abortController.signal.aborted) {\r\n subagent.abortController = new AbortController();\r\n }\r\n\r\n this.fleetBus?.emit({\r\n subagentId: result.subagentId,\r\n ts: Date.now(),\r\n type: 'subagent.idle',\r\n payload: { subagentId: result.subagentId },\r\n });\r\n }\r\n // Clear the terminating flag now that the worker has a terminal\r\n // TaskResult on record. Subsequent stop() calls re-add it; new\r\n // assign() calls can flow normally.\r\n this.terminating.delete(result.subagentId);\r\n\r\n this.emit('task.completed', {\r\n task: subagent?.context.tasks.find((t) => t.id === result.taskId) ?? { id: result.taskId },\r\n result,\r\n });\r\n\r\n this.fleetBus?.emit({\r\n subagentId: result.subagentId,\r\n taskId: result.taskId,\r\n ts: Date.now(),\r\n type: 'subagent.completed',\r\n payload: {\r\n subagentId: result.subagentId,\r\n taskId: result.taskId,\r\n status: result.status,\r\n iterations: result.iterations,\r\n toolCalls: result.toolCalls,\r\n durationMs: result.durationMs,\r\n },\r\n });\r\n\r\n this.tryDispatchNext();\r\n\r\n // Emit after tryDispatchNext so the stats reflect the post-dispatch\r\n // state (either a new running subagent, or idle if the queue is drained).\r\n this.emitCoordinatorStats();\r\n\r\n if (this.isDone()) {\r\n this.emit('done', {\r\n results: this.completedResults,\r\n totalIterations: this.totalIterations,\r\n });\r\n }\r\n }\r\n\r\n /**\r\n * Stop a subagent and remove it from the coordinator. Releases all\r\n * associated resources (AbortController, context, budget state).\r\n * The subagent entry is deleted so the id can be reused in a future spawn.\r\n */\r\n async remove(subagentId: string): Promise<void> {\r\n const subagent = this.subagents.get(subagentId);\r\n if (!subagent) return;\r\n\r\n // Gracefully stop first — same logic as stop() but don't block on it.\r\n if (subagent.status === 'running' || subagent.status === 'idle') {\r\n this.terminating.add(subagentId);\r\n subagent.abortController.abort();\r\n subagent.status = 'stopped';\r\n }\r\n\r\n // Release all resources associated with this subagent.\r\n this.subagents.delete(subagentId);\r\n this.terminating.delete(subagentId);\r\n // Free the nickname slot so the same name can be reused by a future spawn.\r\n const nicknameKey = this.subagentNicknames.get(subagentId);\r\n if (nicknameKey) {\r\n this.usedNicknames.delete(nicknameKey);\r\n this.subagentNicknames.delete(subagentId);\r\n }\r\n\r\n // Clean up any pending tasks assigned to this subagent — emit synthetic\r\n // 'stopped' completions so callers awaiting them via awaitTasks() unblock\r\n // instead of hanging forever. Without this, a task queued for a removed\r\n // subagent would leave its waiter permanently unresolved.\r\n const orphaned = this.pendingTasks.filter((t) => t.subagentId === subagentId);\r\n this.pendingTasks = this.pendingTasks.filter((t) => t.subagentId !== subagentId);\r\n for (const t of orphaned) {\r\n const synthetic: TaskResult = {\r\n subagentId,\r\n taskId: t.id,\r\n status: 'stopped',\r\n error: {\r\n kind: 'aborted_by_parent',\r\n message: `Subagent \"${subagentId}\" was removed while task \"${t.id}\" was pending`,\r\n retryable: false,\r\n },\r\n iterations: 0,\r\n toolCalls: 0,\r\n durationMs: 0,\r\n };\r\n this.recordCompletion(synthetic);\r\n }\r\n\r\n this.fleetBus?.emit({\r\n subagentId,\r\n ts: Date.now(),\r\n type: 'subagent.removed',\r\n payload: { subagentId },\r\n });\r\n\r\n this.emitCoordinatorStats();\r\n }\r\n\r\n private isDone(): boolean {\r\n if (this.config.doneCondition.type === 'all_tasks_done') {\r\n return this.pendingTasks.length === 0 && this.inFlight === 0;\r\n }\r\n if (\r\n this.config.doneCondition.maxIterations !== undefined &&\r\n this.totalIterations >= this.config.doneCondition.maxIterations\r\n ) {\r\n return true;\r\n }\r\n return false;\r\n }\r\n}\r\n\r\n/**\r\n * Map any raw exception thrown out of a subagent's runner into a\r\n * structured `SubagentError`. This is the single point where the\r\n * coordinator decides \"what kind of failure was that\" — so callers\r\n * (delegate tool output, /agents UI, retry policies) branch on\r\n * `kind` instead of substring-matching `error.message`.\r\n *\r\n * The classification order matters:\r\n * 1. Provider errors first (their `status` + `retryable` are\r\n * already structured, just translate to our enum).\r\n * 2. Budget errors next (BudgetExceededError carries a discrete\r\n * `kind` we can lift directly).\r\n * 3. Parent-abort if the subagent's signal was aborted and we\r\n * didn't recognize the error otherwise — distinguishes user\r\n * Ctrl+C from a tool throwing.\r\n * 4. Substring sniffing for stable error markers (\"agent\r\n * aborted\" from agent-subagent-runner, \"Bridge transport\"\r\n * from agent-bridge).\r\n * 5. Fallback to `unknown` so callers know we couldn't classify.\r\n *\r\n * The `cause` field is always populated when `err` is an Error so\r\n * diagnostics survive even when `kind === 'unknown'` — no info is\r\n * dropped, the classifier just refused to commit.\r\n *\r\n * Exported because tests and CLI surfaces want to assert on the\r\n * classification without instantiating a coordinator.\r\n */\r\nexport function classifySubagentError(\r\n err: unknown,\r\n hints: { parentAborted?: boolean } = {},\r\n): SubagentError {\r\n const cause = err instanceof Error\r\n ? { name: err.name, message: err.message, stack: err.stack }\r\n : undefined;\r\n\r\n if (err instanceof ProviderError) {\r\n const baseMessage = err.describe();\r\n return providerErrorToSubagentError(err, baseMessage, cause);\r\n }\r\n\r\n const baseMessage = err instanceof Error ? err.message : String(err);\r\n\r\n if (err instanceof BudgetExceededError) {\r\n const map: Record<BudgetExceededError['kind'], SubagentErrorKind> = {\r\n iterations: 'budget_iterations',\r\n tool_calls: 'budget_tool_calls',\r\n tokens: 'budget_tokens',\r\n cost: 'budget_cost',\r\n timeout: 'budget_timeout',\r\n idle_timeout: 'budget_timeout',\r\n };\r\n return {\r\n kind: map[err.kind],\r\n message: baseMessage,\r\n // Budgets are user-configured ceilings, not transient failures —\r\n // retrying with the same budget will hit the same ceiling. The\r\n // orchestrator must raise the budget or narrow the task first.\r\n retryable: false,\r\n cause,\r\n };\r\n }\r\n\r\n // Distinguish parent-aborted from real failures BEFORE substring\r\n // sniffing — if the parent signal is aborted, the most common\r\n // exception is \"agent aborted\" thrown by agent-subagent-runner.\r\n if (hints.parentAborted) {\r\n return {\r\n kind: 'aborted_by_parent',\r\n message: baseMessage,\r\n retryable: false,\r\n cause,\r\n };\r\n }\r\n\r\n // Stable markers — these strings live in our own code and are\r\n // checked here intentionally so callers can react without\r\n // exception-type imports.\r\n const lower = baseMessage.toLowerCase();\r\n if (/agent aborted$/i.test(baseMessage)) {\r\n return {\r\n kind: 'aborted_by_parent',\r\n message: baseMessage,\r\n retryable: false,\r\n cause,\r\n };\r\n }\r\n if (/agent exhausted iteration limit$/i.test(baseMessage)) {\r\n return { kind: 'budget_iterations', message: baseMessage, retryable: false, cause };\r\n }\r\n if (/empty response$/i.test(baseMessage)) {\r\n return { kind: 'empty_response', message: baseMessage, retryable: false, cause };\r\n }\r\n // The runner throws `Error('tool failed: <name>')` when an executed tool\r\n // returned `ok:false` and the agent ultimately ended without recovering\r\n // (or aborted). Surface as `tool_failed` so callers don't conflate a\r\n // failed tool with a thrown tool — both are useful but mean different\r\n // things at the LLM layer.\r\n if (/^tool failed: /i.test(baseMessage)) {\r\n return { kind: 'tool_failed', message: baseMessage, retryable: false, cause };\r\n }\r\n if (lower.includes('bridge transport') || /bridge.*(closed|disconnect)/i.test(baseMessage)) {\r\n return { kind: 'bridge_failed', message: baseMessage, retryable: false, cause };\r\n }\r\n if (/context length|max.*tokens?.*exceeded|prompt is too long/i.test(baseMessage)) {\r\n return { kind: 'context_overflow', message: baseMessage, retryable: false, cause };\r\n }\r\n\r\n // Final fallback — preserve cause so diagnostics aren't lost.\r\n return {\r\n kind: 'unknown',\r\n message: baseMessage,\r\n retryable: false,\r\n cause,\r\n };\r\n}\r\n\r\nfunction providerErrorToSubagentError(\r\n err: ProviderError,\r\n message: string,\r\n cause: SubagentError['cause'],\r\n): SubagentError {\r\n const status = err.status;\r\n // Read suggested retry-after from the provider body when present so\r\n // the orchestrator doesn't have to invent a backoff. Most providers\r\n // include retry-after as a header / body field which our provider\r\n // layer normalises into `body.message` — we cannot trust a numeric\r\n // field exists, so we leave backoffMs unset when unknown.\r\n if (status === 429 || err.body?.type === 'rate_limit_error') {\r\n return {\r\n kind: 'provider_rate_limit',\r\n message,\r\n retryable: true,\r\n // Conservative default: 5s. Provider-specific code can override\r\n // by emitting an error whose body carries an explicit hint.\r\n backoffMs: 5_000,\r\n cause,\r\n };\r\n }\r\n if (status === 401 || status === 403 || err.body?.type === 'authentication_error') {\r\n return { kind: 'provider_auth', message, retryable: false, cause };\r\n }\r\n if (status === 408 || status === 0) {\r\n return { kind: 'provider_timeout', message, retryable: true, cause };\r\n }\r\n if (status >= 500 && status < 600) {\r\n return {\r\n kind: 'provider_5xx',\r\n message,\r\n retryable: true,\r\n backoffMs: 3_000,\r\n cause,\r\n };\r\n }\r\n // Other provider errors (400 invalid request, 404 not found, etc.)\r\n // are not retryable as-is and don't have a dedicated kind — surface\r\n // as 'unknown' so the orchestrator treats them as terminal.\r\n return { kind: 'unknown', message, retryable: err.retryable, cause };\r\n}\r\n","import { randomUUID } from 'node:crypto';\nimport type { Agent } from '../core/agent.js';\nimport type { AgentFactory } from '../coordination/agent-subagent-runner.js';\nimport { makeAgentSubagentRunner } from '../coordination/agent-subagent-runner.js';\nimport { dispatchAgent } from '../coordination/dispatcher.js';\nimport type { DispatchClassifier, DispatchResult } from '../coordination/dispatcher.js';\nimport type { SubagentConfig, TaskResult } from '../types/multi-agent.js';\nimport type { JournalEntry, GoalFile } from '../storage/goal-store.js';\nimport { loadGoal, saveGoal, appendJournal, goalFilePath } from '../storage/goal-store.js';\nimport type { Compactor } from '../types/compactor.js';\nimport { DefaultMultiAgentCoordinator } from '../coordination/multi-agent-coordinator.js';\nimport type { MultiAgentConfig } from '../types/multi-agent.js';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport type ParallelEngineState = 'idle' | 'running' | 'stopped';\n\nexport type ParallelIterationStage =\n | { phase: 'idle' }\n | { phase: 'decompose' }\n | { phase: 'fanout'; slots: number }\n | { phase: 'await'; taskIds: string[] }\n | {\n phase: 'aggregate';\n successCount: number;\n total: number;\n goalComplete: boolean;\n }\n | { phase: 'sleep'; ms: number }\n | { phase: 'stopped' }\n | { phase: 'error'; message: string };\n\nexport interface ParallelEternalOptions {\n /** The coordinating agent — NOT a subagent. Owns container/tools/providers. */\n agent: Agent;\n /** Project root (used for goal.json path). */\n projectRoot: string;\n /**\n * Override the resolved goal.json path. Defaults to\n * `goalFilePath(projectRoot)` (a hashed location under the home dir).\n * Primarily for tests that want an isolated goal file under a temp dir.\n */\n goalPath?: string;\n /**\n * Number of parallel subagent slots per tick.\n * Default: 4. Range 1–16; values >8 are for high-throughput machines.\n */\n parallelSlots?: number;\n /** Per-subagent default timeout in ms. Default: 300_000 (5 min). */\n iterationTimeoutMs?: number;\n onIteration?: (entry: JournalEntry) => void;\n onError?: (err: Error, iteration: number) => void;\n /** Per-tick phase notifications for live UI/status updates. */\n onStage?: (stage: ParallelIterationStage) => void;\n gitStatusReader?: () => Promise<string>;\n now?: () => Date;\n compactor?: Compactor;\n compactEveryNIterations?: number;\n aggressiveCompactRatio?: number;\n maxContextTokens?: number;\n /** Override the default agent factory (uses main agent if not provided). */\n subagentFactory?: AgentFactory;\n /**\n * Route each decomposed slot task to the best-fit catalog agent via the\n * smart dispatcher (heuristic keyword scoring). When enabled (default), each\n * slot spawns in-role — the role's budget tier applies and a persona line is\n * injected into the task — instead of as a faceless generic worker. Set\n * false to keep the legacy generic spawn.\n */\n dispatch?: boolean;\n /**\n * Optional LLM fallback for ambiguous tasks. Passed straight to\n * `dispatchAgent`; when omitted, routing is pure heuristic (instant, no\n * provider call — preferred for a continuously-ticking autonomous loop).\n */\n dispatchClassifier?: DispatchClassifier;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nconst GOAL_COMPLETE_MARKER = /^\\s*\\[goal[_\\s-]?complete\\]\\s*$/im;\n\n// ---------------------------------------------------------------------------\n// ParallelEternalEngine\n// ---------------------------------------------------------------------------\n\n/**\n * Sense → Decide → Fan-out (4–8 parallel agents) → Aggregate → Loop.\n *\n * Each tick:\n * 1. Sense — load goal, todos, git status\n * 2. Decide — decompose goal into N parallel sub-tasks\n * 3. Fan-out — spawn N subagents simultaneously, await all\n * 4. Aggregate — write journal, update todos, check [GOAL_COMPLETE]\n * 5. Loop — continue until stop() or mission complete\n *\n * Uses DefaultMultiAgentCoordinator + AgentSubagentRunner for subagent lifecycle.\n */\nexport class ParallelEternalEngine {\n private state: ParallelEngineState = 'idle';\n private stopRequested = false;\n private iterationsSinceCompact = 0;\n private iterations = 0;\n private consecutiveFailures = 0;\n private readonly goalPath: string;\n private readonly slots: number;\n private readonly timeoutMs: number;\n private coordinator: DefaultMultiAgentCoordinator | null = null;\n private agentFactory: AgentFactory;\n private readonly dispatchEnabled: boolean;\n private readonly dispatchClassifier?: DispatchClassifier;\n\n constructor(private readonly opts: ParallelEternalOptions) {\n this.goalPath = opts.goalPath ?? goalFilePath(opts.projectRoot);\n this.slots = Math.min(16, Math.max(1, opts.parallelSlots ?? 4));\n this.timeoutMs = opts.iterationTimeoutMs ?? 300_000;\n this.dispatchEnabled = opts.dispatch !== false;\n this.dispatchClassifier = opts.dispatchClassifier;\n this.agentFactory =\n opts.subagentFactory ??\n (async (_config: SubagentConfig) => ({\n agent: this.opts.agent,\n events: this.opts.agent.events,\n }));\n }\n\n get currentState(): ParallelEngineState {\n return this.state;\n }\n\n /**\n * Get the underlying coordinator for stats/monitoring.\n */\n getCoordinator(): DefaultMultiAgentCoordinator | null {\n return this.coordinator;\n }\n\n stop(): void {\n this.stopRequested = true;\n void this.persistState('stopped').catch(() => {});\n this.state = 'stopped';\n }\n\n async prime(): Promise<void> {\n this.stopRequested = false;\n this.state = 'running';\n await this.persistState('running');\n }\n\n async run(): Promise<void> {\n this.state = 'running';\n await this.persistState('running');\n\n const config: MultiAgentConfig = {\n coordinatorId: `parallel-${randomUUID().slice(0, 8)}`,\n maxConcurrent: this.slots,\n doneCondition: { type: 'all_tasks_done' },\n };\n this.coordinator = new DefaultMultiAgentCoordinator(config);\n const runner = makeAgentSubagentRunner({ factory: this.agentFactory });\n this.coordinator.setRunner?.(runner);\n\n try {\n while (!this.stopRequested) {\n try {\n await this.runOneIteration();\n } catch (err) {\n this.consecutiveFailures++;\n this.opts.onError?.(\n err instanceof Error ? err : new Error(String(err)),\n this.consecutiveFailures,\n );\n await this.appendFailure(\n 'engine error',\n err instanceof Error ? err.message : String(err),\n );\n }\n if (this.stopRequested) break;\n await sleep(2000);\n }\n } finally {\n this.state = 'stopped';\n await this.persistState('stopped').catch(() => {});\n }\n }\n\n /**\n * Execute one tick: decompose → fan-out → aggregate → compact.\n * Called by the REPL in its main loop (REPL drives, engine is stateless per tick).\n */\n async runOneIteration(): Promise<boolean> {\n const emit = (stage: ParallelIterationStage) => {\n this.opts.onStage?.(stage);\n };\n\n this.iterations++;\n\n const goal = await loadGoal(this.goalPath);\n if (!goal) {\n this.stopRequested = true;\n emit({ phase: 'stopped' });\n return false;\n }\n if (goal.goalState !== 'active') {\n this.stopRequested = true;\n emit({ phase: 'stopped' });\n return false;\n }\n\n // Build coordinator on first tick.\n if (!this.coordinator) {\n const config: MultiAgentConfig = {\n coordinatorId: `parallel-${randomUUID().slice(0, 8)}`,\n maxConcurrent: this.slots,\n doneCondition: { type: 'all_tasks_done' },\n };\n this.coordinator = new DefaultMultiAgentCoordinator(config);\n const runner = makeAgentSubagentRunner({ factory: this.agentFactory });\n this.coordinator.setRunner?.(runner);\n }\n\n emit({ phase: 'decompose' });\n const tasks = await this.decomposeGoal(goal);\n if (!tasks || tasks.length === 0) {\n // Nothing to do this tick. The run() loop paces idle iterations itself\n // (see its sleep), so a single runOneIteration() must return promptly.\n emit({ phase: 'sleep', ms: 2000 });\n return false;\n }\n\n emit({ phase: 'fanout', slots: Math.min(this.slots, tasks.length) });\n const fanOut = await this.fanOut(goal, tasks);\n this.iterationsSinceCompact++;\n\n const successCount = fanOut.results.filter((r) => r.status === 'success').length;\n const status: JournalEntry['status'] = fanOut.goalComplete\n ? 'success'\n : fanOut.allSuccessful\n ? 'success'\n : 'failure';\n const note = [\n `${successCount}/${fanOut.results.length} subagents succeeded`,\n fanOut.goalComplete ? '[GOAL_COMPLETE]' : '',\n fanOut.partialOutput ? `Output: ${fanOut.partialOutput.slice(0, 120)}` : '',\n ]\n .filter(Boolean)\n .join(' | ');\n\n // Surface routing in the journal: \"role→task-snippet\" per slot so /goal\n // journal shows which agent handled what.\n const routeSummary =\n fanOut.routes.length > 0\n ? fanOut.routes\n .slice(0, 3)\n .map((r) => `${r.role}→${r.task.slice(0, 28)}`)\n .join(', ')\n : tasks.slice(0, 3).join(', ');\n await this.appendIterationEntry({\n source: 'parallel',\n task: `parallel:${tasks.length} slots — ${routeSummary}${tasks.length > 3 ? '...' : ''}`,\n status,\n note,\n });\n emit({\n phase: 'aggregate',\n successCount,\n total: fanOut.results.length,\n goalComplete: fanOut.goalComplete,\n });\n\n if (fanOut.goalComplete) {\n this.stopRequested = true;\n this.state = 'stopped';\n emit({ phase: 'stopped' });\n return true;\n }\n\n await this.maybeCompact();\n emit({ phase: 'sleep', ms: 2000 });\n return fanOut.allSuccessful;\n }\n\n // -------------------------------------------------------------------------\n // Fan-out\n // -------------------------------------------------------------------------\n\n private async fanOut(\n goal: GoalFile,\n tasks: string[],\n ): Promise<{\n results: TaskResult[];\n allSuccessful: boolean;\n goalComplete: boolean;\n partialOutput: string;\n routes: Array<{ slot: number; task: string; role: string; method: string }>;\n }> {\n const coordinator = this.coordinator!;\n const slotCount = Math.min(this.slots, tasks.length);\n\n // Route each slot task to the best-fit catalog agent. Heuristic by default\n // (instant, no provider call); an injected classifier enables LLM fallback.\n // A dispatch failure for one slot is non-fatal — that slot stays generic.\n const routes: (DispatchResult | null)[] = this.dispatchEnabled\n ? await Promise.all(\n tasks\n .slice(0, slotCount)\n .map((t) =>\n dispatchAgent(t, { classifier: this.dispatchClassifier }).catch(() => null),\n ),\n )\n : [];\n\n const recentJournal = goal.journal\n .slice(-5)\n .map(\n (e) =>\n ` #${e.iteration} [${e.status}] ${e.task}${e.note ? ` — ${e.note.slice(0, 80)}` : ''}`,\n )\n .join('\\n');\n\n const directivePreamble = [\n '═══ ETERNAL AUTONOMY — parallel task slot ═══',\n '',\n `Mission: ${goal.goal}`,\n `Total parallel slots: ${slotCount}`,\n '',\n recentJournal ? `Recent journal (last 5):\\n${recentJournal}` : 'No prior iterations.',\n '',\n '── EXECUTION PROTOCOL ──',\n '• Execute the assigned task end-to-end using multiple tool calls.',\n '• Emit `[done]` on its own line when the task is complete.',\n '• Do not ask before routine in-project tool use — YOLO is active for normal project work.',\n '• If a destructive-gated confirmation appears, wait for the permission flow.',\n '• If the overall Mission is accomplished, emit `[GOAL_COMPLETE]` followed by a verification recipe.',\n '• Keep output concise — summarize findings, do not transcribe files.',\n ].join('\\n');\n\n const taskIds: string[] = [];\n const subagentIds: string[] = [];\n const routeInfo: Array<{ slot: number; task: string; role: string; method: string }> = [];\n\n const spawnPromises: Array<Promise<void>> = [];\n for (let i = 0; i < slotCount; i++) {\n const task = tasks[i]!;\n const route = routes[i] ?? null;\n const subagentId = `parallel-${this.iterations}-${i}`;\n const taskId = randomUUID();\n\n // Persona injection — works even with the default factory (which reuses\n // the shared main agent and ignores config.prompt/tools), so the agent\n // adopts the routed role's stance for this slot.\n const personaLine = route\n ? `Acting agent: ${route.definition.config.name} — ${route.definition.capability.summary}\\n`\n : '';\n const spec = {\n id: taskId,\n description: `${directivePreamble}\\n\\n── SLOT ${i + 1}/${slotCount} ──\\n${personaLine}Task: ${task}\\n`,\n subagentId,\n };\n\n routeInfo.push({\n slot: i,\n task,\n role: route?.role ?? 'generic',\n method: route?.method ?? 'none',\n });\n\n spawnPromises.push(\n (async () => {\n try {\n // Spawn in-role when routed: `role` lets applyRosterBudget resolve the\n // role's budget tier; name/tools/systemPromptOverride specialize the\n // worker if a real per-role factory is wired (forward-compatible).\n await coordinator.spawn(\n route\n ? {\n id: subagentId,\n name: route.definition.config.name,\n role: route.role,\n tools: route.definition.config.tools,\n systemPromptOverride: route.definition.config.prompt,\n timeoutMs: this.timeoutMs,\n }\n : {\n id: subagentId,\n name: `slot-${subagentId.slice(-6)}`,\n // Let the coordinator apply its default budget (roster or generic).\n // Hardcoding low limits here defeats the x10 budget improvement.\n timeoutMs: this.timeoutMs,\n },\n );\n subagentIds.push(subagentId);\n taskIds.push(taskId);\n await coordinator.assign(spec);\n } catch {\n // non-fatal: individual spawn failure doesn't block other slots\n }\n })(),\n );\n }\n await Promise.all(spawnPromises);\n\n if (taskIds.length === 0) {\n return {\n results: [],\n allSuccessful: false,\n goalComplete: false,\n partialOutput: '',\n routes: routeInfo,\n };\n }\n\n this.opts.onStage?.({ phase: 'await', taskIds: [...taskIds] });\n\n let results: TaskResult[] = [];\n try {\n // Wait up to 2 hours for subagents to complete. This should cover\n // most subagent tasks since the roster budgets go up to 10 hours.\n // The outer eternal loop manages actual iteration limits.\n const ctrl = new AbortController();\n const timer = setTimeout(() => ctrl.abort(), Math.max(this.timeoutMs * 2, 7200_000));\n try {\n results = await coordinator.awaitTasks(taskIds);\n } finally {\n clearTimeout(timer);\n }\n } catch {\n results = coordinator.results().slice(-taskIds.length);\n }\n\n const allSuccessful = results.length > 0 && results.every((r) => r.status === 'success');\n const goalComplete = results.some(\n (r) =>\n r.status === 'success' &&\n typeof r.result === 'string' &&\n GOAL_COMPLETE_MARKER.test(r.result),\n );\n const partialOutput = results\n .map((r) => (typeof r.result === 'string' ? r.result : ''))\n .filter(Boolean)\n .join('\\n\\n');\n\n return { results, allSuccessful, goalComplete, partialOutput, routes: routeInfo };\n }\n\n // -------------------------------------------------------------------------\n // Goal decomposition\n // -------------------------------------------------------------------------\n\n private async decomposeGoal(goal: GoalFile): Promise<string[] | null> {\n // Strategy 1: pending todos as sub-tasks\n const todos = this.opts.agent.ctx?.todos;\n const tasks: string[] = [];\n if (Array.isArray(todos)) {\n const pending = todos.filter((t) => t.status === 'pending').slice(0, this.slots);\n for (const t of pending) {\n tasks.push(`[todo] ${t.content}`);\n }\n }\n\n // Strategy 2: git dirty files\n if (tasks.length < this.slots) {\n try {\n const gitStatus = await (this.opts.gitStatusReader?.() ?? this.readGitStatus());\n const dirty = gitStatus.trim();\n if (dirty) {\n const lines = dirty.split('\\n').slice(0, this.slots - tasks.length);\n for (const line of lines) {\n const file = line.replace(/^[ MADRUC?]{2}\\s*/, '').trim();\n if (file) tasks.push(`[git] inspect and fix: ${file}`);\n }\n }\n } catch {\n // ignore\n }\n }\n\n // Strategy 3: leader-brainstormed sub-tasks for remaining slots\n if (tasks.length < this.slots) {\n const remaining = this.slots - tasks.length;\n const brainstormed = await this.brainstormSubtasks(goal, remaining);\n tasks.push(...brainstormed);\n }\n\n return tasks.length > 0 ? tasks.slice(0, this.slots) : null;\n }\n\n private async readGitStatus(): Promise<string> {\n const { execFile } = await import('node:child_process');\n const { promisify } = await import('node:util');\n const execFileP = promisify(execFile);\n const { stdout } = await execFileP('git', ['status', '--porcelain'], {\n cwd: this.opts.projectRoot,\n timeout: 5_000,\n });\n return stdout;\n }\n\n private async brainstormSubtasks(goal: GoalFile, count: number): Promise<string[]> {\n const lastFew = goal.journal\n .slice(-5)\n .map((e) => ` - [${e.status}] ${e.task}`)\n .join('\\n');\n const directive = [\n `Decompose this goal into exactly ${count} independent sub-tasks for parallel execution.`,\n '',\n `Goal: ${goal.goal}`,\n '',\n lastFew ? `Recent:\\n${lastFew}` : 'No prior iterations.',\n '',\n `Output exactly ${count} tasks, one per line, under 120 chars each.`,\n 'Format: TASK-1 | TASK-2 | ... (pipe-separated, no numbering, no preamble).',\n 'Each task must be independently actionable with no shared dependencies.',\n ].join('\\n');\n\n try {\n const ctrl = new AbortController();\n const timer = setTimeout(() => ctrl.abort(), 60_000);\n try {\n const result = await this.opts.agent.run([{ type: 'text' as const, text: directive }], {\n signal: ctrl.signal,\n maxIterations: 1,\n });\n if (result.status !== 'done') return [];\n const text = (result.finalText ?? '').trim();\n if (!text) return [];\n const tasks = text\n .split('|')\n .map((t) => t.trim())\n .filter((t) => t.length > 10 && t.length < 240);\n return tasks.slice(0, count);\n } finally {\n clearTimeout(timer);\n }\n } catch (err) {\n // The leader agent failed to brainstorm. Surface it to onError so the\n // failure is visible, but keep the loop alive (return no tasks — the\n // next tick retries) rather than crashing the autonomous engine.\n this.opts.onError?.(\n err instanceof Error ? err : new Error(String(err)),\n this.consecutiveFailures,\n );\n return [];\n }\n }\n\n // -------------------------------------------------------------------------\n // Compaction\n // -------------------------------------------------------------------------\n\n private async maybeCompact(): Promise<void> {\n const compactor = this.opts.compactor;\n if (!compactor) return;\n const ctx = this.opts.agent.ctx;\n if (!ctx) return;\n\n const shouldRun = this.iterationsSinceCompact >= (this.opts.compactEveryNIterations ?? 25);\n if (!shouldRun) return;\n\n const report = await compactor.compact(ctx, { aggressive: false });\n this.iterationsSinceCompact = 0;\n await this.appendIterationEntry({\n source: 'manual',\n task: 'compaction (cadence)',\n status: 'success',\n note: `saved ~${report.before - report.after} tokens`,\n });\n }\n\n // -------------------------------------------------------------------------\n // Helpers\n // -------------------------------------------------------------------------\n\n private async appendIterationEntry(entry: Omit<JournalEntry, 'iteration' | 'at'>): Promise<void> {\n const current = await loadGoal(this.goalPath);\n if (!current) return;\n const updated = appendJournal(current, entry);\n await saveGoal(this.goalPath, updated);\n const entryWithMeta: JournalEntry = {\n at: (this.opts.now?.() ?? new Date()).toISOString(),\n iteration: updated.iterations,\n ...entry,\n };\n this.opts.onIteration?.(entryWithMeta);\n }\n\n private async appendFailure(task: string, note: string): Promise<void> {\n await this.appendIterationEntry({ source: 'manual', task, status: 'failure', note });\n }\n\n private async persistState(state: GoalFile['engineState']): Promise<void> {\n const current = await loadGoal(this.goalPath);\n if (!current) return;\n if (current.engineState === state) return;\n await saveGoal(this.goalPath, { ...current, engineState: state });\n }\n}\n","/**\n * System-prompt contributor that surfaces eternal-autonomy state to the\n * model on every turn.\n *\n * Why this exists: when the engine drives a long-running loop, the\n * per-iteration directive carries the rules. But the directive is a USER\n * message — it scrolls out of working memory after a few compactions and\n * the model forgets it's in autonomy mode (forgets `[GOAL_COMPLETE]`,\n * forgets the todo-state protocol, forgets the no-confirmation rule).\n * Injecting the same anchor as a CACHED system-prompt block solves that\n * — the rules sit next to the identity layer and survive compactions.\n *\n * Block is tagged `ephemeral` so its content (journal tail, iteration\n * counter) changes each turn without invalidating the upstream prefix\n * cache.\n */\n\nimport type { TextBlock } from '../types/blocks.js';\nimport type { SystemPromptContributor } from '../types/system-prompt-contributor.js';\nimport { loadGoal } from '../storage/goal-store.js';\n\nexport interface AutonomyPromptContributorOptions {\n /** Absolute path to the project's `goal.json`. */\n goalPath: string;\n /**\n * Gating function. The contributor consults this on every build and\n * returns an empty array when `false` — without this, the block would\n * leak into interactive runs that happen to have a goal on disk and\n * teach the model loop-control markers it shouldn't emit.\n *\n * Typical wiring: enable while `eternal` or `eternal-parallel` autonomy is active.\n */\n enabled: () => boolean;\n /** Number of journal entries to include in the recent-tail block. Default 5. */\n journalTailSize?: number;\n}\n\n/**\n * Build a contributor that renders the autonomy-state system block.\n * Returns `[]` when disabled, no goal exists, or the goal has been\n * completed/abandoned — all silent fast-paths.\n */\nexport function makeAutonomyPromptContributor(\n opts: AutonomyPromptContributorOptions,\n): SystemPromptContributor {\n return async (ctx): Promise<TextBlock[]> => {\n // Subagents run a single scoped task and don't drive the engine's\n // outer loop — they have no business emitting `[GOAL_COMPLETE]` or\n // marking todos. Skip the block entirely for subagent prompt builds,\n // mirroring how the active-plan layer is suppressed.\n if (ctx.subagent) return [];\n if (!opts.enabled()) return [];\n\n let goal: Awaited<ReturnType<typeof loadGoal>>;\n try {\n goal = await loadGoal(opts.goalPath);\n } catch {\n return [];\n }\n if (!goal) return [];\n\n // `active` is the default for legacy goal files without the field.\n const missionState = goal.goalState ?? 'active';\n if (missionState !== 'active') return [];\n\n const tailSize = opts.journalTailSize ?? 5;\n const journalTail = goal.journal.slice(-tailSize).map((e) => {\n const note = e.note ? ` — ${e.note.slice(0, 80)}` : '';\n return ` #${e.iteration} [${e.status}] ${e.task}${note}`;\n });\n\n const text = [\n '## ETERNAL AUTONOMY — active mission',\n '',\n 'You are inside a long-running autonomous loop. The user is asleep',\n 'and is not available to confirm decisions. Each turn you receive a',\n 'directive describing one concrete sub-task that advances the mission.',\n '',\n `Mission: ${goal.goal}`,\n `Iteration: #${goal.iterations}`,\n journalTail.length > 0\n ? `Recent journal (last ${journalTail.length}):\\n${journalTail.join('\\n')}`\n : 'Recent journal: (none — this is the first iteration)',\n '',\n '### Loop control markers',\n 'Emit these on their own line in your final text — case-insensitive,',\n 'whitespace-tolerant, but they must occupy the entire line:',\n '- `[continue]` — chain to the next internal step without returning.',\n '- `[done]` — the current sub-task is finished; return to the engine.',\n '- `[GOAL_COMPLETE]` — emit ONLY when the OVERALL mission is',\n ' verifiably done. Must be followed by a one-paragraph verification',\n ' recipe (artifact path, test command, or 10-second reproduction).',\n ' The engine halts on this marker — false positives waste real',\n ' human time. If unsure, emit `[done]` and let the next iteration',\n ' decide.',\n '',\n '### Operating principles',\n '- YOLO is active for normal project work. Proceed with routine',\n ' in-project tool use without pre-confirming; pick the best path and execute it.',\n ' If the permission system raises a destructive-gated confirmation, wait',\n ' for that flow instead of trying to bypass it.',\n '- Use tools freely; multiple calls per turn are normal and expected.',\n '- When working on a todo, mark it `in_progress` via the todos tool',\n ' before tool work and `completed` (or `cancelled` with a reason)',\n ' when done. The loop reads todo state between iterations.',\n \"- If an approach fails twice in a row, pivot. Don't grind on the\",\n ' same wall — try a different angle, file a cancel on the todo, or',\n ' surface the obstacle via `[done]` and let the next iteration',\n ' re-plan.',\n ].join('\\n');\n\n return [\n {\n type: 'text',\n text,\n cache_control: { type: 'ephemeral' },\n },\n ];\n };\n}\n","/**\n * `/goal <description>` preamble — the \"no force can stop this\" mode.\n *\n * Unlike STEERING (which redirects mid-flight), GOAL is a contract:\n * the user hands over a problem, the agent commits to verifiably\n * finishing it, and every iteration re-reads this preamble from the\n * conversation history. The hardening is entirely prompt-level —\n * the system has already removed implicit budget caps, so this\n * preamble's job is to remove the MODEL's tendency to hedge, ask\n * permission, or declare premature success.\n *\n * The four sections are intentional:\n * 1. AUTHORITY — explicit grant of unbounded fan-out + model\n * switching. Without this the model self-throttles (\"I shouldn't\n * spawn too many…\") even when budgets are unlimited.\n * 2. DONE — concrete bar for completion. Forces a verifiable\n * artifact (test passing, file written, bug re-run clean).\n * Without this the model returns \"I believe it's fixed\" and\n * counts that as done.\n * 3. NOT DONE — explicit anti-patterns. Each item is something we\n * saw real agents do as a \"completion\" that wasn't.\n * 4. PERSISTENCE — three-angle rule for blockers. Stops the model\n * from giving up on the first tool failure.\n *\n * Located in @wrongstack/core (rather than @wrongstack/tui) so headless\n * callers and the WebUI can issue `/goal set` without dragging the TUI\n * package in. The tui re-exports this for backward compatibility.\n */\nexport function buildGoalPreamble(goal: string): string {\n return [\n '[GOAL — LOCKED IN. You will work on this until it is verifiably done.',\n 'The user granted you full autonomy. Read these constraints once, then act.',\n '',\n 'YOUR GOAL:',\n '---',\n goal,\n '---',\n '',\n 'AUTHORITY YOU HAVE:',\n '- Spawn as many subagents as the work needs (delegate / spawn_subagent).',\n ' Parallel + recursive fan-out are both fine. There is no spawn budget.',\n '- Use any provider/model per subagent — pick the right tool for each',\n ' piece of work. Heavy reasoning model for planning, fast model for',\n ' batch work, specialist model for domain code.',\n '- Run unlimited tool calls and iterations. There is NO hidden budget.',\n ' The Agent loop auto-extends every 100 iterations forever.',\n '- Retry failed tools with different inputs, alternative paths, fresh',\n ' subagents. Switch providers mid-run if one is rate-limited.',\n '- Re-plan freely when an approach hits a dead end. You are not obliged',\n ' to stick with the first plan you proposed.',\n '',\n 'WHAT \"DONE\" MEANS — non-negotiable:',\n '- You can name a concrete artifact (a passing test, a written file at',\n ' a specific path, a fixed bug verified by re-running the failing case,',\n ' a clean grep that previously had matches).',\n '- You can tell the user HOW to verify it themselves in 10 seconds.',\n '- You have NOT hedged. None of: \"looks like it should work\", \"I',\n ' believe this fixes it\", \"the changes appear correct\".',\n '',\n 'WHAT IS NOT DONE — never report any of these as completion:',\n \"- An error message you didn't recover from.\",\n '- An empty result, a 0-line file, a \"no matches found\" you accepted',\n ' without questioning the search.',\n '- \"Should I continue?\" / \"Want me to also...?\" / \"Let me know if you',\n ' want X.\" Those are hedges. The user already told you to finish the',\n ' goal — just do it.',\n '- Partial progress dressed up as success. Fixed 3 of 5 bugs = 60%',\n ' done, not done.',\n \"- A subagent's failed/timeout/stopped TaskResult that you didn't\",\n ' respond to with a fresh attempt (different role, different model,',\n ' tighter prompt).',\n '',\n 'PERSISTENCE PROTOCOL:',\n '- If blocked, try at least 3 different angles before reporting the',\n ' problem to the user. Different tool inputs, different subagent',\n ' roles, different providers, different decomposition of the task.',\n '- If a tool fails, read its error, alter the input, try again. Do',\n ' not just report the failure back.',\n '- If a subagent returns useless output, respawn with a tighter prompt',\n ' or a different role. Do not accept \"I could not determine…\" as the',\n ' final answer.',\n \"- Use `ask_subagent` for one-shot questions when you don't need a\",\n ' full delegated task.',\n '',\n 'REPORTING:',\n '- Stream short progress notes between major actions so the user can',\n ' monitor. Do not go silent for 50 tool calls then dump a wall of',\n ' text — but also do not narrate every tool call.',\n '- Use the shared scratchpad (if available) to leave breadcrumbs',\n ' subagents can read.',\n '- Final response must include: (a) what was accomplished, (b) how',\n ' to verify, (c) any caveats (residual TODOs, things the user',\n ' should know about).',\n '',\n 'BEGIN.]',\n ].join('\\n');\n}\n","/**\n * Shared regex patterns used across execution and security-scanner.\n * Centralized here to avoid duplication and keep patterns in sync.\n */\n\n/** Matches Node.js ECONN* errors and fetch failure messages. */\nexport const NETWORK_ERR_RE = /ECONN|ETIMEDOUT|ETIME|ENOTFOUND|EAI_AGAIN|fetch failed/i;","import { ProviderError } from '../types/provider.js';\nimport { NETWORK_ERR_RE } from './regex-patterns.js';\nimport type { RetryPolicy } from '../types/retry-policy.js';\n\nexport class DefaultRetryPolicy implements RetryPolicy {\n shouldRetry(err: Error | ProviderError, attempt: number): boolean {\n if (err instanceof ProviderError) {\n if (!err.retryable) return false;\n return attempt < this.maxAttempts(err);\n }\n const msg = err.message ?? '';\n const isNetwork = NETWORK_ERR_RE.test(msg);\n if (isNetwork) return attempt < 2;\n return false;\n }\n\n maxAttempts(err: Error | ProviderError): number {\n if (err instanceof ProviderError) {\n if (err.status === 429) return 5;\n if (err.status === 529) return 3;\n if (err.status >= 500) return 3;\n return 0;\n }\n return 2;\n }\n\n delayMs(attempt: number): number {\n const base = 1000;\n const exp = base * 2 ** attempt;\n const jitter = Math.random() * base;\n return Math.min(30_000, exp + jitter);\n }\n}\n","import type { Context } from '../core/context.js';\nimport type { ErrorHandler, RecoveryDecision } from '../types/error-handler.js';\nimport { ProviderError } from '../types/provider.js';\nimport { NETWORK_ERR_RE } from './regex-patterns.js';\nimport type { Compactor } from '../types/compactor.js';\nimport type { ModelsRegistry } from '../types/models-registry.js';\n\n/**\n * Tiered error recovery strategies.\n * Each strategy is attempted in order until one returns a decision.\n */\nexport interface RecoveryStrategy {\n /** Human-readable label for logs. */\n label: string;\n /** Optional compactor for context_overflow recovery. */\n compactor?: Compactor;\n /** Returns an explicit recovery decision, or null to fall through. */\n attempt: (err: unknown, ctx: Context) => Promise<RecoveryDecision | null>;\n}\n\n// Package-level compiled regex for hot paths — avoids repeated compilation.\nconst CONTEXT_OVERFLOW_RE = /context|too long|tokens|exceeds the context window|context window/i;\n\n/**\n * Builds the ordered list of recovery strategies used by DefaultErrorHandler.\n * Exported so callers can customise or extend the strategy chain.\n */\nexport function buildRecoveryStrategies(opts?: {\n compactor?: Compactor;\n modelsRegistry?: ModelsRegistry;\n}): RecoveryStrategy[] {\n return [\n {\n label: 'context_overflow_reduce',\n compactor: opts?.compactor,\n async attempt(err, ctx) {\n if (!(err instanceof ProviderError)) return null;\n if (err.status !== 413 && !isContextOverflowError(err)) return null;\n\n if (this.compactor) {\n try {\n const report = await this.compactor.compact(ctx, { aggressive: true });\n if (report.after < report.before) {\n return { action: 'retry', reason: 'context_compacted' };\n }\n } catch {\n // compact failed; fall through\n }\n }\n return null;\n },\n },\n {\n label: 'rate_limit_backoff',\n async attempt(err) {\n if (!(err instanceof ProviderError) || err.status !== 429) return null;\n\n // Prefer the parsed Retry-After hint the provider extracted into\n // body.retryAfterMs; fall back to 5s when absent.\n const delayMs = err.body?.retryAfterMs ?? 5_000;\n // Clamp between 1s and 60s.\n const delay = Math.min(60_000, Math.max(1_000, delayMs));\n await new Promise((r) => setTimeout(r, delay));\n return { action: 'retry', reason: 'rate_limit_backoff' };\n },\n },\n {\n label: 'downgrade_model',\n async attempt(err, ctx) {\n if (!(err instanceof ProviderError)) return null;\n if (err.status !== 429 && err.status !== 529 && err.status < 500) return null;\n\n const registry = opts?.modelsRegistry;\n if (!registry) return null;\n\n try {\n const providerId = ctx.provider?.id;\n if (!providerId) return null;\n const provider = await registry.getProvider(providerId);\n if (!provider) return null;\n\n const currentModel = await registry.getModel(providerId, ctx.model);\n if (!currentModel) return null;\n\n // Find a cheaper fallback model with the same capabilities.\n // Prefer models with lower input cost, preferring the same family.\n const candidates = provider.models.filter((m) => {\n const modelCost = m.cost?.input ?? Number.POSITIVE_INFINITY;\n const currentCost = currentModel.cost?.input ?? Number.POSITIVE_INFINITY;\n if (modelCost >= currentCost) return false;\n if (currentModel.capabilities.tools && !m.tool_call) return false;\n if (currentModel.capabilities.vision && !m.modalities?.input?.includes('image'))\n return false;\n return true;\n });\n\n if (candidates.length === 0) return null;\n\n const fallback = candidates.reduce((prev, curr) =>\n (curr.cost?.input ?? 0) < (prev.cost?.input ?? 0) ? curr : prev,\n );\n\n return {\n action: 'retry',\n reason: 'model_downgrade',\n model: fallback.id,\n };\n } catch {\n return null;\n }\n },\n },\n ];\n}\n\nexport const DEFAULT_RECOVERY_STRATEGIES = buildRecoveryStrategies();\n\nfunction isContextOverflowError(err: ProviderError): boolean {\n return CONTEXT_OVERFLOW_RE.test([\n err.message,\n err.body?.message,\n err.body?.type,\n err.body?.raw,\n ].filter(Boolean).join('\\n'));\n}\n\nexport class DefaultErrorHandler implements ErrorHandler {\n private readonly strategies: RecoveryStrategy[];\n\n constructor(strategies: RecoveryStrategy[] = DEFAULT_RECOVERY_STRATEGIES) {\n this.strategies = strategies;\n }\n\n classify(err: unknown): {\n kind:\n | 'rate_limit'\n | 'overloaded'\n | 'server'\n | 'client'\n | 'network'\n | 'abort'\n | 'context_overflow'\n | 'unknown';\n retryable: boolean;\n } {\n // AbortError can be thrown in both browser (DOMException) and Node (Error).\n // Guard with typeof check so Node builds don't reference the browser-only DOMException.\n if (\n typeof DOMException !== 'undefined' &&\n err instanceof DOMException &&\n err.name === 'AbortError'\n ) {\n return { kind: 'abort', retryable: false };\n }\n if (err instanceof Error && err.name === 'AbortError') {\n return { kind: 'abort', retryable: false };\n }\n if (err instanceof ProviderError) {\n if (err.status === 429) return { kind: 'rate_limit', retryable: true };\n if (err.status === 529) return { kind: 'overloaded', retryable: true };\n if (err.status >= 500) return { kind: 'server', retryable: true };\n if (err.status === 413 || isContextOverflowError(err)) {\n return { kind: 'context_overflow', retryable: false };\n }\n if (err.status >= 400) return { kind: 'client', retryable: false };\n }\n if (err instanceof Error && NETWORK_ERR_RE.test(err.message)) {\n return { kind: 'network', retryable: true };\n }\n return { kind: 'unknown', retryable: false };\n }\n\n async recover(err: unknown, ctx: Context): Promise<RecoveryDecision | null> {\n for (const strategy of this.strategies) {\n const result = await strategy.attempt(err, ctx);\n if (result !== null) return result;\n }\n return null;\n }\n}\n","import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport type { SkillEntry, SkillLoader, SkillManifest } from '../types/skill.js';\nimport type { WstackPaths } from '../utils/wstack-paths.js';\n\nexport interface SkillLoaderOptions {\n paths: WstackPaths;\n bundledDir?: string;\n}\n\n/**\n * Discovery order (later layers shadow earlier ones at boot, but we walk\n * highest priority first and skip names already seen):\n * 1. Project-committed: <project>/.wrongstack/skills/\n * 2. User-global: ~/.wrongstack/skills/\n * 3. Bundled with build: packages/core/skills/\n */\nexport class DefaultSkillLoader implements SkillLoader {\n private readonly dirs: { dir: string; source: SkillManifest['source'] }[];\n private cache?: SkillManifest[];\n\n constructor(opts: SkillLoaderOptions) {\n this.dirs = [\n { dir: opts.paths.inProjectSkills, source: 'project' },\n { dir: opts.paths.globalSkills, source: 'user' },\n ];\n if (opts.bundledDir) {\n this.dirs.push({ dir: opts.bundledDir, source: 'bundled' });\n }\n }\n\n async list(): Promise<SkillManifest[]> {\n if (this.cache) return this.cache;\n const found: SkillManifest[] = [];\n const seen = new Set<string>();\n for (const { dir, source } of this.dirs) {\n try {\n const entries = await fs.readdir(dir, { withFileTypes: true });\n for (const e of entries) {\n if (!e.isDirectory()) continue;\n const skillFile = path.join(dir, e.name, 'SKILL.md');\n try {\n const raw = await fs.readFile(skillFile, 'utf8');\n const meta = parseFrontmatter(raw);\n if (!meta.name || !meta.description) continue;\n if (seen.has(meta.name)) continue;\n seen.add(meta.name);\n found.push({\n name: meta.name,\n description: meta.description,\n version: meta.version,\n path: skillFile,\n source,\n });\n } catch {\n // skip malformed skill\n }\n }\n } catch {\n // directory may not exist\n }\n }\n this.cache = found;\n return found;\n }\n\n async find(name: string): Promise<SkillManifest | undefined> {\n const all = await this.list();\n return all.find((s) => s.name === name);\n }\n\n async manifestText(): Promise<string> {\n const skills = await this.list();\n if (skills.length === 0) return '';\n const entries = await this.listEntries();\n const lines = ['## Available skills'];\n for (const e of entries) {\n const scopeTag = e.scope.length > 0 ? ` — ${e.scope.slice(0, 3).join(', ')}` : '';\n lines.push(`- **${e.name}**${scopeTag}`);\n lines.push(` Use when: ${e.trigger}`);\n }\n return lines.join('\\n');\n }\n\n async listEntries(): Promise<SkillEntry[]> {\n const skills = await this.list();\n const entries: SkillEntry[] = [];\n for (const s of skills) {\n try {\n const raw = await fs.readFile(s.path, 'utf8');\n const { trigger, scope } = parseDescription(raw);\n entries.push({ name: s.name, trigger, scope, source: s.source, path: s.path });\n } catch {\n // skip\n }\n }\n return entries;\n }\n\n invalidateCache(): void {\n this.cache = undefined;\n }\n\n async readBody(name: string): Promise<string> {\n const m = await this.find(name);\n if (!m) throw new Error(`Skill \"${name}\" not found`);\n return fs.readFile(m.path, 'utf8');\n }\n}\n\ninterface Frontmatter {\n name?: string;\n description?: string;\n version?: string;\n}\n\nfunction parseFrontmatter(raw: string): Frontmatter {\n if (!raw.startsWith('---')) return {};\n const end = raw.indexOf('\\n---', 4);\n if (end === -1) return {};\n const block = raw.slice(4, end);\n const out: Frontmatter = {};\n let key: keyof Frontmatter | null = null;\n let value: string[] = [];\n const flush = () => {\n if (key) {\n out[key] = value.join('\\n').trim();\n }\n key = null;\n value = [];\n };\n for (const line of block.split('\\n')) {\n const m = /^([a-zA-Z_]+):\\s*(\\|?)\\s*(.*)$/.exec(line);\n if (m) {\n flush();\n key = (m[1] ?? '') as keyof Frontmatter;\n const pipe = m[2];\n const rest = m[3] ?? '';\n if (pipe === '|') {\n value = [];\n } else if (rest) {\n value = [rest];\n } else {\n value = [];\n }\n } else if (key) {\n value.push(line.replace(/^\\s+/, ''));\n }\n }\n flush();\n return out;\n}\n\n/**\n * Parse skill description into:\n * - trigger: extracted \"Use when...\" sentence (first sentence of description)\n * - scope: comma-separated items from first line's parenthetical or file-ext list\n */\nfunction parseDescription(raw: string): { trigger: string; scope: string[] } {\n const fm = parseFrontmatter(raw);\n const desc = fm.description ?? '';\n\n // Extract first sentence as trigger\n const firstSentenceEnd = desc.indexOf('. ');\n const trigger =\n firstSentenceEnd !== -1\n ? desc.slice(0, firstSentenceEnd + 1).trim()\n : (desc.trim().split('\\n')[0] ?? '');\n\n // Extract scope from parenthetical: \"Covers X, Y, and Z\" or \"for A, B, C\"\n const scope: string[] = [];\n const coversMatch = /(?:covers|for|including)\\s+([^.]+)/i.exec(desc);\n if (coversMatch) {\n const items = coversMatch[1]!\n .replace(/[·•]/g, ',')\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean);\n scope.push(...items);\n }\n\n return { trigger, scope };\n}\n"]}
|