@dreb/coding-agent 2.71.0 → 2.73.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +3 -3
  2. package/dist/core/agent-session.d.ts +37 -9
  3. package/dist/core/agent-session.d.ts.map +1 -1
  4. package/dist/core/agent-session.js +226 -149
  5. package/dist/core/agent-session.js.map +1 -1
  6. package/dist/core/thinking.d.ts +2 -0
  7. package/dist/core/thinking.d.ts.map +1 -1
  8. package/dist/core/thinking.js +20 -14
  9. package/dist/core/thinking.js.map +1 -1
  10. package/dist/core/tools/index.d.ts +1 -1
  11. package/dist/core/tools/index.d.ts.map +1 -1
  12. package/dist/core/tools/index.js +1 -1
  13. package/dist/core/tools/index.js.map +1 -1
  14. package/dist/core/tools/subagent.d.ts +77 -6
  15. package/dist/core/tools/subagent.d.ts.map +1 -1
  16. package/dist/core/tools/subagent.js +312 -64
  17. package/dist/core/tools/subagent.js.map +1 -1
  18. package/dist/main.d.ts.map +1 -1
  19. package/dist/main.js +6 -8
  20. package/dist/main.js.map +1 -1
  21. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  22. package/dist/modes/interactive/interactive-mode.js +9 -5
  23. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  24. package/dist/modes/rpc/rpc-client.d.ts +6 -0
  25. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  26. package/dist/modes/rpc/rpc-client.js +9 -0
  27. package/dist/modes/rpc/rpc-client.js.map +1 -1
  28. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  29. package/dist/modes/rpc/rpc-mode.js +7 -1
  30. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  31. package/dist/modes/rpc/rpc-types.d.ts +11 -2
  32. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  33. package/dist/modes/rpc/rpc-types.js.map +1 -1
  34. package/docs/agent-models.md +2 -2
  35. package/docs/dashboard.md +46 -3
  36. package/docs/json.md +2 -2
  37. package/docs/models.md +1 -1
  38. package/docs/providers.md +26 -0
  39. package/docs/rpc.md +25 -6
  40. package/docs/settings.md +1 -1
  41. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"subagent.js","sourceRoot":"","sources":["../../../src/core/tools/subagent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAqB,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC9D,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EACN,SAAS,EAET,UAAU,EACV,QAAQ,EACR,WAAW,EACX,YAAY,EACZ,QAAQ,EACR,YAAY,EACZ,QAAQ,GACR,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEpD,OAAO,EAAiD,cAAc,EAAc,MAAM,UAAU,CAAC;AACrG,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAe,IAAI,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAE,eAAe,EAAE,aAAa,EAAE,sBAAsB,EAAE,MAAM,iBAAiB,CAAC;AACzF,OAAO,EAAE,OAAO,EAAE,MAAM,wDAAwD,CAAC;AACjF,OAAO,EAAE,qBAAqB,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAWpF,OAAO,EAAE,GAAG,EAAE,MAAM,cAAc,CAAC;AAEnC,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AACvD,OAAO,EAAE,gCAAgC,EAAE,MAAM,wBAAwB,CAAC;AAC1E,OAAO,EAAE,6BAA6B,EAAE,wBAAwB,EAAE,6BAA6B,EAAE,MAAM,gBAAgB,CAAC;AACxH,OAAO,EAAE,aAAa,EAAE,cAAc,EAAE,GAAG,EAAE,MAAM,mBAAmB,CAAC;AACvE,OAAO,EAAE,kBA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AAM,CAAC,MAAM,sBAAsB,GAAG,4BAA4B,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC;AAClF,MAAM,CAAC,MAAM,YAAY,GAAG,kBAAkB,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC","sourcesContent":["import { type ChildProcess, spawn } from \"node:child_process\";\nimport { randomBytes } from \"node:crypto\";\nimport {\n\tcloseSync,\n\ttype Dirent,\n\texistsSync,\n\topenSync,\n\treaddirSync,\n\treadFileSync,\n\treadSync,\n\trealpathSync,\n\tstatSync,\n} from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { basename, join, resolve } from \"node:path\";\nimport type { AgentTool, ThinkingLevel } from \"@dreb/agent-core\";\nimport { type Api, type AssistantMessage, type Context, completeSimple, type Model } from \"@dreb/ai\";\nimport { Text } from \"@dreb/tui\";\nimport { type Static, Type } from \"@sinclair/typebox\";\nimport { CONFIG_DIR_NAME, getPackageDir, getSubagentSessionsDir } from \"../../config.js\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.js\";\nimport { attachJsonlLineReader, serializeJsonLine } from \"../../modes/rpc/jsonl.js\";\nimport type { RpcClient } from \"../../modes/rpc/rpc-client.js\";\nimport type { RpcPendingMessages } from \"../../modes/rpc/rpc-types.js\";\nimport type {\n\tDispatchAgentSummary,\n\tDispatchArbitrationRecord,\n\tDispatchArbitrationRequest,\n\tDispatchArbitrationResult,\n\tDispatchRoute,\n} from \"../dispatch-arbiter.js\";\nimport type { ToolDefinition, ToolRenderResultOptions } from \"../extensions/types.js\";\nimport { log } from \"../logger.js\";\nimport type { ModelRegistry } from \"../model-registry.js\";\nimport { resolveCliModel } from \"../model-resolver.js\";\nimport { DEFAULT_MAX_CONCURRENT_SUBAGENTS } from \"../settings-manager.js\";\nimport { resolveEffectiveThinkingLevel, thinkingLevelToReasoning, validateThinkingLevelForModel } from \"../thinking.js\";\nimport { getTextOutput, invalidArgText, str } from \"./render-utils.js\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.js\";\nimport { DEFAULT_MAX_BYTES, formatSize, type TruncationResult } from \"./truncate.js\";\n\n// ---------------------------------------------------------------------------\n// Agent type system\n// ---------------------------------------------------------------------------\n\nexport interface AgentTypeConfig {\n\tname: string;\n\tdescription: string;\n\ttools?: string;\n\t/** Single model ID or ordered fallback list. First resolvable model wins. */\n\tmodel?: string | string[];\n\tsystemPrompt: string;\n}\n\nconst DEFAULT_AGENT = \"Explore\";\nconst SUBAGENT_THINKING_LEVELS = [\"off\", \"minimal\", \"low\", \"medium\", \"high\", \"xhigh\", \"max\"] as const;\nexport const DEFAULT_MODEL_AVAILABILITY_PROBE_TIMEOUT_MS = 120_000;\n\nexport function parseAgentFrontmatter(\n\tcontent: string,\n): { ok: true; config: AgentTypeConfig } | { ok: false; error: string } {\n\tconst fmMatch = content.match(/^---\\n([\\s\\S]*?)\\n---\\n?([\\s\\S]*)$/);\n\tif (!fmMatch) return { ok: false, error: \"missing --- frontmatter delimiters\" };\n\n\tconst frontmatter = fmMatch[1];\n\tconst body = fmMatch[2].trim();\n\n\tconst get = (key: string): string | undefined => {\n\t\tconst match = frontmatter.match(new RegExp(`^${key}:\\\\s*(.+)$`, \"m\"));\n\t\treturn match?.[1].trim();\n\t};\n\n\t/** Parse `model` field — supports single string, comma-separated, or YAML list syntax. */\n\tconst getModel = (): string | string[] | undefined => {\n\t\t// First check for YAML list syntax (indented lines starting with \"- \")\n\t\tconst listMatch = frontmatter.match(/^model:\\s*\\n((?:\\s+-\\s+.+\\n?)+)/m);\n\t\tif (listMatch) {\n\t\t\tconst items = listMatch[1]\n\t\t\t\t.split(\"\\n\")\n\t\t\t\t.map((line) => line.replace(/^\\s+-\\s+/, \"\").trim())\n\t\t\t\t.filter(Boolean);\n\t\t\treturn items.length > 1 ? items : items[0];\n\t\t}\n\t\t// Inline value — check for comma-separated list\n\t\tconst value = get(\"model\");\n\t\tif (!value) return undefined;\n\t\tif (value.includes(\",\")) {\n\t\t\tconst items = value\n\t\t\t\t.split(\",\")\n\t\t\t\t.map((s) => s.trim())\n\t\t\t\t.filter(Boolean);\n\t\t\treturn items.length > 1 ? items : items[0];\n\t\t}\n\t\treturn value;\n\t};\n\n\tconst name = get(\"name\");\n\tif (!name) return { ok: false, error: \"missing required 'name' field in frontmatter\" };\n\n\treturn {\n\t\tok: true,\n\t\tconfig: {\n\t\t\tname,\n\t\t\tdescription: get(\"description\") || \"\",\n\t\t\ttools: get(\"tools\"),\n\t\t\tmodel: getModel(),\n\t\t\tsystemPrompt: body,\n\t\t},\n\t};\n}\n\nexport function discoverAgentTypes(cwd: string): Map<string, AgentTypeConfig> {\n\tconst agents = new Map<string, AgentTypeConfig>();\n\n\t// Package-bundled agents (shipped with dreb — the canonical source of truth for built-in agents)\n\tconst packageAgentsDir = join(getPackageDir(), \"agents\");\n\tloadAgentsFromDir(packageAgentsDir, agents);\n\n\t// User-level agents (~/.dreb/agents/*.md)\n\tconst userDir = join(homedir(), CONFIG_DIR_NAME, \"agents\");\n\tloadAgentsFromDir(userDir, agents);\n\n\t// Project-level agents (.dreb/agents/*.md)\n\t// TODO: Security gate — prompt user for confirmation before loading agents from untrusted repos\n\tconst projectDir = join(cwd, \".dreb\", \"agents\");\n\tloadAgentsFromDir(projectDir, agents);\n\n\treturn agents;\n}\n\nfunction loadAgentsFromDir(dir: string, agents: Map<string, AgentTypeConfig>): void {\n\tif (!existsSync(dir)) return;\n\ttry {\n\t\tfor (const file of readdirSync(dir)) {\n\t\t\tif (!file.endsWith(\".md\")) continue;\n\t\t\ttry {\n\t\t\t\tconst content = readFileSync(join(dir, file), \"utf-8\");\n\t\t\t\tconst parsed = parseAgentFrontmatter(content);\n\t\t\t\tif (!parsed.ok) {\n\t\t\t\t\tlog.warn(`[subagent] Skipping agent file ${join(dir, file)}: ${parsed.error}`);\n\t\t\t\t} else {\n\t\t\t\t\tagents.set(parsed.config.name, parsed.config);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tlog.warn(\n\t\t\t\t\t`[subagent] Could not read agent file ${join(dir, file)}: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t} catch (err) {\n\t\tif ((err as NodeJS.ErrnoException).code !== \"ENOENT\") {\n\t\t\tlog.warn(\n\t\t\t\t`[subagent] Could not read agents directory ${dir}: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t);\n\t\t}\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Subagent process spawning\n// ---------------------------------------------------------------------------\n\nexport interface SubagentStepMetadata {\n\tstep: number;\n\tagent: string;\n\tsuccess: boolean;\n\t/** Canonical provider/model identity reported by the child process. */\n\tmodel?: string;\n\t/** Effective thinking level reported by the child process. */\n\tthinking?: ThinkingLevel;\n}\n\nexport interface SubagentArbitrationEvent extends DispatchArbitrationRecord {\n\ttype: \"subagent_arbitration\";\n\tagentId: string;\n}\n\nexport interface SubagentResult {\n\tagent: string;\n\ttask: string;\n\t/** Canonical provider/model identity reported by the child process. */\n\tmodel?: string;\n\t/** Effective thinking level reported by the child process. */\n\tthinking?: ThinkingLevel;\n\t/** Ordered effective metadata for chain steps. */\n\tsteps?: SubagentStepMetadata[];\n\texitCode: number;\n\toutput: string;\n\tstderr: string;\n\terrorMessage: string | null;\n\t/** Path to the persisted session JSONL file, if available */\n\tsessionFile?: string;\n}\n\n// Capture at module load before process.title overwrites argv memory on Linux.\n// After process.title = \"dreb\" (in cli.ts), the original argv area is overwritten\n// and process.argv[1] may return corrupted or truncated data.\nconst DREB_SCRIPT = process.argv[1] || \"dreb\";\nconst NODE_EXEC = process.execPath;\n\n/**\n * Whether RPC-controlled subagent children should emit legacy full\n * message_update frames. Set by an RPC host started with\n * --rpc-full-message-updates so nested background_agent_event payloads relayed\n * from children match the parent's opt-in (issue 535). Children launched with\n * the flag set it again in their own process, so it propagates to every depth.\n */\nlet subagentRpcFullMessageUpdates = false;\n\nexport function setSubagentRpcFullMessageUpdates(enabled: boolean): void {\n\tsubagentRpcFullMessageUpdates = enabled;\n}\n\n// Tools that must never be available to subagents — wait (subagents should\n// never no-op; they have a task to complete), watch_github_ci (parent workflow\n// orchestration), subagent (no recursive spawning), and suggest_next (would end\n// the subagent's turn mid-work).\nconst SUBAGENT_EXCLUDED_TOOLS = [\"wait\", \"watch_github_ci\", \"subagent\", \"suggest_next\"] as const;\n\n// Default standard tools for subagents when no tools are specified in the agent\n// definition. This is the set passed via --tools to the child process.\n//\n// NOTE: Always-active tools (search, skill, tasks_update) are NOT listed here —\n// the child process adds them unconditionally regardless of --tools.\n// Internal tools (tmp_read) are also excluded.\nconst SUBAGENT_DEFAULT_TOOLS = [\"read\", \"bash\", \"edit\", \"write\", \"grep\", \"find\", \"ls\", \"web_search\", \"web_fetch\"];\nconst SUBAGENT_ALWAYS_ACTIVE_TOOLS = [\"search\", \"skill\", \"tasks_update\"];\n\n/**\n * Filter a comma-separated tools string, removing any tools in SUBAGENT_EXCLUDED_TOOLS.\n * Returns the filtered tools as a comma-separated string (always non-empty — falls\n * back to SUBAGENT_DEFAULT_TOOLS if all specified tools were excluded).\n */\nexport function filterSubagentTools(tools: string | undefined): string {\n\tif (!tools) return SUBAGENT_DEFAULT_TOOLS.join(\",\");\n\tconst filtered = tools\n\t\t.split(\",\")\n\t\t.map((t) => t.trim())\n\t\t.filter((t) => !(SUBAGENT_EXCLUDED_TOOLS as readonly string[]).includes(t))\n\t\t.join(\",\");\n\treturn filtered || SUBAGENT_DEFAULT_TOOLS.join(\",\");\n}\n\nfunction summarizeAgentsForArbitration(\n\tagents: Map<string, AgentTypeConfig>,\n\tgetAgentModelsForAgent?: (name: string) => string[] | undefined,\n): DispatchAgentSummary[] {\n\treturn [...agents.values()].map((agent) => {\n\t\tconst settingsModels = getAgentModelsForAgent?.(agent.name);\n\t\treturn {\n\t\t\tname: agent.name,\n\t\t\tdescription: agent.description,\n\t\t\ttools: [\n\t\t\t\t...new Set([\n\t\t\t\t\t...filterSubagentTools(agent.tools).split(\",\").filter(Boolean),\n\t\t\t\t\t...SUBAGENT_ALWAYS_ACTIVE_TOOLS,\n\t\t\t\t]),\n\t\t\t],\n\t\t\tmodelDefaults:\n\t\t\t\tsettingsModels && settingsModels.length > 0\n\t\t\t\t\t? [...settingsModels]\n\t\t\t\t\t: agent.model\n\t\t\t\t\t\t? Array.isArray(agent.model)\n\t\t\t\t\t\t\t? [...agent.model]\n\t\t\t\t\t\t\t: [agent.model]\n\t\t\t\t\t\t: [],\n\t\t};\n\t});\n}\n\n// TODO: Support PATH-based binary discovery.\n// Currently returns the captured argv[1].\nfunction findDrebBinary(): string {\n\treturn DREB_SCRIPT;\n}\n\n/**\n * Sinks for the child process's JSONL stdout stream. Extracted so the line\n * handling is unit-testable without spawning a real child process.\n */\nexport interface ChildLineSinks {\n\t/** Called with every successfully parsed JSONL event (including the session header). */\n\tonEvent?: (event: Record<string, unknown>) => void;\n\t/** Called with each complete assistant message (`message_end`). */\n\tonAssistantMessage: (message: { role: string; content: any[] }) => void;\n\t/** Called with human-readable progress lines (tool start/end). */\n\tonProgress?: (text: string) => void;\n\t/** Called when the child reports its canonical resolved model (`agent_start`). */\n\tonModel: (modelRef: string) => void;\n\t/** Called when the child reports its effective thinking level (`agent_start`). */\n\tonThinking?: (thinkingLevel: ThinkingLevel) => void;\n\t/** Called with lines that failed to parse as JSON (often real startup errors). */\n\tonPlainLine: (line: string) => void;\n\t/** Mutable holder for the last tool name, shared across lines for progress text. */\n\ttoolNameRef: { current: string };\n}\n\nfunction canonicalModelRef(provider: string | undefined, modelId: string): string {\n\tif (!provider || modelId.startsWith(`${provider}/`)) return modelId;\n\treturn `${provider}/${modelId}`;\n}\n\n/**\n * Handle one line of a subagent child's JSONL stdout. Parses the line and\n * dispatches to the sinks: full-event relay, assistant-message collection,\n * tool progress, resolved model, and non-JSON passthrough.\n */\nexport function handleChildJsonlLine(line: string, sinks: ChildLineSinks): void {\n\tif (!line.trim()) return;\n\t// Separate JSON.parse from event handling so only parse failures\n\t// are caught as non-JSON lines — errors in handling propagate normally\n\tlet event: any;\n\ttry {\n\t\tevent = JSON.parse(line);\n\t} catch {\n\t\t// Capture non-JSON lines — on failure these often contain the real error\n\t\t// (e.g. startup errors printed before JSONL mode begins)\n\t\tsinks.onPlainLine(line.trim());\n\t\tif (line.trim().startsWith(\"{\")) {\n\t\t\tlog.warn(`[subagent] Failed to parse JSONL event: ${line.slice(0, 200)}`);\n\t\t}\n\t\treturn;\n\t}\n\tif (event === null || typeof event !== \"object\") {\n\t\t// Valid JSON but not an event object (e.g. a bare string or number) — treat\n\t\t// like a plain line so diagnostic content is preserved.\n\t\tsinks.onPlainLine(line.trim());\n\t\treturn;\n\t}\n\tif (typeof event.type === \"string\") {\n\t\tsinks.onEvent?.(event);\n\t}\n\tif (event.type === \"agent_start\") {\n\t\tif (typeof event.model?.id === \"string\") {\n\t\t\tconst provider = typeof event.model.provider === \"string\" ? event.model.provider : undefined;\n\t\t\tsinks.onModel(canonicalModelRef(provider, event.model.id));\n\t\t}\n\t\tif (\n\t\t\ttypeof event.thinkingLevel === \"string\" &&\n\t\t\t(SUBAGENT_THINKING_LEVELS as readonly string[]).includes(event.thinkingLevel)\n\t\t) {\n\t\t\tsinks.onThinking?.(event.thinkingLevel as ThinkingLevel);\n\t\t}\n\t}\n\tif (event.type === \"message_end\" && event.message?.role === \"assistant\") {\n\t\tsinks.onAssistantMessage(event.message);\n\t}\n\tif (event.type === \"tool_execution_start\" && sinks.onProgress) {\n\t\tsinks.toolNameRef.current = event.toolName || \"\";\n\t\tsinks.onProgress(`Using ${sinks.toolNameRef.current}...`);\n\t}\n\tif (event.type === \"tool_execution_end\" && sinks.onProgress) {\n\t\tsinks.onProgress(`${sinks.toolNameRef.current} done`);\n\t}\n}\n\nasync function spawnSubagent(\n\tagentConfig: AgentTypeConfig,\n\ttask: string,\n\tcwd: string,\n\tsignal?: AbortSignal,\n\tonProgress?: (event: string) => void,\n\tparentProvider?: string,\n\tsessionDir?: string,\n\tparentSessionFile?: string,\n\tonChildEvent?: (event: Record<string, unknown>) => void,\n\tthinkingOverride?: ThinkingLevel,\n\tonControlAvailable?: (client: RpcClient | undefined) => void,\n): Promise<SubagentResult> {\n\tconst drebBin = findDrebBinary();\n\tlog.debug(`[subagent] spawn: agent=${agentConfig.name} cwd=${cwd}`);\n\n\t// Validate cwd exists — spawn() throws a misleading ENOENT blaming the\n\t// binary when the cwd is invalid, making the real cause hard to diagnose\n\tif (!existsSync(cwd)) {\n\t\treturn {\n\t\t\tagent: agentConfig.name,\n\t\t\ttask,\n\t\t\texitCode: 1,\n\t\t\toutput: \"\",\n\t\t\tstderr: \"\",\n\t\t\terrorMessage: `Working directory does not exist: ${cwd}`,\n\t\t};\n\t}\n\n\tconst args: string[] = [\"--mode\", \"json\", \"--ui\", \"agent\"];\n\tif (sessionDir) {\n\t\targs.push(\"--session-dir\", sessionDir);\n\t} else {\n\t\targs.push(\"--no-session\");\n\t}\n\t// By spawn time, model should be a resolved single string (fallback resolution\n\t// happens in executeSingle). Handle string[] defensively by taking the first entry.\n\tconst modelStr = Array.isArray(agentConfig.model) ? agentConfig.model[0] : agentConfig.model;\n\tif (modelStr) {\n\t\targs.push(\"--model\", modelStr);\n\t\t// executeSingle resolves the model and provider independently. Always pass\n\t\t// that exact provider because raw model IDs may themselves contain slashes\n\t\t// (for example, OpenRouter IDs such as \"openai/gpt-oss-120b\").\n\t\tif (parentProvider) {\n\t\t\targs.push(\"--provider\", parentProvider);\n\t\t}\n\t}\n\tif (thinkingOverride) {\n\t\targs.push(\"--thinking\", thinkingOverride);\n\t}\n\t// Always pass --tools to ensure wait/subagent/suggest_next are excluded from child processes.\n\t// filterSubagentTools always returns a non-empty string.\n\targs.push(\"--tools\", filterSubagentTools(agentConfig.tools));\n\tif (agentConfig.systemPrompt) {\n\t\targs.push(\"--append-system-prompt\", agentConfig.systemPrompt);\n\t}\n\t// Pass agent type metadata so the child session can record it in its JSONL header\n\targs.push(\"--agent-type\", agentConfig.name);\n\t// Pass parent session file path so the child session can record it in its JSONL header\n\tif (parentSessionFile) {\n\t\targs.push(\"--parent-session\", parentSessionFile);\n\t}\n\targs.push(\"-p\", task);\n\tif (onControlAvailable) {\n\t\tconst rpcModeIndex = args.indexOf(\"json\");\n\t\tif (rpcModeIndex !== -1) args[rpcModeIndex] = \"rpc\";\n\t\targs.splice(args.length - 2, 2);\n\t\tif (subagentRpcFullMessageUpdates) args.push(\"--rpc-full-message-updates\");\n\t}\n\n\t// Early abort check — if the signal is already aborted (e.g. queued task whose\n\t// AbortController was aborted while waiting on bgAcquire), bail out before\n\t// spawning a child process that can never be killed. addEventListener(\"abort\")\n\t// on an already-aborted signal does NOT fire the callback in Node.js.\n\tif (signal?.aborted) {\n\t\treturn {\n\t\t\tagent: agentConfig.name,\n\t\t\ttask,\n\t\t\texitCode: 1,\n\t\t\toutput: \"\",\n\t\t\tstderr: \"\",\n\t\t\terrorMessage: \"Aborted before spawn\",\n\t\t};\n\t}\n\n\treturn new Promise<SubagentResult>((resolvePromise, rejectPromise) => {\n\t\tlet proc: ChildProcess;\n\t\ttry {\n\t\t\tproc = spawn(NODE_EXEC, [drebBin, ...args], {\n\t\t\t\tcwd,\n\t\t\t\tstdio: [onControlAvailable ? \"pipe\" : \"ignore\", \"pipe\", \"pipe\"],\n\t\t\t\tenv: { ...process.env },\n\t\t\t});\n\t\t} catch (err) {\n\t\t\trejectPromise(new Error(`Failed to spawn subagent: ${err instanceof Error ? err.message : String(err)}`));\n\t\t\treturn;\n\t\t}\n\n\t\tlet settled = false;\n\t\tlet killTimer: ReturnType<typeof setTimeout> | null = null;\n\t\tconst collectedMessages: Array<{ role: string; content: any[] }> = [];\n\t\tconst stderrChunks: string[] = [];\n\t\tlet stderrSize = 0;\n\t\tconst MAX_STDERR_BYTES = 8192;\n\t\tconst plainStdoutLines: string[] = [];\n\t\tconst toolNameRef = { current: \"\" };\n\t\tlet resolvedModel: string | undefined;\n\t\tlet resolvedThinking: ThinkingLevel | undefined;\n\t\tlet rpcRequestId = 0;\n\t\tlet rpcCompleted = false;\n\t\tlet controlError: Error | undefined;\n\t\tconst pendingRpc = new Map<string, { resolve: (value: any) => void; reject: (error: Error) => void }>();\n\t\tconst sendRpc = <T>(command: Record<string, unknown>): Promise<T> => {\n\t\t\tif (!proc.stdin?.writable) return Promise.reject(new Error(\"Subagent control channel is unavailable.\"));\n\t\t\tconst id = `subagent-${++rpcRequestId}`;\n\t\t\tproc.stdin.write(serializeJsonLine({ ...command, id }));\n\t\t\treturn new Promise<T>((resolve, reject) => pendingRpc.set(id, { resolve, reject }));\n\t\t};\n\t\tconst controlClient = onControlAvailable\n\t\t\t? ({\n\t\t\t\t\tsteer: async (message: string) => {\n\t\t\t\t\t\tawait sendRpc({ type: \"steer\", message });\n\t\t\t\t\t},\n\t\t\t\t\tgetPendingMessages: async () => sendRpc<RpcPendingMessages>({ type: \"get_pending_messages\" }),\n\t\t\t\t\tgetState: async () => sendRpc<{ steeringMode: \"all\" | \"one-at-a-time\" }>({ type: \"get_state\" }),\n\t\t\t\t} as RpcClient)\n\t\t\t: undefined;\n\n\t\t// Terminally fail a controlled child: remember the first failure, reject all\n\t\t// in-flight control requests, and stop the process (with the same SIGKILL\n\t\t// backstop as the abort path) so the close handler settles instead of the\n\t\t// child idling in RPC mode forever.\n\t\tconst failControlledChild = (err: Error) => {\n\t\t\tif (!controlError) controlError = err;\n\t\t\tfor (const request of pendingRpc.values()) request.reject(err);\n\t\t\tpendingRpc.clear();\n\t\t\ttry {\n\t\t\t\tproc.kill(\"SIGTERM\");\n\t\t\t} catch {\n\t\t\t\t/* process already exited */\n\t\t\t}\n\t\t\tkillTimer ??= setTimeout(() => {\n\t\t\t\ttry {\n\t\t\t\t\tif (!proc.killed) proc.kill(\"SIGKILL\");\n\t\t\t\t} catch {\n\t\t\t\t\t/* process already exited */\n\t\t\t\t}\n\t\t\t}, 5000);\n\t\t};\n\n\t\tproc.stdin?.on(\"error\", (err) => {\n\t\t\tlog.warn(`[subagent] stdin stream error (agent=${agentConfig.name}): ${err.message}`);\n\t\t\tfailControlledChild(err);\n\t\t});\n\n\t\t// Drain stderr concurrently to avoid pipe deadlock (capped to prevent OOM from verbose subagents)\n\t\tproc.stderr?.on(\"data\", (chunk: Buffer) => {\n\t\t\tif (stderrSize < MAX_STDERR_BYTES) {\n\t\t\t\tconst str = chunk.toString();\n\t\t\t\tstderrChunks.push(str);\n\t\t\t\tstderrSize += str.length;\n\t\t\t}\n\t\t});\n\t\tproc.stderr?.on(\"error\", (err) => {\n\t\t\tlog.warn(`[subagent] stderr stream error (agent=${agentConfig.name}): ${err.message}`);\n\t\t});\n\n\t\t// Parse JSONL events from stdout\n\t\tif (proc.stdout) {\n\t\t\tproc.stdout.on(\"error\", (err) => {\n\t\t\t\tlog.warn(`[subagent] stdout stream error (agent=${agentConfig.name}): ${err.message}`);\n\t\t\t});\n\t\t\tattachJsonlLineReader(proc.stdout, (line) => {\n\t\t\t\tif (onControlAvailable) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst message = JSON.parse(line);\n\t\t\t\t\t\tif (message?.type === \"agent_end\" && !rpcCompleted) {\n\t\t\t\t\t\t\trpcCompleted = true;\n\t\t\t\t\t\t\tsetImmediate(() => proc.kill(\"SIGTERM\"));\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (message?.type === \"response\" && typeof message.id === \"string\") {\n\t\t\t\t\t\t\tconst pending = pendingRpc.get(message.id);\n\t\t\t\t\t\t\tif (pending) {\n\t\t\t\t\t\t\t\tpendingRpc.delete(message.id);\n\t\t\t\t\t\t\t\tif (message.success) pending.resolve(message.data);\n\t\t\t\t\t\t\t\telse pending.reject(new Error(message.error ?? \"Subagent RPC command failed.\"));\n\t\t\t\t\t\t\t} else if (message.command === \"prompt\" && message.success === false && !rpcCompleted) {\n\t\t\t\t\t\t\t\t// Late failure of the initial prompt: the child acknowledged the\n\t\t\t\t\t\t\t\t// command synchronously, then failed before the agent loop started\n\t\t\t\t\t\t\t\t// (e.g. model/API-key validation, or the task was consumed without\n\t\t\t\t\t\t\t\t// starting the loop), so no agent_end will ever settle this process.\n\t\t\t\t\t\t\t\tfailControlledChild(\n\t\t\t\t\t\t\t\t\tnew Error(typeof message.error === \"string\" ? message.error : \"Subagent prompt failed.\"),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// The normal line handler preserves non-JSON diagnostics.\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\thandleChildJsonlLine(line, {\n\t\t\t\t\tonEvent: onChildEvent,\n\t\t\t\t\tonAssistantMessage: (message) => collectedMessages.push(message),\n\t\t\t\t\tonProgress,\n\t\t\t\t\tonModel: (modelRef) => {\n\t\t\t\t\t\tresolvedModel = modelRef;\n\t\t\t\t\t},\n\t\t\t\t\tonThinking: (thinkingLevel) => {\n\t\t\t\t\t\tresolvedThinking = thinkingLevel;\n\t\t\t\t\t},\n\t\t\t\t\tonPlainLine: (plain) => plainStdoutLines.push(plain),\n\t\t\t\t\ttoolNameRef,\n\t\t\t\t});\n\t\t\t});\n\t\t}\n\n\t\tif (onControlAvailable && controlClient) {\n\t\t\tonControlAvailable(controlClient);\n\t\t\tvoid sendRpc({ type: \"prompt\", message: task }).catch((err) => {\n\t\t\t\tconst error = err instanceof Error ? err : new Error(String(err));\n\t\t\t\tlog.warn(`[subagent] initial RPC prompt failed (agent=${agentConfig.name}): ${error.message}`);\n\t\t\t\t// A rejected initial prompt means the agent loop never starts and the\n\t\t\t\t// child would idle in RPC mode forever — terminate it and fail loudly.\n\t\t\t\tfailControlledChild(error);\n\t\t\t});\n\t\t}\n\n\t\t// Handle abort signal (guard kill() against ESRCH race if process already exited)\n\t\tconst onAbort = () => {\n\t\t\ttry {\n\t\t\t\tproc.kill(\"SIGTERM\");\n\t\t\t} catch {\n\t\t\t\t/* process already exited */\n\t\t\t}\n\t\t\tkillTimer = setTimeout(() => {\n\t\t\t\ttry {\n\t\t\t\t\tif (!proc.killed) proc.kill(\"SIGKILL\");\n\t\t\t\t} catch {\n\t\t\t\t\t/* process already exited */\n\t\t\t\t}\n\t\t\t}, 5000);\n\t\t};\n\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\n\t\tproc.on(\"error\", (err) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tonControlAvailable?.(undefined);\n\t\t\tfor (const request of pendingRpc.values()) request.reject(err);\n\t\t\tpendingRpc.clear();\n\t\t\tif (killTimer) clearTimeout(killTimer);\n\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\trejectPromise(new Error(`Subagent process error: ${err.message}`));\n\t\t});\n\n\t\tproc.on(\"close\", (code) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tonControlAvailable?.(undefined);\n\t\t\tfor (const request of pendingRpc.values()) request.reject(new Error(\"Subagent process exited.\"));\n\t\t\tpendingRpc.clear();\n\t\t\tif (killTimer) clearTimeout(killTimer);\n\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\tconst exitCode = rpcCompleted ? 0 : (code ?? 1);\n\t\t\tconst stderr = stderrChunks.join(\"\");\n\t\t\tlog.debug(\n\t\t\t\t`[subagent] close: agent=${agentConfig.name} exit=${exitCode} messages=${collectedMessages.length}${exitCode !== 0 ? ` stderr=${stderr.slice(0, 200)} stdout=${plainStdoutLines.join(\"|\").slice(0, 200)}` : \"\"}`,\n\t\t\t);\n\n\t\t\t// Extract final text output from collected assistant messages\n\t\t\tconst outputParts: string[] = [];\n\t\t\tfor (const msg of collectedMessages) {\n\t\t\t\tif (Array.isArray(msg.content)) {\n\t\t\t\t\tfor (const part of msg.content) {\n\t\t\t\t\t\tif (part.type === \"text\" && part.text) {\n\t\t\t\t\t\t\toutputParts.push(part.text);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst output = outputParts.join(\"\\n\\n\");\n\n\t\t\t// Inspect the final assistant message's stopReason to detect truncation\n\t\t\t// (\"length\") or a loud truncation failure (\"error\") from the core agent loop.\n\t\t\t// stopReason is present at runtime even though collectedMessages is loosely typed.\n\t\t\tconst lastMsg = collectedMessages.length > 0 ? collectedMessages[collectedMessages.length - 1] : undefined;\n\t\t\tconst lastStopReason = lastMsg ? (lastMsg as any).stopReason : undefined;\n\t\t\tconst lastErrorMessage = lastMsg ? (lastMsg as any).errorMessage : undefined;\n\n\t\t\t// Build error message from best available source: stderr, plain stdout lines, or generic\n\t\t\tlet errorMessage: string | null = null;\n\t\t\tif (exitCode !== 0) {\n\t\t\t\tconst stderrTrimmed = stderr.trim();\n\t\t\t\tconst plainOutput = plainStdoutLines.join(\"\\n\").trim();\n\t\t\t\terrorMessage =\n\t\t\t\t\tcontrolError?.message.slice(0, 500) ||\n\t\t\t\t\tstderrTrimmed.slice(0, 500) ||\n\t\t\t\t\tplainOutput.slice(0, 500) ||\n\t\t\t\t\t`Subagent exited with code ${exitCode}`;\n\t\t\t} else if (output.trim() === \"\") {\n\t\t\t\t// Clean exit but no output — surface why instead of returning a silent empty result.\n\t\t\t\tif (lastStopReason === \"length\") {\n\t\t\t\t\terrorMessage = \"Subagent response was truncated at the model's token limit before producing any output.\";\n\t\t\t\t} else if (lastStopReason === \"error\" && lastErrorMessage) {\n\t\t\t\t\terrorMessage = String(lastErrorMessage).slice(0, 500);\n\t\t\t\t} else {\n\t\t\t\t\terrorMessage = \"Subagent completed with no output.\";\n\t\t\t\t}\n\t\t\t} else if (lastStopReason === \"length\") {\n\t\t\t\t// Clean exit with partial output — keep the output but make the truncation loud.\n\t\t\t\terrorMessage = \"Subagent response was truncated at the model's token limit; output may be incomplete.\";\n\t\t\t} else if (lastStopReason === \"error\" && lastErrorMessage) {\n\t\t\t\t// Clean exit with partial output but a loud failure (e.g. length retries\n\t\t\t\t// exhausted → the core agent loop converts the truncation to stopReason\n\t\t\t\t// \"error\" while preserving the partial text). Surface the error instead of\n\t\t\t\t// letting the partial output masquerade as a clean success.\n\t\t\t\terrorMessage = String(lastErrorMessage).slice(0, 500);\n\t\t\t}\n\n\t\t\t// Discover the session file written by the child process\n\t\t\tconst sessionFile = sessionDir ? discoverSessionFile(sessionDir, agentConfig.name) : undefined;\n\t\t\tconst configuredModel = Array.isArray(agentConfig.model) ? agentConfig.model[0] : agentConfig.model;\n\n\t\t\tresolvePromise({\n\t\t\t\tagent: agentConfig.name,\n\t\t\t\ttask,\n\t\t\t\tmodel:\n\t\t\t\t\tresolvedModel ??\n\t\t\t\t\t(exitCode === 0 && configuredModel ? canonicalModelRef(parentProvider, configuredModel) : undefined),\n\t\t\t\tthinking: resolvedThinking ?? (exitCode === 0 ? thinkingOverride : undefined),\n\t\t\t\texitCode,\n\t\t\t\toutput,\n\t\t\t\tstderr: stderr.slice(0, 2000), // cap stderr\n\t\t\t\terrorMessage,\n\t\t\t\tsessionFile,\n\t\t\t});\n\t\t});\n\t});\n}\n\n// ---------------------------------------------------------------------------\n// Session file discovery and cleanup\n// ---------------------------------------------------------------------------\n\ninterface SessionFileCandidate {\n\tpath: string;\n\tmtime: number;\n}\n\nconst STEP_SESSION_DIR_RE = /^step-(\\d+)$/;\n\nfunction findNewestJsonlFileInDir(dir: string, throwOnOperationalError = false): SessionFileCandidate | undefined {\n\tlet best: SessionFileCandidate | undefined;\n\tfor (const entry of readdirSync(dir, { withFileTypes: true })) {\n\t\tif (!entry.name.endsWith(\".jsonl\")) continue;\n\t\tif (entry.isDirectory()) continue;\n\t\tconst fullPath = join(dir, entry.name);\n\t\ttry {\n\t\t\tconst mtime = statSync(fullPath).mtime.getTime();\n\t\t\tif (!best || mtime > best.mtime) best = { path: fullPath, mtime };\n\t\t} catch (err) {\n\t\t\tif (isExpectedFilesystemError(err) && (!throwOnOperationalError || isMissingFilesystemError(err))) continue;\n\t\t\tthrow err;\n\t\t}\n\t}\n\treturn best;\n}\n\nfunction discoverStepSessionFileCandidates(\n\tsessionDir: string,\n\tthrowOnOperationalError = false,\n): SessionFileCandidate[] {\n\tconst steps: Array<{ name: string; index: number }> = [];\n\tfor (const entry of readdirSync(sessionDir, { withFileTypes: true })) {\n\t\tif (!entry.isDirectory()) continue;\n\t\tconst match = STEP_SESSION_DIR_RE.exec(entry.name);\n\t\tif (!match) continue;\n\t\tsteps.push({ name: entry.name, index: Number(match[1]) });\n\t}\n\tsteps.sort((a, b) => a.index - b.index || a.name.localeCompare(b.name));\n\n\tconst files: SessionFileCandidate[] = [];\n\tfor (const step of steps) {\n\t\ttry {\n\t\t\tconst candidate = findNewestJsonlFileInDir(join(sessionDir, step.name), throwOnOperationalError);\n\t\t\tif (candidate) files.push(candidate);\n\t\t} catch (err) {\n\t\t\tif (isExpectedFilesystemError(err) && (!throwOnOperationalError || isMissingFilesystemError(err))) continue;\n\t\t\tthrow err;\n\t\t}\n\t}\n\treturn files;\n}\n\n/**\n * Find session JSONL files for a subagent session directory.\n *\n * Normal subagents write one .jsonl directly under sessionDir, so this returns\n * the most recently modified flat file. Chain-mode subagents register the chain\n * root as sessionDir but write each step under step-N/, so when no flat file is\n * present this recurses one level into step-* directories and returns one file\n * per step in numeric step order.\n */\nexport function discoverSessionFiles(\n\tsessionDir: string,\n\tagentName: string,\n\toptions: { throwOnOperationalError?: boolean } = {},\n): string[] {\n\tconst throwOnOperationalError = options.throwOnOperationalError ?? false;\n\ttry {\n\t\tif (!throwOnOperationalError && !existsSync(sessionDir)) return [];\n\t\tconst flatFile = findNewestJsonlFileInDir(sessionDir, throwOnOperationalError);\n\t\tif (flatFile) {\n\t\t\tlog.debug(`[subagent] session file: ${flatFile.path} (agent=${agentName})`);\n\t\t\treturn [flatFile.path];\n\t\t}\n\n\t\tconst stepFiles = discoverStepSessionFileCandidates(sessionDir, throwOnOperationalError);\n\t\tif (stepFiles.length > 0) {\n\t\t\tlog.debug(\n\t\t\t\t`[subagent] chain session files: ${stepFiles.map((file) => file.path).join(\", \")} (agent=${agentName})`,\n\t\t\t);\n\t\t\treturn stepFiles.map((file) => file.path);\n\t\t}\n\t} catch (err) {\n\t\tif (throwOnOperationalError) {\n\t\t\tif (isMissingFilesystemError(err)) return [];\n\t\t\tthrow err;\n\t\t}\n\t\tif (!isExpectedFilesystemError(err)) throw err;\n\t\tlog.warn(\n\t\t\t`[subagent] failed to discover session file (agent=${agentName}): ${err instanceof Error ? err.message : String(err)}`,\n\t\t);\n\t}\n\treturn [];\n}\n\n/**\n * Find the most recently modified .jsonl file in a session directory.\n * Returns the full path, or undefined if no session file was written\n * (e.g., subagent was killed before the first assistant message).\n */\nexport function discoverSessionFile(sessionDir: string, agentName: string): string | undefined {\n\tconst files = discoverSessionFiles(sessionDir, agentName);\n\tif (files.length <= 1) return files[0];\n\n\tlet best: SessionFileCandidate | undefined;\n\tfor (const file of files) {\n\t\ttry {\n\t\t\tconst candidate = { path: file, mtime: statSync(file).mtime.getTime() };\n\t\t\tif (!best || candidate.mtime > best.mtime) best = candidate;\n\t\t} catch (err) {\n\t\t\tif (isExpectedFilesystemError(err)) continue;\n\t\t\tthrow err;\n\t\t}\n\t}\n\treturn best?.path;\n}\n\n// ---------------------------------------------------------------------------\n// Execution modes\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve a model fallback list against the registry. Tries each model in order,\n * returns the first one that resolves successfully. If all fail, returns the\n * last error. Single strings are treated as a one-element list.\n */\nexport function resolveModelWithFallbacks(\n\tmodels: string | string[],\n\tparentProvider: string | undefined,\n\tregistry: ModelRegistry | undefined,\n\tparentModel?: string,\n): { ok: true; modelId: string; provider?: string; warning?: string } | { ok: false; error: string } {\n\tconst modelList = Array.isArray(models) ? models : [models];\n\tlet lastError = \"\";\n\tfor (const modelStr of modelList) {\n\t\tconst result = resolveModelStringSingle(modelStr, parentProvider, registry);\n\t\tif (result.ok) return result;\n\t\tlastError = result.error;\n\t}\n\t// After all configured fallbacks are exhausted, try the parent model as a last resort\n\tif (parentModel) {\n\t\tconst result = resolveModelStringSingle(parentModel, parentProvider, registry);\n\t\tif (result.ok) {\n\t\t\treturn {\n\t\t\t\t...result,\n\t\t\t\twarning: `Agent preferred models were unavailable. Falling back to parent model \"${result.modelId}\".`,\n\t\t\t};\n\t\t}\n\t\tlastError = result.error;\n\t}\n\tif (modelList.length > 1 || parentModel) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `None of the fallback models resolved: ${[...modelList, ...(parentModel ? [parentModel] : [])].join(\", \")}. Last error: ${lastError}`,\n\t\t};\n\t}\n\treturn { ok: false, error: lastError };\n}\n\nexport function resolveModelStringSingle(\n\tmodelStr: string,\n\tparentProvider: string | undefined,\n\tregistry: ModelRegistry | undefined,\n): { ok: true; modelId: string; provider?: string } | { ok: false; error: string } {\n\tif (!registry) {\n\t\treturn { ok: true, modelId: modelStr };\n\t}\n\n\t// If the model string contains \"/\" the user already specified a provider\n\tconst hasProvider = modelStr.includes(\"/\");\n\tconst resolved = resolveCliModel({\n\t\tcliProvider: hasProvider ? undefined : parentProvider,\n\t\tcliModel: modelStr,\n\t\tmodelRegistry: registry,\n\t});\n\n\tif (resolved.error) {\n\t\treturn { ok: false, error: resolved.error };\n\t}\n\tif (!resolved.model) {\n\t\treturn { ok: false, error: `Model \"${modelStr}\" not found. Use --list-models to see available models.` };\n\t}\n\n\t// resolveCliModel creates a synthetic model for any unknown ID when a\n\t// provider is specified (designed for custom/self-hosted models like Ollama).\n\t// For subagents this causes silent failures — reject synthetic fallbacks\n\t// so the next model in the fallback list is tried instead.\n\tif (resolved.isSyntheticFallback) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `Model \"${modelStr}\" not found for provider \"${resolved.model.provider}\". Use --list-models to see available models.`,\n\t\t};\n\t}\n\n\t// Verify the resolved provider has authentication configured.\n\t// resolveCliModel uses getAll() (all models, not just authenticated ones)\n\t// so a model can resolve successfully to a provider with no API key.\n\t// Reject early so the fallback list can continue to the next model.\n\tif (!registry.authStorage.hasAuth(resolved.model.provider)) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `No authentication configured for provider \"${resolved.model.provider}\". Model \"${modelStr}\" cannot be used.`,\n\t\t};\n\t}\n\n\treturn { ok: true, modelId: resolved.model.id, provider: resolved.model.provider };\n}\n\nexport interface ProbeModelAvailabilityOptions {\n\t/** Parent/tool abort signal. A model availability probe timeout is layered on top. */\n\tsignal?: AbortSignal;\n\t/** Model registry used to resolve provider API keys for the probe call. */\n\tregistry?: ModelRegistry;\n\t/** Override the default model availability probe timeout; primarily useful for tests. */\n\ttimeoutMs?: number;\n\t/** Stable conversation ID forwarded to providers that use session-based routing. */\n\tsessionId?: string;\n}\n\nexport type ProbeModelAvailabilityResult = { ok: true } | { ok: false; reason: string; aborted?: boolean };\n\nfunction compactErrorReason(reason: string): string {\n\tconst singleLine = reason.replace(/\\s+/g, \" \").trim();\n\treturn singleLine.length > 180 ? `${singleLine.slice(0, 177)}...` : singleLine || \"unknown error\";\n}\n\nfunction reasonFromRuntimeError(value: unknown): string {\n\tif (value instanceof Error) return value.message;\n\tif (typeof value === \"string\") return value;\n\tif (value && typeof value === \"object\") {\n\t\tconst maybeMessage = value as Partial<AssistantMessage> & { message?: unknown };\n\t\tif (typeof maybeMessage.errorMessage === \"string\") return maybeMessage.errorMessage;\n\t\tif (typeof maybeMessage.message === \"string\") return maybeMessage.message;\n\t}\n\treturn String(value);\n}\n\nexport function isRuntimeUnavailableError(value: unknown): boolean {\n\tif (value instanceof Error || typeof value === \"string\") return true;\n\tif (value && typeof value === \"object\") {\n\t\tconst maybeMessage = value as Partial<AssistantMessage>;\n\t\treturn maybeMessage.stopReason === \"error\" || maybeMessage.stopReason === \"aborted\";\n\t}\n\treturn false;\n}\n\nfunction makeProbeSignal(\n\tparentSignal: AbortSignal | undefined,\n\ttimeoutMs: number,\n): { signal: AbortSignal; timeoutPromise: Promise<never>; cleanup: () => void } {\n\tconst controller = new AbortController();\n\tconst timeoutError = new Error(`Model availability probe timed out after ${timeoutMs}ms`);\n\tlet timeout: ReturnType<typeof setTimeout>;\n\tconst timeoutPromise = new Promise<never>((_, reject) => {\n\t\ttimeout = setTimeout(() => {\n\t\t\tcontroller.abort(timeoutError);\n\t\t\treject(timeoutError);\n\t\t}, timeoutMs);\n\t});\n\tconst parentAbortHandler = () => controller.abort(parentSignal?.reason);\n\tparentSignal?.addEventListener(\"abort\", parentAbortHandler, { once: true });\n\tif (parentSignal?.aborted) controller.abort(parentSignal.reason);\n\n\treturn {\n\t\tsignal: controller.signal,\n\t\ttimeoutPromise,\n\t\tcleanup: () => {\n\t\t\tclearTimeout(timeout);\n\t\t\tparentSignal?.removeEventListener(\"abort\", parentAbortHandler);\n\t\t},\n\t};\n}\n\nexport async function probeModelAvailability(\n\tmodel: Model<Api>,\n\toptions: ProbeModelAvailabilityOptions = {},\n): Promise<ProbeModelAvailabilityResult> {\n\tconst { signal, registry, timeoutMs = DEFAULT_MODEL_AVAILABILITY_PROBE_TIMEOUT_MS, sessionId } = options;\n\tif (signal?.aborted) return { ok: false, reason: \"Aborted before spawn\", aborted: true };\n\n\tconst probeSignal = makeProbeSignal(signal, timeoutMs);\n\ttry {\n\t\tconst context: Context = {\n\t\t\tsystemPrompt: \"Reply with the single word OK.\",\n\t\t\tmessages: [{ role: \"user\", content: \"hi\", timestamp: Date.now() }],\n\t\t};\n\t\tconst apiKey = await Promise.race([\n\t\t\tregistry ? registry.getApiKey(model) : Promise.resolve(undefined),\n\t\t\tprobeSignal.timeoutPromise,\n\t\t]);\n\t\tif (signal?.aborted) return { ok: false, reason: \"Aborted before spawn\", aborted: true };\n\t\tconst thinkingLevel = resolveEffectiveThinkingLevel(model, undefined);\n\t\tconst reasoning = thinkingLevelToReasoning(thinkingLevel);\n\t\t// Use completeSimple — the same streamSimple path the agent loop uses.\n\t\t// No maxTokens override is passed by the probe; buildBaseOptions applies\n\t\t// normal model defaults. Reasoning is resolved through the shared normal\n\t\t// coding-agent thinking default/clamp path instead of provider-specific\n\t\t// probe logic, so reasoning models are probed with representative options.\n\t\tconst result = await Promise.race([\n\t\t\tcompleteSimple(model, context, {\n\t\t\t\tapiKey,\n\t\t\t\tmaxRetryDelayMs: 0,\n\t\t\t\treasoning,\n\t\t\t\tsignal: probeSignal.signal,\n\t\t\t\t...(sessionId ? { sessionId } : {}),\n\t\t\t}),\n\t\t\tprobeSignal.timeoutPromise,\n\t\t]);\n\t\tif (signal?.aborted) return { ok: false, reason: \"Aborted before spawn\", aborted: true };\n\t\tif (isRuntimeUnavailableError(result)) {\n\t\t\treturn { ok: false, reason: compactErrorReason(reasonFromRuntimeError(result)) };\n\t\t}\n\t\treturn { ok: true };\n\t} catch (err) {\n\t\tif (signal?.aborted) return { ok: false, reason: \"Aborted before spawn\", aborted: true };\n\t\treturn { ok: false, reason: compactErrorReason(reasonFromRuntimeError(err)) };\n\t} finally {\n\t\tprobeSignal.cleanup();\n\t}\n}\n\nexport interface SkippedFallbackModel {\n\tmodel: string;\n\treason: string;\n}\n\nexport type SubagentModelResolution =\n\t| {\n\t\t\tok: true;\n\t\t\tmodelId: string;\n\t\t\tprovider?: string;\n\t\t\twarning?: string;\n\t\t\tskippedModels: SkippedFallbackModel[];\n\t }\n\t| { ok: false; error: string; skippedModels: SkippedFallbackModel[] };\n\nexport async function resolveModelForSubagentSpawn(\n\tmodels: string | string[],\n\tparentProvider: string | undefined,\n\tregistry: ModelRegistry | undefined,\n\tparentModel?: string,\n\tsignal?: AbortSignal,\n\t/** Optional log prefix for warning messages (defaults to \"[subagent]\") */\n\tlogPrefix = \"[subagent]\",\n\t/** Stable conversation ID forwarded to availability probes (issue 500). */\n\tsessionId?: string,\n): Promise<SubagentModelResolution> {\n\tif (signal?.aborted) return { ok: false, error: \"Aborted before spawn\", skippedModels: [] };\n\n\t// Runtime probing only applies to agent definition fallback lists. Single\n\t// models, per-invocation overrides, and registry-less environments keep the\n\t// existing spawn-time resolution behavior exactly.\n\tif (!Array.isArray(models) || !registry) {\n\t\tconst resolved = resolveModelWithFallbacks(models, parentProvider, registry, parentModel);\n\t\treturn { ...resolved, skippedModels: [] };\n\t}\n\n\tconst skippedModels: SkippedFallbackModel[] = [];\n\tlet lastError = \"\";\n\n\tfor (const modelStr of models) {\n\t\tif (signal?.aborted) return { ok: false, error: \"Aborted before spawn\", skippedModels };\n\n\t\tconst resolved = resolveModelStringSingle(modelStr, parentProvider, registry);\n\t\tif (!resolved.ok) {\n\t\t\tlastError = resolved.error;\n\t\t\tconst reason = compactErrorReason(resolved.error);\n\t\t\tskippedModels.push({ model: modelStr, reason });\n\t\t\tlog.warn(`${logPrefix} Model \"${modelStr}\" unavailable (${reason}). Trying next fallback...`);\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst modelObj = resolved.provider ? registry.find(resolved.provider, resolved.modelId) : undefined;\n\t\tif (modelObj) {\n\t\t\tconst probe = await probeModelAvailability(modelObj, { signal, registry, sessionId });\n\t\t\tif (!probe.ok && probe.aborted) {\n\t\t\t\treturn { ok: false, error: \"Aborted before spawn\", skippedModels };\n\t\t\t}\n\t\t\tif (signal?.aborted) return { ok: false, error: \"Aborted before spawn\", skippedModels };\n\t\t\tif (!probe.ok) {\n\t\t\t\tlastError = probe.reason;\n\t\t\t\tskippedModels.push({ model: modelStr, reason: probe.reason });\n\t\t\t\tlog.warn(`${logPrefix} Model \"${modelStr}\" failed probe (${probe.reason}). Trying next fallback...`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tlog.debug(`${logPrefix} Using model \"${resolved.modelId}\".`);\n\t\treturn { ...resolved, skippedModels };\n\t}\n\n\tif (signal?.aborted) return { ok: false, error: \"Aborted before spawn\", skippedModels };\n\n\tif (parentModel) {\n\t\tconst parentResolved = resolveModelStringSingle(parentModel, parentProvider, registry);\n\t\tif (parentResolved.ok) {\n\t\t\tconst warning = `Agent preferred models were unavailable. Falling back to parent model \"${parentResolved.modelId}\".`;\n\t\t\tlog.warn(`${logPrefix} ${warning}`);\n\t\t\treturn { ...parentResolved, warning, skippedModels };\n\t\t}\n\t\tlastError = parentResolved.error;\n\t}\n\n\treturn {\n\t\tok: false,\n\t\tskippedModels,\n\t\terror: `None of the fallback models passed availability checks: ${[\n\t\t\t...models,\n\t\t\t...(parentModel ? [parentModel] : []),\n\t\t].join(\", \")}. Last error: ${lastError || \"all probes failed\"}`,\n\t};\n}\n\nexport function formatModelFallbackSummary(\n\tskippedModels: SkippedFallbackModel[],\n\tproposalModel: string | undefined,\n\tfinalModel?: string,\n): string | undefined {\n\tif (skippedModels.length === 0) return undefined;\n\tconst skipped = skippedModels.map((s) => `- ${s.model}: ${s.reason}`).join(\"\\n\");\n\tconst routeSummary =\n\t\tfinalModel && finalModel !== proposalModel\n\t\t\t? `proposal resolved to \"${proposalModel ?? \"unknown\"}\" before arbitration selected \"${finalModel}\".`\n\t\t\t: `using \"${finalModel ?? proposalModel ?? \"unknown\"}\".`;\n\treturn `[MODEL FALLBACK: skipped ${skippedModels.length} unavailable model(s); ${routeSummary}]\\n${skipped}`;\n}\n\nexport function prependModelFallbackSummary(\n\toutput: string,\n\tskippedModels: SkippedFallbackModel[],\n\tproposalModel: string | undefined,\n\tfinalModel?: string,\n): string {\n\tconst fallbackSummary = formatModelFallbackSummary(skippedModels, proposalModel, finalModel);\n\treturn fallbackSummary ? `${fallbackSummary}\\n\\n${output}` : output;\n}\n\nfunction formatSkippedModelFailureDetails(skippedModels: SkippedFallbackModel[]): string | undefined {\n\tif (skippedModels.length === 0) return undefined;\n\treturn `Skipped models:\\n${skippedModels.map((s) => `- ${s.model}: ${s.reason}`).join(\"\\n\")}`;\n}\n\nconst MAX_PARALLEL_TASKS = 8;\nconst MAX_TASK_LENGTH = 32_768; // 32 KB — prevent E2BIG from oversized argv\n\n/**\n * Bounds the number of concurrently running background subagents. Ownership of the gate is kept\n * separate from the subagent tool definition so that a single logical session keeps one accurate\n * running-child count even when its tool definitions are rebuilt (e.g. on `/reload`).\n */\nexport interface SubagentConcurrencyGate {\n\t/** Resolves immediately if a slot is free, otherwise queues until one is released. */\n\tacquire(): Promise<void>;\n\t/** Returns a slot and wakes the next waiter, if any. */\n\trelease(): void;\n}\n\n/**\n * Create a concurrency gate limited to `maxConcurrent` simultaneous holders. The count lives in\n * this closure, so a single gate instance shared across tool rebuilds keeps counting in-flight\n * children accurately, while distinct instances stay fully isolated from one another.\n */\nexport function createSubagentConcurrencyGate(maxConcurrent: number): SubagentConcurrencyGate {\n\tif (!Number.isSafeInteger(maxConcurrent) || maxConcurrent < 1) {\n\t\tthrow new Error(\"Subagent tool concurrency must be a positive whole number\");\n\t}\n\tlet running = 0;\n\tconst waiters: Array<() => void> = [];\n\treturn {\n\t\tacquire(): Promise<void> {\n\t\t\tif (running < maxConcurrent) {\n\t\t\t\trunning++;\n\t\t\t\treturn Promise.resolve();\n\t\t\t}\n\t\t\treturn new Promise<void>((resolve) => {\n\t\t\t\twaiters.push(() => {\n\t\t\t\t\trunning++;\n\t\t\t\t\tresolve();\n\t\t\t\t});\n\t\t\t});\n\t\t},\n\t\trelease(): void {\n\t\t\trunning--;\n\t\t\tconst next = waiters.shift();\n\t\t\tif (next) next();\n\t\t},\n\t};\n}\n\n/** Resolve per-task thinking precedence for parallel and chain modes. */\nexport function resolveSubagentThinkingOverride(\n\ttaskThinking: ThinkingLevel | undefined,\n\ttopLevelThinking: ThinkingLevel | undefined,\n): ThinkingLevel | undefined {\n\treturn taskThinking ?? topLevelThinking;\n}\n\n/**\n * Resolve a per-task cwd.\n * Accepts absolute paths as-is. Resolves relative paths against the parent cwd,\n * rejecting any that escape outside it.\n * Returns a result object with ok=false and an error string on rejection, so callers can surface it to the model.\n */\nfunction clampCwd(defaultCwd: string, itemCwd?: string): { ok: true; cwd: string } | { ok: false; error: string } {\n\tif (!itemCwd) return { ok: true, cwd: defaultCwd };\n\tif (itemCwd.startsWith(\"/\")) {\n\t\treturn { ok: true, cwd: itemCwd };\n\t}\n\tconst resolved = resolve(defaultCwd, itemCwd);\n\tif (resolved !== defaultCwd && !resolved.startsWith(`${defaultCwd}/`)) {\n\t\treturn { ok: false, error: `Rejected cwd \"${itemCwd}\" — resolves outside parent cwd` };\n\t}\n\treturn { ok: true, cwd: resolved };\n}\n\nexport interface SubagentArbitrationHooks {\n\tarbitrate: (request: DispatchArbitrationRequest, signal?: AbortSignal) => Promise<DispatchArbitrationResult>;\n\tonRecord: (record: DispatchArbitrationRecord) => void;\n\tstep?: number;\n\tdefaultThinkingLevel?: ThinkingLevel;\n\tgetAgentModelsForAgent?: (name: string) => string[] | undefined;\n}\n\nexport async function executeSingle(\n\tagents: Map<string, AgentTypeConfig>,\n\tagentName: string | undefined,\n\ttask: string,\n\tcwd: string,\n\tsignal?: AbortSignal,\n\tonProgress?: (event: string) => void,\n\tmodelOverride?: string,\n\tparentProvider?: string,\n\tregistry?: ModelRegistry,\n\tsessionDir?: string,\n\tparentModel?: string,\n\tagentModels?: string[],\n\tparentSessionFile?: string,\n\tonChildEvent?: (event: Record<string, unknown>) => void,\n\tthinkingOverride?: ThinkingLevel,\n\tarbitration?: SubagentArbitrationHooks,\n\tonControlAvailable?: (client: RpcClient | undefined) => void,\n\t/** Parent session UUID for spawn-time availability probes (issue 500). */\n\tparentSessionId?: string,\n\t/** Single-model mode (issue 517): the child runs on the parent session's model, ignoring model specs and the dispatch arbiter. */\n\tsingleModelMode?: boolean,\n): Promise<SubagentResult> {\n\tlet name = agentName || DEFAULT_AGENT;\n\tlet config = agents.get(name);\n\tif (!config) {\n\t\treturn {\n\t\t\tagent: name,\n\t\t\ttask,\n\t\t\texitCode: 1,\n\t\t\toutput: \"\",\n\t\t\tstderr: \"\",\n\t\t\terrorMessage: `Unknown agent type \"${name}\". Available: ${[...agents.keys()].join(\", \")}. If you expected \"${name}\" to exist, check the .md file in ~/.dreb/agents/ or .dreb/agents/ for syntax errors.`,\n\t\t};\n\t}\n\tif (task.length > MAX_TASK_LENGTH) {\n\t\treturn {\n\t\t\tagent: name,\n\t\t\ttask: `${task.slice(0, 200)}...`,\n\t\t\texitCode: 1,\n\t\t\toutput: \"\",\n\t\t\tstderr: \"\",\n\t\t\terrorMessage: `Task prompt too long (${task.length} chars, max ${MAX_TASK_LENGTH}). Shorten the prompt.`,\n\t\t};\n\t}\n\n\t// Phase 1: resolve the parent's proposal with the existing precedence and\n\t// fallback behavior so the arbiter receives one concrete canonical route.\n\tconst configuredModelSpec =\n\t\tmodelOverride || (agentModels && agentModels.length > 0 ? agentModels : undefined) || config.model;\n\tconst modelSpec = configuredModelSpec || parentModel;\n\tlet effectiveConfig: AgentTypeConfig = modelOverride ? { ...config, model: modelOverride } : config;\n\tlet resolvedProvider = parentProvider;\n\tlet resolvedModel: Model<Api> | undefined;\n\tlet warning: string | undefined;\n\tlet skippedModels: SkippedFallbackModel[] = [];\n\n\tif (singleModelMode) {\n\t\t// Single-model mode (issue 517): every child runs on the parent session's model.\n\t\t// The per-call model override, per-agent model fallback list, agent-definition model\n\t\t// spec, and dispatch arbiter are all bypassed; a requested spec is reported through\n\t\t// the `warning` that is prepended to the child's output below.\n\t\tif (!parentModel) {\n\t\t\treturn {\n\t\t\t\tagent: name,\n\t\t\t\ttask,\n\t\t\t\texitCode: 1,\n\t\t\t\toutput: \"\",\n\t\t\t\tstderr: \"\",\n\t\t\t\terrorMessage:\n\t\t\t\t\t\"Single model mode is enabled, but the parent session's model is unavailable, so subagent \" +\n\t\t\t\t\t`\"${name}\" cannot be spawned. Disable singleModelMode or run the parent session with a model.`,\n\t\t\t};\n\t\t}\n\t\tconst parentResolution = resolveModelStringSingle(parentModel, parentProvider, registry);\n\t\tif (!parentResolution.ok) {\n\t\t\treturn {\n\t\t\t\tagent: name,\n\t\t\t\ttask,\n\t\t\t\texitCode: 1,\n\t\t\t\toutput: \"\",\n\t\t\t\tstderr: \"\",\n\t\t\t\terrorMessage: `Single model mode: ${parentResolution.error}`,\n\t\t\t};\n\t\t}\n\t\teffectiveConfig = { ...effectiveConfig, model: parentResolution.modelId };\n\t\tif (parentResolution.provider) resolvedProvider = parentResolution.provider;\n\t\tif (registry && resolvedProvider) resolvedModel = registry.find(resolvedProvider, parentResolution.modelId);\n\t\tif (configuredModelSpec) {\n\t\t\twarning =\n\t\t\t\t`The user has enabled \"single model mode\" in the settings, so the model selection for this subagent ` +\n\t\t\t\t`was ignored. Using parent model \"${canonicalModelRef(resolvedProvider, parentResolution.modelId)}\".`;\n\t\t}\n\t} else if (modelSpec) {\n\t\tconst parentFallback = configuredModelSpec ? parentModel : undefined;\n\t\tconst resolved = await resolveModelForSubagentSpawn(\n\t\t\tmodelSpec,\n\t\t\tparentProvider,\n\t\t\tregistry,\n\t\t\tparentFallback,\n\t\t\tsignal,\n\t\t\t\"[subagent]\",\n\t\t\tparentSessionId,\n\t\t);\n\t\tskippedModels = resolved.skippedModels;\n\t\tif (!resolved.ok) {\n\t\t\tconst skippedDetails = formatSkippedModelFailureDetails(skippedModels);\n\t\t\treturn {\n\t\t\t\tagent: name,\n\t\t\t\ttask,\n\t\t\t\texitCode: 1,\n\t\t\t\toutput: \"\",\n\t\t\t\tstderr: \"\",\n\t\t\t\terrorMessage: skippedDetails ? `${resolved.error}\\n\\n${skippedDetails}` : resolved.error,\n\t\t\t};\n\t\t}\n\t\teffectiveConfig = { ...effectiveConfig, model: resolved.modelId };\n\t\tif (resolved.provider) resolvedProvider = resolved.provider;\n\t\tif (registry && resolvedProvider) resolvedModel = registry.find(resolvedProvider, resolved.modelId);\n\t\twarning = resolved.warning;\n\t}\n\n\tif (thinkingOverride && thinkingOverride !== \"off\" && !modelSpec) {\n\t\treturn {\n\t\t\tagent: name,\n\t\t\ttask,\n\t\t\texitCode: 1,\n\t\t\toutput: \"\",\n\t\t\tstderr: \"\",\n\t\t\terrorMessage: `Cannot validate thinking level \"${thinkingOverride}\" because agent \"${name}\" has no configured model and no parent model is available. Set a model on the agent or pass a per-call model override.`,\n\t\t};\n\t}\n\n\tconst proposalModelId = Array.isArray(effectiveConfig.model) ? effectiveConfig.model[0] : effectiveConfig.model;\n\tconst proposalSelectedModel = proposalModelId ? canonicalModelRef(resolvedProvider, proposalModelId) : undefined;\n\tlet finalThinking = thinkingOverride;\n\tlet arbitrationEnabled = false;\n\t// Single-model mode (issue 517) bypasses the dispatch arbiter: the parent model is the\n\t// final route, and the requested thinking is validated against it below like any other.\n\tif (arbitration && !singleModelMode) {\n\t\tconst proposed: DispatchRoute = {\n\t\t\tagent: name,\n\t\t\tmodel: proposalSelectedModel ?? \"\",\n\t\t\tthinking: resolveEffectiveThinkingLevel(resolvedModel, thinkingOverride, arbitration.defaultThinkingLevel),\n\t\t};\n\t\tlet arbitrationResult: DispatchArbitrationResult;\n\t\ttry {\n\t\t\tarbitrationResult = await arbitration.arbitrate(\n\t\t\t\t{\n\t\t\t\t\ttask,\n\t\t\t\t\tcwd,\n\t\t\t\t\tproposed,\n\t\t\t\t\tagents: summarizeAgentsForArbitration(agents, arbitration.getAgentModelsForAgent),\n\t\t\t\t\tparentSessionFile,\n\t\t\t\t\tstep: arbitration.step,\n\t\t\t\t},\n\t\t\t\tsignal,\n\t\t\t);\n\t\t} catch {\n\t\t\tconst errorMessage = \"Dispatch arbiter failed internally before child spawn.\";\n\t\t\ttry {\n\t\t\t\tarbitration.onRecord({\n\t\t\t\t\tstatus: \"failure\",\n\t\t\t\t\tproposed,\n\t\t\t\t\tfinal: null,\n\t\t\t\t\tchanged: [],\n\t\t\t\t\tstep: arbitration.step,\n\t\t\t\t\terrorCode: \"internal_error\",\n\t\t\t\t\terrorMessage,\n\t\t\t\t});\n\t\t\t} catch {}\n\t\t\treturn {\n\t\t\t\tagent: name,\n\t\t\t\ttask,\n\t\t\t\texitCode: 1,\n\t\t\t\toutput: \"\",\n\t\t\t\tstderr: \"\",\n\t\t\t\terrorMessage,\n\t\t\t};\n\t\t}\n\t\tif (arbitrationResult.enabled) {\n\t\t\tarbitrationEnabled = true;\n\t\t\tif (!arbitrationResult.ok) {\n\t\t\t\tconst record: DispatchArbitrationRecord = {\n\t\t\t\t\tstatus: \"failure\",\n\t\t\t\t\tproposed,\n\t\t\t\t\tfinal: null,\n\t\t\t\t\tchanged: [],\n\t\t\t\t\tstep: arbitration.step,\n\t\t\t\t\terrorCode: arbitrationResult.code,\n\t\t\t\t\terrorMessage: arbitrationResult.error,\n\t\t\t\t};\n\t\t\t\ttry {\n\t\t\t\t\tarbitration.onRecord(record);\n\t\t\t\t} catch {\n\t\t\t\t\t// The original failure still prevents spawn; do not replace it with an observer error.\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tagent: name,\n\t\t\t\t\ttask,\n\t\t\t\t\texitCode: 1,\n\t\t\t\t\toutput: \"\",\n\t\t\t\t\tstderr: \"\",\n\t\t\t\t\terrorMessage: `Dispatch arbitration failed: ${arbitrationResult.error}`,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst decision = arbitrationResult.decision;\n\t\t\tconst selectedConfig = agents.get(decision.agent);\n\t\t\tconst slash = decision.model.indexOf(\"/\");\n\t\t\tconst selectedProvider = slash > 0 ? decision.model.slice(0, slash) : \"\";\n\t\t\tconst selectedModelId = slash > 0 ? decision.model.slice(slash + 1) : \"\";\n\t\t\tconst selectedModel = registry?.find(selectedProvider, selectedModelId);\n\t\t\tif (!selectedConfig || !selectedModel) {\n\t\t\t\tconst errorMessage = !selectedConfig\n\t\t\t\t\t? \"Arbiter selected an unknown agent.\"\n\t\t\t\t\t: \"Arbiter selected an unavailable model.\";\n\t\t\t\tconst record: DispatchArbitrationRecord = {\n\t\t\t\t\tstatus: \"failure\",\n\t\t\t\t\tproposed,\n\t\t\t\t\tfinal: null,\n\t\t\t\t\tchanged: [],\n\t\t\t\t\tstep: arbitration.step,\n\t\t\t\t\terrorCode: !selectedConfig ? \"unknown_agent\" : \"out_of_scope_model\",\n\t\t\t\t\terrorMessage,\n\t\t\t\t};\n\t\t\t\ttry {\n\t\t\t\t\tarbitration.onRecord(record);\n\t\t\t\t} catch {}\n\t\t\t\treturn {\n\t\t\t\t\tagent: name,\n\t\t\t\t\ttask,\n\t\t\t\t\texitCode: 1,\n\t\t\t\t\toutput: \"\",\n\t\t\t\t\tstderr: \"\",\n\t\t\t\t\terrorMessage: `Dispatch arbitration failed: ${errorMessage}`,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst finalThinkingValidation = validateThinkingLevelForModel(selectedModel, decision.thinking);\n\t\t\tif (!finalThinkingValidation.ok) {\n\t\t\t\tconst record: DispatchArbitrationRecord = {\n\t\t\t\t\tstatus: \"failure\",\n\t\t\t\t\tproposed,\n\t\t\t\t\tfinal: null,\n\t\t\t\t\tchanged: [],\n\t\t\t\t\tstep: arbitration.step,\n\t\t\t\t\terrorCode: \"unsupported_thinking\",\n\t\t\t\t\terrorMessage: finalThinkingValidation.error,\n\t\t\t\t};\n\t\t\t\ttry {\n\t\t\t\t\tarbitration.onRecord(record);\n\t\t\t\t} catch {}\n\t\t\t\treturn {\n\t\t\t\t\tagent: name,\n\t\t\t\t\ttask,\n\t\t\t\t\texitCode: 1,\n\t\t\t\t\toutput: \"\",\n\t\t\t\t\tstderr: \"\",\n\t\t\t\t\terrorMessage: `Dispatch arbitration failed: ${finalThinkingValidation.error}`,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tname = decision.agent;\n\t\t\tconfig = selectedConfig;\n\t\t\teffectiveConfig = { ...config, model: selectedModel.id };\n\t\t\tresolvedProvider = selectedModel.provider;\n\t\t\tresolvedModel = selectedModel;\n\t\t\tfinalThinking = decision.thinking;\n\n\t\t\ttry {\n\t\t\t\tarbitration.onRecord({\n\t\t\t\t\tstatus: \"success\",\n\t\t\t\t\tproposed,\n\t\t\t\t\tfinal: decision,\n\t\t\t\t\tchanged: arbitrationResult.changed,\n\t\t\t\t\tstep: arbitration.step,\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\treturn {\n\t\t\t\t\tagent: name,\n\t\t\t\t\ttask,\n\t\t\t\t\texitCode: 1,\n\t\t\t\t\toutput: \"\",\n\t\t\t\t\tstderr: \"\",\n\t\t\t\t\terrorMessage: `Dispatch arbitration observability failed before spawn: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}\n\n\tif (finalThinking) {\n\t\tconst validation = validateThinkingLevelForModel(resolvedModel, finalThinking);\n\t\tif (!validation.ok) {\n\t\t\treturn {\n\t\t\t\tagent: name,\n\t\t\t\ttask,\n\t\t\t\texitCode: 1,\n\t\t\t\toutput: \"\",\n\t\t\t\tstderr: \"\",\n\t\t\t\terrorMessage: validation.error,\n\t\t\t};\n\t\t}\n\t}\n\n\tconst usedModel = effectiveConfig.model?.toString();\n\tonProgress?.(`Running ${name} agent${usedModel ? ` (${usedModel})` : \"\"}...`);\n\tconst result = await spawnSubagent(\n\t\teffectiveConfig,\n\t\ttask,\n\t\tcwd,\n\t\tsignal,\n\t\tonProgress,\n\t\tresolvedProvider,\n\t\tsessionDir,\n\t\tparentSessionFile,\n\t\tonChildEvent,\n\t\tfinalThinking,\n\t\tonControlAvailable,\n\t);\n\tconst finalSelectedModel = result.model ?? (usedModel ? canonicalModelRef(resolvedProvider, usedModel) : undefined);\n\tresult.output = prependModelFallbackSummary(\n\t\tresult.output,\n\t\tskippedModels,\n\t\tarbitrationEnabled ? proposalSelectedModel : finalSelectedModel,\n\t\tarbitrationEnabled ? finalSelectedModel : undefined,\n\t);\n\tif (warning) {\n\t\tconst warningContext = arbitrationEnabled ? `Proposal resolution: ${warning}` : warning;\n\t\tresult.output = `[WARNING: ${warningContext}]\\n\\n${result.output}`;\n\t}\n\treturn result;\n}\n\nasync function executeChain(\n\tagents: Map<string, AgentTypeConfig>,\n\tchain: Array<{ agent?: string; task: string; cwd?: string; model?: string; thinking?: ThinkingLevel }>,\n\tdefaultCwd: string,\n\tsignal?: AbortSignal,\n\tonProgress?: (event: string) => void,\n\tparentProvider?: string,\n\tregistry?: ModelRegistry,\n\tsessionBaseDir?: string,\n\tdefaultAgent?: string,\n\tdefaultModel?: string,\n\tdefaultThinking?: ThinkingLevel,\n\tparentModel?: string,\n\tgetAgentModelsForAgentFn?: (name: string) => string[] | undefined,\n\tparentSessionFile?: string,\n\tonChildEvent?: (event: Record<string, unknown>) => void,\n\tarbitration?: Omit<SubagentArbitrationHooks, \"step\">,\n\tonControlAvailable?: (client: RpcClient | undefined) => void,\n\t/** Parent session UUID for spawn-time availability probes (issue 500). */\n\tparentSessionId?: string,\n\t/**\n\t * Live single-model mode getter (issue 517): evaluated per step so each chain step\n\t * runs on the parent session's model when enabled, matching the per-spawn semantics\n\t * of single and parallel modes.\n\t */\n\tgetSingleModelMode?: () => boolean,\n): Promise<SubagentResult[]> {\n\tconst results: SubagentResult[] = [];\n\tlet previousOutput = \"\";\n\n\tfor (let i = 0; i < chain.length; i++) {\n\t\tif (signal?.aborted) break;\n\t\tconst step = chain[i];\n\t\tconst task = step.task.replace(/\\{previous\\}/g, previousOutput);\n\t\tonProgress?.(`Chain step ${i + 1}/${chain.length}`);\n\n\t\t// Validate task length after {previous} substitution (can compound across steps)\n\t\tif (task.length > MAX_TASK_LENGTH) {\n\t\t\tresults.push({\n\t\t\t\tagent: step.agent || defaultAgent || DEFAULT_AGENT,\n\t\t\t\ttask: `${task.slice(0, 200)}...`,\n\t\t\t\texitCode: 1,\n\t\t\t\toutput: \"\",\n\t\t\t\tstderr: \"\",\n\t\t\t\terrorMessage: `Task prompt too long after {previous} substitution (${task.length} chars, max ${MAX_TASK_LENGTH}). Shorten the prompt or summarize previous output.`,\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\n\t\tconst cwdResult = clampCwd(defaultCwd, step.cwd);\n\t\tif (!cwdResult.ok) {\n\t\t\tresults.push({\n\t\t\t\tagent: step.agent || defaultAgent || DEFAULT_AGENT,\n\t\t\t\ttask,\n\t\t\t\texitCode: 1,\n\t\t\t\toutput: \"\",\n\t\t\t\tstderr: \"\",\n\t\t\t\terrorMessage: cwdResult.error,\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\n\t\t// Each chain step gets its own session subdirectory\n\t\tconst stepSessionDir = sessionBaseDir ? join(sessionBaseDir, `step-${i + 1}`) : undefined;\n\t\tconst stepAgentName = step.agent || defaultAgent || DEFAULT_AGENT;\n\t\tconst stepMach6Models = getAgentModelsForAgentFn?.(stepAgentName);\n\t\t// Single-model mode (issue 517) is re-read per step so a mid-chain settings\n\t\t// change applies from the next step onward.\n\t\tconst singleModelMode = getSingleModelMode?.() ?? false;\n\t\tconst result = await executeSingle(\n\t\t\tagents,\n\t\t\tstep.agent || defaultAgent,\n\t\t\ttask,\n\t\t\tcwdResult.cwd,\n\t\t\tsignal,\n\t\t\tonProgress,\n\t\t\tstep.model || defaultModel,\n\t\t\tparentProvider,\n\t\t\tregistry,\n\t\t\tstepSessionDir,\n\t\t\tparentModel,\n\t\t\tstepMach6Models,\n\t\t\tparentSessionFile,\n\t\t\tonChildEvent,\n\t\t\tresolveSubagentThinkingOverride(step.thinking, defaultThinking),\n\t\t\tarbitration ? { ...arbitration, step: i + 1 } : undefined,\n\t\t\tonControlAvailable,\n\t\t\tparentSessionId,\n\t\t\tsingleModelMode,\n\t\t);\n\t\tresults.push(result);\n\n\t\tif (result.exitCode !== 0) {\n\t\t\tbreak; // stop chain on error\n\t\t}\n\t\tpreviousOutput = result.output;\n\t}\n\n\treturn results;\n}\n\n// ---------------------------------------------------------------------------\n// Background execution\n// ---------------------------------------------------------------------------\n\nfunction generateAgentId(): string {\n\treturn randomBytes(6).toString(\"hex\");\n}\n\n// ---------------------------------------------------------------------------\n// Background agent registry — queryable by TUI / Telegram frontends\n// ---------------------------------------------------------------------------\n\nexport interface BackgroundAgentInfo {\n\tagentId: string;\n\tagentType: string;\n\ttaskSummary: string;\n\tstartedAt: number;\n\tstatus: \"running\" | \"completed\" | \"failed\";\n\t/** Directory containing the agent's session JSONL file (known at spawn time). */\n\tsessionDir?: string;\n\t/** Path to the agent's session JSONL file (discovered when the child exits). */\n\tsessionFile?: string;\n\t/** Working directory the agent runs in. */\n\tcwd?: string;\n\t/** Safe host-generated pre-spawn routing decisions, ordered by chain step/attempt. */\n\tarbitrations?: DispatchArbitrationRecord[];\n}\n\nconst backgroundAgentRegistry = new Map<string, BackgroundAgentInfo>();\nconst backgroundAbortControllers = new Map<string, AbortController>();\nconst backgroundControlClients = new Map<string, RpcClient>();\n\nconst REHYDRATED_AGENT_ID_PREFIX = \"rehydrated-\";\nconst HEADER_READ_CHUNK_BYTES = 8192;\nconst MAX_HEADER_READ_BYTES = 256 * 1024;\nconst METADATA_READ_BYTES = 256 * 1024;\nconst TAIL_READ_BYTES = 64 * 1024;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null;\n}\n\nfunction isExpectedFilesystemError(err: unknown): boolean {\n\treturn typeof (err as NodeJS.ErrnoException | undefined)?.code === \"string\";\n}\n\n/** Only absence is optional during primary-root restart recovery. */\nfunction isMissingFilesystemError(err: unknown): boolean {\n\treturn (err as NodeJS.ErrnoException | undefined)?.code === \"ENOENT\";\n}\n\nfunction shouldSkipRehydrationFilesystemError(err: unknown, isPrimaryRoot: boolean, context: string): boolean {\n\tif (isMissingFilesystemError(err)) return true;\n\tif (isPrimaryRoot || !isExpectedFilesystemError(err)) return false;\n\tlog.warn(\n\t\t`[subagent] skipped compatibility-root recovery (${context}): ${err instanceof Error ? err.message : String(err)}`,\n\t);\n\treturn true;\n}\n\nfunction parseJsonlLine(line: string): Record<string, unknown> | undefined {\n\ttry {\n\t\tconst parsed = JSON.parse(line);\n\t\treturn isRecord(parsed) ? parsed : undefined;\n\t} catch (err) {\n\t\tif (err instanceof SyntaxError) return undefined;\n\t\tthrow err;\n\t}\n}\n\nfunction readFirstNonEmptyLine(filePath: string): string | undefined {\n\tlet fd: number | undefined;\n\ttry {\n\t\tfd = openSync(filePath, \"r\");\n\t\tconst chunk = Buffer.alloc(HEADER_READ_CHUNK_BYTES);\n\t\tlet buffered = \"\";\n\t\tlet bytesReadTotal = 0;\n\n\t\twhile (bytesReadTotal < MAX_HEADER_READ_BYTES) {\n\t\t\tconst bytesRead = readSync(fd, chunk, 0, Math.min(chunk.length, MAX_HEADER_READ_BYTES - bytesReadTotal), null);\n\t\t\tif (bytesRead === 0) break;\n\t\t\tbytesReadTotal += bytesRead;\n\t\t\tbuffered += chunk.toString(\"utf8\", 0, bytesRead);\n\n\t\t\tconst lines = buffered.split(/\\r?\\n/);\n\t\t\tconst completeLines = buffered.endsWith(\"\\n\") || buffered.endsWith(\"\\r\") ? lines : lines.slice(0, -1);\n\t\t\tfor (const line of completeLines) {\n\t\t\t\tif (line.trim()) return line;\n\t\t\t}\n\t\t\tbuffered = lines.at(-1) ?? \"\";\n\t\t}\n\n\t\treturn buffered.trim() ? buffered : undefined;\n\t} catch (err) {\n\t\tif (isMissingFilesystemError(err)) return undefined;\n\t\tthrow err;\n\t} finally {\n\t\tif (fd !== undefined) {\n\t\t\ttry {\n\t\t\t\tcloseSync(fd);\n\t\t\t} catch {\n\t\t\t\t// Best-effort observability: close errors are filesystem cleanup noise.\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction readFileSlice(filePath: string, start: number, length: number): string | undefined {\n\tlet fd: number | undefined;\n\ttry {\n\t\tfd = openSync(filePath, \"r\");\n\t\tconst buffer = Buffer.alloc(length);\n\t\tconst bytesRead = readSync(fd, buffer, 0, length, start);\n\t\treturn buffer.toString(\"utf8\", 0, bytesRead);\n\t} catch (err) {\n\t\tif (isMissingFilesystemError(err)) return undefined;\n\t\tthrow err;\n\t} finally {\n\t\tif (fd !== undefined) {\n\t\t\ttry {\n\t\t\t\tcloseSync(fd);\n\t\t\t} catch {\n\t\t\t\t// Best-effort observability: close errors are filesystem cleanup noise.\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction readFileStart(filePath: string, maxBytes: number): string | undefined {\n\tlet size = maxBytes;\n\ttry {\n\t\tsize = Math.min(statSync(filePath).size, maxBytes);\n\t} catch (err) {\n\t\tif (isMissingFilesystemError(err)) return undefined;\n\t\tthrow err;\n\t}\n\treturn readFileSlice(filePath, 0, size);\n}\n\nfunction readFileTail(filePath: string, maxBytes: number): string | undefined {\n\tlet start = 0;\n\tlet length = maxBytes;\n\ttry {\n\t\tconst size = statSync(filePath).size;\n\t\tstart = Math.max(0, size - maxBytes);\n\t\tlength = size - start;\n\t} catch (err) {\n\t\tif (isMissingFilesystemError(err)) return undefined;\n\t\tthrow err;\n\t}\n\treturn readFileSlice(filePath, start, length);\n}\n\nfunction parseSessionHeader(sessionFile: string): Record<string, unknown> | undefined {\n\tconst headerLine = readFirstNonEmptyLine(sessionFile);\n\tif (!headerLine) return undefined;\n\treturn parseJsonlLine(headerLine);\n}\n\nfunction comparablePath(pathValue: string): string {\n\tconst resolved = resolve(pathValue);\n\treturn process.platform === \"win32\" ? resolved.toLowerCase() : resolved;\n}\n\n/** Canonical identity for an existing path, with a lexical fallback for races/missing paths. */\nfunction canonicalExistingPath(pathValue: string): string {\n\tlet canonical: string;\n\ttry {\n\t\tcanonical = realpathSync.native(pathValue);\n\t} catch (err) {\n\t\tif (!isMissingFilesystemError(err)) throw err;\n\t\tcanonical = resolve(pathValue);\n\t}\n\treturn process.platform === \"win32\" ? canonical.toLowerCase() : canonical;\n}\n\nfunction parentSessionMatches(recordedParentSession: string, parentSessionFile: string): boolean {\n\tif (recordedParentSession === parentSessionFile) return true;\n\tif (comparablePath(recordedParentSession) === comparablePath(parentSessionFile)) return true;\n\n\t// Older/foreign invocations may disagree about absolute vs relative roots, but\n\t// dreb session filenames include a timestamp and UUID. A basename match is a\n\t// safe final fallback for recovering observability across process boundaries.\n\treturn basename(recordedParentSession) === basename(parentSessionFile);\n}\n\nfunction extractTextFromContent(content: unknown): string | undefined {\n\tif (typeof content === \"string\") return content.trim() || undefined;\n\tif (!Array.isArray(content)) return undefined;\n\n\tconst parts: string[] = [];\n\tfor (const item of content) {\n\t\tif (!isRecord(item)) continue;\n\t\tif (item.type === \"text\" && typeof item.text === \"string\" && item.text.trim()) {\n\t\t\tparts.push(item.text.trim());\n\t\t}\n\t}\n\tconst text = parts.join(\"\\n\").trim();\n\treturn text || undefined;\n}\n\nfunction truncateTaskSummary(text: string): string {\n\tconst normalized = text.replace(/\\s+/g, \" \").trim();\n\treturn normalized.length > 120 ? `${normalized.slice(0, 117)}...` : normalized;\n}\n\nfunction findFirstUserMessageSummary(sessionFile: string): string | undefined {\n\tconst head = readFileStart(sessionFile, METADATA_READ_BYTES);\n\tif (!head) return undefined;\n\n\tfor (const line of head.split(/\\r?\\n/)) {\n\t\tif (!line.trim()) continue;\n\t\tconst entry = parseJsonlLine(line);\n\t\tif (entry?.type !== \"message\" || !isRecord(entry.message)) continue;\n\t\tif (entry.message.role !== \"user\") continue;\n\t\tconst text = extractTextFromContent(entry.message.content);\n\t\tif (text) return truncateTaskSummary(text);\n\t}\n\treturn undefined;\n}\n\nfunction inferCompletedSessionStatus(sessionFile: string): \"completed\" | \"failed\" {\n\tconst tail = readFileTail(sessionFile, TAIL_READ_BYTES);\n\tif (!tail) return \"completed\";\n\n\tconst lines = tail.split(/\\r?\\n/).reverse();\n\tfor (const line of lines) {\n\t\tif (!line.trim()) continue;\n\t\tconst entry = parseJsonlLine(line);\n\t\tif (entry?.type !== \"message\" || !isRecord(entry.message)) continue;\n\t\tif (entry.message.role !== \"assistant\") continue;\n\n\t\tconst stopReason = entry.message.stopReason;\n\t\treturn stopReason === \"error\" || stopReason === \"aborted\" ? \"failed\" : \"completed\";\n\t}\n\treturn \"completed\";\n}\n\nfunction parseStartedAt(header: Record<string, unknown>, sessionFile: string): number {\n\tif (typeof header.timestamp === \"string\") {\n\t\tconst timestamp = Date.parse(header.timestamp);\n\t\tif (Number.isFinite(timestamp)) return timestamp;\n\t}\n\n\ttry {\n\t\treturn statSync(sessionFile).mtime.getTime();\n\t} catch (err) {\n\t\tif (isMissingFilesystemError(err)) return Date.now();\n\t\tthrow err;\n\t}\n}\n\nfunction hasRegisteredSession(sessionDir: string, sessionFile: string): boolean {\n\tconst comparableSessionDir = canonicalExistingPath(sessionDir);\n\tconst comparableSessionFile = canonicalExistingPath(sessionFile);\n\tfor (const agent of backgroundAgentRegistry.values()) {\n\t\tif (agent.sessionDir && canonicalExistingPath(agent.sessionDir) === comparableSessionDir) return true;\n\t\tif (agent.sessionFile && canonicalExistingPath(agent.sessionFile) === comparableSessionFile) return true;\n\t}\n\treturn false;\n}\n\n/**\n * Recover completed background subagents after a dashboard/RPC process resumes\n * an existing parent session. Live background-agent state is an in-memory\n * registry, while child sessions are durable JSONL files under the subagent\n * sessions directory.\n *\n * The first root is authoritative: absence races and malformed JSON are skipped,\n * while operational filesystem failures throw. Later roots are compatibility\n * stores, so their operational filesystem failures are warned and skipped.\n * Returns the number of newly registered agents.\n */\nexport function rehydrateBackgroundAgentsFromDisk(\n\tparentSessionFile: string | undefined,\n\tsubagentSessionRoots: string | readonly string[] = getSubagentSessionsDir(),\n): number {\n\tif (!parentSessionFile) return 0;\n\n\tconst roots = typeof subagentSessionRoots === \"string\" ? [subagentSessionRoots] : subagentSessionRoots;\n\tconst scannedRoots = new Set<string>();\n\tconst seenSessionDirs = new Set<string>();\n\tconst seenSessionFiles = new Set<string>();\n\tlet registered = 0;\n\n\tfor (const [rootIndex, subagentSessionsBase] of roots.entries()) {\n\t\tconst isPrimaryRoot = rootIndex === 0;\n\t\tlet canonicalRoot: string;\n\t\ttry {\n\t\t\tcanonicalRoot = canonicalExistingPath(subagentSessionsBase);\n\t\t} catch (err) {\n\t\t\tif (shouldSkipRehydrationFilesystemError(err, isPrimaryRoot, `root ${subagentSessionsBase}`)) continue;\n\t\t\tthrow err;\n\t\t}\n\t\tif (scannedRoots.has(canonicalRoot)) continue;\n\t\tscannedRoots.add(canonicalRoot);\n\n\t\tlet entries: Dirent[];\n\t\ttry {\n\t\t\tentries = readdirSync(subagentSessionsBase, { withFileTypes: true });\n\t\t} catch (err) {\n\t\t\tif (shouldSkipRehydrationFilesystemError(err, isPrimaryRoot, `root ${subagentSessionsBase}`)) continue;\n\t\t\tthrow err;\n\t\t}\n\n\t\tfor (const entry of entries) {\n\t\t\tconst sessionDir = join(subagentSessionsBase, entry.name);\n\t\t\ttry {\n\t\t\t\tlet isDirectory = entry.isDirectory();\n\t\t\t\tif (!isDirectory && entry.isSymbolicLink()) {\n\t\t\t\t\tisDirectory = statSync(sessionDir).isDirectory();\n\t\t\t\t}\n\t\t\t\tif (!isDirectory) continue;\n\n\t\t\t\tconst canonicalSessionDir = canonicalExistingPath(sessionDir);\n\t\t\t\tif (seenSessionDirs.has(canonicalSessionDir)) continue;\n\t\t\t\tseenSessionDirs.add(canonicalSessionDir);\n\n\t\t\t\tconst sessionFiles = discoverSessionFiles(sessionDir, entry.name, { throwOnOperationalError: true });\n\t\t\t\tif (sessionFiles.length === 0) continue;\n\n\t\t\t\tlet sessionFile: string | undefined;\n\t\t\t\tlet header: Record<string, unknown> | undefined;\n\t\t\t\tfor (const candidateFile of sessionFiles) {\n\t\t\t\t\tconst candidateHeader = parseSessionHeader(candidateFile);\n\t\t\t\t\tif (candidateHeader?.type !== \"session\" || typeof candidateHeader.parentSession !== \"string\") continue;\n\t\t\t\t\tif (!parentSessionMatches(candidateHeader.parentSession, parentSessionFile)) continue;\n\t\t\t\t\tconst canonicalSessionFile = canonicalExistingPath(candidateFile);\n\t\t\t\t\tif (seenSessionFiles.has(canonicalSessionFile)) break;\n\t\t\t\t\tseenSessionFiles.add(canonicalSessionFile);\n\t\t\t\t\tsessionFile = candidateFile;\n\t\t\t\t\theader = candidateHeader;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (!sessionFile || !header || hasRegisteredSession(sessionDir, sessionFile)) continue;\n\n\t\t\t\tconst baseAgentId = `${REHYDRATED_AGENT_ID_PREFIX}${entry.name}`;\n\t\t\t\tlet agentId = baseAgentId;\n\t\t\t\tlet suffix = 2;\n\t\t\t\twhile (backgroundAgentRegistry.has(agentId)) {\n\t\t\t\t\tagentId = `${baseAgentId}-${suffix++}`;\n\t\t\t\t}\n\n\t\t\t\tconst statusFile = sessionFiles[sessionFiles.length - 1] ?? sessionFile;\n\t\t\t\tconst agentType =\n\t\t\t\t\ttypeof header.agentType === \"string\" && header.agentType.trim() ? header.agentType : \"agent\";\n\t\t\t\tconst taskSummary = findFirstUserMessageSummary(sessionFile) ?? `${agentType} (${entry.name})`;\n\t\t\t\tbackgroundAgentRegistry.set(agentId, {\n\t\t\t\t\tagentId,\n\t\t\t\t\tagentType,\n\t\t\t\t\ttaskSummary,\n\t\t\t\t\tstartedAt: parseStartedAt(header, sessionFile),\n\t\t\t\t\tstatus: inferCompletedSessionStatus(statusFile),\n\t\t\t\t\tsessionDir,\n\t\t\t\t\tsessionFile,\n\t\t\t\t\tcwd: typeof header.cwd === \"string\" ? header.cwd : undefined,\n\t\t\t\t});\n\t\t\t\tregistered++;\n\t\t\t} catch (err) {\n\t\t\t\tif (shouldSkipRehydrationFilesystemError(err, isPrimaryRoot, `entry ${sessionDir}`)) continue;\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn registered;\n}\n\nfunction cloneBackgroundAgentInfo(info: BackgroundAgentInfo): BackgroundAgentInfo {\n\treturn {\n\t\t...info,\n\t\tarbitrations: info.arbitrations?.map((record) => structuredClone(record)),\n\t};\n}\n\n/** Get a snapshot of all tracked background agents (running and recently completed). Returns readonly clones. */\nexport function getBackgroundAgents(): readonly Readonly<BackgroundAgentInfo>[] {\n\treturn [...backgroundAgentRegistry.values()].map(cloneBackgroundAgentInfo);\n}\n\n/** Get only currently running background agents. Returns readonly clones. */\nexport function getRunningBackgroundAgents(): readonly Readonly<BackgroundAgentInfo>[] {\n\treturn [...backgroundAgentRegistry.values()].filter((a) => a.status === \"running\").map(cloneBackgroundAgentInfo);\n}\n\nfunction getBackgroundControlClient(agentId: string): RpcClient {\n\tconst info = backgroundAgentRegistry.get(agentId);\n\tif (!info) throw new Error(`Unknown background agent \"${agentId}\".`);\n\tif (info.status !== \"running\") throw new Error(`Background agent \"${agentId}\" is no longer running.`);\n\tconst client = backgroundControlClients.get(agentId);\n\tif (!client) throw new Error(`Background agent \"${agentId}\" has not started a controllable child yet.`);\n\treturn client;\n}\n\n/** Queue the user's message unchanged in the selected live child session. */\nexport async function steerBackgroundAgent(agentId: string, message: string): Promise<void> {\n\tawait getBackgroundControlClient(agentId).steer(message);\n}\n\n/** Read pending steering messages and the effective delivery mode from the selected live child. */\nexport async function getBackgroundAgentPendingSteering(\n\tagentId: string,\n): Promise<{ steeringMode: \"all\" | \"one-at-a-time\"; pending: RpcPendingMessages }> {\n\tconst client = getBackgroundControlClient(agentId);\n\tconst [state, pending] = await Promise.all([client.getState(), client.getPendingMessages()]);\n\treturn { steeringMode: state.steeringMode, pending };\n}\n\n/** Abort all running background agents. */\nexport function abortBackgroundAgents(): void {\n\tfor (const [id, controller] of backgroundAbortControllers) {\n\t\tcontroller.abort();\n\t\tconst entry = backgroundAgentRegistry.get(id);\n\t\tif (entry && entry.status === \"running\") {\n\t\t\tentry.status = \"failed\";\n\t\t}\n\t}\n\tbackgroundAbortControllers.clear();\n\tbackgroundControlClients.clear();\n}\n\n/** Remove completed/failed entries older than the given age (ms). Default: 5 minutes. */\nexport function pruneBackgroundAgents(maxAgeMs = 5 * 60 * 1000): void {\n\tconst now = Date.now();\n\tfor (const [id, info] of backgroundAgentRegistry) {\n\t\tif (info.status !== \"running\" && now - info.startedAt > maxAgeMs) {\n\t\t\tbackgroundAgentRegistry.delete(id);\n\t\t\tbackgroundAbortControllers.delete(id);\n\t\t\tbackgroundControlClients.delete(id);\n\t\t}\n\t}\n}\n\nexport interface SubagentToolOptions {\n\t/** Resolved root for new subagent child-session directories. Defaults to the legacy agent root. */\n\tsubagentSessionsDir?: string;\n\t/** Called when a background subagent starts. Used by TUI to show status indicators. */\n\tonBackgroundStart?: (agentId: string, agentType: string, taskSummary: string, sessionDir?: string) => void;\n\t/** Called when a background subagent completes with its result. `cancelled` is true if the user aborted it. */\n\tonBackgroundComplete?: (agentId: string, result: SubagentResult, cancelled: boolean) => void;\n\t/**\n\t * Called with every JSONL event a background child process emits, tagged with the\n\t * child's agentId. Enables live observability relays (e.g. the dashboard) without\n\t * tailing session files. Chain steps share the chain's agentId.\n\t */\n\tonBackgroundEvent?: (agentId: string, event: Record<string, unknown>) => void;\n\t/** Parent session's current provider (e.g. \"anthropic\"). Called at each invocation to get the live value after mid-session model switches. */\n\tparentProvider?: () => string | undefined;\n\t/** Parent session's current model ID. Used as a final fallback when all subagent-configured models fail to resolve. Called at each invocation for fresh value. */\n\tparentModel?: () => string | undefined;\n\t/** Parent session's current session file path. Used to link subagent child sessions back to their parent session. */\n\tparentSessionFile?: () => string | undefined;\n\t/**\n\t * Parent session's stable conversation UUID. Forwarded to spawn-time model availability\n\t * probes so providers with session-based routing (e.g. OpenCode) can group the probe\n\t * with the parent conversation (issue 500).\n\t */\n\tparentSessionId?: () => string | undefined;\n\t/**\n\t * Live single-model mode setting, evaluated at each spawn. When true, every child runs\n\t * on the parent session's model: the per-call `model` override, per-agent model fallback\n\t * lists, the agent definition's `model` spec, and the dispatch arbiter are all bypassed,\n\t * and a warning is prepended to child output whenever an ignored model spec was requested.\n\t */\n\tsingleModelMode?: () => boolean;\n\t/** Model registry for validating model names before spawning child processes. */\n\tmodelRegistry?: ModelRegistry;\n\t/** Settings-based model override getter for mach6.models. */\n\tgetAgentModelsForAgent?: (agentName: string) => string[] | undefined;\n\t/** Mode-independent headless arbitration callback. Disabled arbitration returns `{ enabled: false }`. */\n\tarbitrate?: (request: DispatchArbitrationRequest, signal?: AbortSignal) => Promise<DispatchArbitrationResult>;\n\t/** Persist and relay one safe host-generated record for each enabled arbitration attempt. */\n\tonArbitration?: (event: SubagentArbitrationEvent) => void;\n\t/** Effective default used to make an omitted proposed thinking level concrete for the arbiter. */\n\tdefaultThinkingLevel?: () => ThinkingLevel;\n\t/**\n\t * Maximum children this parent tool instance may run concurrently. Must be at least one.\n\t * Used for the model-visible description and, when `concurrencyGate` is omitted, to size a\n\t * fresh per-instance gate.\n\t */\n\tmaxConcurrentSubagents?: number;\n\t/**\n\t * Externally owned concurrency gate. Supply this so the running-child count survives tool\n\t * definition rebuilds (e.g. on `/reload`); without it the tool creates its own gate sized by\n\t * `maxConcurrentSubagents`, which resets to zero each time the tool is recreated.\n\t */\n\tconcurrencyGate?: SubagentConcurrencyGate;\n}\n\n// ---------------------------------------------------------------------------\n// Tool schema and definition\n// ---------------------------------------------------------------------------\n\nconst thinkingLevelSchema = Type.Union(\n\t[\n\t\tType.Literal(\"off\"),\n\t\tType.Literal(\"minimal\"),\n\t\tType.Literal(\"low\"),\n\t\tType.Literal(\"medium\"),\n\t\tType.Literal(\"high\"),\n\t\tType.Literal(\"xhigh\"),\n\t\tType.Literal(\"max\"),\n\t],\n\t{ description: \"Thinking level override for the child model.\" },\n);\n\nconst taskItemSchema = Type.Object({\n\tagent: Type.Optional(Type.String({ description: \"Agent type name (default: 'Explore')\" })),\n\ttask: Type.String({ description: \"The task prompt for this subagent\" }),\n\tcwd: Type.Optional(\n\t\tType.String({\n\t\t\tdescription:\n\t\t\t\t\"Working directory (defaults to parent's cwd). Accepts absolute paths or relative paths within parent's cwd.\",\n\t\t}),\n\t),\n\tmodel: Type.Optional(\n\t\tType.String({\n\t\t\tdescription:\n\t\t\t\t\"Model override for this task. Takes precedence over agent definition model. Note: a single-string override discards the agent's fallback list.\",\n\t\t}),\n\t),\n\tthinking: Type.Optional(thinkingLevelSchema),\n});\n\nconst subagentSchema = Type.Object({\n\tagent: Type.Optional(Type.String({ description: \"Agent type name (default: 'Explore')\" })),\n\ttask: Type.Optional(Type.String({ description: \"Task prompt (single mode)\", minLength: 1 })),\n\tmodel: Type.Optional(\n\t\tType.String({\n\t\t\tdescription:\n\t\t\t\t\"Model override. Takes precedence over agent definition model. Note: a single-string override discards the agent's fallback list. For parallel/chain, set per-task instead.\",\n\t\t}),\n\t),\n\tthinking: Type.Optional(\n\t\tType.Union(\n\t\t\t[\n\t\t\t\tType.Literal(\"off\"),\n\t\t\t\tType.Literal(\"minimal\"),\n\t\t\t\tType.Literal(\"low\"),\n\t\t\t\tType.Literal(\"medium\"),\n\t\t\t\tType.Literal(\"high\"),\n\t\t\t\tType.Literal(\"xhigh\"),\n\t\t\t\tType.Literal(\"max\"),\n\t\t\t],\n\t\t\t{\n\t\t\t\tdescription:\n\t\t\t\t\t\"Thinking level override. Per-task values take precedence in parallel and chain modes. Omit to preserve child defaults.\",\n\t\t\t},\n\t\t),\n\t),\n\ttasks: Type.Optional(\n\t\tType.Array(taskItemSchema, {\n\t\t\tdescription: \"Array of tasks to run in parallel (max 8)\",\n\t\t\tminItems: 1,\n\t\t\tmaxItems: MAX_PARALLEL_TASKS,\n\t\t}),\n\t),\n\tchain: Type.Optional(\n\t\tType.Array(taskItemSchema, {\n\t\t\tdescription: \"Sequential pipeline — each step can use {previous} for prior output\",\n\t\t\tminItems: 1,\n\t\t}),\n\t),\n\t// background parameter removed — all subagents run in background mode.\n\t// Kept in schema for backward compatibility (silently ignored if passed).\n\tbackground: Type.Optional(\n\t\tType.Boolean({ description: \"Deprecated — all subagents run in background mode. This parameter is ignored.\" }),\n\t),\n});\n\nexport type SubagentToolInput = Static<typeof subagentSchema>;\n\nexport interface SubagentToolDetails {\n\ttruncation?: TruncationResult;\n\tmode: \"single\" | \"parallel\" | \"chain\";\n\tagentCount: number;\n}\n\nfunction formatSubagentCall(\n\targs: SubagentToolInput | undefined,\n\ttheme: typeof import(\"../../modes/interactive/theme/theme.js\").theme,\n\targsComplete = true,\n): string {\n\tconst invalidArg = invalidArgText(theme);\n\n\tif (args?.tasks) {\n\t\t// Show agent type(s) in the parallel label\n\t\tconst agentCounts = new Map<string, number>();\n\t\tfor (const t of args.tasks) {\n\t\t\tconst name = t.agent || args.agent || DEFAULT_AGENT;\n\t\t\tagentCounts.set(name, (agentCounts.get(name) || 0) + 1);\n\t\t}\n\t\tlet typeLabel: string;\n\t\tif (agentCounts.size === 1) {\n\t\t\tconst [name] = [...agentCounts.keys()];\n\t\t\ttypeLabel = `${args.tasks.length} ${name} tasks`;\n\t\t} else {\n\t\t\tconst parts = [...agentCounts.entries()].map(([name, count]) => `${count} ${name}`);\n\t\t\ttypeLabel = `${args.tasks.length} tasks: ${parts.join(\", \")}`;\n\t\t}\n\t\treturn `${theme.fg(\"toolTitle\", theme.bold(\"subagent\"))} ${theme.fg(\"accent\", `parallel (${typeLabel})`)}`;\n\t}\n\tif (args?.chain) {\n\t\tconst agentName = str(args.agent) || args.chain[0]?.agent || DEFAULT_AGENT;\n\t\treturn `${theme.fg(\"toolTitle\", theme.bold(\"subagent\"))} ${theme.fg(\"accent\", `chain (${agentName}, ${args.chain.length} steps)`)}`;\n\t}\n\n\tconst agent = str(args?.agent) || DEFAULT_AGENT;\n\tconst model = str(args?.model);\n\tconst task = str(args?.task);\n\tconst taskPreview = task ? (task.length > 60 ? `${task.slice(0, 57)}...` : task) : null;\n\tconst modelSuffix = model ? ` ${theme.fg(\"muted\", `(${model})`)}` : \"\";\n\treturn (\n\t\ttheme.fg(\"toolTitle\", theme.bold(\"subagent\")) +\n\t\t\" \" +\n\t\ttheme.fg(\"accent\", agent) +\n\t\tmodelSuffix +\n\t\t\" \" +\n\t\t(taskPreview === null\n\t\t\t? argsComplete\n\t\t\t\t? invalidArg\n\t\t\t\t: theme.fg(\"muted\", \"…\")\n\t\t\t: theme.fg(\"toolOutput\", `\"${taskPreview}\"`))\n\t);\n}\n\nfunction formatSubagentResult(\n\tresult: {\n\t\tcontent: Array<{ type: string; text?: string }>;\n\t\tdetails?: SubagentToolDetails;\n\t},\n\toptions: ToolRenderResultOptions,\n\ttheme: typeof import(\"../../modes/interactive/theme/theme.js\").theme,\n\tshowImages: boolean,\n): string {\n\tconst output = getTextOutput(result, showImages).trim();\n\tlet text = \"\";\n\tif (output) {\n\t\tconst lines = output.split(\"\\n\");\n\t\tconst maxLines = options.expanded ? lines.length : 25;\n\t\tconst displayLines = lines.slice(0, maxLines);\n\t\tconst remaining = lines.length - maxLines;\n\t\ttext += `\\n${displayLines.map((line) => theme.fg(\"toolOutput\", line)).join(\"\\n\")}`;\n\t\tif (remaining > 0) {\n\t\t\ttext += `${theme.fg(\"muted\", `\\n... (${remaining} more lines,`)} ${keyHint(\"app.tools.expand\", \"to expand\")})`;\n\t\t}\n\t}\n\tconst truncation = result.details?.truncation;\n\tif (truncation?.truncated) {\n\t\ttext += `\\n${theme.fg(\"warning\", `[Truncated: ${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit]`)}`;\n\t}\n\treturn text;\n}\n\nexport function formatSingleResult(result: SubagentResult): string {\n\tconst metadata = [\n\t\tresult.model ? `model: ${result.model}` : undefined,\n\t\tresult.thinking ? `thinking: ${result.thinking}` : undefined,\n\t]\n\t\t.filter((value): value is string => value !== undefined)\n\t\t.join(\", \");\n\tlet text = `## Agent: ${result.agent}${metadata ? ` (${metadata})` : \"\"}\\n`;\n\tif (result.exitCode !== 0) {\n\t\ttext += `**Error** (exit ${result.exitCode}): ${result.errorMessage || \"Unknown error\"}\\n`;\n\t\tif (result.stderr) {\n\t\t\ttext += `\\nStderr:\\n${result.stderr}\\n`;\n\t\t}\n\t} else if (result.errorMessage) {\n\t\t// Clean exit but an error was surfaced (e.g. truncation at the token limit).\n\t\ttext += `**Error**: ${result.errorMessage}\\n`;\n\t}\n\tif (result.output) {\n\t\ttext += `\\n${result.output}`;\n\t} else if (result.exitCode === 0 && !result.errorMessage) {\n\t\ttext += \"\\n(No output)\";\n\t}\n\tif (result.sessionFile) {\n\t\ttext += `\\n\\nSession log: ${result.sessionFile}`;\n\t}\n\treturn text;\n}\n\nexport function createSubagentToolDefinition(\n\tcwd: string,\n\toptions?: SubagentToolOptions,\n): ToolDefinition<typeof subagentSchema, SubagentToolDetails | undefined> {\n\tconst subagentSessionsBase = options?.subagentSessionsDir ?? getSubagentSessionsDir();\n\tconst onBackgroundStart = options?.onBackgroundStart;\n\tconst onBackgroundComplete = options?.onBackgroundComplete;\n\tconst onBackgroundEvent = options?.onBackgroundEvent;\n\tconst getParentProvider = options?.parentProvider ?? (() => undefined);\n\tconst getParentModel = options?.parentModel ?? (() => undefined);\n\tconst getParentSessionFile = options?.parentSessionFile ?? (() => undefined);\n\tconst getParentSessionId = options?.parentSessionId ?? (() => undefined);\n\tconst getSingleModelMode = options?.singleModelMode ?? (() => false);\n\tconst modelRegistry = options?.modelRegistry;\n\tconst getAgentModelsForAgent = options?.getAgentModelsForAgent;\n\tconst arbitrate = options?.arbitrate;\n\tconst onArbitration = options?.onArbitration;\n\tconst getDefaultThinkingLevel = options?.defaultThinkingLevel;\n\tconst maxConcurrentSubagents = options?.maxConcurrentSubagents ?? DEFAULT_MAX_CONCURRENT_SUBAGENTS;\n\tif (!Number.isSafeInteger(maxConcurrentSubagents) || maxConcurrentSubagents < 1) {\n\t\tthrow new Error(\"Subagent tool concurrency must be a positive whole number\");\n\t}\n\n\t// The concurrency gate is owned by the caller (e.g. AgentSession) so that it survives\n\t// runtime rebuilds/reloads: the tool definition is recreated on every `/reload`, but the\n\t// gate must keep counting in-flight children launched before the reload. When no gate is\n\t// supplied (external SDK callers, tests) the tool owns a fresh per-instance gate, which\n\t// still keeps separately embedded sessions from coupling through module-global state.\n\tconst concurrencyGate = options?.concurrencyGate ?? createSubagentConcurrencyGate(maxConcurrentSubagents);\n\tconst acquireBackgroundSlot = (): Promise<void> => concurrencyGate.acquire();\n\tconst releaseBackgroundSlot = (): void => concurrencyGate.release();\n\n\t// Discover agents at definition time to build the prompt guidelines.\n\t// This is cheap (reads .md files) and the same call happens on every execute().\n\tconst knownAgents = discoverAgentTypes(cwd);\n\tconst agentListParts: string[] = [];\n\tfor (const [name, config] of knownAgents) {\n\t\tconst defaultTag = name === DEFAULT_AGENT ? \" (default)\" : \"\";\n\t\tconst desc = config.description || name;\n\t\tagentListParts.push(`'${name}'${defaultTag} — ${desc}`);\n\t}\n\tconst builtInAgentsLine = `Built-in agents: ${agentListParts.join(\"; \")}`;\n\n\treturn {\n\t\tname: \"subagent\",\n\t\tlabel: \"subagent\",\n\t\tdescription:\n\t\t\t\"Run focused, independent work in a child agent when the task matches that agent's defined role \" +\n\t\t\t\"(Explore for concrete evidence gathering, Sandbox for isolated /tmp-only analysis). \" +\n\t\t\t`Supports \\`task\\` for a single task, \\`tasks\\` for parallel execution in one call (up to 8, max ${maxConcurrentSubagents} concurrent), ` +\n\t\t\t\"and `chain` for a sequential pipeline with {previous} substitution. \" +\n\t\t\t\"All subagents run in background — returns immediately, notifies on completion.\",\n\t\tpromptSnippet: \"Run role-matched work in independent child agents\",\n\t\tpromptGuidelines: [\n\t\t\t\"`subagent` can be used for focused, independent work that matches a child agent's defined role; delegation is optional, not an unconditional default\",\n\t\t\t\"When `agent` is omitted, the default is `Explore`. Default Explore is for concrete, bounded evidence gathering: locating files, symbols, or documentation; enumerating call sites; quoting exact snippets; and tracing an explicit data flow\",\n\t\t\t\"Do not ask default Explore to diagnose root causes, interpret ambiguous requirements, make architecture or design decisions, recommend an implementation, or produce an implementation plan. The primary agent must synthesize Explore evidence and own those conclusions\",\n\t\t\t\"Good default Explore tasks: find every file that renders a named component; list tests for a specific behavior; quote code that limits a collection; locate documented examples; enumerate call sites. Bad default Explore tasks: investigate a root cause; decide ambiguous behavior; recommend an implementation; design an architecture or refactor; produce an implementation plan\",\n\t\t\t\"Parallel and chain modes do not make a role-inappropriate task suitable for default Explore. Specialized agents may perform the broader work described by their own definitions\",\n\t\t\t\"Available agent types can be discovered from ~/.dreb/agents/ and .dreb/agents/ markdown files\",\n\t\t\tbuiltInAgentsLine,\n\t\t\t'Use the `tasks` array to run multiple independent, role-matched tasks in a single `subagent` call (parallel mode), not separate calls. Typical mach6-review batch: `{ \"tasks\": [{ \"agent\": \"code-reviewer\", \"task\": \"Review code changes\" }, { \"agent\": \"error-auditor\", \"task\": \"Audit runtime failures\" }, { \"agent\": \"test-reviewer\", \"task\": \"Review test coverage\" }, { \"agent\": \"completeness-checker\", \"task\": \"Check issue completeness\" }] }`',\n\t\t\t\"Use chain mode for role-matched steps when each step depends on the previous step's output (reference with {previous})\",\n\t\t\t\"All subagents run in background — the tool returns immediately and you are notified when each agent completes.\",\n\t\t\t\"Subagents have their own context window — provide enough context in the task prompt\",\n\t\t\t\"Each agent notifies independently when done — completion messages include a list of any still-running agents. If you need their results before proceeding, end your current turn with no tool calls (as if you were asking the user a question and waiting for their reply). This emits `agent_end` and lets the framework deliver the completion as a new message that resumes your turn automatically. Do not call `sleep` or any other waiting action, and do not launch filler work.\",\n\t\t\t\"Agent definitions specify a `model` field with a provider fallback list (comma-separated or YAML list). The spawner tries each in order and uses the first one that resolves for the current provider. This makes agents portable across providers.\",\n\t\t\t\"Per-invocation `model` overrides take precedence but **discard the entire fallback list** — if the single override model isn't available on the current provider, the agent fails. Only override when you have a specific reason (e.g. escalating to a stronger tier for a complex task).\",\n\t\t\t\"Optional `thinking` overrides accept off/minimal/low/medium/high/xhigh/max. Per-task values override a top-level value; unsupported levels fail before spawn. Omit thinking to preserve the child's configured default.\",\n\t\t\t\"**Model routing** — choose an agent by role fit first. Agent definitions already specify the normal model tier for that role; override the model only when the assigned task genuinely requires a different capability tier.\",\n\t\t\t\"**Model identity** — Your current model is stated in the system prompt as `You are running on: provider/id`. Use this for explicit routing decisions — e.g. delegate vision tasks if you're on a text-only model, or use a differently-architected model as a critic for tasks where diverse model perspectives improve reliability.\",\n\t\t],\n\t\tparameters: subagentSchema,\n\n\t\tasync execute(_toolCallId, params: SubagentToolInput, _signal, _onUpdate) {\n\t\t\tconst agents = discoverAgentTypes(cwd);\n\n\t\t\t// Determine mode\n\t\t\tconst modeCount = (params.task ? 1 : 0) + (params.tasks ? 1 : 0) + (params.chain ? 1 : 0);\n\t\t\tif (modeCount === 0) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{ type: \"text\", text: \"Error: provide one of `task` (single), `tasks` (parallel), or `chain`.\" },\n\t\t\t\t\t],\n\t\t\t\t\tdetails: undefined,\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (modeCount > 1) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: \"Error: modes are mutually exclusive — provide only one of `task`, `tasks`, or `chain`.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tdetails: undefined,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// All subagents run in background mode — return immediately, notify on completion\n\t\t\t{\n\t\t\t\tif (!onBackgroundComplete) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: \"Subagent execution requires background support, which is not available in this session.\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tdetails: undefined,\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\t/**\n\t\t\t\t * Shared lifecycle for all background launches: generates agent ID,\n\t\t\t\t * sets up registry/abort/notification, gates on the concurrency\n\t\t\t\t * semaphore, and handles errors. The caller provides the actual\n\t\t\t\t * work via `runFn(signal, onChildEvent, onArbitrationRecord)` which must\n\t\t\t\t * return a SubagentResult. Child events are relayed live; arbitration\n\t\t\t\t * records update the registry before being persisted/emitted.\n\t\t\t\t */\n\t\t\t\tconst launchBackgroundLifecycle = (\n\t\t\t\t\tagentName: string,\n\t\t\t\t\ttaskSummary: string,\n\t\t\t\t\tsessionDir: string,\n\t\t\t\t\tagentCwd: string,\n\t\t\t\t\trunFn: (\n\t\t\t\t\t\tsignal: AbortSignal,\n\t\t\t\t\t\tonChildEvent: ((event: Record<string, unknown>) => void) | undefined,\n\t\t\t\t\t\tonArbitrationRecord: (record: DispatchArbitrationRecord) => void,\n\t\t\t\t\t\tonControlAvailable: (client: RpcClient | undefined) => void,\n\t\t\t\t\t) => Promise<SubagentResult>,\n\t\t\t\t): string => {\n\t\t\t\t\tconst agentId = generateAgentId();\n\t\t\t\t\tconst bgAbort = new AbortController();\n\t\t\t\t\tbackgroundAgentRegistry.set(agentId, {\n\t\t\t\t\t\tagentId,\n\t\t\t\t\t\tagentType: agentName,\n\t\t\t\t\t\ttaskSummary,\n\t\t\t\t\t\tstartedAt: Date.now(),\n\t\t\t\t\t\tstatus: \"running\",\n\t\t\t\t\t\tsessionDir,\n\t\t\t\t\t\tcwd: agentCwd,\n\t\t\t\t\t});\n\t\t\t\t\tbackgroundAbortControllers.set(agentId, bgAbort);\n\t\t\t\t\tonBackgroundStart?.(agentId, agentName, taskSummary, sessionDir);\n\n\t\t\t\t\t// Relay child JSONL events tagged with this agent's ID. Guarded so a\n\t\t\t\t\t// throwing relay listener can never kill the stdout reader.\n\t\t\t\t\tconst onChildEvent = onBackgroundEvent\n\t\t\t\t\t\t? (event: Record<string, unknown>) => {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tonBackgroundEvent(agentId, event);\n\t\t\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\t\t\tlog.warn(\n\t\t\t\t\t\t\t\t\t\t`[subagent] onBackgroundEvent threw for agent ${agentId}: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: undefined;\n\n\t\t\t\t\tconst onArbitrationRecord = (record: DispatchArbitrationRecord) => {\n\t\t\t\t\t\tconst entry = backgroundAgentRegistry.get(agentId);\n\t\t\t\t\t\tif (entry) {\n\t\t\t\t\t\t\tentry.arbitrations ??= [];\n\t\t\t\t\t\t\tentry.arbitrations.push(record);\n\t\t\t\t\t\t\tif (record.status === \"success\" && record.final) entry.agentType = record.final.agent;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tonArbitration?.({ type: \"subagent_arbitration\", agentId, ...record });\n\t\t\t\t\t};\n\n\t\t\t\t\tconst bgSignal = bgAbort.signal;\n\t\t\t\t\tconst onControlAvailable = (client: RpcClient | undefined) => {\n\t\t\t\t\t\tif (client) backgroundControlClients.set(agentId, client);\n\t\t\t\t\t\telse backgroundControlClients.delete(agentId);\n\t\t\t\t\t};\n\n\t\t\t\t\tconst safeNotify = (result: SubagentResult) => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tonBackgroundComplete(agentId, result, bgSignal.aborted);\n\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\tlog.warn(\n\t\t\t\t\t\t\t\t`[subagent] onBackgroundComplete threw for agent ${agentId}: ${err instanceof Error ? err.message : String(err)}. Background result lost.`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\n\t\t\t\t\tconst run = async () => {\n\t\t\t\t\t\tawait acquireBackgroundSlot();\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst result = await runFn(bgSignal, onChildEvent, onArbitrationRecord, onControlAvailable);\n\t\t\t\t\t\t\tconst entry = backgroundAgentRegistry.get(agentId);\n\t\t\t\t\t\t\tif (entry && !bgSignal.aborted) entry.status = result.exitCode === 0 ? \"completed\" : \"failed\";\n\t\t\t\t\t\t\tif (entry && result.sessionFile) entry.sessionFile = result.sessionFile;\n\t\t\t\t\t\t\tbackgroundAbortControllers.delete(agentId);\n\t\t\t\t\t\t\tsafeNotify(result);\n\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\tconst entry = backgroundAgentRegistry.get(agentId);\n\t\t\t\t\t\t\tif (entry && !bgSignal.aborted) entry.status = \"failed\";\n\t\t\t\t\t\t\tbackgroundAbortControllers.delete(agentId);\n\t\t\t\t\t\t\tsafeNotify({\n\t\t\t\t\t\t\t\tagent: agentName,\n\t\t\t\t\t\t\t\ttask: taskSummary,\n\t\t\t\t\t\t\t\texitCode: 1,\n\t\t\t\t\t\t\t\toutput: \"\",\n\t\t\t\t\t\t\t\tstderr: \"\",\n\t\t\t\t\t\t\t\terrorMessage: err instanceof Error ? err.message : String(err),\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\tbackgroundControlClients.delete(agentId);\n\t\t\t\t\t\t\treleaseBackgroundSlot();\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t\trun().catch((err) => {\n\t\t\t\t\t\tlog.warn(\n\t\t\t\t\t\t\t`[subagent] Unhandled background error (${agentId}): ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst entry = backgroundAgentRegistry.get(agentId);\n\t\t\t\t\t\tif (entry && entry.status === \"running\") entry.status = \"failed\";\n\t\t\t\t\t\tbackgroundAbortControllers.delete(agentId);\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tonBackgroundComplete(\n\t\t\t\t\t\t\t\tagentId,\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tagent: agentName,\n\t\t\t\t\t\t\t\t\ttask: taskSummary,\n\t\t\t\t\t\t\t\t\texitCode: 1,\n\t\t\t\t\t\t\t\t\toutput: \"\",\n\t\t\t\t\t\t\t\t\tstderr: \"\",\n\t\t\t\t\t\t\t\t\terrorMessage: `Internal error: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tbgSignal.aborted,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t} catch (notifyErr) {\n\t\t\t\t\t\t\tlog.error(\n\t\t\t\t\t\t\t\t`[subagent] CRITICAL: Last-resort notification failed for ${agentId}: ${notifyErr instanceof Error ? notifyErr.message : String(notifyErr)}`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\n\t\t\t\t\treturn agentId;\n\t\t\t\t};\n\n\t\t\t\t// Helper to launch a single background task\n\t\t\t\tconst launchBackgroundTask = (\n\t\t\t\t\tagentName: string,\n\t\t\t\t\ttask: string,\n\t\t\t\t\ttaskLabel: string,\n\t\t\t\t\ttaskCwd?: string,\n\t\t\t\t\tmodelOverride?: string,\n\t\t\t\t\tthinkingOverride?: ThinkingLevel,\n\t\t\t\t) => {\n\t\t\t\t\tconst resolvedCwd = taskCwd ?? cwd;\n\t\t\t\t\t// Each background agent gets its own session subdirectory\n\t\t\t\t\tconst sessionId = generateAgentId();\n\t\t\t\t\tconst sessionDir = join(subagentSessionsBase, sessionId);\n\t\t\t\t\tconst agentModels = getAgentModelsForAgent?.(agentName || DEFAULT_AGENT);\n\t\t\t\t\treturn launchBackgroundLifecycle(\n\t\t\t\t\t\tagentName,\n\t\t\t\t\t\ttaskLabel,\n\t\t\t\t\t\tsessionDir,\n\t\t\t\t\t\tresolvedCwd,\n\t\t\t\t\t\t(signal, onChildEvent, onArbitrationRecord, onControlAvailable) =>\n\t\t\t\t\t\t\texecuteSingle(\n\t\t\t\t\t\t\t\tagents,\n\t\t\t\t\t\t\t\tagentName === DEFAULT_AGENT ? undefined : agentName,\n\t\t\t\t\t\t\t\ttask,\n\t\t\t\t\t\t\t\tresolvedCwd,\n\t\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t\t\tundefined,\n\t\t\t\t\t\t\t\tmodelOverride,\n\t\t\t\t\t\t\t\tgetParentProvider(),\n\t\t\t\t\t\t\t\tmodelRegistry,\n\t\t\t\t\t\t\t\tsessionDir,\n\t\t\t\t\t\t\t\tgetParentModel(),\n\t\t\t\t\t\t\t\tagentModels,\n\t\t\t\t\t\t\t\tgetParentSessionFile(),\n\t\t\t\t\t\t\t\tonChildEvent,\n\t\t\t\t\t\t\t\tthinkingOverride,\n\t\t\t\t\t\t\t\tarbitrate\n\t\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\t\tarbitrate,\n\t\t\t\t\t\t\t\t\t\t\tonRecord: onArbitrationRecord,\n\t\t\t\t\t\t\t\t\t\t\tdefaultThinkingLevel: getDefaultThinkingLevel?.(),\n\t\t\t\t\t\t\t\t\t\t\tgetAgentModelsForAgent,\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t\t\t\tonControlAvailable,\n\t\t\t\t\t\t\t\tgetParentSessionId(),\n\t\t\t\t\t\t\t\tgetSingleModelMode(),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t};\n\n\t\t\t\tif (params.task) {\n\t\t\t\t\t// Single background task\n\t\t\t\t\tconst agentName = params.agent || DEFAULT_AGENT;\n\t\t\t\t\tconst agentId = launchBackgroundTask(\n\t\t\t\t\t\tagentName,\n\t\t\t\t\t\tparams.task,\n\t\t\t\t\t\t`${agentName} task`,\n\t\t\t\t\t\tundefined,\n\t\t\t\t\t\tparams.model,\n\t\t\t\t\t\tparams.thinking,\n\t\t\t\t\t);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: `Background agent ${agentId} started (${agentName}). You will be notified when it completes.`,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tdetails: { mode: \"single\", agentCount: 1 } as SubagentToolDetails,\n\t\t\t\t\t\tendTurn: true,\n\t\t\t\t\t};\n\t\t\t\t} else if (params.tasks) {\n\t\t\t\t\t// Parallel background tasks — each gets its own agent ID and notifies independently\n\t\t\t\t\tconst launched: Array<{ id: string; agentName: string; taskText: string }> = [];\n\t\t\t\t\tconst skipped: Array<{ taskText: string; error: string }> = [];\n\t\t\t\t\tfor (let i = 0; i < params.tasks.length; i++) {\n\t\t\t\t\t\tconst item = params.tasks[i];\n\t\t\t\t\t\tconst agentName = item.agent || params.agent || DEFAULT_AGENT;\n\t\t\t\t\t\tconst cwdResult = clampCwd(cwd, item.cwd);\n\t\t\t\t\t\tif (!cwdResult.ok) {\n\t\t\t\t\t\t\tskipped.push({ taskText: item.task, error: cwdResult.error });\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst agentId = launchBackgroundTask(\n\t\t\t\t\t\t\tagentName,\n\t\t\t\t\t\t\titem.task,\n\t\t\t\t\t\t\t`${agentName} task ${i + 1}/${params.tasks.length}`,\n\t\t\t\t\t\t\tcwdResult.cwd,\n\t\t\t\t\t\t\titem.model || params.model,\n\t\t\t\t\t\t\tresolveSubagentThinkingOverride(item.thinking, params.thinking),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tlaunched.push({ id: agentId, agentName, taskText: item.task });\n\t\t\t\t\t}\n\t\t\t\t\tconst listing = launched\n\t\t\t\t\t\t.map(({ id, agentName, taskText }) => ` ${id} (${agentName}): ${taskText.slice(0, 80)}`)\n\t\t\t\t\t\t.join(\"\\n\");\n\t\t\t\t\tconst skippedListing = skipped\n\t\t\t\t\t\t.map(({ taskText, error }) => ` SKIPPED: ${taskText.slice(0, 60)} — ${error}`)\n\t\t\t\t\t\t.join(\"\\n\");\n\t\t\t\t\tconst parts = [`${launched.length} background agents started:\\n${listing}`];\n\t\t\t\t\tif (skipped.length > 0) {\n\t\t\t\t\t\tparts.push(`\\n${skipped.length} task(s) failed to launch:\\n${skippedListing}`);\n\t\t\t\t\t}\n\t\t\t\t\tif (launched.length > 0) {\n\t\t\t\t\t\tparts.push(\"\\nEach will notify independently when complete.\");\n\t\t\t\t\t} else {\n\t\t\t\t\t\tparts.push(\"\\nNo agents were launched.\");\n\t\t\t\t\t}\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: parts.join(\"\\n\"),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tdetails: { mode: \"parallel\", agentCount: launched.length } as SubagentToolDetails,\n\t\t\t\t\t\tendTurn: launched.length > 0,\n\t\t\t\t\t};\n\t\t\t\t} else {\n\t\t\t\t\t// Chain mode — sequential, stays as one agent since steps depend on each other\n\t\t\t\t\tconst agentName = params.agent || params.chain![0].agent || DEFAULT_AGENT;\n\t\t\t\t\tconst taskSummary = `${params.chain!.length}-step chain`;\n\t\t\t\t\tconst chainSteps = params.chain!;\n\n\t\t\t\t\tconst chainSessionDir = join(subagentSessionsBase, `chain-${generateAgentId()}`);\n\t\t\t\t\tconst agentId = launchBackgroundLifecycle(\n\t\t\t\t\t\tagentName,\n\t\t\t\t\t\ttaskSummary,\n\t\t\t\t\t\tchainSessionDir,\n\t\t\t\t\t\tcwd,\n\t\t\t\t\t\tasync (signal, onChildEvent, onArbitrationRecord, onControlAvailable) => {\n\t\t\t\t\t\t\tconst results = await executeChain(\n\t\t\t\t\t\t\t\tagents,\n\t\t\t\t\t\t\t\tchainSteps,\n\t\t\t\t\t\t\t\tcwd,\n\t\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t\t\tundefined,\n\t\t\t\t\t\t\t\tgetParentProvider(),\n\t\t\t\t\t\t\t\tmodelRegistry,\n\t\t\t\t\t\t\t\tchainSessionDir,\n\t\t\t\t\t\t\t\tparams.agent,\n\t\t\t\t\t\t\t\tparams.model,\n\t\t\t\t\t\t\t\tparams.thinking,\n\t\t\t\t\t\t\t\tgetParentModel(),\n\t\t\t\t\t\t\t\tgetAgentModelsForAgent,\n\t\t\t\t\t\t\t\tgetParentSessionFile(),\n\t\t\t\t\t\t\t\tonChildEvent,\n\t\t\t\t\t\t\t\tarbitrate\n\t\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\t\tarbitrate,\n\t\t\t\t\t\t\t\t\t\t\tonRecord: onArbitrationRecord,\n\t\t\t\t\t\t\t\t\t\t\tdefaultThinkingLevel: getDefaultThinkingLevel?.(),\n\t\t\t\t\t\t\t\t\t\t\tgetAgentModelsForAgent,\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t\t\t\tonControlAvailable,\n\t\t\t\t\t\t\t\tgetParentSessionId(),\n\t\t\t\t\t\t\t\tgetSingleModelMode,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tconst resultText = results\n\t\t\t\t\t\t\t\t.map((r, i) => `### Step ${i + 1}\\n${formatSingleResult(r)}`)\n\t\t\t\t\t\t\t\t.join(\"\\n\\n---\\n\\n\");\n\t\t\t\t\t\t\tconst failed = results.filter((r) => r.exitCode !== 0);\n\t\t\t\t\t\t\t// Per-step session logs are already embedded in resultText via formatSingleResult\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tagent: agentName,\n\t\t\t\t\t\t\t\ttask: taskSummary,\n\t\t\t\t\t\t\t\tsteps: results.map((result, index) => ({\n\t\t\t\t\t\t\t\t\tstep: index + 1,\n\t\t\t\t\t\t\t\t\tagent: result.agent,\n\t\t\t\t\t\t\t\t\tsuccess: result.exitCode === 0,\n\t\t\t\t\t\t\t\t\tmodel: result.model,\n\t\t\t\t\t\t\t\t\tthinking: result.thinking,\n\t\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t\t\texitCode: failed.length > 0 ? 1 : 0,\n\t\t\t\t\t\t\t\toutput: resultText,\n\t\t\t\t\t\t\t\tstderr: \"\",\n\t\t\t\t\t\t\t\terrorMessage:\n\t\t\t\t\t\t\t\t\tfailed.length > 0\n\t\t\t\t\t\t\t\t\t\t? `Chain stopped at step ${results.length} of ${chainSteps.length}: ${results[results.length - 1]?.errorMessage}`\n\t\t\t\t\t\t\t\t\t\t: null,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t},\n\t\t\t\t\t);\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: `Background chain ${agentId} started (${taskSummary}). You will be notified when it completes.`,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tdetails: { mode: \"chain\", agentCount: chainSteps.length } as SubagentToolDetails,\n\t\t\t\t\t\tendTurn: true,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\n\t\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0, undefined, true);\n\t\t\ttext.setText(formatSubagentCall(args, theme, context.argsComplete));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0, undefined, true);\n\t\t\ttext.setText(formatSubagentResult(result as any, options, theme, context.showImages));\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createSubagentTool(cwd: string, options?: SubagentToolOptions): AgentTool<typeof subagentSchema> {\n\treturn wrapToolDefinition(createSubagentToolDefinition(cwd, options));\n}\n\nexport const subagentToolDefinition = createSubagentToolDefinition(process.cwd());\nexport const subagentTool = createSubagentTool(process.cwd());\n"]}
1
+ {"version":3,"file":"subagent.js","sourceRoot":"","sources":["../../../src/core/tools/subagent.ts"],"names":[],"mappings":"AAAA,OAAO,EAAqB,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC9D,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EACN,SAAS,EAET,UAAU,EACV,SAAS,EACT,QAAQ,EACR,WAAW,EACX,YAAY,EACZ,QAAQ,EACR,YAAY,EACZ,QAAQ,EACR,aAAa,GACb,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEpD,OAAO,EAAiD,cAAc,EAAc,MAAM,UAAU,CAAC;AACrG,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAe,IAAI,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAE,eAAe,EAAE,aAAa,EAAE,sBAAsB,EAAE,MAAM,iBAAiB,CAAC;AACzF,OAAO,EAAE,OAAO,EAAE,MAAM,wDAAwD,CAAC;AACjF,OAAO,EAAE,qBAAqB,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAWpF,OAAO,EAAE,GAAG,EAAE,MAAM,cAAc,CAAC;AAEnC,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AACvD,O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AA4B,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC;AAAA,CACtE;AAED,MAAM,CAAC,MAAM,sBAAsB,GAAG,4BAA4B,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC;AAClF,MAAM,CAAC,MAAM,YAAY,GAAG,kBAAkB,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC","sourcesContent":["import { type ChildProcess, spawn } from \"node:child_process\";\nimport { randomBytes } from \"node:crypto\";\nimport {\n\tcloseSync,\n\ttype Dirent,\n\texistsSync,\n\tmkdirSync,\n\topenSync,\n\treaddirSync,\n\treadFileSync,\n\treadSync,\n\trealpathSync,\n\tstatSync,\n\twriteFileSync,\n} from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { basename, join, resolve } from \"node:path\";\nimport type { AgentTool, ThinkingLevel } from \"@dreb/agent-core\";\nimport { type Api, type AssistantMessage, type Context, completeSimple, type Model } from \"@dreb/ai\";\nimport { Text } from \"@dreb/tui\";\nimport { type Static, Type } from \"@sinclair/typebox\";\nimport { CONFIG_DIR_NAME, getPackageDir, getSubagentSessionsDir } from \"../../config.js\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.js\";\nimport { attachJsonlLineReader, serializeJsonLine } from \"../../modes/rpc/jsonl.js\";\nimport type { RpcClient } from \"../../modes/rpc/rpc-client.js\";\nimport type { RpcPendingMessages } from \"../../modes/rpc/rpc-types.js\";\nimport type {\n\tDispatchAgentSummary,\n\tDispatchArbitrationRecord,\n\tDispatchArbitrationRequest,\n\tDispatchArbitrationResult,\n\tDispatchRoute,\n} from \"../dispatch-arbiter.js\";\nimport type { ToolDefinition, ToolRenderResultOptions } from \"../extensions/types.js\";\nimport { log } from \"../logger.js\";\nimport type { ModelRegistry } from \"../model-registry.js\";\nimport { resolveCliModel } from \"../model-resolver.js\";\nimport { DEFAULT_MAX_CONCURRENT_SUBAGENTS } from \"../settings-manager.js\";\nimport { resolveEffectiveThinkingLevel, thinkingLevelToReasoning, validateThinkingLevelForModel } from \"../thinking.js\";\nimport { getTextOutput, invalidArgText, str } from \"./render-utils.js\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.js\";\nimport { DEFAULT_MAX_BYTES, formatSize, type TruncationResult } from \"./truncate.js\";\n\n// ---------------------------------------------------------------------------\n// Agent type system\n// ---------------------------------------------------------------------------\n\nexport interface AgentTypeConfig {\n\tname: string;\n\tdescription: string;\n\ttools?: string;\n\t/** Single model ID or ordered fallback list. First resolvable model wins. */\n\tmodel?: string | string[];\n\tsystemPrompt: string;\n}\n\nconst DEFAULT_AGENT = \"Explore\";\nconst SUBAGENT_THINKING_LEVELS = [\"off\", \"minimal\", \"low\", \"medium\", \"high\", \"xhigh\", \"max\"] as const;\nexport const DEFAULT_MODEL_AVAILABILITY_PROBE_TIMEOUT_MS = 120_000;\n\nexport function parseAgentFrontmatter(\n\tcontent: string,\n): { ok: true; config: AgentTypeConfig } | { ok: false; error: string } {\n\tconst fmMatch = content.match(/^---\\n([\\s\\S]*?)\\n---\\n?([\\s\\S]*)$/);\n\tif (!fmMatch) return { ok: false, error: \"missing --- frontmatter delimiters\" };\n\n\tconst frontmatter = fmMatch[1];\n\tconst body = fmMatch[2].trim();\n\n\tconst get = (key: string): string | undefined => {\n\t\tconst match = frontmatter.match(new RegExp(`^${key}:\\\\s*(.+)$`, \"m\"));\n\t\treturn match?.[1].trim();\n\t};\n\n\t/** Parse `model` field — supports single string, comma-separated, or YAML list syntax. */\n\tconst getModel = (): string | string[] | undefined => {\n\t\t// First check for YAML list syntax (indented lines starting with \"- \")\n\t\tconst listMatch = frontmatter.match(/^model:\\s*\\n((?:\\s+-\\s+.+\\n?)+)/m);\n\t\tif (listMatch) {\n\t\t\tconst items = listMatch[1]\n\t\t\t\t.split(\"\\n\")\n\t\t\t\t.map((line) => line.replace(/^\\s+-\\s+/, \"\").trim())\n\t\t\t\t.filter(Boolean);\n\t\t\treturn items.length > 1 ? items : items[0];\n\t\t}\n\t\t// Inline value — check for comma-separated list\n\t\tconst value = get(\"model\");\n\t\tif (!value) return undefined;\n\t\tif (value.includes(\",\")) {\n\t\t\tconst items = value\n\t\t\t\t.split(\",\")\n\t\t\t\t.map((s) => s.trim())\n\t\t\t\t.filter(Boolean);\n\t\t\treturn items.length > 1 ? items : items[0];\n\t\t}\n\t\treturn value;\n\t};\n\n\tconst name = get(\"name\");\n\tif (!name) return { ok: false, error: \"missing required 'name' field in frontmatter\" };\n\n\treturn {\n\t\tok: true,\n\t\tconfig: {\n\t\t\tname,\n\t\t\tdescription: get(\"description\") || \"\",\n\t\t\ttools: get(\"tools\"),\n\t\t\tmodel: getModel(),\n\t\t\tsystemPrompt: body,\n\t\t},\n\t};\n}\n\nexport function discoverAgentTypes(cwd: string): Map<string, AgentTypeConfig> {\n\tconst agents = new Map<string, AgentTypeConfig>();\n\n\t// Package-bundled agents (shipped with dreb — the canonical source of truth for built-in agents)\n\tconst packageAgentsDir = join(getPackageDir(), \"agents\");\n\tloadAgentsFromDir(packageAgentsDir, agents);\n\n\t// User-level agents (~/.dreb/agents/*.md)\n\tconst userDir = join(homedir(), CONFIG_DIR_NAME, \"agents\");\n\tloadAgentsFromDir(userDir, agents);\n\n\t// Project-level agents (.dreb/agents/*.md)\n\t// TODO: Security gate — prompt user for confirmation before loading agents from untrusted repos\n\tconst projectDir = join(cwd, \".dreb\", \"agents\");\n\tloadAgentsFromDir(projectDir, agents);\n\n\treturn agents;\n}\n\nfunction loadAgentsFromDir(dir: string, agents: Map<string, AgentTypeConfig>): void {\n\tif (!existsSync(dir)) return;\n\ttry {\n\t\tfor (const file of readdirSync(dir)) {\n\t\t\tif (!file.endsWith(\".md\")) continue;\n\t\t\ttry {\n\t\t\t\tconst content = readFileSync(join(dir, file), \"utf-8\");\n\t\t\t\tconst parsed = parseAgentFrontmatter(content);\n\t\t\t\tif (!parsed.ok) {\n\t\t\t\t\tlog.warn(`[subagent] Skipping agent file ${join(dir, file)}: ${parsed.error}`);\n\t\t\t\t} else {\n\t\t\t\t\tagents.set(parsed.config.name, parsed.config);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tlog.warn(\n\t\t\t\t\t`[subagent] Could not read agent file ${join(dir, file)}: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t} catch (err) {\n\t\tif ((err as NodeJS.ErrnoException).code !== \"ENOENT\") {\n\t\t\tlog.warn(\n\t\t\t\t`[subagent] Could not read agents directory ${dir}: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t);\n\t\t}\n\t}\n}\n\n// ---------------------------------------------------------------------------\n// Subagent process spawning\n// ---------------------------------------------------------------------------\n\nexport interface SubagentStepMetadata {\n\tstep: number;\n\tagent: string;\n\tsuccess: boolean;\n\t/** Canonical provider/model identity reported by the child process. */\n\tmodel?: string;\n\t/** Effective thinking level reported by the child process. */\n\tthinking?: ThinkingLevel;\n}\n\nexport interface SubagentArbitrationEvent extends DispatchArbitrationRecord {\n\ttype: \"subagent_arbitration\";\n\tagentId: string;\n}\n\nexport interface SubagentResult {\n\tagent: string;\n\ttask: string;\n\t/** Canonical provider/model identity reported by the child process. */\n\tmodel?: string;\n\t/** Effective thinking level reported by the child process. */\n\tthinking?: ThinkingLevel;\n\t/** Ordered effective metadata for chain steps. */\n\tsteps?: SubagentStepMetadata[];\n\texitCode: number;\n\t/**\n\t * The child agent's own text output (its assistant messages), without system notes.\n\t * For a chain (`steps` set) this is instead the composed per-step report from\n\t * `formatSingleResult`, in which each step's output is already delimited.\n\t */\n\toutput: string;\n\t/**\n\t * System notes about how the run was routed (ignored model-selection warnings, model\n\t * fallback summaries). Rendered before, and outside, the agent-output block.\n\t */\n\tnotes?: string[];\n\tstderr: string;\n\terrorMessage: string | null;\n\t/** Path to the persisted session JSONL file, if available */\n\tsessionFile?: string;\n}\n\n// Capture at module load before process.title overwrites argv memory on Linux.\n// After process.title = \"dreb\" (in cli.ts), the original argv area is overwritten\n// and process.argv[1] may return corrupted or truncated data.\nconst DREB_SCRIPT = process.argv[1] || \"dreb\";\nconst NODE_EXEC = process.execPath;\n\n/**\n * Whether RPC-controlled subagent children should emit legacy full\n * message_update frames. Set by an RPC host started with\n * --rpc-full-message-updates so nested background_agent_event payloads relayed\n * from children match the parent's opt-in (issue 535). Children launched with\n * the flag set it again in their own process, so it propagates to every depth.\n */\nlet subagentRpcFullMessageUpdates = false;\n\nexport function setSubagentRpcFullMessageUpdates(enabled: boolean): void {\n\tsubagentRpcFullMessageUpdates = enabled;\n}\n\n// Tools that must never be available to subagents — wait (subagents should\n// never no-op; they have a task to complete), watch_github_ci (parent workflow\n// orchestration), subagent (no recursive spawning), and suggest_next (would end\n// the subagent's turn mid-work).\nconst SUBAGENT_EXCLUDED_TOOLS = [\"wait\", \"watch_github_ci\", \"subagent\", \"suggest_next\"] as const;\n\n// Default standard tools for subagents when no tools are specified in the agent\n// definition. This is the set passed via --tools to the child process.\n//\n// NOTE: Always-active tools (search, skill, tasks_update) are NOT listed here —\n// the child process adds them unconditionally regardless of --tools.\n// Internal tools (tmp_read) are also excluded.\nconst SUBAGENT_DEFAULT_TOOLS = [\"read\", \"bash\", \"edit\", \"write\", \"grep\", \"find\", \"ls\", \"web_search\", \"web_fetch\"];\nconst SUBAGENT_ALWAYS_ACTIVE_TOOLS = [\"search\", \"skill\", \"tasks_update\"];\n\n/**\n * Filter a comma-separated tools string, removing any tools in SUBAGENT_EXCLUDED_TOOLS.\n * Returns the filtered tools as a comma-separated string (always non-empty — falls\n * back to SUBAGENT_DEFAULT_TOOLS if all specified tools were excluded).\n */\nexport function filterSubagentTools(tools: string | undefined): string {\n\tif (!tools) return SUBAGENT_DEFAULT_TOOLS.join(\",\");\n\tconst filtered = tools\n\t\t.split(\",\")\n\t\t.map((t) => t.trim())\n\t\t.filter((t) => !(SUBAGENT_EXCLUDED_TOOLS as readonly string[]).includes(t))\n\t\t.join(\",\");\n\treturn filtered || SUBAGENT_DEFAULT_TOOLS.join(\",\");\n}\n\nfunction summarizeAgentsForArbitration(\n\tagents: Map<string, AgentTypeConfig>,\n\tgetAgentModelsForAgent?: (name: string) => string[] | undefined,\n): DispatchAgentSummary[] {\n\treturn [...agents.values()].map((agent) => {\n\t\tconst settingsModels = getAgentModelsForAgent?.(agent.name);\n\t\treturn {\n\t\t\tname: agent.name,\n\t\t\tdescription: agent.description,\n\t\t\ttools: [\n\t\t\t\t...new Set([\n\t\t\t\t\t...filterSubagentTools(agent.tools).split(\",\").filter(Boolean),\n\t\t\t\t\t...SUBAGENT_ALWAYS_ACTIVE_TOOLS,\n\t\t\t\t]),\n\t\t\t],\n\t\t\tmodelDefaults:\n\t\t\t\tsettingsModels && settingsModels.length > 0\n\t\t\t\t\t? [...settingsModels]\n\t\t\t\t\t: agent.model\n\t\t\t\t\t\t? Array.isArray(agent.model)\n\t\t\t\t\t\t\t? [...agent.model]\n\t\t\t\t\t\t\t: [agent.model]\n\t\t\t\t\t\t: [],\n\t\t};\n\t});\n}\n\n// TODO: Support PATH-based binary discovery.\n// Currently returns the captured argv[1].\nfunction findDrebBinary(): string {\n\treturn DREB_SCRIPT;\n}\n\n/**\n * Sinks for the child process's JSONL stdout stream. Extracted so the line\n * handling is unit-testable without spawning a real child process.\n */\nexport interface ChildLineSinks {\n\t/** Called with every successfully parsed JSONL event (including the session header). */\n\tonEvent?: (event: Record<string, unknown>) => void;\n\t/** Called with each complete assistant message (`message_end`). */\n\tonAssistantMessage: (message: { role: string; content: any[] }) => void;\n\t/** Called with human-readable progress lines (tool start/end). */\n\tonProgress?: (text: string) => void;\n\t/** Called when the child reports its canonical resolved model (`agent_start`). */\n\tonModel: (modelRef: string) => void;\n\t/** Called when the child reports its effective thinking level (`agent_start`). */\n\tonThinking?: (thinkingLevel: ThinkingLevel) => void;\n\t/** Called with lines that failed to parse as JSON (often real startup errors). */\n\tonPlainLine: (line: string) => void;\n\t/** Mutable holder for the last tool name, shared across lines for progress text. */\n\ttoolNameRef: { current: string };\n}\n\nfunction canonicalModelRef(provider: string | undefined, modelId: string): string {\n\tif (!provider || modelId.startsWith(`${provider}/`)) return modelId;\n\treturn `${provider}/${modelId}`;\n}\n\n/**\n * Handle one line of a subagent child's JSONL stdout. Parses the line and\n * dispatches to the sinks: full-event relay, assistant-message collection,\n * tool progress, resolved model, and non-JSON passthrough.\n */\nexport function handleChildJsonlLine(line: string, sinks: ChildLineSinks): void {\n\tif (!line.trim()) return;\n\t// Separate JSON.parse from event handling so only parse failures\n\t// are caught as non-JSON lines — errors in handling propagate normally\n\tlet event: any;\n\ttry {\n\t\tevent = JSON.parse(line);\n\t} catch {\n\t\t// Capture non-JSON lines — on failure these often contain the real error\n\t\t// (e.g. startup errors printed before JSONL mode begins)\n\t\tsinks.onPlainLine(line.trim());\n\t\tif (line.trim().startsWith(\"{\")) {\n\t\t\tlog.warn(`[subagent] Failed to parse JSONL event: ${line.slice(0, 200)}`);\n\t\t}\n\t\treturn;\n\t}\n\tif (event === null || typeof event !== \"object\") {\n\t\t// Valid JSON but not an event object (e.g. a bare string or number) — treat\n\t\t// like a plain line so diagnostic content is preserved.\n\t\tsinks.onPlainLine(line.trim());\n\t\treturn;\n\t}\n\tif (typeof event.type === \"string\") {\n\t\tsinks.onEvent?.(event);\n\t}\n\tif (event.type === \"agent_start\") {\n\t\tif (typeof event.model?.id === \"string\") {\n\t\t\tconst provider = typeof event.model.provider === \"string\" ? event.model.provider : undefined;\n\t\t\tsinks.onModel(canonicalModelRef(provider, event.model.id));\n\t\t}\n\t\tif (\n\t\t\ttypeof event.thinkingLevel === \"string\" &&\n\t\t\t(SUBAGENT_THINKING_LEVELS as readonly string[]).includes(event.thinkingLevel)\n\t\t) {\n\t\t\tsinks.onThinking?.(event.thinkingLevel as ThinkingLevel);\n\t\t}\n\t}\n\tif (event.type === \"message_end\" && event.message?.role === \"assistant\") {\n\t\tsinks.onAssistantMessage(event.message);\n\t}\n\tif (event.type === \"tool_execution_start\" && sinks.onProgress) {\n\t\tsinks.toolNameRef.current = event.toolName || \"\";\n\t\tsinks.onProgress(`Using ${sinks.toolNameRef.current}...`);\n\t}\n\tif (event.type === \"tool_execution_end\" && sinks.onProgress) {\n\t\tsinks.onProgress(`${sinks.toolNameRef.current} done`);\n\t}\n}\n\n/**\n * How long a gracefully aborted (RPC `abort`) child may take to finish its run and\n * emit `agent_end` before it is terminated with SIGTERM.\n */\nexport const SUBAGENT_ABORT_GRACE_MS = 5000;\n/** Delay between SIGTERM and the SIGKILL backstop for a child that is still alive. */\nexport const SUBAGENT_SIGKILL_BACKSTOP_MS = 5000;\n\nasync function spawnSubagent(\n\tagentConfig: AgentTypeConfig,\n\ttask: string,\n\tcwd: string,\n\tsignal?: AbortSignal,\n\tonProgress?: (event: string) => void,\n\tparentProvider?: string,\n\tsessionDir?: string,\n\tparentSessionFile?: string,\n\tonChildEvent?: (event: Record<string, unknown>) => void,\n\tthinkingOverride?: ThinkingLevel,\n\tonControlAvailable?: (client: RpcClient | undefined) => void,\n): Promise<SubagentResult> {\n\tconst drebBin = findDrebBinary();\n\tlog.debug(`[subagent] spawn: agent=${agentConfig.name} cwd=${cwd}`);\n\n\t// Validate cwd exists — spawn() throws a misleading ENOENT blaming the\n\t// binary when the cwd is invalid, making the real cause hard to diagnose\n\tif (!existsSync(cwd)) {\n\t\treturn {\n\t\t\tagent: agentConfig.name,\n\t\t\ttask,\n\t\t\texitCode: 1,\n\t\t\toutput: \"\",\n\t\t\tstderr: \"\",\n\t\t\terrorMessage: `Working directory does not exist: ${cwd}`,\n\t\t};\n\t}\n\n\tconst args: string[] = [\"--mode\", \"json\", \"--ui\", \"agent\"];\n\tif (sessionDir) {\n\t\targs.push(\"--session-dir\", sessionDir);\n\t} else {\n\t\targs.push(\"--no-session\");\n\t}\n\t// By spawn time, model should be a resolved single string (fallback resolution\n\t// happens in executeSingle). Handle string[] defensively by taking the first entry.\n\tconst modelStr = Array.isArray(agentConfig.model) ? agentConfig.model[0] : agentConfig.model;\n\tif (modelStr) {\n\t\targs.push(\"--model\", modelStr);\n\t\t// executeSingle resolves the model and provider independently. Always pass\n\t\t// that exact provider because raw model IDs may themselves contain slashes\n\t\t// (for example, OpenRouter IDs such as \"openai/gpt-oss-120b\").\n\t\tif (parentProvider) {\n\t\t\targs.push(\"--provider\", parentProvider);\n\t\t}\n\t}\n\tif (thinkingOverride) {\n\t\targs.push(\"--thinking\", thinkingOverride);\n\t}\n\t// Always pass --tools to ensure wait/subagent/suggest_next are excluded from child processes.\n\t// filterSubagentTools always returns a non-empty string.\n\targs.push(\"--tools\", filterSubagentTools(agentConfig.tools));\n\tif (agentConfig.systemPrompt) {\n\t\targs.push(\"--append-system-prompt\", agentConfig.systemPrompt);\n\t}\n\t// Pass agent type metadata so the child session can record it in its JSONL header\n\targs.push(\"--agent-type\", agentConfig.name);\n\t// Pass parent session file path so the child session can record it in its JSONL header\n\tif (parentSessionFile) {\n\t\targs.push(\"--parent-session\", parentSessionFile);\n\t}\n\targs.push(\"-p\", task);\n\tif (onControlAvailable) {\n\t\tconst rpcModeIndex = args.indexOf(\"json\");\n\t\tif (rpcModeIndex !== -1) args[rpcModeIndex] = \"rpc\";\n\t\targs.splice(args.length - 2, 2);\n\t\tif (subagentRpcFullMessageUpdates) args.push(\"--rpc-full-message-updates\");\n\t}\n\n\t// Early abort check — if the signal is already aborted (e.g. queued task whose\n\t// AbortController was aborted while waiting on bgAcquire), bail out before\n\t// spawning a child process that can never be killed. addEventListener(\"abort\")\n\t// on an already-aborted signal does NOT fire the callback in Node.js.\n\tif (signal?.aborted) {\n\t\treturn {\n\t\t\tagent: agentConfig.name,\n\t\t\ttask,\n\t\t\texitCode: 1,\n\t\t\toutput: \"\",\n\t\t\tstderr: \"\",\n\t\t\terrorMessage: \"Aborted before spawn\",\n\t\t};\n\t}\n\n\treturn new Promise<SubagentResult>((resolvePromise, rejectPromise) => {\n\t\tlet proc: ChildProcess;\n\t\ttry {\n\t\t\tproc = spawn(NODE_EXEC, [drebBin, ...args], {\n\t\t\t\tcwd,\n\t\t\t\tstdio: [onControlAvailable ? \"pipe\" : \"ignore\", \"pipe\", \"pipe\"],\n\t\t\t\tenv: { ...process.env },\n\t\t\t});\n\t\t} catch (err) {\n\t\t\trejectPromise(new Error(`Failed to spawn subagent: ${err instanceof Error ? err.message : String(err)}`));\n\t\t\treturn;\n\t\t}\n\n\t\tlet settled = false;\n\t\tlet killTimer: ReturnType<typeof setTimeout> | null = null;\n\t\tlet abortGraceTimer: ReturnType<typeof setTimeout> | null = null;\n\t\tconst collectedMessages: Array<{ role: string; content: any[] }> = [];\n\t\tconst stderrChunks: string[] = [];\n\t\tlet stderrSize = 0;\n\t\tconst MAX_STDERR_BYTES = 8192;\n\t\tconst plainStdoutLines: string[] = [];\n\t\tconst toolNameRef = { current: \"\" };\n\t\tlet resolvedModel: string | undefined;\n\t\tlet resolvedThinking: ThinkingLevel | undefined;\n\t\tlet rpcRequestId = 0;\n\t\tlet rpcCompleted = false;\n\t\t/** Set once a graceful RPC `abort` has been sent for a user stop. */\n\t\tlet gracefulAbortRequested = false;\n\t\tlet controlError: Error | undefined;\n\t\tconst pendingRpc = new Map<string, { resolve: (value: any) => void; reject: (error: Error) => void }>();\n\t\tconst sendRpc = <T>(command: Record<string, unknown>): Promise<T> => {\n\t\t\tif (!proc.stdin?.writable) return Promise.reject(new Error(\"Subagent control channel is unavailable.\"));\n\t\t\tconst id = `subagent-${++rpcRequestId}`;\n\t\t\tproc.stdin.write(serializeJsonLine({ ...command, id }));\n\t\t\treturn new Promise<T>((resolve, reject) => pendingRpc.set(id, { resolve, reject }));\n\t\t};\n\t\tconst controlClient = onControlAvailable\n\t\t\t? ({\n\t\t\t\t\tsteer: async (message: string) => {\n\t\t\t\t\t\tawait sendRpc({ type: \"steer\", message });\n\t\t\t\t\t},\n\t\t\t\t\tgetPendingMessages: async () => sendRpc<RpcPendingMessages>({ type: \"get_pending_messages\" }),\n\t\t\t\t\tgetState: async () => sendRpc<{ steeringMode: \"all\" | \"one-at-a-time\" }>({ type: \"get_state\" }),\n\t\t\t\t} as RpcClient)\n\t\t\t: undefined;\n\n\t\t// Escalating termination: SIGTERM now, SIGKILL if the process is still alive\n\t\t// after the backstop delay. Liveness is judged by exitCode/signalCode —\n\t\t// `proc.killed` only reports that a signal was *sent*, so it is already true\n\t\t// after the SIGTERM and cannot gate the SIGKILL escalation.\n\t\tconst forceKill = () => {\n\t\t\ttry {\n\t\t\t\tproc.kill(\"SIGTERM\");\n\t\t\t} catch {\n\t\t\t\t/* process already exited */\n\t\t\t}\n\t\t\tkillTimer ??= setTimeout(() => {\n\t\t\t\tif (proc.exitCode !== null || proc.signalCode !== null) return;\n\t\t\t\ttry {\n\t\t\t\t\tproc.kill(\"SIGKILL\");\n\t\t\t\t} catch {\n\t\t\t\t\t/* process already exited */\n\t\t\t\t}\n\t\t\t}, SUBAGENT_SIGKILL_BACKSTOP_MS);\n\t\t};\n\n\t\t// Terminally fail a controlled child: remember the first failure, reject all\n\t\t// in-flight control requests, and stop the process (with the same SIGKILL\n\t\t// backstop as the abort path) so the close handler settles instead of the\n\t\t// child idling in RPC mode forever.\n\t\tconst failControlledChild = (err: Error) => {\n\t\t\tif (!controlError) controlError = err;\n\t\t\tfor (const request of pendingRpc.values()) request.reject(err);\n\t\t\tpendingRpc.clear();\n\t\t\tforceKill();\n\t\t};\n\n\t\t// Ask a controlled child to abort its own run (graceful stop). If the request cannot\n\t\t// be delivered or the child refuses it, terminate the child instead.\n\t\tconst requestGracefulAbort = () => {\n\t\t\tif (!proc.stdin?.writable) {\n\t\t\t\tforceKill();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsendRpc({ type: \"abort\" }).catch((err) => {\n\t\t\t\tif (settled) return;\n\t\t\t\tlog.warn(\n\t\t\t\t\t`[subagent] graceful abort failed (agent=${agentConfig.name}): ${err instanceof Error ? err.message : String(err)}; terminating child`,\n\t\t\t\t);\n\t\t\t\tforceKill();\n\t\t\t});\n\t\t};\n\n\t\tproc.stdin?.on(\"error\", (err) => {\n\t\t\tlog.warn(`[subagent] stdin stream error (agent=${agentConfig.name}): ${err.message}`);\n\t\t\tfailControlledChild(err);\n\t\t});\n\n\t\t// Drain stderr concurrently to avoid pipe deadlock (capped to prevent OOM from verbose subagents)\n\t\tproc.stderr?.on(\"data\", (chunk: Buffer) => {\n\t\t\tif (stderrSize < MAX_STDERR_BYTES) {\n\t\t\t\tconst str = chunk.toString();\n\t\t\t\tstderrChunks.push(str);\n\t\t\t\tstderrSize += str.length;\n\t\t\t}\n\t\t});\n\t\tproc.stderr?.on(\"error\", (err) => {\n\t\t\tlog.warn(`[subagent] stderr stream error (agent=${agentConfig.name}): ${err.message}`);\n\t\t});\n\n\t\t// Parse JSONL events from stdout\n\t\tif (proc.stdout) {\n\t\t\tproc.stdout.on(\"error\", (err) => {\n\t\t\t\tlog.warn(`[subagent] stdout stream error (agent=${agentConfig.name}): ${err.message}`);\n\t\t\t});\n\t\t\tattachJsonlLineReader(proc.stdout, (line) => {\n\t\t\t\tif (onControlAvailable) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst message = JSON.parse(line);\n\t\t\t\t\t\tif (message?.type === \"agent_end\" && !rpcCompleted) {\n\t\t\t\t\t\t\trpcCompleted = true;\n\t\t\t\t\t\t\tsetImmediate(forceKill);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (message?.type === \"agent_start\" && gracefulAbortRequested && !rpcCompleted) {\n\t\t\t\t\t\t\t// The child handles commands concurrently. An abort that arrived while\n\t\t\t\t\t\t\t// its initial prompt was still in its pre-run preamble (API-key\n\t\t\t\t\t\t\t// resolution, input/before-start hooks) was acknowledged without\n\t\t\t\t\t\t\t// aborting anything, because no run existed yet. Abort the run that\n\t\t\t\t\t\t\t// has now started, before it can execute tools the user just stopped.\n\t\t\t\t\t\t\t// Otherwise it would keep working until the grace period expires, and\n\t\t\t\t\t\t\t// SIGTERM would orphan any tool process tree it had started.\n\t\t\t\t\t\t\trequestGracefulAbort();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (message?.type === \"response\" && typeof message.id === \"string\") {\n\t\t\t\t\t\t\tconst pending = pendingRpc.get(message.id);\n\t\t\t\t\t\t\tif (pending) {\n\t\t\t\t\t\t\t\tpendingRpc.delete(message.id);\n\t\t\t\t\t\t\t\tif (message.success) pending.resolve(message.data);\n\t\t\t\t\t\t\t\telse pending.reject(new Error(message.error ?? \"Subagent RPC command failed.\"));\n\t\t\t\t\t\t\t} else if (message.command === \"prompt\" && message.success === false && !rpcCompleted) {\n\t\t\t\t\t\t\t\t// Late failure of the initial prompt: the child acknowledged the\n\t\t\t\t\t\t\t\t// command synchronously, then failed before the agent loop started\n\t\t\t\t\t\t\t\t// (e.g. model/API-key validation, or the task was consumed without\n\t\t\t\t\t\t\t\t// starting the loop), so no agent_end will ever settle this process.\n\t\t\t\t\t\t\t\tfailControlledChild(\n\t\t\t\t\t\t\t\t\tnew Error(typeof message.error === \"string\" ? message.error : \"Subagent prompt failed.\"),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// The normal line handler preserves non-JSON diagnostics.\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\thandleChildJsonlLine(line, {\n\t\t\t\t\tonEvent: onChildEvent,\n\t\t\t\t\tonAssistantMessage: (message) => collectedMessages.push(message),\n\t\t\t\t\tonProgress,\n\t\t\t\t\tonModel: (modelRef) => {\n\t\t\t\t\t\tresolvedModel = modelRef;\n\t\t\t\t\t},\n\t\t\t\t\tonThinking: (thinkingLevel) => {\n\t\t\t\t\t\tresolvedThinking = thinkingLevel;\n\t\t\t\t\t},\n\t\t\t\t\tonPlainLine: (plain) => plainStdoutLines.push(plain),\n\t\t\t\t\ttoolNameRef,\n\t\t\t\t});\n\t\t\t});\n\t\t}\n\n\t\tif (onControlAvailable && controlClient) {\n\t\t\tonControlAvailable(controlClient);\n\t\t\tvoid sendRpc({ type: \"prompt\", message: task }).catch((err) => {\n\t\t\t\tconst error = err instanceof Error ? err : new Error(String(err));\n\t\t\t\tlog.warn(`[subagent] initial RPC prompt failed (agent=${agentConfig.name}): ${error.message}`);\n\t\t\t\t// A rejected initial prompt means the agent loop never starts and the\n\t\t\t\t// child would idle in RPC mode forever — terminate it and fail loudly.\n\t\t\t\tfailControlledChild(error);\n\t\t\t});\n\t\t}\n\n\t\t// Handle abort signal (user stop / stop-all). A controlled child is stopped\n\t\t// gracefully first: the RPC `abort` makes the child abort its own run, so its\n\t\t// tools unwind — notably the bash tool kills its detached process group on its\n\t\t// abort signal, which a bare SIGTERM to this child would orphan. The child's\n\t\t// resulting agent_end triggers the normal SIGTERM above; a run that starts only\n\t\t// after the abort was handled is aborted again on its agent_start. If the abort\n\t\t// cannot be delivered or the child does not finish within the grace period,\n\t\t// escalate to SIGTERM and then the SIGKILL backstop.\n\t\tconst onAbort = () => {\n\t\t\tif (!controlClient || rpcCompleted || controlError || !proc.stdin?.writable) {\n\t\t\t\tforceKill();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tgracefulAbortRequested = true;\n\t\t\tabortGraceTimer ??= setTimeout(forceKill, SUBAGENT_ABORT_GRACE_MS);\n\t\t\trequestGracefulAbort();\n\t\t};\n\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\n\t\tproc.on(\"error\", (err) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tonControlAvailable?.(undefined);\n\t\t\tfor (const request of pendingRpc.values()) request.reject(err);\n\t\t\tpendingRpc.clear();\n\t\t\tif (killTimer) clearTimeout(killTimer);\n\t\t\tif (abortGraceTimer) clearTimeout(abortGraceTimer);\n\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\trejectPromise(new Error(`Subagent process error: ${err.message}`));\n\t\t});\n\n\t\tproc.on(\"close\", (code) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tonControlAvailable?.(undefined);\n\t\t\tfor (const request of pendingRpc.values()) request.reject(new Error(\"Subagent process exited.\"));\n\t\t\tpendingRpc.clear();\n\t\t\tif (killTimer) clearTimeout(killTimer);\n\t\t\tif (abortGraceTimer) clearTimeout(abortGraceTimer);\n\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\tconst exitCode = rpcCompleted ? 0 : (code ?? 1);\n\t\t\tconst stderr = stderrChunks.join(\"\");\n\t\t\tlog.debug(\n\t\t\t\t`[subagent] close: agent=${agentConfig.name} exit=${exitCode} messages=${collectedMessages.length}${exitCode !== 0 ? ` stderr=${stderr.slice(0, 200)} stdout=${plainStdoutLines.join(\"|\").slice(0, 200)}` : \"\"}`,\n\t\t\t);\n\n\t\t\t// Extract final text output from collected assistant messages\n\t\t\tconst outputParts: string[] = [];\n\t\t\tfor (const msg of collectedMessages) {\n\t\t\t\tif (Array.isArray(msg.content)) {\n\t\t\t\t\tfor (const part of msg.content) {\n\t\t\t\t\t\tif (part.type === \"text\" && part.text) {\n\t\t\t\t\t\t\toutputParts.push(part.text);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst output = outputParts.join(\"\\n\\n\");\n\n\t\t\t// Inspect the final assistant message's stopReason to detect truncation\n\t\t\t// (\"length\") or a loud truncation failure (\"error\") from the core agent loop.\n\t\t\t// stopReason is present at runtime even though collectedMessages is loosely typed.\n\t\t\tconst lastMsg = collectedMessages.length > 0 ? collectedMessages[collectedMessages.length - 1] : undefined;\n\t\t\tconst lastStopReason = lastMsg ? (lastMsg as any).stopReason : undefined;\n\t\t\tconst lastErrorMessage = lastMsg ? (lastMsg as any).errorMessage : undefined;\n\n\t\t\t// Build error message from best available source: stderr, plain stdout lines, or generic\n\t\t\tlet errorMessage: string | null = null;\n\t\t\tif (exitCode !== 0) {\n\t\t\t\tconst stderrTrimmed = stderr.trim();\n\t\t\t\tconst plainOutput = plainStdoutLines.join(\"\\n\").trim();\n\t\t\t\terrorMessage =\n\t\t\t\t\tcontrolError?.message.slice(0, 500) ||\n\t\t\t\t\tstderrTrimmed.slice(0, 500) ||\n\t\t\t\t\tplainOutput.slice(0, 500) ||\n\t\t\t\t\t`Subagent exited with code ${exitCode}`;\n\t\t\t} else if (output.trim() === \"\") {\n\t\t\t\t// Clean exit but no output — surface why instead of returning a silent empty result.\n\t\t\t\tif (lastStopReason === \"length\") {\n\t\t\t\t\terrorMessage = \"Subagent response was truncated at the model's token limit before producing any output.\";\n\t\t\t\t} else if (lastStopReason === \"error\" && lastErrorMessage) {\n\t\t\t\t\terrorMessage = String(lastErrorMessage).slice(0, 500);\n\t\t\t\t} else {\n\t\t\t\t\terrorMessage = \"Subagent completed with no output.\";\n\t\t\t\t}\n\t\t\t} else if (lastStopReason === \"length\") {\n\t\t\t\t// Clean exit with partial output — keep the output but make the truncation loud.\n\t\t\t\terrorMessage = \"Subagent response was truncated at the model's token limit; output may be incomplete.\";\n\t\t\t} else if (lastStopReason === \"error\" && lastErrorMessage) {\n\t\t\t\t// Clean exit with partial output but a loud failure (e.g. length retries\n\t\t\t\t// exhausted → the core agent loop converts the truncation to stopReason\n\t\t\t\t// \"error\" while preserving the partial text). Surface the error instead of\n\t\t\t\t// letting the partial output masquerade as a clean success.\n\t\t\t\terrorMessage = String(lastErrorMessage).slice(0, 500);\n\t\t\t}\n\n\t\t\t// Discover the session file written by the child process\n\t\t\tconst sessionFile = sessionDir ? discoverSessionFile(sessionDir, agentConfig.name) : undefined;\n\t\t\tconst configuredModel = Array.isArray(agentConfig.model) ? agentConfig.model[0] : agentConfig.model;\n\n\t\t\tresolvePromise({\n\t\t\t\tagent: agentConfig.name,\n\t\t\t\ttask,\n\t\t\t\tmodel:\n\t\t\t\t\tresolvedModel ??\n\t\t\t\t\t(exitCode === 0 && configuredModel ? canonicalModelRef(parentProvider, configuredModel) : undefined),\n\t\t\t\tthinking: resolvedThinking ?? (exitCode === 0 ? thinkingOverride : undefined),\n\t\t\t\texitCode,\n\t\t\t\toutput,\n\t\t\t\tstderr: stderr.slice(0, 2000), // cap stderr\n\t\t\t\terrorMessage,\n\t\t\t\tsessionFile,\n\t\t\t});\n\t\t});\n\t});\n}\n\n// ---------------------------------------------------------------------------\n// Session file discovery and cleanup\n// ---------------------------------------------------------------------------\n\ninterface SessionFileCandidate {\n\tpath: string;\n\tmtime: number;\n}\n\nconst STEP_SESSION_DIR_RE = /^step-(\\d+)$/;\n\nfunction findNewestJsonlFileInDir(dir: string, throwOnOperationalError = false): SessionFileCandidate | undefined {\n\tlet best: SessionFileCandidate | undefined;\n\tfor (const entry of readdirSync(dir, { withFileTypes: true })) {\n\t\tif (!entry.name.endsWith(\".jsonl\")) continue;\n\t\tif (entry.isDirectory()) continue;\n\t\tconst fullPath = join(dir, entry.name);\n\t\ttry {\n\t\t\tconst mtime = statSync(fullPath).mtime.getTime();\n\t\t\tif (!best || mtime > best.mtime) best = { path: fullPath, mtime };\n\t\t} catch (err) {\n\t\t\tif (isExpectedFilesystemError(err) && (!throwOnOperationalError || isMissingFilesystemError(err))) continue;\n\t\t\tthrow err;\n\t\t}\n\t}\n\treturn best;\n}\n\nfunction discoverStepSessionFileCandidates(\n\tsessionDir: string,\n\tthrowOnOperationalError = false,\n): SessionFileCandidate[] {\n\tconst steps: Array<{ name: string; index: number }> = [];\n\tfor (const entry of readdirSync(sessionDir, { withFileTypes: true })) {\n\t\tif (!entry.isDirectory()) continue;\n\t\tconst match = STEP_SESSION_DIR_RE.exec(entry.name);\n\t\tif (!match) continue;\n\t\tsteps.push({ name: entry.name, index: Number(match[1]) });\n\t}\n\tsteps.sort((a, b) => a.index - b.index || a.name.localeCompare(b.name));\n\n\tconst files: SessionFileCandidate[] = [];\n\tfor (const step of steps) {\n\t\ttry {\n\t\t\tconst candidate = findNewestJsonlFileInDir(join(sessionDir, step.name), throwOnOperationalError);\n\t\t\tif (candidate) files.push(candidate);\n\t\t} catch (err) {\n\t\t\tif (isExpectedFilesystemError(err) && (!throwOnOperationalError || isMissingFilesystemError(err))) continue;\n\t\t\tthrow err;\n\t\t}\n\t}\n\treturn files;\n}\n\n/**\n * Find session JSONL files for a subagent session directory.\n *\n * Normal subagents write one .jsonl directly under sessionDir, so this returns\n * the most recently modified flat file. Chain-mode subagents register the chain\n * root as sessionDir but write each step under step-N/, so when no flat file is\n * present this recurses one level into step-* directories and returns one file\n * per step in numeric step order.\n */\nexport function discoverSessionFiles(\n\tsessionDir: string,\n\tagentName: string,\n\toptions: { throwOnOperationalError?: boolean } = {},\n): string[] {\n\tconst throwOnOperationalError = options.throwOnOperationalError ?? false;\n\ttry {\n\t\tif (!throwOnOperationalError && !existsSync(sessionDir)) return [];\n\t\tconst flatFile = findNewestJsonlFileInDir(sessionDir, throwOnOperationalError);\n\t\tif (flatFile) {\n\t\t\tlog.debug(`[subagent] session file: ${flatFile.path} (agent=${agentName})`);\n\t\t\treturn [flatFile.path];\n\t\t}\n\n\t\tconst stepFiles = discoverStepSessionFileCandidates(sessionDir, throwOnOperationalError);\n\t\tif (stepFiles.length > 0) {\n\t\t\tlog.debug(\n\t\t\t\t`[subagent] chain session files: ${stepFiles.map((file) => file.path).join(\", \")} (agent=${agentName})`,\n\t\t\t);\n\t\t\treturn stepFiles.map((file) => file.path);\n\t\t}\n\t} catch (err) {\n\t\tif (throwOnOperationalError) {\n\t\t\tif (isMissingFilesystemError(err)) return [];\n\t\t\tthrow err;\n\t\t}\n\t\tif (!isExpectedFilesystemError(err)) throw err;\n\t\tlog.warn(\n\t\t\t`[subagent] failed to discover session file (agent=${agentName}): ${err instanceof Error ? err.message : String(err)}`,\n\t\t);\n\t}\n\treturn [];\n}\n\n/**\n * Find the most recently modified .jsonl file in a session directory.\n * Returns the full path, or undefined if no session file was written\n * (e.g., subagent was killed before the first assistant message).\n */\nexport function discoverSessionFile(sessionDir: string, agentName: string): string | undefined {\n\tconst files = discoverSessionFiles(sessionDir, agentName);\n\tif (files.length <= 1) return files[0];\n\n\tlet best: SessionFileCandidate | undefined;\n\tfor (const file of files) {\n\t\ttry {\n\t\t\tconst candidate = { path: file, mtime: statSync(file).mtime.getTime() };\n\t\t\tif (!best || candidate.mtime > best.mtime) best = candidate;\n\t\t} catch (err) {\n\t\t\tif (isExpectedFilesystemError(err)) continue;\n\t\t\tthrow err;\n\t\t}\n\t}\n\treturn best?.path;\n}\n\n// ---------------------------------------------------------------------------\n// Execution modes\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve a model fallback list against the registry. Tries each model in order,\n * returns the first one that resolves successfully. If all fail, returns the\n * last error. Single strings are treated as a one-element list.\n */\nexport function resolveModelWithFallbacks(\n\tmodels: string | string[],\n\tparentProvider: string | undefined,\n\tregistry: ModelRegistry | undefined,\n\tparentModel?: string,\n): { ok: true; modelId: string; provider?: string; warning?: string } | { ok: false; error: string } {\n\tconst modelList = Array.isArray(models) ? models : [models];\n\tlet lastError = \"\";\n\tfor (const modelStr of modelList) {\n\t\tconst result = resolveModelStringSingle(modelStr, parentProvider, registry);\n\t\tif (result.ok) return result;\n\t\tlastError = result.error;\n\t}\n\t// After all configured fallbacks are exhausted, try the parent model as a last resort\n\tif (parentModel) {\n\t\tconst result = resolveModelStringSingle(parentModel, parentProvider, registry);\n\t\tif (result.ok) {\n\t\t\treturn {\n\t\t\t\t...result,\n\t\t\t\twarning: `Agent preferred models were unavailable. Falling back to parent model \"${result.modelId}\".`,\n\t\t\t};\n\t\t}\n\t\tlastError = result.error;\n\t}\n\tif (modelList.length > 1 || parentModel) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `None of the fallback models resolved: ${[...modelList, ...(parentModel ? [parentModel] : [])].join(\", \")}. Last error: ${lastError}`,\n\t\t};\n\t}\n\treturn { ok: false, error: lastError };\n}\n\nexport function resolveModelStringSingle(\n\tmodelStr: string,\n\tparentProvider: string | undefined,\n\tregistry: ModelRegistry | undefined,\n): { ok: true; modelId: string; provider?: string } | { ok: false; error: string } {\n\tif (!registry) {\n\t\treturn { ok: true, modelId: modelStr };\n\t}\n\n\t// If the model string contains \"/\" the user already specified a provider\n\tconst hasProvider = modelStr.includes(\"/\");\n\tconst resolved = resolveCliModel({\n\t\tcliProvider: hasProvider ? undefined : parentProvider,\n\t\tcliModel: modelStr,\n\t\tmodelRegistry: registry,\n\t});\n\n\tif (resolved.error) {\n\t\treturn { ok: false, error: resolved.error };\n\t}\n\tif (!resolved.model) {\n\t\treturn { ok: false, error: `Model \"${modelStr}\" not found. Use --list-models to see available models.` };\n\t}\n\n\t// resolveCliModel creates a synthetic model for any unknown ID when a\n\t// provider is specified (designed for custom/self-hosted models like Ollama).\n\t// For subagents this causes silent failures — reject synthetic fallbacks\n\t// so the next model in the fallback list is tried instead.\n\tif (resolved.isSyntheticFallback) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `Model \"${modelStr}\" not found for provider \"${resolved.model.provider}\". Use --list-models to see available models.`,\n\t\t};\n\t}\n\n\t// Verify the resolved provider has authentication configured.\n\t// resolveCliModel uses getAll() (all models, not just authenticated ones)\n\t// so a model can resolve successfully to a provider with no API key.\n\t// Reject early so the fallback list can continue to the next model.\n\tif (!registry.authStorage.hasAuth(resolved.model.provider)) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `No authentication configured for provider \"${resolved.model.provider}\". Model \"${modelStr}\" cannot be used.`,\n\t\t};\n\t}\n\n\treturn { ok: true, modelId: resolved.model.id, provider: resolved.model.provider };\n}\n\nexport interface ProbeModelAvailabilityOptions {\n\t/** Parent/tool abort signal. A model availability probe timeout is layered on top. */\n\tsignal?: AbortSignal;\n\t/** Model registry used to resolve provider API keys for the probe call. */\n\tregistry?: ModelRegistry;\n\t/** Override the default model availability probe timeout; primarily useful for tests. */\n\ttimeoutMs?: number;\n\t/** Stable conversation ID forwarded to providers that use session-based routing. */\n\tsessionId?: string;\n}\n\nexport type ProbeModelAvailabilityResult = { ok: true } | { ok: false; reason: string; aborted?: boolean };\n\nfunction compactErrorReason(reason: string): string {\n\tconst singleLine = reason.replace(/\\s+/g, \" \").trim();\n\treturn singleLine.length > 180 ? `${singleLine.slice(0, 177)}...` : singleLine || \"unknown error\";\n}\n\nfunction reasonFromRuntimeError(value: unknown): string {\n\tif (value instanceof Error) return value.message;\n\tif (typeof value === \"string\") return value;\n\tif (value && typeof value === \"object\") {\n\t\tconst maybeMessage = value as Partial<AssistantMessage> & { message?: unknown };\n\t\tif (typeof maybeMessage.errorMessage === \"string\") return maybeMessage.errorMessage;\n\t\tif (typeof maybeMessage.message === \"string\") return maybeMessage.message;\n\t}\n\treturn String(value);\n}\n\nexport function isRuntimeUnavailableError(value: unknown): boolean {\n\tif (value instanceof Error || typeof value === \"string\") return true;\n\tif (value && typeof value === \"object\") {\n\t\tconst maybeMessage = value as Partial<AssistantMessage>;\n\t\treturn maybeMessage.stopReason === \"error\" || maybeMessage.stopReason === \"aborted\";\n\t}\n\treturn false;\n}\n\nfunction makeProbeSignal(\n\tparentSignal: AbortSignal | undefined,\n\ttimeoutMs: number,\n): { signal: AbortSignal; timeoutPromise: Promise<never>; cleanup: () => void } {\n\tconst controller = new AbortController();\n\tconst timeoutError = new Error(`Model availability probe timed out after ${timeoutMs}ms`);\n\tlet timeout: ReturnType<typeof setTimeout>;\n\tconst timeoutPromise = new Promise<never>((_, reject) => {\n\t\ttimeout = setTimeout(() => {\n\t\t\tcontroller.abort(timeoutError);\n\t\t\treject(timeoutError);\n\t\t}, timeoutMs);\n\t});\n\tconst parentAbortHandler = () => controller.abort(parentSignal?.reason);\n\tparentSignal?.addEventListener(\"abort\", parentAbortHandler, { once: true });\n\tif (parentSignal?.aborted) controller.abort(parentSignal.reason);\n\n\treturn {\n\t\tsignal: controller.signal,\n\t\ttimeoutPromise,\n\t\tcleanup: () => {\n\t\t\tclearTimeout(timeout);\n\t\t\tparentSignal?.removeEventListener(\"abort\", parentAbortHandler);\n\t\t},\n\t};\n}\n\nexport async function probeModelAvailability(\n\tmodel: Model<Api>,\n\toptions: ProbeModelAvailabilityOptions = {},\n): Promise<ProbeModelAvailabilityResult> {\n\tconst { signal, registry, timeoutMs = DEFAULT_MODEL_AVAILABILITY_PROBE_TIMEOUT_MS, sessionId } = options;\n\tif (signal?.aborted) return { ok: false, reason: \"Aborted before spawn\", aborted: true };\n\n\tconst probeSignal = makeProbeSignal(signal, timeoutMs);\n\ttry {\n\t\tconst context: Context = {\n\t\t\tsystemPrompt: \"Reply with the single word OK.\",\n\t\t\tmessages: [{ role: \"user\", content: \"hi\", timestamp: Date.now() }],\n\t\t};\n\t\tconst apiKey = await Promise.race([\n\t\t\tregistry ? registry.getApiKey(model) : Promise.resolve(undefined),\n\t\t\tprobeSignal.timeoutPromise,\n\t\t]);\n\t\tif (signal?.aborted) return { ok: false, reason: \"Aborted before spawn\", aborted: true };\n\t\tconst thinkingLevel = resolveEffectiveThinkingLevel(model, undefined);\n\t\tconst reasoning = thinkingLevelToReasoning(thinkingLevel);\n\t\t// Use completeSimple — the same streamSimple path the agent loop uses.\n\t\t// No maxTokens override is passed by the probe; buildBaseOptions applies\n\t\t// normal model defaults. Reasoning is resolved through the shared normal\n\t\t// coding-agent thinking default/clamp path instead of provider-specific\n\t\t// probe logic, so reasoning models are probed with representative options.\n\t\tconst result = await Promise.race([\n\t\t\tcompleteSimple(model, context, {\n\t\t\t\tapiKey,\n\t\t\t\tmaxRetryDelayMs: 0,\n\t\t\t\treasoning,\n\t\t\t\tsignal: probeSignal.signal,\n\t\t\t\t...(sessionId ? { sessionId } : {}),\n\t\t\t}),\n\t\t\tprobeSignal.timeoutPromise,\n\t\t]);\n\t\tif (signal?.aborted) return { ok: false, reason: \"Aborted before spawn\", aborted: true };\n\t\tif (isRuntimeUnavailableError(result)) {\n\t\t\treturn { ok: false, reason: compactErrorReason(reasonFromRuntimeError(result)) };\n\t\t}\n\t\treturn { ok: true };\n\t} catch (err) {\n\t\tif (signal?.aborted) return { ok: false, reason: \"Aborted before spawn\", aborted: true };\n\t\treturn { ok: false, reason: compactErrorReason(reasonFromRuntimeError(err)) };\n\t} finally {\n\t\tprobeSignal.cleanup();\n\t}\n}\n\nexport interface SkippedFallbackModel {\n\tmodel: string;\n\treason: string;\n}\n\nexport type SubagentModelResolution =\n\t| {\n\t\t\tok: true;\n\t\t\tmodelId: string;\n\t\t\tprovider?: string;\n\t\t\twarning?: string;\n\t\t\tskippedModels: SkippedFallbackModel[];\n\t }\n\t| { ok: false; error: string; skippedModels: SkippedFallbackModel[] };\n\nexport async function resolveModelForSubagentSpawn(\n\tmodels: string | string[],\n\tparentProvider: string | undefined,\n\tregistry: ModelRegistry | undefined,\n\tparentModel?: string,\n\tsignal?: AbortSignal,\n\t/** Optional log prefix for warning messages (defaults to \"[subagent]\") */\n\tlogPrefix = \"[subagent]\",\n\t/** Stable conversation ID forwarded to availability probes (issue 500). */\n\tsessionId?: string,\n): Promise<SubagentModelResolution> {\n\tif (signal?.aborted) return { ok: false, error: \"Aborted before spawn\", skippedModels: [] };\n\n\t// Runtime probing only applies to agent definition fallback lists. Single\n\t// models, per-invocation overrides, and registry-less environments keep the\n\t// existing spawn-time resolution behavior exactly.\n\tif (!Array.isArray(models) || !registry) {\n\t\tconst resolved = resolveModelWithFallbacks(models, parentProvider, registry, parentModel);\n\t\treturn { ...resolved, skippedModels: [] };\n\t}\n\n\tconst skippedModels: SkippedFallbackModel[] = [];\n\tlet lastError = \"\";\n\n\tfor (const modelStr of models) {\n\t\tif (signal?.aborted) return { ok: false, error: \"Aborted before spawn\", skippedModels };\n\n\t\tconst resolved = resolveModelStringSingle(modelStr, parentProvider, registry);\n\t\tif (!resolved.ok) {\n\t\t\tlastError = resolved.error;\n\t\t\tconst reason = compactErrorReason(resolved.error);\n\t\t\tskippedModels.push({ model: modelStr, reason });\n\t\t\tlog.warn(`${logPrefix} Model \"${modelStr}\" unavailable (${reason}). Trying next fallback...`);\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst modelObj = resolved.provider ? registry.find(resolved.provider, resolved.modelId) : undefined;\n\t\tif (modelObj) {\n\t\t\tconst probe = await probeModelAvailability(modelObj, { signal, registry, sessionId });\n\t\t\tif (!probe.ok && probe.aborted) {\n\t\t\t\treturn { ok: false, error: \"Aborted before spawn\", skippedModels };\n\t\t\t}\n\t\t\tif (signal?.aborted) return { ok: false, error: \"Aborted before spawn\", skippedModels };\n\t\t\tif (!probe.ok) {\n\t\t\t\tlastError = probe.reason;\n\t\t\t\tskippedModels.push({ model: modelStr, reason: probe.reason });\n\t\t\t\tlog.warn(`${logPrefix} Model \"${modelStr}\" failed probe (${probe.reason}). Trying next fallback...`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tlog.debug(`${logPrefix} Using model \"${resolved.modelId}\".`);\n\t\treturn { ...resolved, skippedModels };\n\t}\n\n\tif (signal?.aborted) return { ok: false, error: \"Aborted before spawn\", skippedModels };\n\n\tif (parentModel) {\n\t\tconst parentResolved = resolveModelStringSingle(parentModel, parentProvider, registry);\n\t\tif (parentResolved.ok) {\n\t\t\tconst warning = `Agent preferred models were unavailable. Falling back to parent model \"${parentResolved.modelId}\".`;\n\t\t\tlog.warn(`${logPrefix} ${warning}`);\n\t\t\treturn { ...parentResolved, warning, skippedModels };\n\t\t}\n\t\tlastError = parentResolved.error;\n\t}\n\n\treturn {\n\t\tok: false,\n\t\tskippedModels,\n\t\terror: `None of the fallback models passed availability checks: ${[\n\t\t\t...models,\n\t\t\t...(parentModel ? [parentModel] : []),\n\t\t].join(\", \")}. Last error: ${lastError || \"all probes failed\"}`,\n\t};\n}\n\nexport function formatModelFallbackSummary(\n\tskippedModels: SkippedFallbackModel[],\n\tproposalModel: string | undefined,\n\tfinalModel?: string,\n): string | undefined {\n\tif (skippedModels.length === 0) return undefined;\n\tconst skipped = skippedModels.map((s) => `- ${s.model}: ${s.reason}`).join(\"\\n\");\n\tconst routeSummary =\n\t\tfinalModel && finalModel !== proposalModel\n\t\t\t? `proposal resolved to \"${proposalModel ?? \"unknown\"}\" before arbitration selected \"${finalModel}\".`\n\t\t\t: `using \"${finalModel ?? proposalModel ?? \"unknown\"}\".`;\n\treturn `[MODEL FALLBACK: skipped ${skippedModels.length} unavailable model(s); ${routeSummary}]\\n${skipped}`;\n}\n\nfunction formatSkippedModelFailureDetails(skippedModels: SkippedFallbackModel[]): string | undefined {\n\tif (skippedModels.length === 0) return undefined;\n\treturn `Skipped models:\\n${skippedModels.map((s) => `- ${s.model}: ${s.reason}`).join(\"\\n\")}`;\n}\n\nconst MAX_PARALLEL_TASKS = 8;\nconst MAX_TASK_LENGTH = 32_768; // 32 KB — prevent E2BIG from oversized argv\n\n/**\n * Bounds the number of concurrently running background subagents. Ownership of the gate is kept\n * separate from the subagent tool definition so that a single logical session keeps one accurate\n * running-child count even when its tool definitions are rebuilt (e.g. on `/reload`).\n */\nexport interface SubagentConcurrencyGate {\n\t/**\n\t * Resolves immediately if a slot is free, otherwise queues until one is released.\n\t * When `signal` aborts before a slot is granted, the waiter is removed and the\n\t * promise rejects without taking a slot (the caller must not `release()`).\n\t */\n\tacquire(signal?: AbortSignal): Promise<void>;\n\t/** Returns a slot and wakes the next waiter, if any. */\n\trelease(): void;\n}\n\n/** Thrown by {@link SubagentConcurrencyGate.acquire} when its signal aborts before a slot is granted. */\nexport class SubagentSlotWaitAbortedError extends Error {\n\tconstructor() {\n\t\tsuper(\"Cancelled while waiting for a subagent concurrency slot.\");\n\t\tthis.name = \"SubagentSlotWaitAbortedError\";\n\t}\n}\n\n/**\n * Create a concurrency gate limited to `maxConcurrent` simultaneous holders. The count lives in\n * this closure, so a single gate instance shared across tool rebuilds keeps counting in-flight\n * children accurately, while distinct instances stay fully isolated from one another.\n */\nexport function createSubagentConcurrencyGate(maxConcurrent: number): SubagentConcurrencyGate {\n\tif (!Number.isSafeInteger(maxConcurrent) || maxConcurrent < 1) {\n\t\tthrow new Error(\"Subagent tool concurrency must be a positive whole number\");\n\t}\n\tlet running = 0;\n\tconst waiters: Array<() => void> = [];\n\treturn {\n\t\tacquire(signal?: AbortSignal): Promise<void> {\n\t\t\tif (signal?.aborted) return Promise.reject(new SubagentSlotWaitAbortedError());\n\t\t\tif (running < maxConcurrent) {\n\t\t\t\trunning++;\n\t\t\t\treturn Promise.resolve();\n\t\t\t}\n\t\t\treturn new Promise<void>((resolve, reject) => {\n\t\t\t\tconst grant = () => {\n\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\trunning++;\n\t\t\t\t\tresolve();\n\t\t\t\t};\n\t\t\t\tconst onAbort = () => {\n\t\t\t\t\tconst index = waiters.indexOf(grant);\n\t\t\t\t\tif (index !== -1) waiters.splice(index, 1);\n\t\t\t\t\treject(new SubagentSlotWaitAbortedError());\n\t\t\t\t};\n\t\t\t\twaiters.push(grant);\n\t\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t});\n\t\t},\n\t\trelease(): void {\n\t\t\trunning--;\n\t\t\tconst next = waiters.shift();\n\t\t\tif (next) next();\n\t\t},\n\t};\n}\n\n/** Resolve per-task thinking precedence for parallel and chain modes. */\nexport function resolveSubagentThinkingOverride(\n\ttaskThinking: ThinkingLevel | undefined,\n\ttopLevelThinking: ThinkingLevel | undefined,\n): ThinkingLevel | undefined {\n\treturn taskThinking ?? topLevelThinking;\n}\n\n/**\n * Resolve a per-task cwd.\n * Accepts absolute paths as-is. Resolves relative paths against the parent cwd,\n * rejecting any that escape outside it.\n * Returns a result object with ok=false and an error string on rejection, so callers can surface it to the model.\n */\nfunction clampCwd(defaultCwd: string, itemCwd?: string): { ok: true; cwd: string } | { ok: false; error: string } {\n\tif (!itemCwd) return { ok: true, cwd: defaultCwd };\n\tif (itemCwd.startsWith(\"/\")) {\n\t\treturn { ok: true, cwd: itemCwd };\n\t}\n\tconst resolved = resolve(defaultCwd, itemCwd);\n\tif (resolved !== defaultCwd && !resolved.startsWith(`${defaultCwd}/`)) {\n\t\treturn { ok: false, error: `Rejected cwd \"${itemCwd}\" — resolves outside parent cwd` };\n\t}\n\treturn { ok: true, cwd: resolved };\n}\n\nexport interface SubagentArbitrationHooks {\n\tarbitrate: (request: DispatchArbitrationRequest, signal?: AbortSignal) => Promise<DispatchArbitrationResult>;\n\tonRecord: (record: DispatchArbitrationRecord) => void;\n\tstep?: number;\n\tdefaultThinkingLevel?: ThinkingLevel;\n\tgetAgentModelsForAgent?: (name: string) => string[] | undefined;\n}\n\nexport async function executeSingle(\n\tagents: Map<string, AgentTypeConfig>,\n\tagentName: string | undefined,\n\ttask: string,\n\tcwd: string,\n\tsignal?: AbortSignal,\n\tonProgress?: (event: string) => void,\n\tmodelOverride?: string,\n\tparentProvider?: string,\n\tregistry?: ModelRegistry,\n\tsessionDir?: string,\n\tparentModel?: string,\n\tagentModels?: string[],\n\tparentSessionFile?: string,\n\tonChildEvent?: (event: Record<string, unknown>) => void,\n\tthinkingOverride?: ThinkingLevel,\n\tarbitration?: SubagentArbitrationHooks,\n\tonControlAvailable?: (client: RpcClient | undefined) => void,\n\t/** Parent session UUID for spawn-time availability probes (issue 500). */\n\tparentSessionId?: string,\n\t/** Single-model mode (issue 517): the child runs on the parent session's model, ignoring model specs and the dispatch arbiter. */\n\tsingleModelMode?: boolean,\n): Promise<SubagentResult> {\n\tlet name = agentName || DEFAULT_AGENT;\n\tlet config = agents.get(name);\n\tif (!config) {\n\t\treturn {\n\t\t\tagent: name,\n\t\t\ttask,\n\t\t\texitCode: 1,\n\t\t\toutput: \"\",\n\t\t\tstderr: \"\",\n\t\t\terrorMessage: `Unknown agent type \"${name}\". Available: ${[...agents.keys()].join(\", \")}. If you expected \"${name}\" to exist, check the .md file in ~/.dreb/agents/ or .dreb/agents/ for syntax errors.`,\n\t\t};\n\t}\n\tif (task.length > MAX_TASK_LENGTH) {\n\t\treturn {\n\t\t\tagent: name,\n\t\t\ttask: `${task.slice(0, 200)}...`,\n\t\t\texitCode: 1,\n\t\t\toutput: \"\",\n\t\t\tstderr: \"\",\n\t\t\terrorMessage: `Task prompt too long (${task.length} chars, max ${MAX_TASK_LENGTH}). Shorten the prompt.`,\n\t\t};\n\t}\n\n\t// Phase 1: resolve the parent's proposal with the existing precedence and\n\t// fallback behavior so the arbiter receives one concrete canonical route.\n\tconst configuredModelSpec =\n\t\tmodelOverride || (agentModels && agentModels.length > 0 ? agentModels : undefined) || config.model;\n\tconst modelSpec = configuredModelSpec || parentModel;\n\tlet effectiveConfig: AgentTypeConfig = modelOverride ? { ...config, model: modelOverride } : config;\n\tlet resolvedProvider = parentProvider;\n\tlet resolvedModel: Model<Api> | undefined;\n\tlet warning: string | undefined;\n\tlet skippedModels: SkippedFallbackModel[] = [];\n\n\tif (singleModelMode) {\n\t\t// Single-model mode (issue 517): every child runs on the parent session's model.\n\t\t// The per-call model override, per-agent model fallback list, agent-definition model\n\t\t// spec, and dispatch arbiter are all bypassed; a requested spec is reported through\n\t\t// the `warning` that is prepended to the child's output below.\n\t\tif (!parentModel) {\n\t\t\treturn {\n\t\t\t\tagent: name,\n\t\t\t\ttask,\n\t\t\t\texitCode: 1,\n\t\t\t\toutput: \"\",\n\t\t\t\tstderr: \"\",\n\t\t\t\terrorMessage:\n\t\t\t\t\t\"Single model mode is enabled, but the parent session's model is unavailable, so subagent \" +\n\t\t\t\t\t`\"${name}\" cannot be spawned. Disable singleModelMode or run the parent session with a model.`,\n\t\t\t};\n\t\t}\n\t\tconst parentResolution = resolveModelStringSingle(parentModel, parentProvider, registry);\n\t\tif (!parentResolution.ok) {\n\t\t\treturn {\n\t\t\t\tagent: name,\n\t\t\t\ttask,\n\t\t\t\texitCode: 1,\n\t\t\t\toutput: \"\",\n\t\t\t\tstderr: \"\",\n\t\t\t\terrorMessage: `Single model mode: ${parentResolution.error}`,\n\t\t\t};\n\t\t}\n\t\teffectiveConfig = { ...effectiveConfig, model: parentResolution.modelId };\n\t\tif (parentResolution.provider) resolvedProvider = parentResolution.provider;\n\t\tif (registry && resolvedProvider) resolvedModel = registry.find(resolvedProvider, parentResolution.modelId);\n\t\tif (configuredModelSpec) {\n\t\t\twarning =\n\t\t\t\t`The user has enabled \"single model mode\" in the settings, so the model selection for this subagent ` +\n\t\t\t\t`was ignored. Using parent model \"${canonicalModelRef(resolvedProvider, parentResolution.modelId)}\".`;\n\t\t}\n\t} else if (modelSpec) {\n\t\tconst parentFallback = configuredModelSpec ? parentModel : undefined;\n\t\tconst resolved = await resolveModelForSubagentSpawn(\n\t\t\tmodelSpec,\n\t\t\tparentProvider,\n\t\t\tregistry,\n\t\t\tparentFallback,\n\t\t\tsignal,\n\t\t\t\"[subagent]\",\n\t\t\tparentSessionId,\n\t\t);\n\t\tskippedModels = resolved.skippedModels;\n\t\tif (!resolved.ok) {\n\t\t\tconst skippedDetails = formatSkippedModelFailureDetails(skippedModels);\n\t\t\treturn {\n\t\t\t\tagent: name,\n\t\t\t\ttask,\n\t\t\t\texitCode: 1,\n\t\t\t\toutput: \"\",\n\t\t\t\tstderr: \"\",\n\t\t\t\terrorMessage: skippedDetails ? `${resolved.error}\\n\\n${skippedDetails}` : resolved.error,\n\t\t\t};\n\t\t}\n\t\teffectiveConfig = { ...effectiveConfig, model: resolved.modelId };\n\t\tif (resolved.provider) resolvedProvider = resolved.provider;\n\t\tif (registry && resolvedProvider) resolvedModel = registry.find(resolvedProvider, resolved.modelId);\n\t\twarning = resolved.warning;\n\t}\n\n\tif (thinkingOverride && thinkingOverride !== \"off\" && !modelSpec) {\n\t\treturn {\n\t\t\tagent: name,\n\t\t\ttask,\n\t\t\texitCode: 1,\n\t\t\toutput: \"\",\n\t\t\tstderr: \"\",\n\t\t\terrorMessage: `Cannot validate thinking level \"${thinkingOverride}\" because agent \"${name}\" has no configured model and no parent model is available. Set a model on the agent or pass a per-call model override.`,\n\t\t};\n\t}\n\n\tconst proposalModelId = Array.isArray(effectiveConfig.model) ? effectiveConfig.model[0] : effectiveConfig.model;\n\tconst proposalSelectedModel = proposalModelId ? canonicalModelRef(resolvedProvider, proposalModelId) : undefined;\n\tlet finalThinking = thinkingOverride;\n\tlet arbitrationEnabled = false;\n\t// Single-model mode (issue 517) bypasses the dispatch arbiter: the parent model is the\n\t// final route, and the requested thinking is validated against it below like any other.\n\tif (arbitration && !singleModelMode) {\n\t\tconst proposed: DispatchRoute = {\n\t\t\tagent: name,\n\t\t\tmodel: proposalSelectedModel ?? \"\",\n\t\t\tthinking: resolveEffectiveThinkingLevel(resolvedModel, thinkingOverride, arbitration.defaultThinkingLevel),\n\t\t};\n\t\tlet arbitrationResult: DispatchArbitrationResult;\n\t\ttry {\n\t\t\tarbitrationResult = await arbitration.arbitrate(\n\t\t\t\t{\n\t\t\t\t\ttask,\n\t\t\t\t\tcwd,\n\t\t\t\t\tproposed,\n\t\t\t\t\tagents: summarizeAgentsForArbitration(agents, arbitration.getAgentModelsForAgent),\n\t\t\t\t\tparentSessionFile,\n\t\t\t\t\tstep: arbitration.step,\n\t\t\t\t},\n\t\t\t\tsignal,\n\t\t\t);\n\t\t} catch {\n\t\t\tconst errorMessage = \"Dispatch arbiter failed internally before child spawn.\";\n\t\t\ttry {\n\t\t\t\tarbitration.onRecord({\n\t\t\t\t\tstatus: \"failure\",\n\t\t\t\t\tproposed,\n\t\t\t\t\tfinal: null,\n\t\t\t\t\tchanged: [],\n\t\t\t\t\tstep: arbitration.step,\n\t\t\t\t\terrorCode: \"internal_error\",\n\t\t\t\t\terrorMessage,\n\t\t\t\t});\n\t\t\t} catch {}\n\t\t\treturn {\n\t\t\t\tagent: name,\n\t\t\t\ttask,\n\t\t\t\texitCode: 1,\n\t\t\t\toutput: \"\",\n\t\t\t\tstderr: \"\",\n\t\t\t\terrorMessage,\n\t\t\t};\n\t\t}\n\t\tif (arbitrationResult.enabled) {\n\t\t\tarbitrationEnabled = true;\n\t\t\tif (!arbitrationResult.ok) {\n\t\t\t\tconst record: DispatchArbitrationRecord = {\n\t\t\t\t\tstatus: \"failure\",\n\t\t\t\t\tproposed,\n\t\t\t\t\tfinal: null,\n\t\t\t\t\tchanged: [],\n\t\t\t\t\tstep: arbitration.step,\n\t\t\t\t\terrorCode: arbitrationResult.code,\n\t\t\t\t\terrorMessage: arbitrationResult.error,\n\t\t\t\t};\n\t\t\t\ttry {\n\t\t\t\t\tarbitration.onRecord(record);\n\t\t\t\t} catch {\n\t\t\t\t\t// The original failure still prevents spawn; do not replace it with an observer error.\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tagent: name,\n\t\t\t\t\ttask,\n\t\t\t\t\texitCode: 1,\n\t\t\t\t\toutput: \"\",\n\t\t\t\t\tstderr: \"\",\n\t\t\t\t\terrorMessage: `Dispatch arbitration failed: ${arbitrationResult.error}`,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst decision = arbitrationResult.decision;\n\t\t\tconst selectedConfig = agents.get(decision.agent);\n\t\t\tconst slash = decision.model.indexOf(\"/\");\n\t\t\tconst selectedProvider = slash > 0 ? decision.model.slice(0, slash) : \"\";\n\t\t\tconst selectedModelId = slash > 0 ? decision.model.slice(slash + 1) : \"\";\n\t\t\tconst selectedModel = registry?.find(selectedProvider, selectedModelId);\n\t\t\tif (!selectedConfig || !selectedModel) {\n\t\t\t\tconst errorMessage = !selectedConfig\n\t\t\t\t\t? \"Arbiter selected an unknown agent.\"\n\t\t\t\t\t: \"Arbiter selected an unavailable model.\";\n\t\t\t\tconst record: DispatchArbitrationRecord = {\n\t\t\t\t\tstatus: \"failure\",\n\t\t\t\t\tproposed,\n\t\t\t\t\tfinal: null,\n\t\t\t\t\tchanged: [],\n\t\t\t\t\tstep: arbitration.step,\n\t\t\t\t\terrorCode: !selectedConfig ? \"unknown_agent\" : \"out_of_scope_model\",\n\t\t\t\t\terrorMessage,\n\t\t\t\t};\n\t\t\t\ttry {\n\t\t\t\t\tarbitration.onRecord(record);\n\t\t\t\t} catch {}\n\t\t\t\treturn {\n\t\t\t\t\tagent: name,\n\t\t\t\t\ttask,\n\t\t\t\t\texitCode: 1,\n\t\t\t\t\toutput: \"\",\n\t\t\t\t\tstderr: \"\",\n\t\t\t\t\terrorMessage: `Dispatch arbitration failed: ${errorMessage}`,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst finalThinkingValidation = validateThinkingLevelForModel(selectedModel, decision.thinking);\n\t\t\tif (!finalThinkingValidation.ok) {\n\t\t\t\tconst record: DispatchArbitrationRecord = {\n\t\t\t\t\tstatus: \"failure\",\n\t\t\t\t\tproposed,\n\t\t\t\t\tfinal: null,\n\t\t\t\t\tchanged: [],\n\t\t\t\t\tstep: arbitration.step,\n\t\t\t\t\terrorCode: \"unsupported_thinking\",\n\t\t\t\t\terrorMessage: finalThinkingValidation.error,\n\t\t\t\t};\n\t\t\t\ttry {\n\t\t\t\t\tarbitration.onRecord(record);\n\t\t\t\t} catch {}\n\t\t\t\treturn {\n\t\t\t\t\tagent: name,\n\t\t\t\t\ttask,\n\t\t\t\t\texitCode: 1,\n\t\t\t\t\toutput: \"\",\n\t\t\t\t\tstderr: \"\",\n\t\t\t\t\terrorMessage: `Dispatch arbitration failed: ${finalThinkingValidation.error}`,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tname = decision.agent;\n\t\t\tconfig = selectedConfig;\n\t\t\teffectiveConfig = { ...config, model: selectedModel.id };\n\t\t\tresolvedProvider = selectedModel.provider;\n\t\t\tresolvedModel = selectedModel;\n\t\t\tfinalThinking = decision.thinking;\n\n\t\t\ttry {\n\t\t\t\tarbitration.onRecord({\n\t\t\t\t\tstatus: \"success\",\n\t\t\t\t\tproposed,\n\t\t\t\t\tfinal: decision,\n\t\t\t\t\tchanged: arbitrationResult.changed,\n\t\t\t\t\tstep: arbitration.step,\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\treturn {\n\t\t\t\t\tagent: name,\n\t\t\t\t\ttask,\n\t\t\t\t\texitCode: 1,\n\t\t\t\t\toutput: \"\",\n\t\t\t\t\tstderr: \"\",\n\t\t\t\t\terrorMessage: `Dispatch arbitration observability failed before spawn: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}\n\n\tif (finalThinking) {\n\t\tconst validation = validateThinkingLevelForModel(resolvedModel, finalThinking);\n\t\tif (!validation.ok) {\n\t\t\treturn {\n\t\t\t\tagent: name,\n\t\t\t\ttask,\n\t\t\t\texitCode: 1,\n\t\t\t\toutput: \"\",\n\t\t\t\tstderr: \"\",\n\t\t\t\terrorMessage: validation.error,\n\t\t\t};\n\t\t}\n\t}\n\n\tconst usedModel = effectiveConfig.model?.toString();\n\tonProgress?.(`Running ${name} agent${usedModel ? ` (${usedModel})` : \"\"}...`);\n\tconst result = await spawnSubagent(\n\t\teffectiveConfig,\n\t\ttask,\n\t\tcwd,\n\t\tsignal,\n\t\tonProgress,\n\t\tresolvedProvider,\n\t\tsessionDir,\n\t\tparentSessionFile,\n\t\tonChildEvent,\n\t\tfinalThinking,\n\t\tonControlAvailable,\n\t);\n\tconst finalSelectedModel = result.model ?? (usedModel ? canonicalModelRef(resolvedProvider, usedModel) : undefined);\n\t// Spawn-time routing notes are system text, not the child's words: keep them out of\n\t// `output` so the parent sees them outside the agent-output block (and so a chain's\n\t// `{previous}` carries only the previous agent's output).\n\tconst notes: string[] = [];\n\tif (warning) {\n\t\tconst warningContext = arbitrationEnabled ? `Proposal resolution: ${warning}` : warning;\n\t\tnotes.push(`[WARNING: ${warningContext}]`);\n\t}\n\tconst fallbackSummary = formatModelFallbackSummary(\n\t\tskippedModels,\n\t\tarbitrationEnabled ? proposalSelectedModel : finalSelectedModel,\n\t\tarbitrationEnabled ? finalSelectedModel : undefined,\n\t);\n\tif (fallbackSummary) notes.push(fallbackSummary);\n\tif (notes.length > 0) result.notes = notes;\n\treturn result;\n}\n\nasync function executeChain(\n\tagents: Map<string, AgentTypeConfig>,\n\tchain: Array<{ agent?: string; task: string; cwd?: string; model?: string; thinking?: ThinkingLevel }>,\n\tdefaultCwd: string,\n\tsignal?: AbortSignal,\n\tonProgress?: (event: string) => void,\n\tparentProvider?: string,\n\tregistry?: ModelRegistry,\n\tsessionBaseDir?: string,\n\tdefaultAgent?: string,\n\tdefaultModel?: string,\n\tdefaultThinking?: ThinkingLevel,\n\tparentModel?: string,\n\tgetAgentModelsForAgentFn?: (name: string) => string[] | undefined,\n\tparentSessionFile?: string,\n\tonChildEvent?: (event: Record<string, unknown>) => void,\n\tarbitration?: Omit<SubagentArbitrationHooks, \"step\">,\n\tonControlAvailable?: (client: RpcClient | undefined) => void,\n\t/** Parent session UUID for spawn-time availability probes (issue 500). */\n\tparentSessionId?: string,\n\t/**\n\t * Live single-model mode getter (issue 517): evaluated per step so each chain step\n\t * runs on the parent session's model when enabled, matching the per-spawn semantics\n\t * of single and parallel modes.\n\t */\n\tgetSingleModelMode?: () => boolean,\n): Promise<SubagentResult[]> {\n\tconst results: SubagentResult[] = [];\n\tlet previousOutput = \"\";\n\n\tfor (let i = 0; i < chain.length; i++) {\n\t\tif (signal?.aborted) break;\n\t\tconst step = chain[i];\n\t\tconst task = step.task.replace(/\\{previous\\}/g, previousOutput);\n\t\tonProgress?.(`Chain step ${i + 1}/${chain.length}`);\n\n\t\t// Validate task length after {previous} substitution (can compound across steps)\n\t\tif (task.length > MAX_TASK_LENGTH) {\n\t\t\tresults.push({\n\t\t\t\tagent: step.agent || defaultAgent || DEFAULT_AGENT,\n\t\t\t\ttask: `${task.slice(0, 200)}...`,\n\t\t\t\texitCode: 1,\n\t\t\t\toutput: \"\",\n\t\t\t\tstderr: \"\",\n\t\t\t\terrorMessage: `Task prompt too long after {previous} substitution (${task.length} chars, max ${MAX_TASK_LENGTH}). Shorten the prompt or summarize previous output.`,\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\n\t\tconst cwdResult = clampCwd(defaultCwd, step.cwd);\n\t\tif (!cwdResult.ok) {\n\t\t\tresults.push({\n\t\t\t\tagent: step.agent || defaultAgent || DEFAULT_AGENT,\n\t\t\t\ttask,\n\t\t\t\texitCode: 1,\n\t\t\t\toutput: \"\",\n\t\t\t\tstderr: \"\",\n\t\t\t\terrorMessage: cwdResult.error,\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\n\t\t// Each chain step gets its own session subdirectory\n\t\tconst stepSessionDir = sessionBaseDir ? join(sessionBaseDir, `step-${i + 1}`) : undefined;\n\t\tconst stepAgentName = step.agent || defaultAgent || DEFAULT_AGENT;\n\t\tconst stepMach6Models = getAgentModelsForAgentFn?.(stepAgentName);\n\t\t// Single-model mode (issue 517) is re-read per step so a mid-chain settings\n\t\t// change applies from the next step onward.\n\t\tconst singleModelMode = getSingleModelMode?.() ?? false;\n\t\tconst result = await executeSingle(\n\t\t\tagents,\n\t\t\tstep.agent || defaultAgent,\n\t\t\ttask,\n\t\t\tcwdResult.cwd,\n\t\t\tsignal,\n\t\t\tonProgress,\n\t\t\tstep.model || defaultModel,\n\t\t\tparentProvider,\n\t\t\tregistry,\n\t\t\tstepSessionDir,\n\t\t\tparentModel,\n\t\t\tstepMach6Models,\n\t\t\tparentSessionFile,\n\t\t\tonChildEvent,\n\t\t\tresolveSubagentThinkingOverride(step.thinking, defaultThinking),\n\t\t\tarbitration ? { ...arbitration, step: i + 1 } : undefined,\n\t\t\tonControlAvailable,\n\t\t\tparentSessionId,\n\t\t\tsingleModelMode,\n\t\t);\n\t\tresults.push(result);\n\n\t\tif (result.exitCode !== 0) {\n\t\t\tbreak; // stop chain on error\n\t\t}\n\t\tpreviousOutput = result.output;\n\t}\n\n\treturn results;\n}\n\n// ---------------------------------------------------------------------------\n// Background execution\n// ---------------------------------------------------------------------------\n\nfunction generateAgentId(): string {\n\treturn randomBytes(6).toString(\"hex\");\n}\n\n// ---------------------------------------------------------------------------\n// Background agent registry — queryable by TUI / Telegram frontends\n// ---------------------------------------------------------------------------\n\n/**\n * Lifecycle status of a background agent. `cancelled` means the user stopped it\n * (a single-agent stop or a stop-all such as Esc / the parent stop control) —\n * distinct from `failed`, which means the child itself errored.\n */\nexport type BackgroundAgentStatus = \"running\" | \"completed\" | \"failed\" | \"cancelled\";\n\nexport interface BackgroundAgentInfo {\n\tagentId: string;\n\tagentType: string;\n\ttaskSummary: string;\n\tstartedAt: number;\n\tstatus: BackgroundAgentStatus;\n\t/** Directory containing the agent's session JSONL file (known at spawn time). */\n\tsessionDir?: string;\n\t/** Path to the agent's session JSONL file (discovered when the child exits). */\n\tsessionFile?: string;\n\t/** Working directory the agent runs in. */\n\tcwd?: string;\n\t/**\n\t * Parent session file the agent was launched from. A user stop records it in the\n\t * agent's cancellation marker so rehydration can match the marker to its parent.\n\t */\n\tparentSessionFile?: string;\n\t/** Safe host-generated pre-spawn routing decisions, ordered by chain step/attempt. */\n\tarbitrations?: DispatchArbitrationRecord[];\n}\n\nconst backgroundAgentRegistry = new Map<string, BackgroundAgentInfo>();\nconst backgroundAbortControllers = new Map<string, AbortController>();\nconst backgroundControlClients = new Map<string, RpcClient>();\n\nconst REHYDRATED_AGENT_ID_PREFIX = \"rehydrated-\";\nconst HEADER_READ_CHUNK_BYTES = 8192;\nconst MAX_HEADER_READ_BYTES = 256 * 1024;\nconst METADATA_READ_BYTES = 256 * 1024;\nconst TAIL_READ_BYTES = 64 * 1024;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null;\n}\n\nfunction isExpectedFilesystemError(err: unknown): boolean {\n\treturn typeof (err as NodeJS.ErrnoException | undefined)?.code === \"string\";\n}\n\n/** Only absence is optional during primary-root restart recovery. */\nfunction isMissingFilesystemError(err: unknown): boolean {\n\treturn (err as NodeJS.ErrnoException | undefined)?.code === \"ENOENT\";\n}\n\nfunction shouldSkipRehydrationFilesystemError(err: unknown, isPrimaryRoot: boolean, context: string): boolean {\n\tif (isMissingFilesystemError(err)) return true;\n\tif (isPrimaryRoot || !isExpectedFilesystemError(err)) return false;\n\tlog.warn(\n\t\t`[subagent] skipped compatibility-root recovery (${context}): ${err instanceof Error ? err.message : String(err)}`,\n\t);\n\treturn true;\n}\n\nfunction parseJsonlLine(line: string): Record<string, unknown> | undefined {\n\ttry {\n\t\tconst parsed = JSON.parse(line);\n\t\treturn isRecord(parsed) ? parsed : undefined;\n\t} catch (err) {\n\t\tif (err instanceof SyntaxError) return undefined;\n\t\tthrow err;\n\t}\n}\n\nfunction readFirstNonEmptyLine(filePath: string): string | undefined {\n\tlet fd: number | undefined;\n\ttry {\n\t\tfd = openSync(filePath, \"r\");\n\t\tconst chunk = Buffer.alloc(HEADER_READ_CHUNK_BYTES);\n\t\tlet buffered = \"\";\n\t\tlet bytesReadTotal = 0;\n\n\t\twhile (bytesReadTotal < MAX_HEADER_READ_BYTES) {\n\t\t\tconst bytesRead = readSync(fd, chunk, 0, Math.min(chunk.length, MAX_HEADER_READ_BYTES - bytesReadTotal), null);\n\t\t\tif (bytesRead === 0) break;\n\t\t\tbytesReadTotal += bytesRead;\n\t\t\tbuffered += chunk.toString(\"utf8\", 0, bytesRead);\n\n\t\t\tconst lines = buffered.split(/\\r?\\n/);\n\t\t\tconst completeLines = buffered.endsWith(\"\\n\") || buffered.endsWith(\"\\r\") ? lines : lines.slice(0, -1);\n\t\t\tfor (const line of completeLines) {\n\t\t\t\tif (line.trim()) return line;\n\t\t\t}\n\t\t\tbuffered = lines.at(-1) ?? \"\";\n\t\t}\n\n\t\treturn buffered.trim() ? buffered : undefined;\n\t} catch (err) {\n\t\tif (isMissingFilesystemError(err)) return undefined;\n\t\tthrow err;\n\t} finally {\n\t\tif (fd !== undefined) {\n\t\t\ttry {\n\t\t\t\tcloseSync(fd);\n\t\t\t} catch {\n\t\t\t\t// Best-effort observability: close errors are filesystem cleanup noise.\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction readFileSlice(filePath: string, start: number, length: number): string | undefined {\n\tlet fd: number | undefined;\n\ttry {\n\t\tfd = openSync(filePath, \"r\");\n\t\tconst buffer = Buffer.alloc(length);\n\t\tconst bytesRead = readSync(fd, buffer, 0, length, start);\n\t\treturn buffer.toString(\"utf8\", 0, bytesRead);\n\t} catch (err) {\n\t\tif (isMissingFilesystemError(err)) return undefined;\n\t\tthrow err;\n\t} finally {\n\t\tif (fd !== undefined) {\n\t\t\ttry {\n\t\t\t\tcloseSync(fd);\n\t\t\t} catch {\n\t\t\t\t// Best-effort observability: close errors are filesystem cleanup noise.\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction readFileStart(filePath: string, maxBytes: number): string | undefined {\n\tlet size = maxBytes;\n\ttry {\n\t\tsize = Math.min(statSync(filePath).size, maxBytes);\n\t} catch (err) {\n\t\tif (isMissingFilesystemError(err)) return undefined;\n\t\tthrow err;\n\t}\n\treturn readFileSlice(filePath, 0, size);\n}\n\nfunction readFileTail(filePath: string, maxBytes: number): string | undefined {\n\tlet start = 0;\n\tlet length = maxBytes;\n\ttry {\n\t\tconst size = statSync(filePath).size;\n\t\tstart = Math.max(0, size - maxBytes);\n\t\tlength = size - start;\n\t} catch (err) {\n\t\tif (isMissingFilesystemError(err)) return undefined;\n\t\tthrow err;\n\t}\n\treturn readFileSlice(filePath, start, length);\n}\n\nfunction parseSessionHeader(sessionFile: string): Record<string, unknown> | undefined {\n\tconst headerLine = readFirstNonEmptyLine(sessionFile);\n\tif (!headerLine) return undefined;\n\treturn parseJsonlLine(headerLine);\n}\n\nfunction comparablePath(pathValue: string): string {\n\tconst resolved = resolve(pathValue);\n\treturn process.platform === \"win32\" ? resolved.toLowerCase() : resolved;\n}\n\n/** Canonical identity for an existing path, with a lexical fallback for races/missing paths. */\nfunction canonicalExistingPath(pathValue: string): string {\n\tlet canonical: string;\n\ttry {\n\t\tcanonical = realpathSync.native(pathValue);\n\t} catch (err) {\n\t\tif (!isMissingFilesystemError(err)) throw err;\n\t\tcanonical = resolve(pathValue);\n\t}\n\treturn process.platform === \"win32\" ? canonical.toLowerCase() : canonical;\n}\n\nfunction parentSessionMatches(recordedParentSession: string, parentSessionFile: string): boolean {\n\tif (recordedParentSession === parentSessionFile) return true;\n\tif (comparablePath(recordedParentSession) === comparablePath(parentSessionFile)) return true;\n\n\t// Older/foreign invocations may disagree about absolute vs relative roots, but\n\t// dreb session filenames include a timestamp and UUID. A basename match is a\n\t// safe final fallback for recovering observability across process boundaries.\n\treturn basename(recordedParentSession) === basename(parentSessionFile);\n}\n\nfunction extractTextFromContent(content: unknown): string | undefined {\n\tif (typeof content === \"string\") return content.trim() || undefined;\n\tif (!Array.isArray(content)) return undefined;\n\n\tconst parts: string[] = [];\n\tfor (const item of content) {\n\t\tif (!isRecord(item)) continue;\n\t\tif (item.type === \"text\" && typeof item.text === \"string\" && item.text.trim()) {\n\t\t\tparts.push(item.text.trim());\n\t\t}\n\t}\n\tconst text = parts.join(\"\\n\").trim();\n\treturn text || undefined;\n}\n\nfunction truncateTaskSummary(text: string): string {\n\tconst normalized = text.replace(/\\s+/g, \" \").trim();\n\treturn normalized.length > 120 ? `${normalized.slice(0, 117)}...` : normalized;\n}\n\nfunction findFirstUserMessageSummary(sessionFile: string): string | undefined {\n\tconst head = readFileStart(sessionFile, METADATA_READ_BYTES);\n\tif (!head) return undefined;\n\n\tfor (const line of head.split(/\\r?\\n/)) {\n\t\tif (!line.trim()) continue;\n\t\tconst entry = parseJsonlLine(line);\n\t\tif (entry?.type !== \"message\" || !isRecord(entry.message)) continue;\n\t\tif (entry.message.role !== \"user\") continue;\n\t\tconst text = extractTextFromContent(entry.message.content);\n\t\tif (text) return truncateTaskSummary(text);\n\t}\n\treturn undefined;\n}\n\n/**\n * Infer a finished child's status from the last assistant message in its session log.\n * `aborted` only occurs when the parent gracefully cancelled the child (user stop), so it\n * maps to `cancelled`; `error` maps to `failed`.\n */\nfunction inferCompletedSessionStatus(sessionFile: string): Exclude<BackgroundAgentStatus, \"running\"> {\n\tconst tail = readFileTail(sessionFile, TAIL_READ_BYTES);\n\tif (!tail) return \"completed\";\n\n\tconst lines = tail.split(/\\r?\\n/).reverse();\n\tfor (const line of lines) {\n\t\tif (!line.trim()) continue;\n\t\tconst entry = parseJsonlLine(line);\n\t\tif (entry?.type !== \"message\" || !isRecord(entry.message)) continue;\n\t\tif (entry.message.role !== \"assistant\") continue;\n\n\t\tconst stopReason = entry.message.stopReason;\n\t\tif (stopReason === \"aborted\") return \"cancelled\";\n\t\treturn stopReason === \"error\" ? \"failed\" : \"completed\";\n\t}\n\treturn \"completed\";\n}\n\n/**\n * File in a background agent's session directory recording that the user stopped it.\n * A stop doesn't always leave a trailing `aborted` message in the child's log: a chain\n * stopped between steps, a child terminated after the grace period, and an agent stopped\n * while queued or before spawn (which has no log at all). The marker is the authoritative\n * record that rehydration checks first.\n */\nexport const SUBAGENT_CANCELLED_MARKER_FILE = \"cancelled.json\";\n\ninterface SubagentCancellationMarker {\n\ttype: \"subagent_cancelled\";\n\tversion: 1;\n\tcancelledAt: string;\n\t/** Parent session file the agent was launched from (matched during rehydration). */\n\tparentSession: string;\n\tagentType: string;\n\ttaskSummary: string;\n\tstartedAt: string;\n\tcwd?: string;\n}\n\n/**\n * Record a user stop in the agent's session directory (created if the agent never\n * spawned). Agents without a session directory or parent session file can't be\n * rehydrated, so nothing is written for them. A write failure doesn't block the stop\n * itself. It is logged as an error, because the agent may show as completed or be\n * missing after a reload.\n */\nfunction writeCancellationMarker(info: BackgroundAgentInfo): void {\n\tif (!info.sessionDir || !info.parentSessionFile) return;\n\tconst marker: SubagentCancellationMarker = {\n\t\ttype: \"subagent_cancelled\",\n\t\tversion: 1,\n\t\tcancelledAt: new Date().toISOString(),\n\t\tparentSession: info.parentSessionFile,\n\t\tagentType: info.agentType,\n\t\ttaskSummary: info.taskSummary,\n\t\tstartedAt: new Date(info.startedAt).toISOString(),\n\t\t...(info.cwd ? { cwd: info.cwd } : {}),\n\t};\n\ttry {\n\t\tmkdirSync(info.sessionDir, { recursive: true });\n\t\twriteFileSync(join(info.sessionDir, SUBAGENT_CANCELLED_MARKER_FILE), `${JSON.stringify(marker)}\\n`);\n\t} catch (err) {\n\t\tlog.error(\n\t\t\t`[subagent] Failed to record the cancellation of background agent ${info.agentId} in ${info.sessionDir}: ${err instanceof Error ? err.message : String(err)}. After a reload it may show as completed or be missing.`,\n\t\t);\n\t}\n}\n\nfunction isCancellationMarker(value: unknown): value is SubagentCancellationMarker {\n\treturn (\n\t\tisRecord(value) &&\n\t\tvalue.type === \"subagent_cancelled\" &&\n\t\ttypeof value.parentSession === \"string\" &&\n\t\ttypeof value.agentType === \"string\" &&\n\t\tvalue.agentType.trim() !== \"\" &&\n\t\ttypeof value.taskSummary === \"string\" &&\n\t\ttypeof value.startedAt === \"string\" &&\n\t\tNumber.isFinite(Date.parse(value.startedAt)) &&\n\t\t(value.cwd === undefined || typeof value.cwd === \"string\")\n\t);\n}\n\n/**\n * Read an agent's cancellation marker. Returns `undefined` when there is none, the parsed\n * marker when valid, and `\"malformed\"` (after a warning) when the file exists but can't be\n * used. A malformed marker still proves the stop happened, but can't identify the parent.\n * Filesystem errors other than absence propagate to the caller's recovery policy.\n */\nfunction readCancellationMarker(sessionDir: string): SubagentCancellationMarker | \"malformed\" | undefined {\n\tconst markerPath = join(sessionDir, SUBAGENT_CANCELLED_MARKER_FILE);\n\tlet raw: string;\n\ttry {\n\t\traw = readFileSync(markerPath, \"utf8\");\n\t} catch (err) {\n\t\tif (isMissingFilesystemError(err)) return undefined;\n\t\tthrow err;\n\t}\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(raw);\n\t} catch {\n\t\tparsed = undefined;\n\t}\n\tif (isCancellationMarker(parsed)) return parsed;\n\tlog.warn(\n\t\t`[subagent] ignoring malformed cancellation marker ${markerPath}; the agent is still reported as cancelled`,\n\t);\n\treturn \"malformed\";\n}\n\nfunction parseStartedAt(header: Record<string, unknown>, sessionFile: string): number {\n\tif (typeof header.timestamp === \"string\") {\n\t\tconst timestamp = Date.parse(header.timestamp);\n\t\tif (Number.isFinite(timestamp)) return timestamp;\n\t}\n\n\ttry {\n\t\treturn statSync(sessionFile).mtime.getTime();\n\t} catch (err) {\n\t\tif (isMissingFilesystemError(err)) return Date.now();\n\t\tthrow err;\n\t}\n}\n\nfunction hasRegisteredSession(sessionDir: string, sessionFile?: string): boolean {\n\tconst comparableSessionDir = canonicalExistingPath(sessionDir);\n\tconst comparableSessionFile = sessionFile ? canonicalExistingPath(sessionFile) : undefined;\n\tfor (const agent of backgroundAgentRegistry.values()) {\n\t\tif (agent.sessionDir && canonicalExistingPath(agent.sessionDir) === comparableSessionDir) return true;\n\t\tif (\n\t\t\tcomparableSessionFile &&\n\t\t\tagent.sessionFile &&\n\t\t\tcanonicalExistingPath(agent.sessionFile) === comparableSessionFile\n\t\t) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\n/** A registry ID for a rehydrated agent, derived from its session directory name and kept unique. */\nfunction nextRehydratedAgentId(sessionDirName: string): string {\n\tconst baseAgentId = `${REHYDRATED_AGENT_ID_PREFIX}${sessionDirName}`;\n\tlet agentId = baseAgentId;\n\tlet suffix = 2;\n\twhile (backgroundAgentRegistry.has(agentId)) {\n\t\tagentId = `${baseAgentId}-${suffix++}`;\n\t}\n\treturn agentId;\n}\n\n/**\n * Recover completed background subagents after a dashboard/RPC process resumes\n * an existing parent session. Live background-agent state is an in-memory\n * registry, while child sessions are durable JSONL files under the subagent\n * sessions directory.\n *\n * A user stop's cancellation marker ({@link SUBAGENT_CANCELLED_MARKER_FILE}) takes\n * precedence over status inferred from the log. An agent stopped before it spawned has\n * only the marker, and is recovered from it.\n *\n * The first root is authoritative: absence races and malformed JSON are skipped,\n * while operational filesystem failures throw. Later roots are compatibility\n * stores, so their operational filesystem failures are warned and skipped.\n * Returns the number of newly registered agents.\n */\nexport function rehydrateBackgroundAgentsFromDisk(\n\tparentSessionFile: string | undefined,\n\tsubagentSessionRoots: string | readonly string[] = getSubagentSessionsDir(),\n): number {\n\tif (!parentSessionFile) return 0;\n\n\tconst roots = typeof subagentSessionRoots === \"string\" ? [subagentSessionRoots] : subagentSessionRoots;\n\tconst scannedRoots = new Set<string>();\n\tconst seenSessionDirs = new Set<string>();\n\tconst seenSessionFiles = new Set<string>();\n\tlet registered = 0;\n\n\tfor (const [rootIndex, subagentSessionsBase] of roots.entries()) {\n\t\tconst isPrimaryRoot = rootIndex === 0;\n\t\tlet canonicalRoot: string;\n\t\ttry {\n\t\t\tcanonicalRoot = canonicalExistingPath(subagentSessionsBase);\n\t\t} catch (err) {\n\t\t\tif (shouldSkipRehydrationFilesystemError(err, isPrimaryRoot, `root ${subagentSessionsBase}`)) continue;\n\t\t\tthrow err;\n\t\t}\n\t\tif (scannedRoots.has(canonicalRoot)) continue;\n\t\tscannedRoots.add(canonicalRoot);\n\n\t\tlet entries: Dirent[];\n\t\ttry {\n\t\t\tentries = readdirSync(subagentSessionsBase, { withFileTypes: true });\n\t\t} catch (err) {\n\t\t\tif (shouldSkipRehydrationFilesystemError(err, isPrimaryRoot, `root ${subagentSessionsBase}`)) continue;\n\t\t\tthrow err;\n\t\t}\n\n\t\tfor (const entry of entries) {\n\t\t\tconst sessionDir = join(subagentSessionsBase, entry.name);\n\t\t\ttry {\n\t\t\t\tlet isDirectory = entry.isDirectory();\n\t\t\t\tif (!isDirectory && entry.isSymbolicLink()) {\n\t\t\t\t\tisDirectory = statSync(sessionDir).isDirectory();\n\t\t\t\t}\n\t\t\t\tif (!isDirectory) continue;\n\n\t\t\t\tconst canonicalSessionDir = canonicalExistingPath(sessionDir);\n\t\t\t\tif (seenSessionDirs.has(canonicalSessionDir)) continue;\n\t\t\t\tseenSessionDirs.add(canonicalSessionDir);\n\n\t\t\t\tconst sessionFiles = discoverSessionFiles(sessionDir, entry.name, { throwOnOperationalError: true });\n\t\t\t\tconst cancellationMarker = readCancellationMarker(sessionDir);\n\t\t\t\tif (sessionFiles.length === 0) {\n\t\t\t\t\t// A user stop while the agent was queued or before it spawned leaves no log,\n\t\t\t\t\t// only the cancellation marker.\n\t\t\t\t\tif (cancellationMarker === undefined || cancellationMarker === \"malformed\") continue;\n\t\t\t\t\tif (!parentSessionMatches(cancellationMarker.parentSession, parentSessionFile)) continue;\n\t\t\t\t\tif (hasRegisteredSession(sessionDir)) continue;\n\t\t\t\t\tconst agentId = nextRehydratedAgentId(entry.name);\n\t\t\t\t\tbackgroundAgentRegistry.set(agentId, {\n\t\t\t\t\t\tagentId,\n\t\t\t\t\t\tagentType: cancellationMarker.agentType,\n\t\t\t\t\t\ttaskSummary: cancellationMarker.taskSummary,\n\t\t\t\t\t\tstartedAt: Date.parse(cancellationMarker.startedAt),\n\t\t\t\t\t\tstatus: \"cancelled\",\n\t\t\t\t\t\tsessionDir,\n\t\t\t\t\t\tcwd: cancellationMarker.cwd,\n\t\t\t\t\t});\n\t\t\t\t\tregistered++;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tlet sessionFile: string | undefined;\n\t\t\t\tlet header: Record<string, unknown> | undefined;\n\t\t\t\tfor (const candidateFile of sessionFiles) {\n\t\t\t\t\tconst candidateHeader = parseSessionHeader(candidateFile);\n\t\t\t\t\tif (candidateHeader?.type !== \"session\" || typeof candidateHeader.parentSession !== \"string\") continue;\n\t\t\t\t\tif (!parentSessionMatches(candidateHeader.parentSession, parentSessionFile)) continue;\n\t\t\t\t\tconst canonicalSessionFile = canonicalExistingPath(candidateFile);\n\t\t\t\t\tif (seenSessionFiles.has(canonicalSessionFile)) break;\n\t\t\t\t\tseenSessionFiles.add(canonicalSessionFile);\n\t\t\t\t\tsessionFile = candidateFile;\n\t\t\t\t\theader = candidateHeader;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (!sessionFile || !header || hasRegisteredSession(sessionDir, sessionFile)) continue;\n\n\t\t\t\tconst agentId = nextRehydratedAgentId(entry.name);\n\n\t\t\t\tconst statusFile = sessionFiles[sessionFiles.length - 1] ?? sessionFile;\n\t\t\t\tconst agentType =\n\t\t\t\t\ttypeof header.agentType === \"string\" && header.agentType.trim() ? header.agentType : \"agent\";\n\t\t\t\tconst taskSummary = findFirstUserMessageSummary(sessionFile) ?? `${agentType} (${entry.name})`;\n\t\t\t\tbackgroundAgentRegistry.set(agentId, {\n\t\t\t\t\tagentId,\n\t\t\t\t\tagentType,\n\t\t\t\t\ttaskSummary,\n\t\t\t\t\tstartedAt: parseStartedAt(header, sessionFile),\n\t\t\t\t\t// The marker is authoritative: a stop between chain steps or a terminated child\n\t\t\t\t\t// doesn't leave a trailing `aborted` message for inference to find.\n\t\t\t\t\tstatus: cancellationMarker !== undefined ? \"cancelled\" : inferCompletedSessionStatus(statusFile),\n\t\t\t\t\tsessionDir,\n\t\t\t\t\tsessionFile,\n\t\t\t\t\tcwd: typeof header.cwd === \"string\" ? header.cwd : undefined,\n\t\t\t\t});\n\t\t\t\tregistered++;\n\t\t\t} catch (err) {\n\t\t\t\tif (shouldSkipRehydrationFilesystemError(err, isPrimaryRoot, `entry ${sessionDir}`)) continue;\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn registered;\n}\n\nfunction cloneBackgroundAgentInfo(info: BackgroundAgentInfo): BackgroundAgentInfo {\n\treturn {\n\t\t...info,\n\t\tarbitrations: info.arbitrations?.map((record) => structuredClone(record)),\n\t};\n}\n\n/** Get a snapshot of all tracked background agents (running and recently completed). Returns readonly clones. */\nexport function getBackgroundAgents(): readonly Readonly<BackgroundAgentInfo>[] {\n\treturn [...backgroundAgentRegistry.values()].map(cloneBackgroundAgentInfo);\n}\n\n/** Get only currently running background agents. Returns readonly clones. */\nexport function getRunningBackgroundAgents(): readonly Readonly<BackgroundAgentInfo>[] {\n\treturn [...backgroundAgentRegistry.values()].filter((a) => a.status === \"running\").map(cloneBackgroundAgentInfo);\n}\n\nfunction getBackgroundControlClient(agentId: string): RpcClient {\n\tconst info = backgroundAgentRegistry.get(agentId);\n\tif (!info) throw new Error(`Unknown background agent \"${agentId}\".`);\n\tif (info.status !== \"running\") throw new Error(`Background agent \"${agentId}\" is no longer running.`);\n\tconst client = backgroundControlClients.get(agentId);\n\tif (!client) throw new Error(`Background agent \"${agentId}\" has not started a controllable child yet.`);\n\treturn client;\n}\n\n/** Queue the user's message unchanged in the selected live child session. */\nexport async function steerBackgroundAgent(agentId: string, message: string): Promise<void> {\n\tawait getBackgroundControlClient(agentId).steer(message);\n}\n\n/** Read pending steering messages and the effective delivery mode from the selected live child. */\nexport async function getBackgroundAgentPendingSteering(\n\tagentId: string,\n): Promise<{ steeringMode: \"all\" | \"one-at-a-time\"; pending: RpcPendingMessages }> {\n\tconst client = getBackgroundControlClient(agentId);\n\tconst [state, pending] = await Promise.all([client.getState(), client.getPendingMessages()]);\n\treturn { steeringMode: state.steeringMode, pending };\n}\n\n/**\n * Mark one registry entry cancelled, record the stop on disk, and abort its\n * controller. The status is set before aborting so anything reacting\n * synchronously to the abort (and the lifecycle, which skips status updates once\n * its signal is aborted) observes `cancelled` rather than `running`. The\n * controller's abort listeners perform the graceful child shutdown (RPC abort\n * first, then SIGTERM/SIGKILL backstops).\n */\nfunction cancelBackgroundAgentEntry(agentId: string, controller: AbortController): void {\n\tconst entry = backgroundAgentRegistry.get(agentId);\n\tif (entry && entry.status === \"running\") {\n\t\tentry.status = \"cancelled\";\n\t\twriteCancellationMarker(entry);\n\t}\n\tbackgroundAbortControllers.delete(agentId);\n\tbackgroundControlClients.delete(agentId);\n\tcontroller.abort();\n}\n\n/**\n * Cancel exactly one running background agent (user stop). Siblings, the parent\n * session, and their control channels are untouched. Works for agents that are\n * executing, queued for a concurrency slot, or between chain steps; a chain is\n * stopped as a whole. Completion is reported asynchronously through the normal\n * background-complete path with `cancelled = true`.\n *\n * Throws for unknown agents and agents that are no longer running (completed,\n * failed, cancelled, or rehydrated from disk) — never a silent no-op.\n */\nexport function abortBackgroundAgent(agentId: string): void {\n\tconst info = backgroundAgentRegistry.get(agentId);\n\tif (!info) throw new Error(`Unknown background agent \"${agentId}\".`);\n\tif (info.status !== \"running\") throw new Error(`Background agent \"${agentId}\" is no longer running.`);\n\tconst controller = backgroundAbortControllers.get(agentId);\n\tif (!controller) throw new Error(`Background agent \"${agentId}\" has no abort controller; it cannot be stopped.`);\n\tcancelBackgroundAgentEntry(agentId, controller);\n}\n\n/** Cancel all running background agents (Esc / parent stop). */\nexport function abortBackgroundAgents(): void {\n\tfor (const [id, controller] of [...backgroundAbortControllers]) {\n\t\tcancelBackgroundAgentEntry(id, controller);\n\t}\n\tbackgroundAbortControllers.clear();\n\tbackgroundControlClients.clear();\n}\n\n/** Remove completed/failed entries older than the given age (ms). Default: 5 minutes. */\nexport function pruneBackgroundAgents(maxAgeMs = 5 * 60 * 1000): void {\n\tconst now = Date.now();\n\tfor (const [id, info] of backgroundAgentRegistry) {\n\t\tif (info.status !== \"running\" && now - info.startedAt > maxAgeMs) {\n\t\t\tbackgroundAgentRegistry.delete(id);\n\t\t\tbackgroundAbortControllers.delete(id);\n\t\t\tbackgroundControlClients.delete(id);\n\t\t}\n\t}\n}\n\nexport interface SubagentToolOptions {\n\t/** Resolved root for new subagent child-session directories. Defaults to the legacy agent root. */\n\tsubagentSessionsDir?: string;\n\t/** Called when a background subagent starts. Used by TUI to show status indicators. */\n\tonBackgroundStart?: (agentId: string, agentType: string, taskSummary: string, sessionDir?: string) => void;\n\t/** Called when a background subagent completes with its result. `cancelled` is true if the user aborted it. */\n\tonBackgroundComplete?: (agentId: string, result: SubagentResult, cancelled: boolean) => void;\n\t/**\n\t * Called with every JSONL event a background child process emits, tagged with the\n\t * child's agentId. Enables live observability relays (e.g. the dashboard) without\n\t * tailing session files. Chain steps share the chain's agentId.\n\t */\n\tonBackgroundEvent?: (agentId: string, event: Record<string, unknown>) => void;\n\t/** Parent session's current provider (e.g. \"anthropic\"). Called at each invocation to get the live value after mid-session model switches. */\n\tparentProvider?: () => string | undefined;\n\t/** Parent session's current model ID. Used as a final fallback when all subagent-configured models fail to resolve. Called at each invocation for fresh value. */\n\tparentModel?: () => string | undefined;\n\t/** Parent session's current session file path. Used to link subagent child sessions back to their parent session. */\n\tparentSessionFile?: () => string | undefined;\n\t/**\n\t * Parent session's stable conversation UUID. Forwarded to spawn-time model availability\n\t * probes so providers with session-based routing (e.g. OpenCode) can group the probe\n\t * with the parent conversation (issue 500).\n\t */\n\tparentSessionId?: () => string | undefined;\n\t/**\n\t * Live single-model mode setting, evaluated at each spawn. When true, every child runs\n\t * on the parent session's model: the per-call `model` override, per-agent model fallback\n\t * lists, the agent definition's `model` spec, and the dispatch arbiter are all bypassed,\n\t * and a warning is prepended to child output whenever an ignored model spec was requested.\n\t */\n\tsingleModelMode?: () => boolean;\n\t/** Model registry for validating model names before spawning child processes. */\n\tmodelRegistry?: ModelRegistry;\n\t/** Settings-based model override getter for mach6.models. */\n\tgetAgentModelsForAgent?: (agentName: string) => string[] | undefined;\n\t/** Mode-independent headless arbitration callback. Disabled arbitration returns `{ enabled: false }`. */\n\tarbitrate?: (request: DispatchArbitrationRequest, signal?: AbortSignal) => Promise<DispatchArbitrationResult>;\n\t/** Persist and relay one safe host-generated record for each enabled arbitration attempt. */\n\tonArbitration?: (event: SubagentArbitrationEvent) => void;\n\t/** Effective default used to make an omitted proposed thinking level concrete for the arbiter. */\n\tdefaultThinkingLevel?: () => ThinkingLevel;\n\t/**\n\t * Maximum children this parent tool instance may run concurrently. Must be at least one.\n\t * Used for the model-visible description and, when `concurrencyGate` is omitted, to size a\n\t * fresh per-instance gate.\n\t */\n\tmaxConcurrentSubagents?: number;\n\t/**\n\t * Externally owned concurrency gate. Supply this so the running-child count survives tool\n\t * definition rebuilds (e.g. on `/reload`); without it the tool creates its own gate sized by\n\t * `maxConcurrentSubagents`, which resets to zero each time the tool is recreated.\n\t */\n\tconcurrencyGate?: SubagentConcurrencyGate;\n}\n\n// ---------------------------------------------------------------------------\n// Tool schema and definition\n// ---------------------------------------------------------------------------\n\nconst thinkingLevelSchema = Type.Union(\n\t[\n\t\tType.Literal(\"off\"),\n\t\tType.Literal(\"minimal\"),\n\t\tType.Literal(\"low\"),\n\t\tType.Literal(\"medium\"),\n\t\tType.Literal(\"high\"),\n\t\tType.Literal(\"xhigh\"),\n\t\tType.Literal(\"max\"),\n\t],\n\t{ description: \"Thinking level override for the child model.\" },\n);\n\nconst taskItemSchema = Type.Object({\n\tagent: Type.Optional(Type.String({ description: \"Agent type name (default: 'Explore')\" })),\n\ttask: Type.String({ description: \"The task prompt for this subagent\" }),\n\tcwd: Type.Optional(\n\t\tType.String({\n\t\t\tdescription:\n\t\t\t\t\"Working directory (defaults to parent's cwd). Accepts absolute paths or relative paths within parent's cwd.\",\n\t\t}),\n\t),\n\tmodel: Type.Optional(\n\t\tType.String({\n\t\t\tdescription:\n\t\t\t\t\"Model override for this task. Takes precedence over agent definition model. Note: a single-string override discards the agent's fallback list.\",\n\t\t}),\n\t),\n\tthinking: Type.Optional(thinkingLevelSchema),\n});\n\nconst subagentSchema = Type.Object({\n\tagent: Type.Optional(Type.String({ description: \"Agent type name (default: 'Explore')\" })),\n\ttask: Type.Optional(Type.String({ description: \"Task prompt (single mode)\", minLength: 1 })),\n\tmodel: Type.Optional(\n\t\tType.String({\n\t\t\tdescription:\n\t\t\t\t\"Model override. Takes precedence over agent definition model. Note: a single-string override discards the agent's fallback list. For parallel/chain, set per-task instead.\",\n\t\t}),\n\t),\n\tthinking: Type.Optional(\n\t\tType.Union(\n\t\t\t[\n\t\t\t\tType.Literal(\"off\"),\n\t\t\t\tType.Literal(\"minimal\"),\n\t\t\t\tType.Literal(\"low\"),\n\t\t\t\tType.Literal(\"medium\"),\n\t\t\t\tType.Literal(\"high\"),\n\t\t\t\tType.Literal(\"xhigh\"),\n\t\t\t\tType.Literal(\"max\"),\n\t\t\t],\n\t\t\t{\n\t\t\t\tdescription:\n\t\t\t\t\t\"Thinking level override. Per-task values take precedence in parallel and chain modes. Omit to preserve child defaults.\",\n\t\t\t},\n\t\t),\n\t),\n\ttasks: Type.Optional(\n\t\tType.Array(taskItemSchema, {\n\t\t\tdescription: \"Array of tasks to run in parallel (max 8)\",\n\t\t\tminItems: 1,\n\t\t\tmaxItems: MAX_PARALLEL_TASKS,\n\t\t}),\n\t),\n\tchain: Type.Optional(\n\t\tType.Array(taskItemSchema, {\n\t\t\tdescription: \"Sequential pipeline — each step can use {previous} for prior output\",\n\t\t\tminItems: 1,\n\t\t}),\n\t),\n\t// background parameter removed — all subagents run in background mode.\n\t// Kept in schema for backward compatibility (silently ignored if passed).\n\tbackground: Type.Optional(\n\t\tType.Boolean({ description: \"Deprecated — all subagents run in background mode. This parameter is ignored.\" }),\n\t),\n});\n\nexport type SubagentToolInput = Static<typeof subagentSchema>;\n\nexport interface SubagentToolDetails {\n\ttruncation?: TruncationResult;\n\tmode: \"single\" | \"parallel\" | \"chain\";\n\tagentCount: number;\n}\n\nfunction formatSubagentCall(\n\targs: SubagentToolInput | undefined,\n\ttheme: typeof import(\"../../modes/interactive/theme/theme.js\").theme,\n\targsComplete = true,\n): string {\n\tconst invalidArg = invalidArgText(theme);\n\n\tif (args?.tasks) {\n\t\t// Show agent type(s) in the parallel label\n\t\tconst agentCounts = new Map<string, number>();\n\t\tfor (const t of args.tasks) {\n\t\t\tconst name = t.agent || args.agent || DEFAULT_AGENT;\n\t\t\tagentCounts.set(name, (agentCounts.get(name) || 0) + 1);\n\t\t}\n\t\tlet typeLabel: string;\n\t\tif (agentCounts.size === 1) {\n\t\t\tconst [name] = [...agentCounts.keys()];\n\t\t\ttypeLabel = `${args.tasks.length} ${name} tasks`;\n\t\t} else {\n\t\t\tconst parts = [...agentCounts.entries()].map(([name, count]) => `${count} ${name}`);\n\t\t\ttypeLabel = `${args.tasks.length} tasks: ${parts.join(\", \")}`;\n\t\t}\n\t\treturn `${theme.fg(\"toolTitle\", theme.bold(\"subagent\"))} ${theme.fg(\"accent\", `parallel (${typeLabel})`)}`;\n\t}\n\tif (args?.chain) {\n\t\tconst agentName = str(args.agent) || args.chain[0]?.agent || DEFAULT_AGENT;\n\t\treturn `${theme.fg(\"toolTitle\", theme.bold(\"subagent\"))} ${theme.fg(\"accent\", `chain (${agentName}, ${args.chain.length} steps)`)}`;\n\t}\n\n\tconst agent = str(args?.agent) || DEFAULT_AGENT;\n\tconst model = str(args?.model);\n\tconst task = str(args?.task);\n\tconst taskPreview = task ? (task.length > 60 ? `${task.slice(0, 57)}...` : task) : null;\n\tconst modelSuffix = model ? ` ${theme.fg(\"muted\", `(${model})`)}` : \"\";\n\treturn (\n\t\ttheme.fg(\"toolTitle\", theme.bold(\"subagent\")) +\n\t\t\" \" +\n\t\ttheme.fg(\"accent\", agent) +\n\t\tmodelSuffix +\n\t\t\" \" +\n\t\t(taskPreview === null\n\t\t\t? argsComplete\n\t\t\t\t? invalidArg\n\t\t\t\t: theme.fg(\"muted\", \"…\")\n\t\t\t: theme.fg(\"toolOutput\", `\"${taskPreview}\"`))\n\t);\n}\n\nfunction formatSubagentResult(\n\tresult: {\n\t\tcontent: Array<{ type: string; text?: string }>;\n\t\tdetails?: SubagentToolDetails;\n\t},\n\toptions: ToolRenderResultOptions,\n\ttheme: typeof import(\"../../modes/interactive/theme/theme.js\").theme,\n\tshowImages: boolean,\n): string {\n\tconst output = getTextOutput(result, showImages).trim();\n\tlet text = \"\";\n\tif (output) {\n\t\tconst lines = output.split(\"\\n\");\n\t\tconst maxLines = options.expanded ? lines.length : 25;\n\t\tconst displayLines = lines.slice(0, maxLines);\n\t\tconst remaining = lines.length - maxLines;\n\t\ttext += `\\n${displayLines.map((line) => theme.fg(\"toolOutput\", line)).join(\"\\n\")}`;\n\t\tif (remaining > 0) {\n\t\t\ttext += `${theme.fg(\"muted\", `\\n... (${remaining} more lines,`)} ${keyHint(\"app.tools.expand\", \"to expand\")})`;\n\t\t}\n\t}\n\tconst truncation = result.details?.truncation;\n\tif (truncation?.truncated) {\n\t\ttext += `\\n${theme.fg(\"warning\", `[Truncated: ${formatSize(truncation.maxBytes ?? DEFAULT_MAX_BYTES)} limit]`)}`;\n\t}\n\treturn text;\n}\n\n/**\n * Wrap a subagent's own output in labelled delimiter lines so it can't be mistaken for\n * the system lines around it (execution metadata, cancellation/error notes, session log,\n * still-running list). `partial` marks output from a run that did not finish cleanly\n * (cancelled, failed, or truncated). Blank lines around the delimiters keep them as\n * separate paragraphs when the text is rendered as Markdown (dashboard, Telegram).\n */\nexport function formatAgentOutputBlock(output: string, partial: boolean): string {\n\treturn `--- agent output${partial ? \" (partial)\" : \"\"} ---\\n\\n${output}\\n\\n--- end of agent output ---`;\n}\n\n/**\n * Render one subagent result (used for each chain step). The agent's output is wrapped by\n * `formatAgentOutputBlock`; `cancelled` marks a step that was stopped by the user, whose\n * output is therefore partial.\n */\nexport function formatSingleResult(result: SubagentResult, cancelled = false): string {\n\tconst metadata = [\n\t\tresult.model ? `model: ${result.model}` : undefined,\n\t\tresult.thinking ? `thinking: ${result.thinking}` : undefined,\n\t]\n\t\t.filter((value): value is string => value !== undefined)\n\t\t.join(\", \");\n\tlet text = `## Agent: ${result.agent}${metadata ? ` (${metadata})` : \"\"}\\n`;\n\tif (result.exitCode !== 0) {\n\t\ttext += `**Error** (exit ${result.exitCode}): ${result.errorMessage || \"Unknown error\"}\\n`;\n\t\tif (result.stderr) {\n\t\t\ttext += `\\nStderr:\\n${result.stderr}\\n`;\n\t\t}\n\t} else if (result.errorMessage) {\n\t\t// Clean exit but an error was surfaced (e.g. truncation at the token limit).\n\t\ttext += `**Error**: ${result.errorMessage}\\n`;\n\t}\n\tif (result.notes && result.notes.length > 0) {\n\t\ttext += `\\n${result.notes.join(\"\\n\\n\")}\\n`;\n\t}\n\tif (result.output) {\n\t\tconst partial = cancelled || result.exitCode !== 0 || !!result.errorMessage;\n\t\ttext += `\\n${formatAgentOutputBlock(result.output, partial)}`;\n\t} else if (result.exitCode === 0 && !result.errorMessage) {\n\t\ttext += \"\\n(No output)\";\n\t}\n\tif (result.sessionFile) {\n\t\ttext += `\\n\\nSession log: ${result.sessionFile}`;\n\t}\n\treturn text;\n}\n\nexport function createSubagentToolDefinition(\n\tcwd: string,\n\toptions?: SubagentToolOptions,\n): ToolDefinition<typeof subagentSchema, SubagentToolDetails | undefined> {\n\tconst subagentSessionsBase = options?.subagentSessionsDir ?? getSubagentSessionsDir();\n\tconst onBackgroundStart = options?.onBackgroundStart;\n\tconst onBackgroundComplete = options?.onBackgroundComplete;\n\tconst onBackgroundEvent = options?.onBackgroundEvent;\n\tconst getParentProvider = options?.parentProvider ?? (() => undefined);\n\tconst getParentModel = options?.parentModel ?? (() => undefined);\n\tconst getParentSessionFile = options?.parentSessionFile ?? (() => undefined);\n\tconst getParentSessionId = options?.parentSessionId ?? (() => undefined);\n\tconst getSingleModelMode = options?.singleModelMode ?? (() => false);\n\tconst modelRegistry = options?.modelRegistry;\n\tconst getAgentModelsForAgent = options?.getAgentModelsForAgent;\n\tconst arbitrate = options?.arbitrate;\n\tconst onArbitration = options?.onArbitration;\n\tconst getDefaultThinkingLevel = options?.defaultThinkingLevel;\n\tconst maxConcurrentSubagents = options?.maxConcurrentSubagents ?? DEFAULT_MAX_CONCURRENT_SUBAGENTS;\n\tif (!Number.isSafeInteger(maxConcurrentSubagents) || maxConcurrentSubagents < 1) {\n\t\tthrow new Error(\"Subagent tool concurrency must be a positive whole number\");\n\t}\n\n\t// The concurrency gate is owned by the caller (e.g. AgentSession) so that it survives\n\t// runtime rebuilds/reloads: the tool definition is recreated on every `/reload`, but the\n\t// gate must keep counting in-flight children launched before the reload. When no gate is\n\t// supplied (external SDK callers, tests) the tool owns a fresh per-instance gate, which\n\t// still keeps separately embedded sessions from coupling through module-global state.\n\tconst concurrencyGate = options?.concurrencyGate ?? createSubagentConcurrencyGate(maxConcurrentSubagents);\n\tconst acquireBackgroundSlot = (signal: AbortSignal): Promise<void> => concurrencyGate.acquire(signal);\n\tconst releaseBackgroundSlot = (): void => concurrencyGate.release();\n\n\t// Discover agents at definition time to build the prompt guidelines.\n\t// This is cheap (reads .md files) and the same call happens on every execute().\n\tconst knownAgents = discoverAgentTypes(cwd);\n\tconst agentListParts: string[] = [];\n\tfor (const [name, config] of knownAgents) {\n\t\tconst defaultTag = name === DEFAULT_AGENT ? \" (default)\" : \"\";\n\t\tconst desc = config.description || name;\n\t\tagentListParts.push(`'${name}'${defaultTag} — ${desc}`);\n\t}\n\tconst builtInAgentsLine = `Built-in agents: ${agentListParts.join(\"; \")}`;\n\n\treturn {\n\t\tname: \"subagent\",\n\t\tlabel: \"subagent\",\n\t\tdescription:\n\t\t\t\"Run focused, independent work in a child agent when the task matches that agent's defined role \" +\n\t\t\t\"(Explore for concrete evidence gathering, Sandbox for isolated /tmp-only analysis). \" +\n\t\t\t`Supports \\`task\\` for a single task, \\`tasks\\` for parallel execution in one call (up to 8, max ${maxConcurrentSubagents} concurrent), ` +\n\t\t\t\"and `chain` for a sequential pipeline with {previous} substitution. \" +\n\t\t\t\"All subagents run in background — returns immediately, notifies on completion.\",\n\t\tpromptSnippet: \"Run role-matched work in independent child agents\",\n\t\tpromptGuidelines: [\n\t\t\t\"`subagent` can be used for focused, independent work that matches a child agent's defined role; delegation is optional, not an unconditional default\",\n\t\t\t\"When `agent` is omitted, the default is `Explore`. Default Explore is for concrete, bounded evidence gathering: locating files, symbols, or documentation; enumerating call sites; quoting exact snippets; and tracing an explicit data flow\",\n\t\t\t\"Do not ask default Explore to diagnose root causes, interpret ambiguous requirements, make architecture or design decisions, recommend an implementation, or produce an implementation plan. The primary agent must synthesize Explore evidence and own those conclusions\",\n\t\t\t\"Good default Explore tasks: find every file that renders a named component; list tests for a specific behavior; quote code that limits a collection; locate documented examples; enumerate call sites. Bad default Explore tasks: investigate a root cause; decide ambiguous behavior; recommend an implementation; design an architecture or refactor; produce an implementation plan\",\n\t\t\t\"Parallel and chain modes do not make a role-inappropriate task suitable for default Explore. Specialized agents may perform the broader work described by their own definitions\",\n\t\t\t\"Available agent types can be discovered from ~/.dreb/agents/ and .dreb/agents/ markdown files\",\n\t\t\tbuiltInAgentsLine,\n\t\t\t'Use the `tasks` array to run multiple independent, role-matched tasks in a single `subagent` call (parallel mode), not separate calls. Typical mach6-review batch: `{ \"tasks\": [{ \"agent\": \"code-reviewer\", \"task\": \"Review code changes\" }, { \"agent\": \"error-auditor\", \"task\": \"Audit runtime failures\" }, { \"agent\": \"test-reviewer\", \"task\": \"Review test coverage\" }, { \"agent\": \"completeness-checker\", \"task\": \"Check issue completeness\" }] }`',\n\t\t\t\"Use chain mode for role-matched steps when each step depends on the previous step's output (reference with {previous})\",\n\t\t\t\"All subagents run in background — the tool returns immediately and you are notified when each agent completes.\",\n\t\t\t\"Subagents have their own context window — provide enough context in the task prompt\",\n\t\t\t\"Each agent notifies independently when done — completion messages include a list of any still-running agents. If you need their results before proceeding, end your current turn with no tool calls (as if you were asking the user a question and waiting for their reply). This emits `agent_end` and lets the framework deliver the completion as a new message that resumes your turn automatically. Do not call `sleep` or any other waiting action, and do not launch filler work.\",\n\t\t\t\"Agent definitions specify a `model` field with a provider fallback list (comma-separated or YAML list). The spawner tries each in order and uses the first one that resolves for the current provider. This makes agents portable across providers.\",\n\t\t\t\"Per-invocation `model` overrides take precedence but **discard the entire fallback list** — if the single override model isn't available on the current provider, the agent fails. Only override when you have a specific reason (e.g. escalating to a stronger tier for a complex task).\",\n\t\t\t\"Optional `thinking` overrides accept off/minimal/low/medium/high/xhigh/max. Per-task values override a top-level value; unsupported levels fail before spawn. Omit thinking to preserve the child's configured default.\",\n\t\t\t\"**Model routing** — choose an agent by role fit first. Agent definitions already specify the normal model tier for that role; override the model only when the assigned task genuinely requires a different capability tier.\",\n\t\t\t\"**Model identity** — Your current model is stated in the system prompt as `You are running on: provider/id`. Use this for explicit routing decisions — e.g. delegate vision tasks if you're on a text-only model, or use a differently-architected model as a critic for tasks where diverse model perspectives improve reliability.\",\n\t\t],\n\t\tparameters: subagentSchema,\n\n\t\tasync execute(_toolCallId, params: SubagentToolInput, _signal, _onUpdate) {\n\t\t\tconst agents = discoverAgentTypes(cwd);\n\n\t\t\t// Determine mode\n\t\t\tconst modeCount = (params.task ? 1 : 0) + (params.tasks ? 1 : 0) + (params.chain ? 1 : 0);\n\t\t\tif (modeCount === 0) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{ type: \"text\", text: \"Error: provide one of `task` (single), `tasks` (parallel), or `chain`.\" },\n\t\t\t\t\t],\n\t\t\t\t\tdetails: undefined,\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (modeCount > 1) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: \"Error: modes are mutually exclusive — provide only one of `task`, `tasks`, or `chain`.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tdetails: undefined,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// All subagents run in background mode — return immediately, notify on completion\n\t\t\t{\n\t\t\t\tif (!onBackgroundComplete) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: \"Subagent execution requires background support, which is not available in this session.\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tdetails: undefined,\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\t/**\n\t\t\t\t * Shared lifecycle for all background launches: generates agent ID,\n\t\t\t\t * sets up registry/abort/notification, gates on the concurrency\n\t\t\t\t * semaphore, and handles errors. The caller provides the actual\n\t\t\t\t * work via `runFn(signal, onChildEvent, onArbitrationRecord)` which must\n\t\t\t\t * return a SubagentResult. Child events are relayed live; arbitration\n\t\t\t\t * records update the registry before being persisted/emitted.\n\t\t\t\t */\n\t\t\t\tconst launchBackgroundLifecycle = (\n\t\t\t\t\tagentName: string,\n\t\t\t\t\ttaskSummary: string,\n\t\t\t\t\tsessionDir: string,\n\t\t\t\t\tagentCwd: string,\n\t\t\t\t\trunFn: (\n\t\t\t\t\t\tsignal: AbortSignal,\n\t\t\t\t\t\tonChildEvent: ((event: Record<string, unknown>) => void) | undefined,\n\t\t\t\t\t\tonArbitrationRecord: (record: DispatchArbitrationRecord) => void,\n\t\t\t\t\t\tonControlAvailable: (client: RpcClient | undefined) => void,\n\t\t\t\t\t) => Promise<SubagentResult>,\n\t\t\t\t): string => {\n\t\t\t\t\tconst agentId = generateAgentId();\n\t\t\t\t\tconst bgAbort = new AbortController();\n\t\t\t\t\tbackgroundAgentRegistry.set(agentId, {\n\t\t\t\t\t\tagentId,\n\t\t\t\t\t\tagentType: agentName,\n\t\t\t\t\t\ttaskSummary,\n\t\t\t\t\t\tstartedAt: Date.now(),\n\t\t\t\t\t\tstatus: \"running\",\n\t\t\t\t\t\tsessionDir,\n\t\t\t\t\t\tcwd: agentCwd,\n\t\t\t\t\t\tparentSessionFile: getParentSessionFile(),\n\t\t\t\t\t});\n\t\t\t\t\tbackgroundAbortControllers.set(agentId, bgAbort);\n\t\t\t\t\tonBackgroundStart?.(agentId, agentName, taskSummary, sessionDir);\n\n\t\t\t\t\t// Relay child JSONL events tagged with this agent's ID. Guarded so a\n\t\t\t\t\t// throwing relay listener can never kill the stdout reader.\n\t\t\t\t\tconst onChildEvent = onBackgroundEvent\n\t\t\t\t\t\t? (event: Record<string, unknown>) => {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tonBackgroundEvent(agentId, event);\n\t\t\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\t\t\tlog.warn(\n\t\t\t\t\t\t\t\t\t\t`[subagent] onBackgroundEvent threw for agent ${agentId}: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: undefined;\n\n\t\t\t\t\tconst onArbitrationRecord = (record: DispatchArbitrationRecord) => {\n\t\t\t\t\t\tconst entry = backgroundAgentRegistry.get(agentId);\n\t\t\t\t\t\tif (entry) {\n\t\t\t\t\t\t\tentry.arbitrations ??= [];\n\t\t\t\t\t\t\tentry.arbitrations.push(record);\n\t\t\t\t\t\t\tif (record.status === \"success\" && record.final) entry.agentType = record.final.agent;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tonArbitration?.({ type: \"subagent_arbitration\", agentId, ...record });\n\t\t\t\t\t};\n\n\t\t\t\t\tconst bgSignal = bgAbort.signal;\n\t\t\t\t\tconst onControlAvailable = (client: RpcClient | undefined) => {\n\t\t\t\t\t\tif (client) backgroundControlClients.set(agentId, client);\n\t\t\t\t\t\telse backgroundControlClients.delete(agentId);\n\t\t\t\t\t};\n\n\t\t\t\t\tconst safeNotify = (result: SubagentResult) => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tonBackgroundComplete(agentId, result, bgSignal.aborted);\n\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\tlog.warn(\n\t\t\t\t\t\t\t\t`[subagent] onBackgroundComplete threw for agent ${agentId}: ${err instanceof Error ? err.message : String(err)}. Background result lost.`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\n\t\t\t\t\tconst run = async () => {\n\t\t\t\t\t\t// A stop while queued for a slot settles immediately (the gate rejects\n\t\t\t\t\t\t// without taking a slot), so only release a slot this run acquired.\n\t\t\t\t\t\tlet slotAcquired = false;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tawait acquireBackgroundSlot(bgSignal);\n\t\t\t\t\t\t\tslotAcquired = true;\n\t\t\t\t\t\t\tconst result = await runFn(bgSignal, onChildEvent, onArbitrationRecord, onControlAvailable);\n\t\t\t\t\t\t\tconst entry = backgroundAgentRegistry.get(agentId);\n\t\t\t\t\t\t\tif (entry && !bgSignal.aborted) entry.status = result.exitCode === 0 ? \"completed\" : \"failed\";\n\t\t\t\t\t\t\tif (entry && result.sessionFile) entry.sessionFile = result.sessionFile;\n\t\t\t\t\t\t\tbackgroundAbortControllers.delete(agentId);\n\t\t\t\t\t\t\tsafeNotify(result);\n\t\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\t\tconst entry = backgroundAgentRegistry.get(agentId);\n\t\t\t\t\t\t\tif (entry && !bgSignal.aborted) entry.status = \"failed\";\n\t\t\t\t\t\t\tbackgroundAbortControllers.delete(agentId);\n\t\t\t\t\t\t\tsafeNotify({\n\t\t\t\t\t\t\t\tagent: agentName,\n\t\t\t\t\t\t\t\ttask: taskSummary,\n\t\t\t\t\t\t\t\texitCode: 1,\n\t\t\t\t\t\t\t\toutput: \"\",\n\t\t\t\t\t\t\t\tstderr: \"\",\n\t\t\t\t\t\t\t\terrorMessage: err instanceof Error ? err.message : String(err),\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\tbackgroundControlClients.delete(agentId);\n\t\t\t\t\t\t\tif (slotAcquired) releaseBackgroundSlot();\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\t\t\t\t\trun().catch((err) => {\n\t\t\t\t\t\tlog.warn(\n\t\t\t\t\t\t\t`[subagent] Unhandled background error (${agentId}): ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst entry = backgroundAgentRegistry.get(agentId);\n\t\t\t\t\t\tif (entry && entry.status === \"running\") entry.status = \"failed\";\n\t\t\t\t\t\tbackgroundAbortControllers.delete(agentId);\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tonBackgroundComplete(\n\t\t\t\t\t\t\t\tagentId,\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tagent: agentName,\n\t\t\t\t\t\t\t\t\ttask: taskSummary,\n\t\t\t\t\t\t\t\t\texitCode: 1,\n\t\t\t\t\t\t\t\t\toutput: \"\",\n\t\t\t\t\t\t\t\t\tstderr: \"\",\n\t\t\t\t\t\t\t\t\terrorMessage: `Internal error: ${err instanceof Error ? err.message : String(err)}`,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tbgSignal.aborted,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t} catch (notifyErr) {\n\t\t\t\t\t\t\tlog.error(\n\t\t\t\t\t\t\t\t`[subagent] CRITICAL: Last-resort notification failed for ${agentId}: ${notifyErr instanceof Error ? notifyErr.message : String(notifyErr)}`,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\n\t\t\t\t\treturn agentId;\n\t\t\t\t};\n\n\t\t\t\t// Helper to launch a single background task\n\t\t\t\tconst launchBackgroundTask = (\n\t\t\t\t\tagentName: string,\n\t\t\t\t\ttask: string,\n\t\t\t\t\ttaskLabel: string,\n\t\t\t\t\ttaskCwd?: string,\n\t\t\t\t\tmodelOverride?: string,\n\t\t\t\t\tthinkingOverride?: ThinkingLevel,\n\t\t\t\t) => {\n\t\t\t\t\tconst resolvedCwd = taskCwd ?? cwd;\n\t\t\t\t\t// Each background agent gets its own session subdirectory\n\t\t\t\t\tconst sessionId = generateAgentId();\n\t\t\t\t\tconst sessionDir = join(subagentSessionsBase, sessionId);\n\t\t\t\t\tconst agentModels = getAgentModelsForAgent?.(agentName || DEFAULT_AGENT);\n\t\t\t\t\treturn launchBackgroundLifecycle(\n\t\t\t\t\t\tagentName,\n\t\t\t\t\t\ttaskLabel,\n\t\t\t\t\t\tsessionDir,\n\t\t\t\t\t\tresolvedCwd,\n\t\t\t\t\t\t(signal, onChildEvent, onArbitrationRecord, onControlAvailable) =>\n\t\t\t\t\t\t\texecuteSingle(\n\t\t\t\t\t\t\t\tagents,\n\t\t\t\t\t\t\t\tagentName === DEFAULT_AGENT ? undefined : agentName,\n\t\t\t\t\t\t\t\ttask,\n\t\t\t\t\t\t\t\tresolvedCwd,\n\t\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t\t\tundefined,\n\t\t\t\t\t\t\t\tmodelOverride,\n\t\t\t\t\t\t\t\tgetParentProvider(),\n\t\t\t\t\t\t\t\tmodelRegistry,\n\t\t\t\t\t\t\t\tsessionDir,\n\t\t\t\t\t\t\t\tgetParentModel(),\n\t\t\t\t\t\t\t\tagentModels,\n\t\t\t\t\t\t\t\tgetParentSessionFile(),\n\t\t\t\t\t\t\t\tonChildEvent,\n\t\t\t\t\t\t\t\tthinkingOverride,\n\t\t\t\t\t\t\t\tarbitrate\n\t\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\t\tarbitrate,\n\t\t\t\t\t\t\t\t\t\t\tonRecord: onArbitrationRecord,\n\t\t\t\t\t\t\t\t\t\t\tdefaultThinkingLevel: getDefaultThinkingLevel?.(),\n\t\t\t\t\t\t\t\t\t\t\tgetAgentModelsForAgent,\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t\t\t\tonControlAvailable,\n\t\t\t\t\t\t\t\tgetParentSessionId(),\n\t\t\t\t\t\t\t\tgetSingleModelMode(),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t};\n\n\t\t\t\tif (params.task) {\n\t\t\t\t\t// Single background task\n\t\t\t\t\tconst agentName = params.agent || DEFAULT_AGENT;\n\t\t\t\t\tconst agentId = launchBackgroundTask(\n\t\t\t\t\t\tagentName,\n\t\t\t\t\t\tparams.task,\n\t\t\t\t\t\t`${agentName} task`,\n\t\t\t\t\t\tundefined,\n\t\t\t\t\t\tparams.model,\n\t\t\t\t\t\tparams.thinking,\n\t\t\t\t\t);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: `Background agent ${agentId} started (${agentName}). You will be notified when it completes.`,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tdetails: { mode: \"single\", agentCount: 1 } as SubagentToolDetails,\n\t\t\t\t\t\tendTurn: true,\n\t\t\t\t\t};\n\t\t\t\t} else if (params.tasks) {\n\t\t\t\t\t// Parallel background tasks — each gets its own agent ID and notifies independently\n\t\t\t\t\tconst launched: Array<{ id: string; agentName: string; taskText: string }> = [];\n\t\t\t\t\tconst skipped: Array<{ taskText: string; error: string }> = [];\n\t\t\t\t\tfor (let i = 0; i < params.tasks.length; i++) {\n\t\t\t\t\t\tconst item = params.tasks[i];\n\t\t\t\t\t\tconst agentName = item.agent || params.agent || DEFAULT_AGENT;\n\t\t\t\t\t\tconst cwdResult = clampCwd(cwd, item.cwd);\n\t\t\t\t\t\tif (!cwdResult.ok) {\n\t\t\t\t\t\t\tskipped.push({ taskText: item.task, error: cwdResult.error });\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst agentId = launchBackgroundTask(\n\t\t\t\t\t\t\tagentName,\n\t\t\t\t\t\t\titem.task,\n\t\t\t\t\t\t\t`${agentName} task ${i + 1}/${params.tasks.length}`,\n\t\t\t\t\t\t\tcwdResult.cwd,\n\t\t\t\t\t\t\titem.model || params.model,\n\t\t\t\t\t\t\tresolveSubagentThinkingOverride(item.thinking, params.thinking),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tlaunched.push({ id: agentId, agentName, taskText: item.task });\n\t\t\t\t\t}\n\t\t\t\t\tconst listing = launched\n\t\t\t\t\t\t.map(({ id, agentName, taskText }) => ` ${id} (${agentName}): ${taskText.slice(0, 80)}`)\n\t\t\t\t\t\t.join(\"\\n\");\n\t\t\t\t\tconst skippedListing = skipped\n\t\t\t\t\t\t.map(({ taskText, error }) => ` SKIPPED: ${taskText.slice(0, 60)} — ${error}`)\n\t\t\t\t\t\t.join(\"\\n\");\n\t\t\t\t\tconst parts = [`${launched.length} background agents started:\\n${listing}`];\n\t\t\t\t\tif (skipped.length > 0) {\n\t\t\t\t\t\tparts.push(`\\n${skipped.length} task(s) failed to launch:\\n${skippedListing}`);\n\t\t\t\t\t}\n\t\t\t\t\tif (launched.length > 0) {\n\t\t\t\t\t\tparts.push(\"\\nEach will notify independently when complete.\");\n\t\t\t\t\t} else {\n\t\t\t\t\t\tparts.push(\"\\nNo agents were launched.\");\n\t\t\t\t\t}\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: parts.join(\"\\n\"),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tdetails: { mode: \"parallel\", agentCount: launched.length } as SubagentToolDetails,\n\t\t\t\t\t\tendTurn: launched.length > 0,\n\t\t\t\t\t};\n\t\t\t\t} else {\n\t\t\t\t\t// Chain mode — sequential, stays as one agent since steps depend on each other\n\t\t\t\t\tconst agentName = params.agent || params.chain![0].agent || DEFAULT_AGENT;\n\t\t\t\t\tconst taskSummary = `${params.chain!.length}-step chain`;\n\t\t\t\t\tconst chainSteps = params.chain!;\n\n\t\t\t\t\tconst chainSessionDir = join(subagentSessionsBase, `chain-${generateAgentId()}`);\n\t\t\t\t\tconst agentId = launchBackgroundLifecycle(\n\t\t\t\t\t\tagentName,\n\t\t\t\t\t\ttaskSummary,\n\t\t\t\t\t\tchainSessionDir,\n\t\t\t\t\t\tcwd,\n\t\t\t\t\t\tasync (signal, onChildEvent, onArbitrationRecord, onControlAvailable) => {\n\t\t\t\t\t\t\tconst results = await executeChain(\n\t\t\t\t\t\t\t\tagents,\n\t\t\t\t\t\t\t\tchainSteps,\n\t\t\t\t\t\t\t\tcwd,\n\t\t\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t\t\tundefined,\n\t\t\t\t\t\t\t\tgetParentProvider(),\n\t\t\t\t\t\t\t\tmodelRegistry,\n\t\t\t\t\t\t\t\tchainSessionDir,\n\t\t\t\t\t\t\t\tparams.agent,\n\t\t\t\t\t\t\t\tparams.model,\n\t\t\t\t\t\t\t\tparams.thinking,\n\t\t\t\t\t\t\t\tgetParentModel(),\n\t\t\t\t\t\t\t\tgetAgentModelsForAgent,\n\t\t\t\t\t\t\t\tgetParentSessionFile(),\n\t\t\t\t\t\t\t\tonChildEvent,\n\t\t\t\t\t\t\t\tarbitrate\n\t\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\t\tarbitrate,\n\t\t\t\t\t\t\t\t\t\t\tonRecord: onArbitrationRecord,\n\t\t\t\t\t\t\t\t\t\t\tdefaultThinkingLevel: getDefaultThinkingLevel?.(),\n\t\t\t\t\t\t\t\t\t\t\tgetAgentModelsForAgent,\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t\t\t\tonControlAvailable,\n\t\t\t\t\t\t\t\tgetParentSessionId(),\n\t\t\t\t\t\t\t\tgetSingleModelMode,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t// A user stop ends the chain at its current (last) step, so only that step's\n\t\t\t\t\t\t\t// output can be cut short.\n\t\t\t\t\t\t\tconst stoppedAtLastStep = signal.aborted;\n\t\t\t\t\t\t\tconst resultText = results\n\t\t\t\t\t\t\t\t.map(\n\t\t\t\t\t\t\t\t\t(r, i) =>\n\t\t\t\t\t\t\t\t\t\t`### Step ${i + 1}\\n${formatSingleResult(r, stoppedAtLastStep && i === results.length - 1)}`,\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t.join(\"\\n\\n---\\n\\n\");\n\t\t\t\t\t\t\tconst failed = results.filter((r) => r.exitCode !== 0);\n\t\t\t\t\t\t\t// Per-step session logs are already embedded in resultText via formatSingleResult\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tagent: agentName,\n\t\t\t\t\t\t\t\ttask: taskSummary,\n\t\t\t\t\t\t\t\tsteps: results.map((result, index) => ({\n\t\t\t\t\t\t\t\t\tstep: index + 1,\n\t\t\t\t\t\t\t\t\tagent: result.agent,\n\t\t\t\t\t\t\t\t\tsuccess: result.exitCode === 0,\n\t\t\t\t\t\t\t\t\tmodel: result.model,\n\t\t\t\t\t\t\t\t\tthinking: result.thinking,\n\t\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t\t\texitCode: failed.length > 0 ? 1 : 0,\n\t\t\t\t\t\t\t\toutput: resultText,\n\t\t\t\t\t\t\t\tstderr: \"\",\n\t\t\t\t\t\t\t\terrorMessage:\n\t\t\t\t\t\t\t\t\tfailed.length > 0\n\t\t\t\t\t\t\t\t\t\t? `Chain stopped at step ${results.length} of ${chainSteps.length}: ${results[results.length - 1]?.errorMessage}`\n\t\t\t\t\t\t\t\t\t\t: null,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t},\n\t\t\t\t\t);\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\ttext: `Background chain ${agentId} started (${taskSummary}). You will be notified when it completes.`,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t],\n\t\t\t\t\t\tdetails: { mode: \"chain\", agentCount: chainSteps.length } as SubagentToolDetails,\n\t\t\t\t\t\tendTurn: true,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\n\t\trenderCall(args, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0, undefined, true);\n\t\t\ttext.setText(formatSubagentCall(args, theme, context.argsComplete));\n\t\t\treturn text;\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\tconst text = (context.lastComponent as Text | undefined) ?? new Text(\"\", 0, 0, undefined, true);\n\t\t\ttext.setText(formatSubagentResult(result as any, options, theme, context.showImages));\n\t\t\treturn text;\n\t\t},\n\t};\n}\n\nexport function createSubagentTool(cwd: string, options?: SubagentToolOptions): AgentTool<typeof subagentSchema> {\n\treturn wrapToolDefinition(createSubagentToolDefinition(cwd, options));\n}\n\nexport const subagentToolDefinition = createSubagentToolDefinition(process.cwd());\nexport const subagentTool = createSubagentTool(process.cwd());\n"]}