@khalilgharbaoui/opencode-claude-code-plugin 0.15.4 → 0.17.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.
- package/README.md +48 -4
- package/dist/index.d.ts +32 -1
- package/dist/index.js +621 -169
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/claude-code-language-model.ts","../src/logger.ts","../src/todo-ledger.ts","../src/tool-mapping.ts","../src/cli-version.ts","../src/session-manager.ts","../src/proxy-broker.ts","../src/proxy-mcp.ts","../src/tmp.ts","../src/plan-mode-question.ts","../src/compression-store.ts","../src/side-question.ts","../src/btw-command.ts","../src/message-builder.ts","../src/agent-models.ts","../src/models.ts","../src/mcp-bridge.ts","../src/runtime-status.ts","../src/claude-session-wrapper.ts","../src/claude-session-bun.ts","../src/accounts.ts","../src/cleanup-stale.ts","../src/startup-diagnostics.ts","../src/index.ts"],"sourcesContent":["import type {\n LanguageModelV3,\n LanguageModelV3CallOptions,\n LanguageModelV3Content,\n LanguageModelV3FinishReason,\n LanguageModelV3StreamPart,\n LanguageModelV3Usage,\n SharedV3Warning,\n} from \"@ai-sdk/provider\"\nimport { generateId } from \"@ai-sdk/provider-utils\"\nimport type {\n ClaudeCodeConfig,\n ControlRequestBehavior,\n ClaudeStreamMessage,\n ReasoningEffort,\n} from \"./types.js\"\nimport { mapTool, isWebSearchTool, isWebSearchHandledByCli } from \"./tool-mapping.js\"\nimport { applyTaskCreateToolResult } from \"./todo-ledger.js\"\nimport { getClaudeUserMessage } from \"./message-builder.js\"\nimport { resolveAgentEffort, resolveAgentModel } from \"./agent-models.js\"\nimport { parseSideQuestion, requestSideQuestion, collectSideQuestionHistory, SIDE_QUESTION_USAGE, type SideQuestionResult } from \"./side-question.js\"\nimport { BTW_NO_SESSION_MESSAGE, registerAsideSink, takeSideQuestionAnswer } from \"./btw-command.js\"\nimport { parseModelId } from \"./models.js\"\nimport {\n QUESTION_TOOL_NAME,\n consumeExitPlanModeQuestionResult,\n createExitPlanModeQuestionCall,\n isPlanModeQuestionActive,\n} from \"./plan-mode-question.js\"\nimport { bridgeOpencodeMcp, type RuntimeMcpStatus } from \"./mcp-bridge.js\"\nimport {\n getRuntimeMcpStatus,\n fetchOpencodeToolList,\n resolveSpawnCwd,\n} from \"./runtime-status.js\"\nimport {\n getActiveProcess,\n setActiveProcess,\n spawnClaudeProcess,\n buildCliArgs,\n setClaudeSessionId,\n getClaudeSessionId,\n deleteClaudeSessionId,\n deleteActiveProcess,\n deleteActiveProcessAndWait,\n respawnActiveProcess,\n takeUnattendedLines,\n claudeSpawnEnv,\n isClaudeThinkingDisabled,\n sessionKey,\n effortSessionKey,\n invalidateOtherEffortSessions,\n} from \"./session-manager.js\"\nimport { spawnInteractiveProcess } from \"./claude-session-wrapper.js\"\nimport {\n clearCompression,\n consumeCompressionRestart,\n getCompressionSummary,\n storeCompressionSummary,\n} from \"./compression-store.js\"\nimport { log } from \"./logger.js\"\nimport { detectCliVersion } from \"./cli-version.js\"\nimport {\n createProxyMcpServer,\n resolveDisallowedTools,\n DEFAULT_PROXY_TOOLS,\n overlayTaskProxyDescription,\n overlayQuestionProxyDescription,\n filterQuestionProxyByOpencodeSupport,\n PROXY_TOOL_PREFIX,\n type ProxyMcpServer,\n type ProxyToolCall,\n type ProxyToolDef,\n type ProxyToolInterceptor,\n type ProxyToolResult,\n} from \"./proxy-mcp.js\"\nimport {\n getPendingProxyCalls,\n isPendingProxyCallChannelClosed,\n markPendingProxyCallEmitted,\n onPendingProxyCall,\n queuePendingProxyCall,\n rejectAllPendingProxyCallsForSession,\n rejectPendingProxyCallById,\n resolvePendingProxyCallById,\n type PendingProxyCall,\n} from \"./proxy-broker.js\"\nimport { readFileSync, writeFileSync } from \"node:fs\"\nimport { unlink } from \"node:fs/promises\"\nimport { homedir, tmpdir } from \"node:os\"\nimport { randomUUID } from \"node:crypto\"\nimport { dirname, join } from \"node:path\"\n\n/**\n * Default model used for opencode `/compact`. Haiku 4.5 is fast\n * (~150 tok/s), has a hard 8k output cap that bounds latency, and is a\n * strong structured summarizer. Override per-project via the\n * `compactionModel` provider setting in opencode.json / opencode.jsonc,\n * or per-run via the `CLAUDE_CODE_COMPACTION_MODEL` env var (env wins).\n */\nexport const DEFAULT_COMPACTION_MODEL = \"claude-haiku-4-5\"\n\n/**\n * Pick the model used to handle /compact. Precedence:\n * 1. `CLAUDE_CODE_COMPACTION_MODEL` env var (per-process override)\n * 2. `configured` argument (the `compactionModel` provider setting)\n * 3. `DEFAULT_COMPACTION_MODEL`\n *\n * Exported as a free function so it can be unit-tested without\n * instantiating the language model class.\n */\nexport function resolveCompactionModel(configured?: string): string {\n const env = process.env.CLAUDE_CODE_COMPACTION_MODEL?.trim()\n if (env) return env\n const trimmed = configured?.trim()\n if (trimmed) return trimmed\n return DEFAULT_COMPACTION_MODEL\n}\n\n/**\n * Resolve the session affinity token for a given LLM call. The affinity\n * token is part of the session key in session-manager so two different\n * opencode sessions sharing the same cwd+model still get separate Claude\n * CLI processes.\n *\n * Priority:\n * 1. `x-session-affinity` request header (primary — opencode sets it for\n * third-party providers in packages/opencode/src/session/llm.ts).\n * 2. `opencodeSessionID` inside `providerOptions` (injected by the\n * `chat.params` hook in index.ts). Covers cases where the header is\n * absent: provider switch mid-session, title synthesis paths, older\n * opencode versions. opencode wraps `output.options` under the\n * providerID before passing it to the language model, so we look up\n * both the configured provider key and the canonical `\"claude-code\"`.\n * 3. `\"default\"` — safe fallback when neither source is available.\n *\n * Exported as a free function so it can be unit-tested without\n * instantiating the language model class.\n */\nexport function resolveSessionAffinity(\n headers: Record<string, string | undefined> | undefined,\n providerOptions: Record<string, unknown> | undefined,\n providerKey: string,\n): string {\n if (headers) {\n for (const key of Object.keys(headers)) {\n if (key.toLowerCase() === \"x-session-affinity\") {\n const v = headers[key]\n if (typeof v === \"string\" && v.length > 0) return v\n }\n }\n }\n if (providerOptions) {\n const bag =\n (providerOptions as any)[providerKey] ??\n (providerOptions as any)[\"claude-code\"]\n const sid = bag?.opencodeSessionID\n if (typeof sid === \"string\" && sid.length > 0) return sid\n }\n return \"default\"\n}\n\n/**\n * Stream delta types we handle explicitly. `signature_delta` is listed as\n * known-and-silent: it carries encrypted thinking-block signatures that\n * are opaque to clients (the server uses them to reconstitute thinking\n * across turns), so there's nothing for us to do but ignore it.\n */\nconst KNOWN_DELTA_TYPES = new Set([\n \"thinking_delta\",\n \"text_delta\",\n \"input_json_delta\",\n \"signature_delta\",\n])\n\n/**\n * True if the prompt has any user-side content after the last assistant\n * message (text, tool_result, or any user role entry). False when the\n * prompt ends with an assistant message and there is nothing for Claude\n * to respond to — opencode sometimes iterates the agent loop one more\n * time after a turn naturally completed; without short-circuiting we'd\n * spawn Claude CLI on an empty turn and the model would reply with a\n * stub like \"Did you mean to send a message?\".\n */\nexport function hasNewUserContent(\n prompt: LanguageModelV3CallOptions[\"prompt\"],\n): boolean {\n for (let i = prompt.length - 1; i >= 0; i--) {\n const msg = prompt[i]\n if (msg.role === \"assistant\") return false\n // Tool-result turns from opencode's outer loop arrive in `tool`-role\n // messages (AI SDK V3 shape). Treat any tool-result part as new\n // content so the short-circuit doesn't drop turns where opencode is\n // delivering the result for a still-pending proxy MCP call — letting\n // that fire `stop` is what was forcing the user to press \"continue\".\n if (msg.role === \"tool\") {\n const content: any = msg.content\n if (Array.isArray(content)) {\n for (const part of content as any[]) {\n if (part?.type === \"tool-result\") return true\n }\n }\n continue\n }\n if (msg.role !== \"user\") continue\n const content: any = msg.content\n if (typeof content === \"string\") {\n if (content.trim()) return true\n continue\n }\n if (Array.isArray(content)) {\n for (const part of content as any[]) {\n if (part.type === \"text\" && part.text && part.text.trim()) return true\n if (part.type === \"tool-result\") return true\n // Image/file-only user turns count as new input — without this the\n // short-circuit drops them as if the turn were empty.\n if (part.type === \"image\" || part.type === \"file\") return true\n }\n }\n }\n return false\n}\n\nconst AUTO_CONTINUE_MAX_ATTEMPTS = 8\nconst AUTO_CONTINUE_MAX_ELAPSED_MS = 10 * 60 * 1000\nconst AUTO_CONTINUE_NO_PROGRESS_LIMIT = 2\nconst PROXY_RESULT_BOUNDARY_GRACE_MS = 250\n\nconst AUTO_CONTINUE_PROMPT =\n \"Continue the task from where you stopped. Do not summarize; keep working until the requested task is complete, you need clarification, or you hit a real blocker.\"\n\n/** One per-turn snapshot of opencode's live tool registry. */\ninterface LiveToolInfo {\n /** False when nothing answered (no SDK client, fetch failed). */\n resolved: boolean\n taskDescription: string | undefined\n questionDescription: string | undefined\n hasQuestion: boolean\n}\n\ninterface AutoContinueState {\n enabled: boolean | \"smart\" | undefined\n attempts: number\n startedAt: number\n noProgressCount: number\n lastSignature?: string\n aborted?: boolean\n /**\n * Latched true once AskUserQuestion is rendered this turn. Auto-continue\n * must never fire afterwards: the model has handed control to the operator\n * and is waiting for a real reply. Without this, a short trailing text after\n * the question (one that doesn't trip looksLikeQuestion) would let the turn\n * look \"incomplete\", and the auto-continue nudge would make the model\n * proceed on its own — which the operator sees as the question being\n * answered/cancelled without them ever interacting.\n */\n sawAskUserQuestion?: boolean\n}\n\ninterface AutoContinueSnapshot {\n text: string\n /**\n * Text of the most recent assistant text block only. Used for final-answer\n * detection so mid-task narration like \"Implementing now. Updated the\n * search index.\" in an earlier block doesn't trip the keyword regex.\n */\n lastVisibleText: string\n hadReasoning: boolean\n hadToolActivity: boolean\n hadProxyActivity: boolean\n isError?: boolean\n /**\n * Protocol-level stop signal from the Claude API (forwarded by Claude\n * CLI). When present and non-empty, we trust it as authoritative — the\n * model itself signaled why the turn ended (`end_turn`, `max_tokens`,\n * `stop_sequence`, `refusal`, `pause_turn`, `tool_use`, etc.) — and stop\n * without running the keyword regex. The heuristic only runs as a\n * fallback when `stop_reason` is missing (older CLI versions, abrupt\n * termination).\n */\n stopReason?: string | null\n now?: number\n}\n\ninterface AutoContinueDecision {\n continue: boolean\n reason: string\n}\n\nfunction normalizeVisibleText(text: string): string {\n return text.replace(/\\s+/g, \" \").trim()\n}\n\n/** Tool names that mean \"ask the human a question\" (CLI casing variants). */\nexport function isAskUserQuestionTool(name: string | undefined): boolean {\n if (!name) return false\n const n = name.toLowerCase()\n return n === \"askuserquestion\" || n === \"ask_user_question\"\n}\n\n/**\n * Deny message returned to the model when it invokes AskUserQuestion.\n *\n * AskUserQuestion is denied (see controlRequestBehaviorForTool) so the\n * headless CLI cannot self-answer against an empty TTY. The question is\n * already rendered to the operator by formatAskUserQuestion, so this text\n * tells the model to stop and wait — unconditionally. Earlier versions\n * offered an \"if this is non-interactive, proceed with a reasonable guess\"\n * escape hatch, but the model could not reliably tell interactive opencode\n * from a headless run and routinely took it, so questions appeared to be\n * skipped (issue #8). Stopping is the correct default for opencode; a\n * headless run simply ends the turn with the question as its final output.\n */\nconst ASK_USER_QUESTION_DENY_MESSAGE =\n \"Your question and its options have already been presented to the\" +\n \" operator verbatim. This is NOT a cancellation or a refusal — the\" +\n \" operator simply has not answered yet. Stop now: end your turn without\" +\n \" calling any more tools and without answering the question yourself. Do\" +\n \" not say the question was cancelled, skipped, or declined, and do not\" +\n \" guess, assume, or proceed on their behalf. Wait for the operator's\" +\n \" reply, which arrives as the next user message.\"\n\n/** Build the deny message for an auto-denied control request. */\nexport function denyMessageForTool(\n toolName: string | undefined,\n configuredDenyMessage?: string,\n): string {\n if (isAskUserQuestionTool(toolName)) return ASK_USER_QUESTION_DENY_MESSAGE\n return (\n configuredDenyMessage ??\n `Denied by opencode-claude-code policy for tool ${toolName}`\n )\n}\n\n/**\n * Render Claude Code's `AskUserQuestion` tool input as visible markdown.\n *\n * This is the fallback path used when the `Question` proxy is off or the\n * opencode build lacks the `question` registry entry. When the proxy is\n * enabled, `AskUserQuestion` is disabled via `--disallowedTools` and the\n * model calls `mcp__opencode_proxy__question` instead (opencode's native\n * `question` tool renders the TUI form). Here, the question + every\n * option is rendered as readable assistant text and the user answers in\n * the next turn — same approach as the `ExitPlanMode` handling. The\n * previous behavior collapsed the whole payload to a single faint\n * `_Asking: <q>_` line, dropping all options and any question past the\n * first.\n */\nfunction formatAskUserQuestion(input: Record<string, unknown>): string {\n const anyInput = input as any\n const questions: any[] = Array.isArray(anyInput?.questions)\n ? anyInput.questions\n : []\n\n if (questions.length === 0) {\n const single = anyInput?.question ?? anyInput?.text\n const q =\n typeof single === \"string\" && single.trim() ? single.trim() : \"Question?\"\n return `\\n\\n**${q}**\\n\\n_Reply with your answer to continue._\\n\\n`\n }\n\n const out: string[] = [\"\\n\\n\"]\n const multiQ = questions.length > 1\n questions.forEach((q, i) => {\n const text =\n (typeof q?.question === \"string\" && q.question.trim()) ||\n (typeof q?.text === \"string\" && q.text.trim()) ||\n \"Question?\"\n const header =\n typeof q?.header === \"string\" && q.header.trim() ? q.header.trim() : \"\"\n out.push(`**${multiQ ? `${i + 1}. ` : \"\"}${text}**`)\n if (header) out.push(` _(${header})_`)\n out.push(\"\\n\\n\")\n\n const options: any[] = Array.isArray(q?.options) ? q.options : []\n options.forEach((opt, j) => {\n const label =\n (typeof opt?.label === \"string\" && opt.label.trim()) ||\n (typeof opt === \"string\" && opt.trim()) ||\n `Option ${j + 1}`\n const desc =\n typeof opt?.description === \"string\" && opt.description.trim()\n ? ` — ${opt.description.trim()}`\n : \"\"\n out.push(`${j + 1}. **${label}**${desc}\\n`)\n })\n\n out.push(\n q?.multiSelect === true\n ? \"\\n_Select one or more — reply with the numbers or labels._\\n\\n\"\n : \"\\n_Reply with your choice (the number or label)._\\n\\n\",\n )\n })\n return out.join(\"\")\n}\n\nfunction looksLikeQuestion(text: string): boolean {\n const normalized = normalizeVisibleText(text).toLowerCase()\n if (!normalized) return false\n // v0.4.10 tweak 5a: '?' anywhere in the last block, not just trailing.\n // Catches long answers that pose a question mid-text then list options\n // and end with a period. FP risk on inline code (`result?.value`) is\n // accepted — cost is one extra \"continue\" press, in the safe direction.\n if (normalized.includes(\"?\")) return true\n // v0.4.11 additions: ready when you are / standing by / i'll stand by /\n // let me know when. These are awaiting-input idioms with no '?'. The\n // \"standing by\" addition has historical significance — it's the exact\n // stub phrase Claude CLI emits on empty turns that commit 49345e3 was\n // designed to suppress at the message-builder layer. This adds a second\n // line of defense at the model-output layer for cases where the model\n // organically produces the same idiom.\n //\n // v0.4.12 additions: over to you / your turn / all yours / let me know\n // how / i'm here. Defensive coverage of soft-proceed idioms in the\n // model's vocabulary. \"i'm here\" has the highest FP risk (\"I'm here to\n // help with X\" is a conversational opener) but cost of FP is one extra\n // continue press — safe direction.\n return /\\b(please confirm|can you confirm|should i|would you like|do you want|which option|choose|pick one|need your|need you to|what would you like|let me know if|let me know whether|let me know what|let me know when|let me know how|if you'?d like|if you want to|tell me if|tell me which|tell me whether|say (?:go|yes|no)|push back|sign off|sounds? (?:good|right)|your call|your move|your turn|over to you|all yours|up to you|ready to (?:ship|go|proceed|merge)|ready (?:when|whenever|once|if) you|standing by|i'?ll stand ?by|i'?m here|happy to (?:ship|go|proceed|merge))\\b/.test(normalized)\n}\n\nfunction looksLikeBlocker(text: string): boolean {\n const normalized = normalizeVisibleText(text).toLowerCase()\n if (!normalized) return false\n // v0.4.10 tweak 3: 'needs your' / 'needs you to' / 'action required'\n // are intent-equivalent to 'requires your' but use the verb-with-s form.\n return /\\b(blocked|blocker|cannot proceed|can't proceed|unable to proceed|need clarification|need more information|permission denied|failed and needs|requires your|needs your|needs you to|action required|manual step|required from you)\\b/.test(normalized)\n}\n\nfunction looksLikeFinalAnswer(text: string): boolean {\n const normalized = normalizeVisibleText(text).toLowerCase()\n if (looksLikeQuestion(normalized) || looksLikeBlocker(normalized)) return false\n // v0.4.15: strong-completion phrases bypass the 30-char length floor.\n // These are unambiguous end-of-turn signals at any text length — even\n // a short standalone \"We're done.\" should stop.\n if (/\\b(we'?re done|we are done|all done|all set)\\b/.test(normalized)) {\n return true\n }\n // v0.4.10 tweak 4: floor lowered 40 → 30 chars. Catches short clean\n // completions like \"Task is now completely done. Pushed.\" (36 chars)\n // while keeping a buffer against ambiguous short narration.\n if (normalized.length < 30) return false\n // v0.4.15: keyword list extended with deploy/ship verbs the model\n // routinely uses at turn end (shipped, deployed, merged, tagged, live,\n // pinned). FP risk highest on \"live\" — \"live data\" mid-turn could match\n // — but cost of FP is one extra continue press, safe direction.\n return /\\b(done|completed|fixed|implemented|verified|published|released|sent|delivered|updated|shipped|deployed|merged|tagged|live|pinned)\\b/.test(normalized) ||\n // v0.4.15: also accept present-tense \"tests pass\" / \"checks pass\".\n // Real fire 03:31 ended in \"78/78 tests pass\" — past-tense-only regex\n // missed it.\n /\\b(checks?|tests?) (?:pass|passes|passed)\\b/.test(normalized) ||\n /\\b(summary|what changed|verification)\\b/.test(normalized)\n}\n\nfunction continuationSignature(snapshot: AutoContinueSnapshot): string {\n const text = normalizeVisibleText(snapshot.text).slice(-500)\n return JSON.stringify({\n text,\n reasoning: snapshot.hadReasoning,\n tools: snapshot.hadToolActivity,\n proxy: snapshot.hadProxyActivity,\n })\n}\n\nexport function shouldAutoContinueIncompleteTurn(\n state: AutoContinueState,\n snapshot: AutoContinueSnapshot,\n): AutoContinueDecision {\n if (state.enabled === false) return { continue: false, reason: \"disabled\" }\n if (snapshot.isError) return { continue: false, reason: \"error\" }\n if (state.aborted) return { continue: false, reason: \"aborted\" }\n // Once the model asked the operator a question this turn, never nudge it to\n // continue — it is waiting for a reply, not stalled. Latched so it holds\n // even when the trailing text after the question doesn't read as a question.\n if (state.sawAskUserQuestion) return { continue: false, reason: \"question\" }\n // v0.4.17: trust ANY protocol-level stop_reason as authoritative. If\n // Claude CLI emitted a stop_reason value at all, the model has signaled\n // a stop — honor it without consulting the keyword heuristic. The\n // heuristic only runs as a fallback when stop_reason is missing (older\n // CLI versions / edge cases). Maps snake_case → kebab-case for reason\n // label consistency with other reasons.\n if (snapshot.stopReason) {\n return {\n continue: false,\n reason: snapshot.stopReason.replace(/_/g, \"-\"),\n }\n }\n if (state.attempts >= AUTO_CONTINUE_MAX_ATTEMPTS) {\n return { continue: false, reason: \"max-attempts\" }\n }\n const now = snapshot.now ?? Date.now()\n if (now - state.startedAt > AUTO_CONTINUE_MAX_ELAPSED_MS) {\n return { continue: false, reason: \"max-elapsed\" }\n }\n\n const text = normalizeVisibleText(snapshot.text)\n const lastText = normalizeVisibleText(snapshot.lastVisibleText)\n if (looksLikeQuestion(text)) return { continue: false, reason: \"question\" }\n if (looksLikeBlocker(text)) return { continue: false, reason: \"blocker\" }\n // Final-answer detection runs on the most recent text block only. Earlier\n // blocks may contain mid-task narration that would false-positive the\n // keyword regex; the model's actual \"I'm done\" sentence is in the last\n // block before result/end_turn.\n if (looksLikeFinalAnswer(lastText)) {\n return { continue: false, reason: \"final-answer\" }\n }\n\n const hadActivity =\n snapshot.hadReasoning || snapshot.hadToolActivity || snapshot.hadProxyActivity\n if (!hadActivity) return { continue: false, reason: \"no-activity\" }\n\n const signature = continuationSignature(snapshot)\n const noProgress = signature === state.lastSignature\n if (noProgress && state.noProgressCount + 1 >= AUTO_CONTINUE_NO_PROGRESS_LIMIT) {\n return { continue: false, reason: \"no-progress\" }\n }\n\n if (!text) {\n return { continue: true, reason: \"activity-without-visible-answer\" }\n }\n\n return { continue: true, reason: \"non-final-progress\" }\n}\n\nfunction makeAutoContinueMessage(): string {\n return JSON.stringify({\n type: \"user\",\n message: {\n role: \"user\",\n content: [{ type: \"text\", text: AUTO_CONTINUE_PROMPT }],\n },\n })\n}\n\n/**\n * A proxy result whose HTTP reply channel Claude already abandoned cannot\n * go back as a `tool_result` (the CLI closed that tool_use with a timeout\n * error). Hand it over as a user message that names the call instead.\n */\nexport function makeLateProxyResultMessage(\n entries: Array<{ call: PendingProxyCall; result: ProxyToolResult }>,\n): string {\n const sections = entries.map(({ call, result }) => {\n const failed = result.kind === \"error\" || result.isError === true\n const body = result.kind === \"error\" ? result.message : result.text\n return (\n `Your earlier \\`${call.toolName}\\` tool call (id ${call.toolCallId})` +\n ` has ${failed ? \"failed\" : \"completed\"}, but delivery or continuation was interrupted.` +\n ` Treat the following as its ${failed ? \"error\" : \"result\"} and continue from there;` +\n ` do not re-run it.\\n\\n${body}`\n )\n })\n return JSON.stringify({\n type: \"user\",\n message: {\n role: \"user\",\n content: [{ type: \"text\", text: sections.join(\"\\n\\n---\\n\\n\") }],\n },\n })\n}\n\nfunction readPromptFileIfPresent(path: string): string | undefined {\n try {\n const content = readFileSync(path, \"utf8\").trim()\n return content || undefined\n } catch {\n return undefined\n }\n}\n\nfunction nearestWorkspaceAgentsPrompt(cwd: string): string | undefined {\n let dir = cwd\n while (true) {\n const content = readPromptFileIfPresent(join(dir, \"AGENTS.md\"))\n if (content) return content\n const parent = dirname(dir)\n if (parent === dir) return undefined\n dir = parent\n }\n}\n\nconst AGENTS_MAINTENANCE_HINT = `## Keeping AGENTS.md up to date\n\nWhen you complete a task, phase, or to-do item that is listed in AGENTS.md, update the file\nimmediately after the work is done — mark it ✅, check it off, or remove it. Do this inside\nthe same turn so the next session does not repeat work that is already finished.`\n\nconst MULTI_STEP_TASK_HINT = `## Continuing through multi-step tasks\n\nopencode requires the user to press \"continue\" after each turn ends. When a\ntask has multiple steps, do them all in one turn — chain tool calls rather\nthan pausing for user confirmation between subtasks. End the turn only\nwhen the task is done, you need clarification on intent, or you hit a real\nblocker. The user can interrupt or abort at any time; turn endings should\nmark meaningful checkpoints, not every completed substep.`\n\n/**\n * Appended to the system prompt whenever the `task` proxy tool is\n * enabled. Live sessions (2026-07-04) showed models resolving opencode's\n * \"call the task tool with subagent: X\" mention hint to Claude Code's\n * native TaskCreate: haiku created a todo and narrated a dispatch that\n * never happened; sonnet probed TaskCreate's schema before recovering.\n * The proxy tool can also be deferred behind ToolSearch, in which case\n * \"the task tool\" is invisible while TaskCreate is not. Name the exact\n * tool, the recovery path, and the failure mode.\n */\nexport const SUBAGENT_DISPATCH_HINT = `## opencode subagents\n\nSubagent dispatch in this environment goes through exactly one tool: \\`mcp__opencode_proxy__task\\`.\n\n- When the user mentions \\`@<agent>\\` or an instruction says \"call the task tool with subagent: <name>\", call \\`mcp__opencode_proxy__task\\` with \\`subagent_type: \"<name>\"\\`.\n- If that tool is not in your visible tool list it is deferred — load it with ToolSearch (\\`select:mcp__opencode_proxy__task\\`), then call it.\n- Claude Code's built-in TaskCreate/TaskUpdate/TaskList manage a local todo list. They cannot dispatch subagents; creating a task there runs nothing. Never report a subagent as dispatched unless \\`mcp__opencode_proxy__task\\` returned its result.\n- Do not verify a subagent's existence by searching config files — the tool's description lists the available agent types, and invalid types fail fast with a clear error.`\n\n/**\n * Appended to the system prompt whenever the `question` proxy tool is\n * enabled. Live testing (2026-07-05, haiku) showed the model's reasoning\n * correctly identified `mcp__opencode_proxy__question` as the tool to use,\n * but then emitted a tool call for bare `question` — stripping the MCP\n * prefix. opencode's AI SDK bridge has no bare `question` tool, so the\n * call rendered as `⚙ invalid`. Same near-miss pattern the task proxy\n * hit (TaskCreate vs mcp__opencode_proxy__task); the fix is the same:\n * name the exact tool in the system prompt so the model doesn't\n * abbreviate.\n */\nexport const QUESTION_PROXY_HINT = `## Asking the operator questions\n\nStructured questions in this environment go through exactly one tool: \\`mcp__opencode_proxy__question\\`.\n\n- When you need to ask the operator a question with options, call \\`mcp__opencode_proxy__question\\` with a \\`questions\\` array (each item has \\`question\\`, \\`header\\`, \\`options\\` of \\`{label, description}\\`, and optional \\`multiple\\`).\n- If that tool is not in your visible tool list it is deferred — load it with ToolSearch (\\`select:mcp__opencode_proxy__question\\`), then call it by its FULL name.\n- Do NOT call bare \\`question\\` — that is not a tool. Always use the full \\`mcp__opencode_proxy__question\\` name when invoking it.\n- Claude Code's built-in \\`AskUserQuestion\\` is disabled in this environment; the proxy is the only way to ask structured questions.`\n\n/**\n * Prepended to every appended system prompt so Claude knows which\n * context-management tools exist in the Claude CLI runtime versus a\n * direct API provider. DCP and similar plugins forward compress/distill/\n * prune instructions via system.transform; those reach us through\n * extractSystemMessages, but the tools themselves are not available in\n * the CLI environment. Without this note Claude wastes thinking cycles\n * searching for tools that don't exist.\n */\nconst CLAUDE_CLI_CONTEXT_NOTE = `## Runtime environment: Claude Code CLI\n\nYou are running via the Claude Code CLI (not a direct API call). This affects context management:\n\n- The \\`compress\\` tool is NOT available. Do not attempt to call it.\n- The \\`distill\\`, \\`prune\\`, and \\`extract\\` tools are NOT available.\n- Context window management is handled automatically by Claude CLI's own session history.\n- Ignore any system instructions that tell you to call \\`compress\\` — they are intended for direct API providers, not this environment.\n- DCP context injections (AGENTS.md, dynamic state) arrive via the system prompt and are already applied.`\n\n/**\n * Replaces the note above when `compress` is in the resolved proxy list.\n * The full MCP name is spelled out for the same reason the question proxy\n * hint spells its own out: models strip the prefix and call bare\n * `compress`, which opencode renders as `⚙ invalid`.\n */\nconst CLAUDE_CLI_COMPRESS_NOTE = `## Runtime environment: Claude Code CLI\n\nYou are running via the Claude Code CLI (not a direct API call). This affects context management:\n\n- To compress context, call \\`mcp__opencode_proxy__compress\\` with a \\`summary\\` argument. Use that exact full name.\n- The reset happens at the start of your NEXT turn: this Claude Code session is discarded and a fresh one starts with your summary as its only prior context. Keep working normally after the call.\n- Everything outside the summary is gone after the reset — tool output, files you read, and the earlier conversation are not replayed. Write the summary as the authoritative record.\n- The \\`distill\\`, \\`prune\\`, and \\`extract\\` tools are NOT available.\n- DCP context injections (AGENTS.md, dynamic state) arrive via the system prompt and are already applied.`\n\n/**\n * Extract text content from all `system`-role messages in the prompt.\n * Standard API providers forward these as the `system` parameter; for\n * Claude CLI, the only equivalent path is --append-system-prompt-file.\n * Plugins like opencode-dcp inject AGENTS.md and other context via\n * system-role messages and would otherwise be silently dropped.\n */\nfunction extractSystemMessages(\n prompt: LanguageModelV3CallOptions[\"prompt\"],\n): string[] {\n const out: string[] = []\n for (const msg of prompt) {\n if (msg.role !== \"system\") continue\n if (typeof msg.content === \"string\") {\n if (msg.content.trim()) out.push(msg.content.trim())\n } else if (Array.isArray(msg.content)) {\n for (const part of msg.content as any[]) {\n if (\n part?.type === \"text\" &&\n typeof part.text === \"string\" &&\n part.text.trim()\n ) {\n out.push(part.text.trim())\n }\n }\n }\n }\n return out\n}\n\nexport interface AppendedSystemPromptOptions {\n /** True when `compress` is in the resolved proxy list for this spawn. */\n compressEnabled?: boolean\n /** Summary from a previous `compress` call, if this key has one. */\n compressionSummary?: string\n}\n\nexport function buildAppendedSystemPrompt(\n cwd: string,\n includeMultiStepHint = true,\n extraSystemContent: string[] = [],\n options: AppendedSystemPromptOptions = {},\n): string | undefined {\n const parts: string[] = []\n // First, so it reads as prior context for everything that follows.\n if (options.compressionSummary?.trim()) {\n parts.push(\n `## Summary of earlier work (context was compressed)\\n\\n${options.compressionSummary.trim()}`,\n )\n }\n parts.push(\n options.compressEnabled ? CLAUDE_CLI_COMPRESS_NOTE : CLAUDE_CLI_CONTEXT_NOTE,\n )\n for (const s of extraSystemContent) {\n if (s.trim()) parts.push(s.trim())\n }\n const configRoot =\n process.env.XDG_CONFIG_HOME ?? join(homedir(), \".config\")\n const globalAgents = readPromptFileIfPresent(join(configRoot, \"opencode\", \"AGENTS.md\"))\n const workspaceAgents = nearestWorkspaceAgentsPrompt(cwd)\n\n if (globalAgents) parts.push(globalAgents)\n if (workspaceAgents && workspaceAgents !== globalAgents) parts.push(workspaceAgents)\n if (globalAgents || workspaceAgents) parts.push(AGENTS_MAINTENANCE_HINT)\n if (includeMultiStepHint) parts.push(MULTI_STEP_TASK_HINT)\n\n const content = parts.join(\"\\n\\n\")\n if (!content) return undefined\n\n const path = join(tmpdir(), `opencode-cc-sys-${randomUUID()}.md`)\n try {\n writeFileSync(path, content, \"utf8\")\n return path\n } catch (err) {\n log.warn(\"failed to write system prompt file\", { error: String(err) })\n return undefined\n }\n}\n\n/**\n * Human-readable explanations for the CLI's `fast_mode_disabled_reason` codes,\n * so a downgrade tells the user what to do instead of leaking an enum.\n */\nconst FAST_MODE_REASONS: Record<string, string> = {\n sdk_opt_in_required:\n \"the CLI did not receive the headless opt-in (--settings). This is a plugin bug, please report it\",\n extra_usage_disabled:\n \"your account has usage credits turned off. Run /usage-credits in an interactive `claude` session to enable them\",\n free: \"fast mode requires a paid subscription or purchased credits\",\n preference: \"fast mode is turned off for your organization\",\n model_not_allowed:\n \"this model is not in your organization's allowed models\",\n not_first_party:\n \"fast mode only works against the Anthropic API directly, not Bedrock / Vertex / Foundry\",\n network_error: \"the CLI could not reach Anthropic to check availability\",\n disabled_by_env: \"CLAUDE_CODE_DISABLE_FAST_MODE is set in the environment\",\n pending: \"the CLI is still checking availability\",\n}\n\n/** Reasons already surfaced this process, so a persistent block warns once. */\nconst warnedFastModeReasons = new Set<string>()\n\n/** Test-only. */\nexport function _resetFastModeWarnings(): void {\n warnedFastModeReasons.clear()\n}\n\n/**\n * Report what actually happened to a fast-mode request.\n *\n * Fast mode fails soft: an ineligible account or a rate-limit cooldown drops\n * back to standard speed with no error. That silence is the problem worth\n * solving here: the fast model ids advertise 10x pricing in opencode's picker,\n * so a downgrade the user cannot see means the picker is lying about cost for\n * every subsequent turn.\n *\n * A hard block is therefore a WARN, which this codebase routes to the TUI\n * unconditionally (NOTICE only surfaces in debug mode, which would defeat the\n * purpose). It is deduped per reason per process because the blocking\n * conditions are account-level and would otherwise repeat on every respawn.\n * Cooldown stays quieter: it is transient and clears on its own.\n */\nexport function reportFastModeState(\n msg: ClaudeStreamMessage,\n requested: boolean,\n): void {\n const state = msg.fast_mode_state\n if (!state) return\n\n if (!requested) {\n // Nothing was asked for. Only interesting at debug level.\n log.debug(\"fast mode state\", { state })\n return\n }\n\n if (state === \"on\") {\n log.info(\"fast mode active\", { state })\n return\n }\n\n const reason = msg.fast_mode_disabled_reason\n if (state === \"cooldown\") {\n log.notice(\n \"fast mode is in cooldown after a rate limit; this turn runs at standard speed and is billed at standard Opus rates, not the 10x shown in the model picker.\",\n { state, reason: reason ?? null },\n )\n return\n }\n\n const key = reason ?? \"unknown\"\n const explanation = reason ? FAST_MODE_REASONS[reason] : undefined\n const message = `fast mode was requested but is off${\n explanation ? `: ${explanation}` : reason ? ` (${reason})` : \"\"\n }. Turns run at standard speed and are billed at standard Opus rates, not the 10x shown in the model picker. Switch to the non-fast model id to make the picker's price accurate.`\n\n if (warnedFastModeReasons.has(key)) {\n log.debug(message, { state, reason: reason ?? null })\n return\n }\n warnedFastModeReasons.add(key)\n log.warn(message, { state, reason: reason ?? null })\n}\n\nexport class ClaudeCodeLanguageModel implements LanguageModelV3 {\n readonly specificationVersion = \"v3\"\n readonly modelId: string\n private readonly config: ClaudeCodeConfig\n\n constructor(modelId: string, config: ClaudeCodeConfig) {\n this.modelId = modelId\n this.config = config\n }\n\n readonly supportedUrls: Record<string, RegExp[]> = {}\n\n get provider(): string {\n return this.config.provider\n }\n\n private toUsage(rawUsage?: ClaudeStreamMessage[\"usage\"]): LanguageModelV3Usage {\n // Prefer the last iteration's counters over cumulative totals.\n // CLI usage is the sum across all internal tool-use iterations;\n // using it directly inflates context size and triggers premature compaction.\n const iter = rawUsage?.iterations\n const effective = iter?.length ? iter[iter.length - 1] : rawUsage\n // Claude CLI reports input_tokens as non-cached input only.\n // OpenCode expects total = noCache + cacheRead + cacheWrite.\n const noCache = effective?.input_tokens ?? 0\n const cacheRead = effective?.cache_read_input_tokens ?? 0\n const cacheWrite = effective?.cache_creation_input_tokens ?? 0\n return {\n inputTokens: {\n total: noCache + cacheRead + cacheWrite,\n noCache,\n cacheRead: cacheRead || undefined,\n cacheWrite: cacheWrite || undefined,\n },\n outputTokens: {\n total: effective?.output_tokens,\n text: effective?.output_tokens,\n reasoning: undefined,\n },\n raw: rawUsage as any,\n }\n }\n\n private toFinishReason(\n reason: \"stop\" | \"tool-calls\" = \"stop\",\n ): LanguageModelV3FinishReason {\n return {\n unified: reason,\n raw: reason,\n }\n }\n\n private requestScope(options: { tools?: unknown }): \"tools\" | \"no-tools\" {\n const tools = options?.tools\n if (Array.isArray(tools)) return \"tools\"\n if (tools && typeof tools === \"object\") {\n return Object.keys(tools as Record<string, unknown>).length > 0\n ? \"tools\"\n : \"no-tools\"\n }\n return \"no-tools\"\n }\n\n /**\n * Build the combined `--mcp-config` list and return both the list and the\n * hash of the bridged opencode MCP block (or null when bridging is off /\n * yields nothing). The hash is used to detect mid-session config changes\n * and respawn the underlying claude process.\n *\n * `runtimeStatus` is a snapshot of opencode's `client.mcp.status()`. When\n * provided it overlays opencode's UI-toggled state on top of disk config\n * so `/mcps` toggles propagate without a config file write.\n */\n private effectiveMcpConfig(\n cwd: string,\n proxyConfigPath?: string,\n runtimeStatus?: RuntimeMcpStatus,\n excludeServers?: ReadonlySet<string>,\n ): {\n paths: string[]\n bridgedHash: string | null\n allEnabledServerNames: string[]\n } {\n const paths = Array.isArray(this.config.mcpConfig)\n ? this.config.mcpConfig.slice()\n : this.config.mcpConfig\n ? [this.config.mcpConfig]\n : []\n let bridgedHash: string | null = null\n let allEnabledServerNames: string[] = []\n if (this.config.bridgeOpencodeMcp !== false) {\n const bridged = bridgeOpencodeMcp(cwd, runtimeStatus, excludeServers)\n if (bridged) {\n if (bridged.path) paths.push(bridged.path)\n bridgedHash = bridged.hash\n allEnabledServerNames = bridged.allEnabledServerNames\n }\n }\n if (proxyConfigPath) paths.push(proxyConfigPath)\n return { paths, bridgedHash, allEnabledServerNames }\n }\n\n /** Resolve ProxyToolDef[] for the configured proxyTools names. */\n private resolvedProxyTools(): ProxyToolDef[] | null {\n const names = this.config.proxyTools\n if (!names || names.length === 0) return null\n const defsByName = new Map(\n DEFAULT_PROXY_TOOLS.map((t) => [t.name.toLowerCase(), t]),\n )\n const picked: ProxyToolDef[] = []\n const unknown: string[] = []\n for (const n of names) {\n const def = defsByName.get(String(n).toLowerCase())\n if (def) picked.push(def)\n else unknown.push(String(n))\n }\n // A typo used to vanish here. Silence is the wrong response: unknown\n // names are not proxied, so the matching Claude built-in stays enabled\n // and unmediated, and if *every* name is unknown the whole turn runs\n // with no proxy at all (issue #26).\n if (unknown.length > 0) {\n const known = [...defsByName.keys()].join(\", \")\n if (picked.length === 0) {\n log.warn(\n \"no proxyTools entry was recognised; nothing will be proxied this turn\",\n { unknown, known },\n )\n } else {\n log.warn(\"ignoring unknown proxyTools entries\", { unknown, known })\n }\n }\n return picked.length > 0 ? picked : null\n }\n\n /**\n * Resolve ProxyToolDef[] for opencode's MCP-bridged tools so they go\n * through the in-process proxy instead of being bridged into Claude CLI's\n * `--mcp-config`. Direct bridging causes double execution because both\n * Claude CLI's own MCP child and opencode hold their own connection to\n * the same server; routing through the proxy keeps a single execution\n * site (opencode). Returns null when the feature is disabled, the SDK\n * client is unavailable, or no MCP servers are configured.\n */\n private async resolvedProxyMcpTools(\n allEnabledServerNames: string[],\n ): Promise<ProxyToolDef[] | null> {\n if (this.config.proxyOpencodeMcpTools === false) return null\n if (this.config.bridgeOpencodeMcp === false) return null\n if (allEnabledServerNames.length === 0) return null\n\n const items = await fetchOpencodeToolList(\n this.config.provider,\n this.modelId,\n this.config.cwd,\n )\n if (!items || items.length === 0) return null\n\n // opencode names MCP tools `<server>_<originalToolName>`. Match the\n // longest server name prefix first so e.g. `slack_intl_*` resolves to\n // server `slack_intl` not `slack`.\n const serversByLengthDesc = [...allEnabledServerNames].sort(\n (a, b) => b.length - a.length,\n )\n const out: ProxyToolDef[] = []\n const seen = new Set<string>()\n for (const item of items) {\n const matchedServer = serversByLengthDesc.find(\n (name) => item.id === name || item.id.startsWith(`${name}_`),\n )\n if (!matchedServer) continue\n if (seen.has(item.id)) continue\n seen.add(item.id)\n out.push({\n name: item.id,\n description: item.description ?? \"\",\n inputSchema:\n item.parameters && typeof item.parameters === \"object\"\n ? item.parameters\n : { type: \"object\", properties: {} },\n })\n }\n return out.length > 0 ? out : null\n }\n\n /**\n * Live tool info derived from a single `client.tool.list()` fetch:\n *\n * - `taskDescription`: opencode's `task` tool description exactly as the\n * registry renders it for native models, including the \"Available\n * agent types\" list. Overlaid onto the static `task` proxy def so\n * Claude sees the same subagent catalog native models see, instead\n * of hunting through config files.\n * - `questionDescription` / `hasQuestion`: opencode's `question` tool\n * description and whether the registry has the entry at all. Older\n * builds lack it, in which case a `mcp__opencode_proxy__question`\n * call resolves to `⚙ invalid`; the version gate drops the def.\n *\n * Returns undefined/false when the SDK client is unavailable (direct\n * AI-SDK use, tests) so the static defs stand. `resolved` distinguishes\n * \"the registry answered and has no `question` entry\" from \"nobody\n * answered\": only the former is a real version-gate signal.\n */\n private async fetchLiveToolInfo(): Promise<LiveToolInfo> {\n const items = await fetchOpencodeToolList(\n this.config.provider,\n this.modelId,\n this.config.cwd,\n )\n const question = items?.find((item) => item.id === \"question\")\n return {\n resolved: items !== undefined,\n taskDescription: items?.find((item) => item.id === \"task\")?.description,\n questionDescription: question?.description,\n hasQuestion: !!question,\n }\n }\n\n /** Share one lazy registry request within a turn without making it stale. */\n private createLiveToolInfoLoader(): () => Promise<LiveToolInfo> {\n let pending: Promise<LiveToolInfo> | undefined\n return () => {\n pending ??= this.fetchLiveToolInfo()\n return pending\n }\n }\n\n /**\n * Whether the ExitPlanMode approval bridge is live for this turn: the\n * operator opted in AND opencode's registry actually has the `question`\n * tool. Without the registry entry the emitted tool-call would render as\n * `⚙ invalid` and wedge the turn, so the plugin keeps the text path.\n */\n private async resolvePlanModeQuestion(\n compactionMode: boolean,\n loadLiveToolInfo = () => this.fetchLiveToolInfo(),\n ): Promise<boolean> {\n if (compactionMode || this.config.planModeQuestion !== true) return false\n const info = await loadLiveToolInfo()\n const active = isPlanModeQuestionActive({\n configured: this.config.planModeQuestion,\n opencodeHasQuestion: info.hasQuestion,\n compactionMode,\n })\n if (!active) {\n // Same reasoning as the question proxy's version-gate log: a silent\n // fallback to the text path looks from the outside like the setting\n // was ignored.\n log.info(\"plan-mode question gate\", {\n opencodeHasQuestion: info.hasQuestion,\n registryResolved: info.resolved,\n active,\n })\n }\n return active\n }\n\n /**\n * Create a proxy MCP server for a single active Claude process/session.\n * The process lifecycle owns the server lifecycle via session-manager.\n */\n private async ensureProxyServer(\n tools: ProxyToolDef[],\n sessionKeyForCalls: string,\n ): Promise<ProxyMcpServer> {\n const timeoutOverrides = this.config.proxyToolTimeoutMs\n const interceptors = new Map<string, ProxyToolInterceptor>()\n if (tools.some((t) => t.name === \"compress\")) {\n interceptors.set(\"compress\", (input) => {\n const summary = typeof input.summary === \"string\" ? input.summary.trim() : \"\"\n if (!summary) {\n return {\n kind: \"error\",\n message:\n \"compress needs a non-empty `summary`: it becomes the only\" +\n \" prior context after the reset. Nothing was compressed.\",\n }\n }\n storeCompressionSummary(sessionKeyForCalls, summary)\n log.info(\"compress stored summary; session resets next turn\", {\n sessionKey: sessionKeyForCalls,\n summaryLength: summary.length,\n })\n return {\n kind: \"text\",\n text:\n \"Summary stored. Finish this turn as normal; the next turn starts\" +\n \" a fresh Claude Code session with this summary as its only prior\" +\n \" context.\",\n }\n })\n }\n const srv = await createProxyMcpServer(tools, timeoutOverrides, interceptors)\n srv.calls.on(\"call\", (call: ProxyToolCall) => {\n queuePendingProxyCall(sessionKeyForCalls, call, timeoutOverrides)\n })\n return srv\n }\n\n private extractPendingProxyResult(\n prompt: LanguageModelV3CallOptions[\"prompt\"],\n toolCallId: string,\n ): ProxyToolResult | null {\n for (let i = prompt.length - 1; i >= 0; i--) {\n const msg = prompt[i]\n if (msg.role !== \"tool\" || !Array.isArray(msg.content)) continue\n\n for (const part of msg.content) {\n if (part.type !== \"tool-result\" || part.toolCallId !== toolCallId) continue\n\n const output = part.output as any\n if (!output || typeof output !== \"object\") {\n return {\n kind: \"text\",\n text: String(output ?? \"\"),\n }\n }\n\n if (output.type === \"text\") {\n return {\n kind: \"text\",\n text: String(output.value ?? \"\"),\n }\n }\n\n if (output.type === \"json\") {\n return {\n kind: \"text\",\n text: JSON.stringify(output.value),\n }\n }\n\n if (output.type === \"content\" && Array.isArray(output.value)) {\n const text = output.value\n .filter((v: any) => v?.type === \"text\" && typeof v.text === \"string\")\n .map((v: any) => v.text)\n .join(\"\\n\")\n return {\n kind: \"text\",\n text,\n }\n }\n\n return {\n kind: \"text\",\n text: JSON.stringify(output),\n }\n }\n }\n\n return null\n }\n\n /**\n * Resolve the session affinity token for this LLM call. Delegates to the\n * exported `resolveSessionAffinity` helper so the logic is unit-testable.\n * Priority:\n * 1. `x-session-affinity` request header (primary).\n * 2. `opencodeSessionID` in providerOptions (chat.params hook fallback —\n * covers provider switches mid-session and title synthesis paths\n * where the header is absent).\n * 3. `\"default\"`.\n */\n private sessionAffinity(\n options: LanguageModelV3CallOptions,\n ): string {\n const headers = (options as any)?.headers as\n | Record<string, string | undefined>\n | undefined\n return resolveSessionAffinity(\n headers,\n options.providerOptions as Record<string, unknown> | undefined,\n this.config.provider,\n )\n }\n\n private controlRequestBehaviorForTool(toolName: string): ControlRequestBehavior {\n const configured = this.config.controlRequestToolBehaviors\n if (configured && toolName) {\n const direct = configured[toolName] ?? configured[toolName.toLowerCase()]\n if (direct === \"allow\" || direct === \"deny\") return direct\n\n const lower = toolName.toLowerCase()\n for (const [key, behavior] of Object.entries(configured)) {\n if (key.toLowerCase() === lower && (behavior === \"allow\" || behavior === \"deny\")) {\n return behavior\n }\n }\n }\n\n // AskUserQuestion must never be auto-allowed. Allowing it lets the\n // Claude CLI resolve its own question internally — in headless mode\n // there is no TTY, so the CLI fabricates/empties the answer and the\n // model proceeds on a guess. Deny so the CLI cannot self-answer; the\n // tool_use is still streamed and rendered to the opencode user by\n // formatAskUserQuestion, and the turn stops for a real reply. An\n // explicit controlRequestToolBehaviors entry above can still override.\n if (isAskUserQuestionTool(toolName)) return \"deny\"\n\n return this.config.controlRequestBehavior ?? \"allow\"\n }\n\n private writeControlResponse(\n proc: import(\"child_process\").ChildProcess,\n requestId: string,\n response?: Record<string, unknown>,\n ): void {\n const payload = {\n type: \"control_response\",\n response: {\n subtype: \"success\",\n request_id: requestId,\n response,\n },\n }\n\n try {\n proc.stdin?.write(JSON.stringify(payload) + \"\\n\")\n } catch (error) {\n log.warn(\"failed to write control response\", {\n requestId,\n error: error instanceof Error ? error.message : String(error),\n })\n }\n }\n\n /**\n * Handle Claude stream-json control requests (`can_use_tool`, etc.) and\n * respond via stdin with a matching `control_response`.\n */\n private handleControlRequest(\n msg: ClaudeStreamMessage,\n proc: import(\"child_process\").ChildProcess,\n ): boolean {\n if (msg.type !== \"control_request\") return false\n const requestId = msg.request_id\n const request = msg.request\n if (!requestId || !request?.subtype) return false\n\n if (request.subtype === \"can_use_tool\") {\n const toolName = request.tool_name ?? \"unknown\"\n const behavior = this.controlRequestBehaviorForTool(toolName)\n\n if (behavior === \"allow\") {\n this.writeControlResponse(proc, requestId, {\n behavior: \"allow\",\n updatedInput: request.input ?? {},\n toolUseID: request.tool_use_id,\n })\n log.info(\"control request auto-allowed\", {\n requestId,\n toolName,\n })\n } else {\n const denyMessage = denyMessageForTool(\n toolName,\n this.config.controlRequestDenyMessage,\n )\n this.writeControlResponse(proc, requestId, {\n behavior: \"deny\",\n message: denyMessage,\n toolUseID: request.tool_use_id,\n })\n log.info(\"control request auto-denied\", {\n requestId,\n toolName,\n })\n }\n\n return true\n }\n\n // For control request subtypes we don't actively handle yet, acknowledge\n // with an empty success so the CLI stream does not stall.\n this.writeControlResponse(proc, requestId, {})\n log.debug(\"control request acknowledged\", {\n requestId,\n subtype: request.subtype,\n })\n return true\n }\n\n private getReasoningEffort(\n providerOptions?: LanguageModelV3CallOptions[\"providerOptions\"],\n ): ReasoningEffort | undefined {\n if (!providerOptions) return undefined\n const ownKey = this.config.provider\n const bag =\n (providerOptions as any)[ownKey] ??\n (providerOptions as any)[\"claude-code\"]\n const effort = bag?.reasoningEffort\n const valid: ReasoningEffort[] = [\n \"minimal\",\n \"low\",\n \"medium\",\n \"high\",\n \"xhigh\",\n \"max\",\n ]\n return valid.includes(effort) ? effort : undefined\n }\n\n private getOpencodeAgent(\n providerOptions?: LanguageModelV3CallOptions[\"providerOptions\"],\n ): string | undefined {\n if (!providerOptions) return undefined\n const ownKey = this.config.provider\n const bag =\n (providerOptions as any)[ownKey] ??\n (providerOptions as any)[\"claude-code\"]\n const agent = bag?.opencodeAgent\n return typeof agent === \"string\" ? agent : undefined\n }\n\n private isCompactionCall(\n options: LanguageModelV3CallOptions,\n ): boolean {\n return this.getOpencodeAgent(options.providerOptions) === \"compaction\"\n }\n\n /**\n * Pick the model used to handle /compact. Precedence:\n * 1. `CLAUDE_CODE_COMPACTION_MODEL` env var (per-process override)\n * 2. `compactionModel` provider setting (opencode.json / .jsonc)\n * 3. Built-in default (claude-haiku-4-5)\n */\n private resolveCompactionModel(): string {\n return resolveCompactionModel(this.config.compactionModel)\n }\n\n private thinkingCliOptions(): {\n thinking?: \"enabled\"\n thinkingDisplay?: \"summarized\"\n } {\n if (isClaudeThinkingDisabled()) return {}\n\n return {\n thinking: \"enabled\",\n thinkingDisplay:\n process.env.CLAUDE_CODE_SHOW_THINKING_SUMMARIES === undefined\n ? \"summarized\"\n : undefined,\n }\n }\n\n private latestUserText(\n prompt: LanguageModelV3CallOptions[\"prompt\"],\n ): string {\n for (let i = prompt.length - 1; i >= 0; i--) {\n const msg = prompt[i]\n if (msg.role !== \"user\") continue\n\n if (typeof msg.content === \"string\") {\n return String(msg.content).trim()\n }\n\n if (Array.isArray(msg.content)) {\n const text = (msg.content as any[])\n .filter((part) => part.type === \"text\" && typeof part.text === \"string\")\n .map((part: any) => String(part.text).trim())\n .filter(Boolean)\n .join(\" \")\n if (text) return text\n }\n }\n\n return \"\"\n }\n\n private synthesizeTitle(\n prompt: LanguageModelV3CallOptions[\"prompt\"],\n ): string {\n const source = this.latestUserText(prompt)\n .replace(/\\s+/g, \" \")\n .replace(/[^\\p{L}\\p{N}\\s-]/gu, \" \")\n .trim()\n\n if (!source) return \"New Session\"\n\n const stop = new Set([\n \"a\",\n \"an\",\n \"the\",\n \"and\",\n \"or\",\n \"but\",\n \"to\",\n \"for\",\n \"of\",\n \"in\",\n \"on\",\n \"at\",\n \"with\",\n \"can\",\n \"could\",\n \"would\",\n \"should\",\n \"please\",\n \"hi\",\n \"hello\",\n \"hey\",\n \"there\",\n \"you\",\n \"your\",\n \"this\",\n \"that\",\n \"is\",\n \"are\",\n \"was\",\n \"were\",\n \"be\",\n \"do\",\n \"does\",\n \"did\",\n \"summarize\",\n \"summary\",\n \"project\",\n ])\n\n const words = source\n .split(\" \")\n .map((word) => word.trim())\n .filter(Boolean)\n .filter((word) => !stop.has(word.toLowerCase()))\n\n const picked = (words.length > 0 ? words : source.split(\" \").filter(Boolean))\n .slice(0, 6)\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1))\n .join(\" \")\n\n return picked || \"New Session\"\n }\n\n private async doGenerateViaStream(\n options: LanguageModelV3CallOptions,\n ): Promise<Awaited<ReturnType<LanguageModelV3[\"doGenerate\"]>>> {\n const result = await this.doStream(options)\n const reader = result.stream.getReader()\n\n let text = \"\"\n let reasoning = \"\"\n const toolCalls: LanguageModelV3Content[] = []\n let finishReason = this.toFinishReason(\"stop\")\n let usage: LanguageModelV3Usage = this.toUsage()\n let providerMetadata: any\n\n while (true) {\n const { value, done } = await reader.read()\n if (done) break\n\n switch ((value as any).type) {\n case \"text-delta\":\n text += (value as any).delta ?? \"\"\n break\n case \"reasoning-delta\":\n reasoning += (value as any).delta ?? \"\"\n break\n case \"tool-call\":\n toolCalls.push({\n type: \"tool-call\",\n toolCallId: (value as any).toolCallId,\n toolName: (value as any).toolName,\n input: (value as any).input,\n providerExecuted: (value as any).providerExecuted,\n } as any)\n break\n case \"finish\":\n finishReason = (value as any).finishReason ?? finishReason\n usage = (value as any).usage ?? usage\n providerMetadata = (value as any).providerMetadata ?? providerMetadata\n break\n }\n }\n\n const content: LanguageModelV3Content[] = []\n if (reasoning) {\n content.push({ type: \"reasoning\", text: reasoning } as any)\n }\n if (text) {\n content.push({ type: \"text\", text, providerMetadata } as any)\n }\n content.push(...toolCalls)\n\n return {\n content,\n finishReason,\n usage,\n request: result.request,\n response: {\n id: generateId(),\n timestamp: new Date(),\n modelId: this.modelId,\n },\n providerMetadata,\n warnings: [],\n }\n }\n\n async doGenerate(\n options: LanguageModelV3CallOptions,\n ): Promise<Awaited<ReturnType<LanguageModelV3[\"doGenerate\"]>>> {\n if (!this.isCompactionCall(options) && this.requestScope(options as any) !== \"no-tools\" && parseSideQuestion(options.prompt)) {\n return this.doGenerateViaStream(options)\n }\n const warnings: SharedV3Warning[] = []\n const cwd = resolveSpawnCwd(this.config.cwd)\n const scope = this.requestScope(options as any)\n const affinity = this.sessionAffinity(options)\n // An agent may run on a different model than the one opencode routed here\n // (see agent-models.ts). The session key must carry the effective model or\n // an overridden agent shares a claude process with its caller.\n const effectiveModelId = resolveAgentModel(\n this.getOpencodeAgent(options.providerOptions),\n this.modelId,\n )\n const reasoningEffort = resolveAgentEffort(\n this.getOpencodeAgent(options.providerOptions),\n this.getReasoningEffort(options.providerOptions),\n ) as ReasoningEffort | undefined\n // Keep effort invalidation inside one agent/provider, even when callers\n // share a model and opencode session (for example switching agents).\n const baseKey = sessionKey(\n cwd,\n `${effectiveModelId}::${scope}::${affinity}::context=${JSON.stringify([this.config.provider, this.getOpencodeAgent(options.providerOptions) ?? null])}`,\n )\n const sk = effortSessionKey(baseKey, reasoningEffort)\n\n // When selective proxying is enabled, doGenerate must not bypass the\n // proxy path. Reuse doStream and aggregate its events so proxied tools\n // still route through opencode permissions/execution. Same for\n // opencode MCP proxying — doStream is the only path that wires up the\n // proxy server with the dynamically-discovered MCP tool defs.\n const compactionMode = this.isCompactionCall(options)\n\n if (\n scope === \"tools\" &&\n (this.resolvedProxyTools() ||\n (this.config.proxyOpencodeMcpTools !== false &&\n this.config.bridgeOpencodeMcp !== false))\n ) {\n return this.doGenerateViaStream(options)\n }\n\n // Route compaction through doStream so it gets the lean spawn path,\n // model override, and rich transcript handling. Aggregating a stream\n // for doGenerate matches what doGenerateViaStream already does for\n // proxy tools.\n if (compactionMode) {\n return this.doGenerateViaStream(options)\n }\n\n if (scope === \"no-tools\") {\n log.info(\"doGenerate no-tools title stub\", {\n compactionMode,\n opencodeAgent: this.getOpencodeAgent(options.providerOptions),\n providerOptionsKeys: options.providerOptions\n ? Object.keys(options.providerOptions)\n : [],\n })\n const text = this.synthesizeTitle(options.prompt)\n return {\n content: [{ type: \"text\", text }] as any,\n finishReason: this.toFinishReason(\"stop\"),\n usage: this.toUsage({ input_tokens: 0, output_tokens: 0 }),\n request: { body: { text: \"\" } },\n response: {\n id: generateId(),\n timestamp: new Date(),\n modelId: this.modelId,\n },\n providerMetadata: {\n \"claude-code\": {\n synthetic: true,\n path: \"no-tools\",\n },\n },\n warnings,\n }\n }\n\n // Short-circuit when opencode iterates the agent loop one more time\n // after a turn already finished. The prompt ends with an assistant\n // message and has no fresh user input — spawning Claude here would\n // just produce a stub like \"No input received. Standing by\".\n if (!hasNewUserContent(options.prompt)) {\n log.info(\"doGenerate short-circuit: no new user content\")\n return {\n content: [],\n finishReason: this.toFinishReason(\"stop\"),\n usage: this.toUsage({ input_tokens: 0, output_tokens: 0 }),\n request: { body: { text: \"\" } },\n response: {\n id: generateId(),\n timestamp: new Date(),\n modelId: this.modelId,\n },\n providerMetadata: {\n \"claude-code\": { synthetic: true, path: \"no-new-user-content\" },\n },\n warnings,\n }\n }\n\n invalidateOtherEffortSessions(baseKey, reasoningEffort)\n\n const hasPriorConversation =\n options.prompt.filter((m) => m.role === \"user\" || m.role === \"assistant\")\n .length > 1\n\n // New session — clear any stale state from a previous session.\n // A compression summary is scoped to one conversation, so this is the\n // one place it is dropped: the compress restart itself calls\n // deleteClaudeSessionId, and clearing there would wipe the summary\n // just before the fresh spawn reads it.\n if (!hasPriorConversation) {\n deleteClaudeSessionId(sk)\n deleteActiveProcess(sk)\n clearCompression(sk)\n }\n\n const hasExistingSession = !!getClaudeSessionId(sk)\n const includeHistoryContext = !hasExistingSession && hasPriorConversation\n\n const userMsg =\n consumeExitPlanModeQuestionResult(sk, options.prompt as any) ??\n // doGenerate has no proxy wiring, so this process issued no tool calls\n // at all: every tool result reaching it belongs to opencode and must be\n // rendered as text rather than an orphaned `tool_result` (issue #29).\n getClaudeUserMessage(options.prompt, includeHistoryContext, {\n cliToolCallIds: new Set<string>(),\n })\n\n // doGenerate always spawns a fresh process, never reuse session ID.\n // Pre-fetch opencode's MCP runtime status so the bridge overlays\n // UI-toggled state on top of disk config.\n const [runtimeStatus, cliVersion, planModeQuestionActive] = await Promise.all([\n getRuntimeMcpStatus(),\n detectCliVersion(this.config.cliPath),\n this.resolvePlanModeQuestion(compactionMode),\n ])\n const systemPromptFile = buildAppendedSystemPrompt(\n cwd,\n this.config.multiStepContinuation !== false,\n extractSystemMessages(options.prompt),\n // doGenerate has no proxy wiring, so `compress` is not callable here.\n // An existing summary still carries: it is this key's prior context.\n { compressEnabled: false, compressionSummary: getCompressionSummary(sk) },\n )\n const { model: spawnModelId, fast: fastMode } = parseModelId(effectiveModelId)\n const cliArgs = buildCliArgs({\n sessionKey: sk,\n skipPermissions: this.config.skipPermissions !== false,\n includeSessionId: false,\n model: spawnModelId,\n permissionMode: this.config.permissionMode,\n mcpConfig: this.effectiveMcpConfig(cwd, undefined, runtimeStatus).paths,\n strictMcpConfig: this.config.strictMcpConfig,\n disallowedTools:\n this.config.webSearch === \"disabled\" ? [\"WebSearch\"] : undefined,\n appendSystemPromptFile: systemPromptFile,\n ...this.thinkingCliOptions(),\n fastMode,\n cliVersion,\n })\n\n log.info(\"doGenerate starting\", {\n cwd,\n model: effectiveModelId,\n requestedModel: this.modelId,\n textLength: userMsg.length,\n includeHistoryContext,\n })\n\n const { spawn } = await import(\"node:child_process\")\n const { createInterface } = await import(\"node:readline\")\n\n const proc = spawn(this.config.cliPath, cliArgs, {\n cwd,\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n env: claudeSpawnEnv({\n ignoreAnthropicApiKey: this.config.ignoreAnthropicApiKey,\n effort: reasoningEffort,\n }),\n shell: process.platform === \"win32\",\n })\n\n if (systemPromptFile) {\n proc.on(\"exit\", () => {\n void unlink(systemPromptFile).catch(() => {})\n })\n }\n\n const rl = createInterface({ input: proc.stdout! })\n\n let responseText = \"\"\n let thinkingText = \"\"\n let resultMeta: {\n sessionId?: string\n costUsd?: number\n durationMs?: number\n usage?: ClaudeStreamMessage[\"usage\"]\n } = {}\n const toolCalls: Array<{ id: string; name: string; args: unknown }> = []\n // Streaming tool_use entries keyed by content-block index. We accumulate\n // partial_json chunks here instead of trying to JSON.parse each chunk\n // independently, and flush to `toolCalls` at content_block_stop. The\n // previous code indexed `toolCalls` by `msg.index` directly, which is\n // wrong whenever non-tool blocks (text, thinking) precede a tool_use.\n const toolCallStreams = new Map<\n number,\n { id: string; name: string; inputJson: string }\n >()\n\n // Set true once we observe a `stream_event` envelope. When on, the\n // top-level `assistant` message is a duplicate of content already\n // accumulated via the inner content_block_* events — skip it.\n let gotPartialEvents = false\n\n const result = await new Promise<\n typeof resultMeta & {\n text: string\n thinking: string\n toolCalls: typeof toolCalls\n }\n >((resolve, reject) => {\n const cleanup = () => {\n try {\n if (!proc.killed && proc.exitCode === null) proc.kill()\n } catch {}\n }\n\n rl.on(\"line\", (line) => {\n if (!line.trim()) return\n try {\n const outer: ClaudeStreamMessage = JSON.parse(line)\n\n // Unwrap stream_event envelope (--include-partial-messages).\n // Inner event uses the same content_block_* / message_* shape.\n const msg: ClaudeStreamMessage =\n outer.type === \"stream_event\" && outer.event\n ? { ...outer.event, session_id: outer.session_id }\n : outer\n\n if (outer.type === \"stream_event\") {\n gotPartialEvents = true\n }\n\n if (this.handleControlRequest(msg, proc)) {\n return\n }\n\n if (msg.type === \"system\" && msg.subtype === \"init\") {\n if (msg.session_id) {\n setClaudeSessionId(sk, msg.session_id)\n }\n reportFastModeState(msg, fastMode)\n }\n\n if (\n msg.type === \"assistant\" &&\n msg.message?.content &&\n !gotPartialEvents\n ) {\n for (const block of msg.message.content) {\n if (block.type === \"text\" && block.text) {\n responseText += block.text\n }\n if (block.type === \"thinking\" && block.thinking) {\n thinkingText += block.thinking\n }\n if (block.type === \"tool_use\" && block.id && block.name) {\n if (isAskUserQuestionTool(block.name)) {\n // Render the full question + options as visible text so\n // the user can actually see and answer it.\n const parsedInput = (block.input ?? {}) as Record<\n string,\n unknown\n >\n responseText += formatAskUserQuestion(parsedInput)\n continue\n }\n\n if (block.name === \"ExitPlanMode\") {\n const parsedInput = (block.input ?? {}) as Record<\n string,\n unknown\n >\n const plan = (parsedInput?.plan as string) || \"\"\n if (planModeQuestionActive) {\n const questionCall = createExitPlanModeQuestionCall(\n sk,\n block.id,\n plan,\n )\n responseText += questionCall.text\n toolCalls.push({\n id: questionCall.toolCallId,\n name: questionCall.toolName,\n args: questionCall.input,\n })\n continue\n }\n responseText += `\\n\\n${plan}\\n\\n---\\n**Do you want to proceed with this plan?** (yes/no)\\n`\n continue\n }\n\n toolCalls.push({\n id: block.id,\n name: block.name,\n args: block.input ?? {},\n })\n }\n }\n }\n\n if (\n msg.type === \"content_block_start\" &&\n msg.content_block &&\n msg.index !== undefined\n ) {\n if (\n msg.content_block.type === \"tool_use\" &&\n msg.content_block.id &&\n msg.content_block.name\n ) {\n toolCallStreams.set(msg.index, {\n id: msg.content_block.id,\n name: msg.content_block.name,\n inputJson: \"\",\n })\n }\n }\n\n if (\n msg.type === \"content_block_delta\" &&\n msg.delta &&\n msg.index !== undefined\n ) {\n if (msg.delta.type === \"text_delta\" && msg.delta.text) {\n responseText += msg.delta.text\n }\n if (msg.delta.type === \"thinking_delta\" && msg.delta.thinking) {\n thinkingText += msg.delta.thinking\n }\n if (\n msg.delta.type === \"input_json_delta\" &&\n msg.delta.partial_json\n ) {\n const tc = toolCallStreams.get(msg.index)\n if (tc) tc.inputJson += msg.delta.partial_json\n }\n }\n\n if (msg.type === \"content_block_stop\" && msg.index !== undefined) {\n const tc = toolCallStreams.get(msg.index)\n if (tc) {\n let args: unknown = {}\n try {\n args = tc.inputJson ? JSON.parse(tc.inputJson) : {}\n } catch (err) {\n log.warn(\"tool input JSON parse failed\", {\n name: tc.name,\n error: String(err),\n })\n }\n if (tc.name === \"ExitPlanMode\" && planModeQuestionActive) {\n const parsedInput = args as Record<string, unknown>\n const plan = (parsedInput?.plan as string) || \"\"\n const questionCall = createExitPlanModeQuestionCall(sk, tc.id, plan)\n responseText += questionCall.text\n toolCalls.push({\n id: questionCall.toolCallId,\n name: questionCall.toolName,\n args: questionCall.input,\n })\n } else {\n toolCalls.push({ id: tc.id, name: tc.name, args })\n }\n toolCallStreams.delete(msg.index)\n }\n }\n\n if (msg.type === \"result\") {\n if (msg.session_id) {\n setClaudeSessionId(sk, msg.session_id)\n }\n\n // Some CLI failures only surface user-readable text on the final\n // `result` message (without prior assistant text blocks). Preserve\n // that so callers don't receive an empty response.\n if (\n !responseText &&\n msg.is_error &&\n typeof msg.result === \"string\" &&\n msg.result.trim().length > 0\n ) {\n responseText = msg.result\n }\n\n resultMeta = {\n sessionId: msg.session_id,\n costUsd: msg.total_cost_usd,\n durationMs: msg.duration_ms,\n usage: msg.usage,\n }\n cleanup()\n resolve({\n ...resultMeta,\n text: responseText,\n thinking: thinkingText,\n toolCalls,\n })\n }\n } catch {\n // Ignore non-JSON lines\n }\n })\n\n rl.on(\"close\", () => {\n cleanup()\n resolve({\n ...resultMeta,\n text: responseText,\n thinking: thinkingText,\n toolCalls,\n })\n })\n\n proc.on(\"error\", (err) => {\n log.error(\"process error\", { error: err.message })\n cleanup()\n reject(err)\n })\n\n proc.stderr?.on(\"data\", (data: Buffer) => {\n log.debug(\"stderr\", { data: data.toString().slice(0, 200) })\n })\n\n proc.stdin?.write(userMsg + \"\\n\")\n })\n\n const content: LanguageModelV3Content[] = []\n\n if (result.thinking) {\n content.push({\n type: \"reasoning\",\n text: result.thinking,\n } as any)\n }\n\n if (result.text) {\n content.push({\n type: \"text\",\n text: result.text,\n providerMetadata: {\n \"claude-code\": {\n sessionId: result.sessionId ?? null,\n costUsd: result.costUsd ?? null,\n durationMs: result.durationMs ?? null,\n },\n ...(typeof result.usage?.cache_creation_input_tokens === \"number\"\n ? {\n anthropic: {\n cacheCreationInputTokens:\n result.usage.cache_creation_input_tokens,\n },\n }\n : {}),\n },\n })\n }\n\n for (const tc of result.toolCalls) {\n if (tc.name === QUESTION_TOOL_NAME) {\n content.push({\n type: \"tool-call\",\n toolCallId: tc.id,\n toolName: tc.name,\n input: JSON.stringify(tc.args),\n providerExecuted: false,\n } as any)\n continue\n }\n\n const {\n name: mappedName,\n input: mappedInput,\n executed,\n skip,\n } = mapTool(tc.name, tc.args, {\n webSearch: this.config.webSearch,\n sessionId: getClaudeSessionId(sk),\n toolUseId: tc.id,\n })\n if (skip) continue\n content.push({\n type: \"tool-call\",\n toolCallId: tc.id,\n toolName: mappedName,\n input: JSON.stringify(mappedInput),\n providerExecuted: executed,\n } as any)\n }\n\n const usage = this.toUsage(result.usage)\n\n return {\n content,\n // Claude CLI's `result` message normally signals a fully-completed turn:\n // tools have already been executed internally and final assistant text\n // has been produced. ExitPlanMode is the exception: we surface it as\n // opencode's native question tool so the outer loop must run that tool.\n finishReason: this.toFinishReason(\n result.toolCalls.some((tc) => tc.name === QUESTION_TOOL_NAME)\n ? \"tool-calls\"\n : \"stop\",\n ),\n usage,\n request: { body: { text: userMsg } },\n response: {\n id: result.sessionId ?? generateId(),\n timestamp: new Date(),\n modelId: this.modelId,\n },\n providerMetadata: {\n \"claude-code\": {\n sessionId: result.sessionId ?? null,\n costUsd: result.costUsd ?? null,\n durationMs: result.durationMs ?? null,\n },\n ...(typeof result.usage?.cache_creation_input_tokens === \"number\"\n ? {\n anthropic: {\n cacheCreationInputTokens:\n result.usage.cache_creation_input_tokens,\n },\n }\n : {}),\n },\n warnings,\n }\n }\n\n async doStream(\n options: LanguageModelV3CallOptions,\n ): Promise<Awaited<ReturnType<LanguageModelV3[\"doStream\"]>>> {\n const warnings: SharedV3Warning[] = []\n const cwd = resolveSpawnCwd(this.config.cwd)\n const cliPath = this.config.cliPath\n const skipPermissions = this.config.skipPermissions !== false\n const scope = this.requestScope(options as any)\n const affinity = this.sessionAffinity(options)\n const compactionMode = this.isCompactionCall(options)\n // Use a separate session key for compaction so its short-lived spawn\n // never collides with the main conversation's claude process.\n const effectiveModelId = compactionMode\n ? this.resolveCompactionModel()\n : resolveAgentModel(\n this.getOpencodeAgent(options.providerOptions),\n this.modelId,\n )\n // `effectiveModelId` stays intact for session keys, logs, and metadata;\n // only the name handed to the CLI gets the `-fast` marker stripped.\n // Session keys keeping it is deliberate: fast and standard must not share\n // a claude process, both because the spawn flags differ and because\n // switching speed invalidates the prompt cache anyway.\n const { model: spawnModelId, fast: fastMode } = parseModelId(effectiveModelId)\n // Compaction skips request/agent effort overrides; other calls key on it.\n const reasoningEffort = compactionMode\n ? undefined\n : (resolveAgentEffort(\n this.getOpencodeAgent(options.providerOptions),\n this.getReasoningEffort(options.providerOptions),\n ) as ReasoningEffort | undefined)\n const baseKey = sessionKey(\n cwd,\n `${effectiveModelId}::${scope}::${affinity}::context=${JSON.stringify([this.config.provider, this.getOpencodeAgent(options.providerOptions) ?? null])}`,\n )\n const sk = compactionMode\n ? sessionKey(cwd, `${effectiveModelId}::compaction::${affinity}`)\n : effortSessionKey(baseKey, reasoningEffort)\n const toUsage = this.toUsage.bind(this)\n const toFinishReason = this.toFinishReason.bind(this)\n const handleControlRequest = this.handleControlRequest.bind(this)\n const flagOn = (v: string | undefined) =>\n v !== undefined &&\n ![\"\", \"0\", \"false\", \"no\", \"off\"].includes(v.trim().toLowerCase())\n // Interactive (subscription) transport: drive the claude TUI over Bun's\n // native ConPTY + JSONL tail instead of headless `--print` stream-json.\n // Prefer the provider option (config-driven, reliable in the GUI app where\n // process env vars are not inherited); fall back to the env var. Self-healing:\n // if Bun.Terminal is unavailable (e.g. not under Bun), use the headless path.\n const interactivePref =\n this.config.interactive ??\n flagOn(process.env.CLAUDE_CODE_INTERACTIVE_TRANSPORT)\n const useInteractive =\n interactivePref && typeof (globalThis as any).Bun?.Terminal === \"function\"\n const interactiveBypassRequested =\n this.config.interactiveBypass ??\n flagOn(process.env.CLAUDE_CODE_INTERACTIVE_BYPASS)\n\n // Tagged onto the process each turn so the /btw command hook, which only\n // knows the opencode session id, can find it and ask it early\n // (btw-command.ts).\n const asideTransportRef = { cliPath, interactive: !!useInteractive }\n\n const aside = !compactionMode && scope !== \"no-tools\" ? parseSideQuestion(options.prompt) : null\n if (aside) {\n // `/btw` is an ordinary user message in this conversation, so opencode\n // keeps the exchange, but it is answered over the CLI's side_question\n // control channel, never as a turn. The command hook normally sent the\n // question ahead, while the previous turn was still streaming, and its\n // answer is taken here; otherwise the process is idle now and is asked\n // directly. Earlier asides in this conversation ride along as history.\n const active = getActiveProcess(sk)\n const early = aside.question ? takeSideQuestionAnswer(affinity, aside.question) : undefined\n const history = collectSideQuestionHistory(options.prompt)\n const answerAside = async (): Promise<SideQuestionResult> => {\n if (!aside.question) return { response: SIDE_QUESTION_USAGE, synthetic: true }\n if (early) {\n try {\n return await early\n } catch (error) {\n log.info(\"btw: early answer failed, asking the idle process\", { error: String(error) })\n }\n }\n if (!active) return { response: BTW_NO_SESSION_MESSAGE, synthetic: true }\n return requestSideQuestion(active, aside.question, {\n cliVersion: await detectCliVersion(cliPath),\n interactive: useInteractive,\n abortSignal: options.abortSignal,\n ...(history.length ? { history } : {}),\n })\n }\n const stream = new ReadableStream<LanguageModelV3StreamPart>({\n async start(controller) {\n controller.enqueue({ type: \"stream-start\", warnings })\n try {\n const answer = await answerAside()\n const id = generateId()\n controller.enqueue({ type: \"text-start\", id })\n controller.enqueue({ type: \"text-delta\", id, delta: answer.response })\n controller.enqueue({ type: \"text-end\", id })\n controller.enqueue({\n type: \"finish\",\n finishReason: toFinishReason(\"stop\"),\n usage: toUsage({}),\n providerMetadata: { \"claude-code\": { path: \"side-question\", synthetic: answer.synthetic, usageUnavailable: true } },\n })\n } catch (error) {\n controller.enqueue({ type: \"error\", error })\n } finally {\n controller.close()\n }\n },\n })\n return { stream, request: { body: { text: aside.question } } }\n }\n\n if (scope === \"no-tools\" && !compactionMode) {\n log.info(\"doStream no-tools title stub\", {\n compactionMode,\n opencodeAgent: this.getOpencodeAgent(options.providerOptions),\n providerOptionsKeys: options.providerOptions\n ? Object.keys(options.providerOptions)\n : [],\n })\n const text = this.synthesizeTitle(options.prompt)\n const textId = generateId()\n const stream = new ReadableStream<LanguageModelV3StreamPart>({\n start(controller) {\n controller.enqueue({ type: \"stream-start\", warnings })\n controller.enqueue({ type: \"text-start\", id: textId } as any)\n controller.enqueue({\n type: \"text-delta\",\n id: textId,\n delta: text,\n })\n controller.enqueue({ type: \"text-end\", id: textId })\n controller.enqueue({\n type: \"finish\",\n finishReason: toFinishReason(\"stop\"),\n usage: toUsage({ input_tokens: 0, output_tokens: 0 }),\n providerMetadata: {\n \"claude-code\": {\n synthetic: true,\n path: \"no-tools\",\n },\n },\n })\n controller.close()\n },\n })\n\n return {\n stream,\n request: { body: { text: \"\" } },\n }\n }\n\n // Short-circuit when opencode iterates the agent loop one more time\n // after a turn already finished. The prompt ends with an assistant\n // message and has no fresh user input — spawning Claude here would\n // just produce a stub like \"No input received. Standing by\".\n if (!hasNewUserContent(options.prompt)) {\n log.info(\"doStream short-circuit: no new user content\")\n const stream = new ReadableStream<LanguageModelV3StreamPart>({\n start(controller) {\n controller.enqueue({ type: \"stream-start\", warnings })\n controller.enqueue({\n type: \"finish\",\n finishReason: toFinishReason(\"stop\"),\n usage: toUsage({ input_tokens: 0, output_tokens: 0 }),\n providerMetadata: {\n \"claude-code\": { synthetic: true, path: \"no-new-user-content\" },\n },\n })\n controller.close()\n },\n })\n return { stream, request: { body: { text: \"\" } } }\n }\n\n if (!compactionMode) invalidateOtherEffortSessions(baseKey, reasoningEffort)\n\n const hasPriorConversation =\n options.prompt.filter((m) => m.role === \"user\" || m.role === \"assistant\")\n .length > 1\n\n // New session — clear any stale state from a previous session.\n // A compression summary is scoped to one conversation, so this is the\n // one place it is dropped: the compress restart itself calls\n // deleteClaudeSessionId, and clearing there would wipe the summary\n // just before the fresh spawn reads it.\n if (!hasPriorConversation) {\n deleteClaudeSessionId(sk)\n deleteActiveProcess(sk)\n clearCompression(sk)\n }\n\n const hasExistingSession = !!getClaudeSessionId(sk)\n const hasActiveProcess = !!getActiveProcess(sk)\n const includeHistoryContext =\n !hasExistingSession && !hasActiveProcess && hasPriorConversation\n\n const exitPlanModeQuestionResult = compactionMode\n ? null\n : consumeExitPlanModeQuestionResult(sk, options.prompt as any)\n if (exitPlanModeQuestionResult) {\n // The whole user message for this turn is the `tool_result` for the\n // pending ExitPlanMode call, so say so: an operator looking at a turn\n // that carries none of their typed text needs the reason in the log.\n log.info(\"sending plan approval decision to claude\", { sk })\n }\n // Read before the envelope is built, and used by it: only these ids were\n // issued by this CLI process, so only these may be sent back as\n // `tool_result` blocks (issue #29).\n const previousPendingProxyCalls = compactionMode\n ? []\n : getPendingProxyCalls(sk)\n const userMsg =\n exitPlanModeQuestionResult ??\n getClaudeUserMessage(options.prompt, includeHistoryContext, {\n compactionMode,\n cliToolCallIds: new Set(previousPendingProxyCalls.map((c) => c.toolCallId)),\n })\n const resolvedProxy = compactionMode ? null : this.resolvedProxyTools()\n const loadLiveToolInfo = this.createLiveToolInfoLoader()\n // Resolved here, not inside the stream body: the ExitPlanMode branches\n // run in a synchronous line handler and a reused process never reaches\n // the spawn block where the registry snapshot is otherwise taken.\n const planModeQuestionActive = await this.resolvePlanModeQuestion(\n compactionMode,\n loadLiveToolInfo,\n )\n const self = this\n\n const previousPendingProxyMatches: Array<{\n call: PendingProxyCall\n result: ProxyToolResult | null\n }> = previousPendingProxyCalls.map((call) => ({\n call,\n result: this.extractPendingProxyResult(options.prompt, call.toolCallId),\n }))\n const hasMatchedPendingResults = previousPendingProxyMatches.some(\n (m) => m.result !== null,\n )\n\n // Pre-fetch opencode's MCP runtime status before constructing the\n // ReadableStream so the sync hot-reload check and async setup() see\n // the same overlay snapshot. One in-process call per turn — cheap;\n // the SDK client routes through `Server.app.fetch` (no socket).\n // Detect the Claude CLI version in parallel so the spawn can decide\n // which optional flags it supports without crashing older binaries.\n const [runtimeStatus, cliVersion] = await Promise.all([\n compactionMode ? Promise.resolve(undefined) : getRuntimeMcpStatus(),\n detectCliVersion(this.config.cliPath),\n ])\n\n log.info(\"doStream starting\", {\n cwd,\n model: effectiveModelId,\n textLength: userMsg.length,\n includeHistoryContext,\n hasActiveProcess,\n reasoningEffort,\n proxyTools: resolvedProxy?.map((t) => t.name) ?? null,\n compactionMode,\n scope,\n opencodeAgent: this.getOpencodeAgent(options.providerOptions),\n providerOptionsKeys: options.providerOptions\n ? Object.keys(options.providerOptions)\n : [],\n })\n\n const stream = new ReadableStream<LanguageModelV3StreamPart>({\n start(controller) {\n // Compaction is a one-shot call. Don't reuse any cached process\n // from a prior compaction — each /compact gets a fresh spawn so\n // the new transcript isn't appended to a stale claude session.\n if (compactionMode) {\n deleteActiveProcess(sk)\n deleteClaudeSessionId(sk)\n }\n\n // A compress call lands mid-turn, when the child is still streaming,\n // so the reset it asks for happens here instead: drop the child and\n // its session id, and the spawn below starts clean. `userMsg` and\n // `includeHistoryContext` were resolved above while the session\n // still existed, so the fresh process is given only this turn's\n // message — the summary in its system prompt is the whole of its\n // prior context, exactly as the tool promised.\n //\n // Not while this turn carries results for the live child: evicting\n // it would send a tool_result to a process that never issued the\n // matching tool_use. The mark survives to the next turn.\n if (!compactionMode && !hasMatchedPendingResults && consumeCompressionRestart(sk)) {\n deleteActiveProcess(sk)\n deleteClaudeSessionId(sk)\n log.info(\"compress reset: dropped claude process and session id\", {\n sessionKey: sk,\n })\n }\n\n let activeProcess = getActiveProcess(sk)\n let proc: import(\"child_process\").ChildProcess\n let lineEmitter: import(\"events\").EventEmitter\n let cliArgs: string[]\n let proxyServer: ProxyMcpServer | null = activeProcess?.proxyServer ?? null\n\n const setup = async () => {\n // Wait for the old owner to exit before resuming its session ID in\n // the replacement, so two processes never append to one transcript.\n if (\n !compactionMode &&\n activeProcess &&\n self.config.hotReloadMcp !== false &&\n self.config.bridgeOpencodeMcp !== false\n ) {\n const probe = self.effectiveMcpConfig(cwd, undefined, runtimeStatus!)\n const previousHash = activeProcess.mcpHash ?? null\n if (previousHash !== probe.bridgedHash) {\n if (previousPendingProxyCalls.length > 0) {\n log.info(\"deferring MCP hot reload until proxy calls resolve\", {\n sk,\n previousHash,\n currentHash: probe.bridgedHash,\n pendingCalls: previousPendingProxyCalls.length,\n })\n } else {\n log.info(\"opencode MCP config changed, respawning claude\", {\n sk,\n previousHash,\n currentHash: probe.bridgedHash,\n })\n await deleteActiveProcessAndWait(sk)\n activeProcess = undefined\n proxyServer = null\n }\n }\n }\n\n if (useInteractive && !compactionMode) {\n // Interactive Bun-ConPTY transport. Reuse the live session if one\n // exists for this key; else spawn a new interactive claude. The\n // wrapper conforms to ActiveProcess, so reuse/eviction/hot-reload\n // and the whole emission body below work unchanged.\n const mcp = self.effectiveMcpConfig(cwd, undefined, runtimeStatus!)\n if (activeProcess) {\n proc = activeProcess.proc\n lineEmitter = activeProcess.lineEmitter\n log.debug(\"reusing active interactive session\", { sk })\n } else {\n // MCP wildcards are always derived from the live bridge config;\n // the built-in tool list is overridable via interactiveAllowTools.\n const allow = [\n ...mcp.allEnabledServerNames.map((n) => `mcp__${n}__*`),\n \"mcp__opencode_proxy__*\",\n ...(self.config.interactiveAllowTools ?? [\n \"Bash\",\n \"Edit\",\n \"Write\",\n \"Read\",\n \"WebFetch\",\n ]),\n ]\n const systemPromptFile =\n self.config.interactiveSystemPrompt === false\n ? undefined\n : buildAppendedSystemPrompt(\n cwd,\n self.config.multiStepContinuation !== false,\n // Do not forward opencode's own system prompt into the\n // interactive TUI. Live subscription-account testing\n // showed that large forwarded payload can trigger Claude\n // Code's third-party-app usage gate, while our static\n // CLI/AGENTS/continuation prompt remains safe.\n )\n if (self.config.interactiveSystemPrompt === false) {\n log.warn(\n \"interactive system prompt disabled; opencode agent prompts will not be appended\",\n )\n }\n if (interactiveBypassRequested) {\n log.warn(\n \"interactiveBypass ignored: Claude Code prompts for bypassPermissions confirmation in the interactive TUI\",\n )\n }\n const ap = spawnInteractiveProcess({\n cwd,\n cliPath,\n configDir: self.config.configDir,\n model: spawnModelId,\n fastMode,\n mcpConfigPaths: mcp.paths,\n permissionsAllow: allow,\n systemPromptFile,\n ignoreAnthropicApiKey: self.config.ignoreAnthropicApiKey,\n effort: reasoningEffort,\n })\n ap.mcpHash = mcp.bridgedHash\n setActiveProcess(sk, ap)\n proc = ap.proc\n lineEmitter = ap.lineEmitter\n activeProcess = ap\n log.info(\"spawned interactive claude session\", {\n sk,\n cliPath,\n configDir: self.config.configDir,\n model: effectiveModelId,\n })\n }\n } else {\n let spawnSystemPromptFile: string | undefined\n let spawnProxyServer: ProxyMcpServer | null = null\n let spawnMcpHash: string | null = null\n\n if (compactionMode) {\n // Compaction takes a lean spawn: no MCP servers, no proxy, no\n // appended system prompt, no disallowed-tools list. The model\n // is asked for text output only on a single turn — all the\n // normal tool wiring is pure overhead and adds latency.\n // Explicitly opt out of `--resume` so a stale id can never\n // resume into the lean spawn.\n cliArgs = buildCliArgs({\n sessionKey: sk,\n skipPermissions,\n includeSessionId: false,\n model: spawnModelId,\n permissionMode: self.config.permissionMode,\n fastMode,\n cliVersion,\n })\n } else {\n // First pass: discover which opencode MCP servers would be\n // bridged. We use this to decide which ones to re-route through\n // the proxy instead. No --mcp-config path is consumed here;\n // it's recomputed below with the exclusion set in place.\n const discovery = self.effectiveMcpConfig(\n cwd,\n undefined,\n runtimeStatus!,\n )\n\n // Fetch the proxy MCP tools (one ProxyToolDef per opencode\n // MCP-bridged tool). If discovery returns nothing or the SDK\n // is unreachable, this is null and we fall back to direct\n // bridging.\n const proxyMcpTools = await self.resolvedProxyMcpTools(\n discovery.allEnabledServerNames,\n )\n const excludeServers: ReadonlySet<string> | undefined = proxyMcpTools\n ? new Set(discovery.allEnabledServerNames)\n : undefined\n\n // Overlay opencode's live tool info onto the static proxy defs.\n // Both the `task` description (with the \"Available agent types\"\n // list, so the model sees which subagents exist instead of\n // grepping configs) and the `question` version gate (older\n // opencode builds lack the `question` registry entry; the def\n // must be dropped or a forwarded call renders `⚙ invalid`)\n // derive from a single tool-list fetch. Spawn-time only, like\n // the rest of this block; a reused process keeps its defs.\n const taskProxyEnabled =\n resolvedProxy?.some((t) => t.name === \"task\") ?? false\n const questionProxyEnabled =\n resolvedProxy?.some((t) => t.name === \"question\") ?? false\n const liveToolInfo =\n taskProxyEnabled || questionProxyEnabled\n ? await loadLiveToolInfo()\n : {\n resolved: false,\n taskDescription: undefined,\n questionDescription: undefined,\n hasQuestion: false,\n }\n let enrichedProxy = resolvedProxy\n if (enrichedProxy && taskProxyEnabled) {\n enrichedProxy = overlayTaskProxyDescription(\n enrichedProxy,\n liveToolInfo.taskDescription,\n )\n // Whether the model will see opencode's agent list is the\n // difference between a dispatch and an \"Unknown agent type\"\n // guess, so say so out loud.\n log.info(\"task proxy description overlay\", {\n applied: Boolean(liveToolInfo.taskDescription),\n liveDescriptionLength: liveToolInfo.taskDescription?.length ?? 0,\n listsAgentTypes: Boolean(\n liveToolInfo.taskDescription?.includes(\n \"Available agent types\",\n ),\n ),\n })\n }\n if (enrichedProxy && questionProxyEnabled) {\n // When the version gate is about to drop the def\n // (`hasQuestion === false`) the live description is moot,\n // so only overlay when the entry actually exists.\n enrichedProxy = overlayQuestionProxyDescription(\n enrichedProxy,\n liveToolInfo.hasQuestion\n ? liveToolInfo.questionDescription\n : undefined,\n )\n enrichedProxy = filterQuestionProxyByOpencodeSupport(\n enrichedProxy,\n liveToolInfo.hasQuestion,\n )\n // Same reasoning as the task overlay log: when the gate drops\n // the def the model silently falls back to the deny/markdown\n // path, which looks from the outside like the feature is off.\n log.info(\"question proxy version gate\", {\n opencodeHasQuestion: liveToolInfo.hasQuestion,\n kept: liveToolInfo.hasQuestion,\n })\n }\n\n // Combine the static proxy defs with any MCP-bridged proxy\n // tools. Guard against the empty case: a version gate can\n // drop every configured def (e.g. `proxyTools: [\"Question\"]`\n // on an opencode build that lacks the `question` registry\n // entry), and spinning up an MCP server with zero tools is\n // wasteful and wrong shape.\n const combinedList = [\n ...(enrichedProxy ?? []),\n ...(proxyMcpTools ?? []),\n ]\n const combinedProxyTools: ProxyToolDef[] | null =\n combinedList.length > 0 ? combinedList : null\n\n if (!proxyServer && combinedProxyTools) {\n proxyServer = await self.ensureProxyServer(combinedProxyTools, sk)\n }\n\n // Whether the question proxy actually survived the version\n // gate (post-filter). Used to decide whether to inject the\n // QUESTION_PROXY_HINT — if the gate dropped the def, the\n // model must fall back to AskUserQuestion (the deny/markdown\n // path) and must NOT be told to call a proxy tool that does\n // not exist.\n const questionProxyActive =\n enrichedProxy?.some((t) => t.name === \"question\") ?? false\n\n // Compute disallowed flags from the POST-FILTER proxy list\n // (enrichedProxy), not the pre-filter one (resolvedProxy).\n // When the version gate drops `question` on an older opencode\n // build, AskUserQuestion must NOT be added to\n // --disallowedTools — otherwise the native tool is disabled\n // while the proxy replacement is absent, leaving the model\n // with no way to ask questions at all (neither proxy nor the\n // deny/markdown fallback path fires).\n const allDisallowed = resolveDisallowedTools({\n proxyTools: enrichedProxy,\n extraDisallowedTools: self.config.extraDisallowedTools,\n disableWebSearch: self.config.webSearch === \"disabled\",\n })\n const mcp = self.effectiveMcpConfig(\n cwd,\n proxyServer?.configPath(),\n runtimeStatus!,\n excludeServers,\n )\n const systemPromptFile = activeProcess\n ? undefined\n : buildAppendedSystemPrompt(\n cwd,\n self.config.multiStepContinuation !== false,\n [\n ...extractSystemMessages(options.prompt),\n ...(taskProxyEnabled ? [SUBAGENT_DISPATCH_HINT] : []),\n ...(questionProxyActive ? [QUESTION_PROXY_HINT] : []),\n ],\n {\n compressEnabled:\n enrichedProxy?.some((t) => t.name === \"compress\") ?? false,\n compressionSummary: getCompressionSummary(sk),\n },\n )\n cliArgs = buildCliArgs({\n sessionKey: sk,\n skipPermissions,\n model: spawnModelId,\n permissionMode: self.config.permissionMode,\n mcpConfig: mcp.paths,\n strictMcpConfig: self.config.strictMcpConfig,\n disallowedTools: allDisallowed.length > 0 ? allDisallowed : undefined,\n appendSystemPromptFile: systemPromptFile,\n ...self.thinkingCliOptions(),\n fastMode,\n cliVersion,\n })\n spawnSystemPromptFile = systemPromptFile\n spawnProxyServer = proxyServer\n spawnMcpHash = mcp.bridgedHash\n }\n\n if (activeProcess && !compactionMode) {\n proc = activeProcess.proc\n lineEmitter = activeProcess.lineEmitter\n log.debug(\"reusing active process\", { sk })\n } else {\n const ap = spawnClaudeProcess(\n cliPath,\n cliArgs,\n cwd,\n sk,\n spawnProxyServer,\n spawnMcpHash,\n spawnSystemPromptFile,\n self.config.ignoreAnthropicApiKey,\n reasoningEffort,\n )\n proc = ap.proc\n lineEmitter = ap.lineEmitter\n activeProcess = ap\n }\n }\n\n controller.enqueue({ type: \"stream-start\", warnings })\n\n let currentTextId: string | null = null\n const textBlockIndices = new Set<number>()\n\n const startTextBlock = (): string => {\n if (currentTextId) {\n controller.enqueue({ type: \"text-end\", id: currentTextId })\n }\n const id = generateId()\n currentTextId = id\n controller.enqueue({ type: \"text-start\", id } as any)\n return id\n }\n\n const endTextBlock = (): void => {\n if (currentTextId) {\n controller.enqueue({ type: \"text-end\", id: currentTextId })\n currentTextId = null\n }\n }\n\n const reasoningIds = new Map<number, string>()\n const reasoningStarted = new Map<number, boolean>()\n let hadThinkingTextFromStream = false\n\n let turnCompleted = false\n let controllerClosed = false\n // Buffered terminal results belong to the previous CLI turn.\n let unattendedTurnEnded = false\n let watchdogMessage = userMsg\n let pendingProxyUnsubscribe: (() => void) | null = null\n let asideSinkUnregister: (() => void) | null = null\n let resultFallbackTimer: ReturnType<typeof setTimeout> | null = null\n let pendingResultCompletion: (() => void) | null = null\n let hasReceivedContent = false\n let hasReceivedProgress = false\n let visibleTextSinceContinue = \"\"\n let lastVisibleTextSinceContinue = \"\"\n let hadReasoningSinceContinue = false\n let hadToolActivitySinceContinue = false\n let hadProxyActivitySinceContinue = false\n // v0.4.16: protocol-level stop signal captured from Claude CLI's\n // stream. Set by either the `message_delta` partial event or the\n // top-level `assistant` message, whichever arrives first.\n let lastStopReason: string | null = null\n const autoContinueState: AutoContinueState = {\n enabled: self.config.autoContinueIncompleteTurns,\n attempts: 0,\n startedAt: Date.now(),\n noProgressCount: 0,\n }\n\n const clearFallbackTimer = () => {\n if (resultFallbackTimer) {\n clearTimeout(resultFallbackTimer)\n resultFallbackTimer = null\n }\n }\n\n // Wire-inactivity watchdog. Resets on every line received from the\n // CLI; only fires if the CLI has emitted content and then gone\n // silent on stdout for `delayMs` without sending a `result`. The\n // previous design armed this on every text content_block_stop,\n // which killed legitimate mid-turn think pauses (most visibly\n // with sonnet between text-end and the next tool_use_start).\n const startResultFallback = (delayMs = 60_000) => {\n clearFallbackTimer()\n if ((!hasReceivedContent && !hasReceivedProgress) || controllerClosed) return\n resultFallbackTimer = setTimeout(() => {\n if (controllerClosed) return\n log.warn(\"result fallback timer fired — closing stream without result event\", {\n delayMs,\n })\n closeHandler()\n }, delayMs)\n }\n\n // Start watchdog: complementary to the inactivity watchdog above.\n // That one only arms once content has arrived; this one covers the\n // gap the other explicitly skips — a reused process that produces\n // NO stdout at all after a fresh-turn envelope write. Seen after a\n // very long proxy-blocked tool call resumed successfully (the child\n // stays silent on stdout). On first fire we respawn the child with\n // --session-id to resume the conversation transparently; on a\n // second fire (respawn also silent) we end the turn cleanly so the\n // next opencode turn spawns fresh. Tunable via env for reproduces.\n const START_WATCHDOG_MS = (() => {\n const env = process.env.CLAUDE_CODE_START_WATCHDOG_MS\n const parsed = env ? Number.parseInt(env, 10) : NaN\n return Number.isFinite(parsed) && parsed > 0 ? parsed : 90_000\n })()\n let startWatchdog: ReturnType<typeof setTimeout> | null = null\n let respawnAttempted = false\n const clearStartWatchdog = () => {\n if (startWatchdog) {\n clearTimeout(startWatchdog)\n startWatchdog = null\n }\n }\n const onStartWatchdogFire = () => {\n startWatchdog = null\n if (controllerClosed || hasReceivedContent || hasReceivedProgress) return\n if (respawnAttempted) {\n log.error(\n \"claude process still silent after respawn; ending turn\",\n { sessionKey: sk },\n )\n deleteActiveProcess(sk)\n deleteClaudeSessionId(sk)\n controllerClosed = true\n cleanupTurn()\n controller.enqueue({\n type: \"error\",\n error: new Error(\n \"Claude process produced no output after the envelope write (start watchdog timeout).\",\n ),\n })\n try {\n controller.close()\n } catch {}\n return\n }\n respawnAttempted = true\n log.warn(\n \"no stdout after envelope write; respawning claude process to resume conversation\",\n { sessionKey: sk, startWatchdogMs: START_WATCHDOG_MS },\n )\n lineEmitter.off(\"line\", lineHandler)\n lineEmitter.off(\"close\", closeHandler)\n proc.off(\"error\", procErrorHandler)\n const newAp = respawnActiveProcess(\n sk,\n cliPath,\n cliArgs,\n cwd,\n self.config.ignoreAnthropicApiKey,\n )\n if (!newAp) {\n log.error(\n \"no active process to respawn (start watchdog); ending turn\",\n { sessionKey: sk },\n )\n controllerClosed = true\n cleanupTurn()\n controller.enqueue({\n type: \"error\",\n error: new Error(\n \"No active claude process to respawn after start watchdog timeout.\",\n ),\n })\n try {\n controller.close()\n } catch {}\n return\n }\n proc = newAp.proc\n lineEmitter = newAp.lineEmitter\n activeProcess = newAp\n lineEmitter.on(\"line\", lineHandler)\n lineEmitter.on(\"close\", closeHandler)\n proc.on(\"error\", procErrorHandler)\n try {\n if (!deliverPendingCompletions(true)) proc.stdin?.write(watchdogMessage + \"\\n\")\n log.debug(\"re-sent user message after respawn\", {\n textLength: watchdogMessage.length,\n })\n } catch (err) {\n log.error(\"failed to re-send envelope after respawn\", {\n error: err instanceof Error ? err.message : String(err),\n })\n }\n armStartWatchdog()\n }\n const armStartWatchdog = () => {\n clearStartWatchdog()\n if (controllerClosed) return\n startWatchdog = setTimeout(onStartWatchdogFire, START_WATCHDOG_MS)\n }\n\n // Both buffered/live terminal boundaries and respawn consume through\n // this path. Open-channel results remain available for a later close.\n const deliverPendingCompletions = (force = false): boolean => {\n const pending = activeProcess?.pendingProxyCompletions\n const entries = [...(pending?.values() ?? [])].filter(\n (entry) => force || entry.recoveryRequired || isPendingProxyCallChannelClosed(entry.call),\n )\n if (entries.length === 0) return false\n endTextBlock()\n watchdogMessage = makeLateProxyResultMessage(entries)\n proc.stdin!.write(watchdogMessage + \"\\n\")\n for (const { call } of entries) pending!.delete(call.toolCallId)\n log.warn(\"delivering proxy results after interrupted continuation\", {\n sessionKey: sk,\n toolCallIds: entries.map(({ call }) => call.toolCallId),\n respawn: force,\n })\n gotPartialEvents = false\n hasReceivedContent = false\n hasReceivedProgress = false\n turnCompleted = false\n resetAutoContinueWindow()\n clearFallbackTimer()\n armStartWatchdog()\n return true\n }\n\n const toolCallMap = new Map<\n number,\n { id: string; name: string; inputJson: string; started: boolean }\n >()\n // Tool calls the plugin reported as providerExecuted:false — opencode\n // will run these itself and emit its own tool-result, so we must NOT\n // forward Claude CLI's tool_result for them (would short-circuit\n // opencode's execute).\n const skipResultForIds = new Set<string>()\n const toolCallsById = new Map<\n string,\n { id: string; name: string; input: unknown }\n >()\n\n let resultMeta: {\n sessionId?: string\n costUsd?: number\n durationMs?: number\n usage?: ClaudeStreamMessage[\"usage\"]\n } = {}\n\n // Batched drain so claude CLI's parallel tool_use blocks (e.g. two\n // bash calls in one assistant message) end up in a single\n // tool-calls finish event. Without this, the broker would reject\n // every overlapping call and claude would see spurious tool errors.\n const drainBuffer: PendingProxyCall[] = []\n let drainTimer: ReturnType<typeof setTimeout> | null = null\n const DRAIN_QUIET_MS = 100\n\n const finishWithToolCalls = (calls: PendingProxyCall[]) => {\n if (controllerClosed) return\n if (calls.length === 0) return\n for (const call of calls) {\n controller.enqueue({\n type: \"tool-input-start\",\n id: call.toolCallId,\n toolName: call.toolName,\n } as any)\n controller.enqueue({\n type: \"tool-call\",\n toolCallId: call.toolCallId,\n toolName: call.toolName,\n input: JSON.stringify(call.input),\n providerExecuted: false,\n } as any)\n skipResultForIds.add(call.toolCallId)\n markPendingProxyCallEmitted(call.toolCallId)\n }\n controller.enqueue({\n type: \"finish\",\n finishReason: toFinishReason(\"tool-calls\"),\n usage: toUsage(resultMeta.usage),\n providerMetadata: {\n \"claude-code\": resultMeta,\n },\n })\n controllerClosed = true\n cleanupTurn()\n try {\n controller.close()\n } catch {}\n }\n\n const finishWithExitPlanQuestion = (\n call: ReturnType<typeof createExitPlanModeQuestionCall>,\n ) => {\n if (controllerClosed) return\n endTextBlock()\n controller.enqueue({\n type: \"tool-input-start\",\n id: call.toolCallId,\n toolName: call.toolName,\n providerExecuted: false,\n } as any)\n controller.enqueue({\n type: \"tool-call\",\n toolCallId: call.toolCallId,\n toolName: call.toolName,\n input: JSON.stringify(call.input),\n providerExecuted: false,\n } as any)\n controller.enqueue({\n type: \"finish\",\n finishReason: toFinishReason(\"tool-calls\"),\n usage: toUsage(resultMeta.usage),\n providerMetadata: {\n \"claude-code\": resultMeta,\n },\n })\n controllerClosed = true\n cleanupTurn()\n try {\n controller.close()\n } catch {}\n }\n\n const drainNow = () => {\n if (drainTimer) {\n clearTimeout(drainTimer)\n drainTimer = null\n }\n if (drainBuffer.length === 0) return\n if (controllerClosed) return\n const batch = drainBuffer.splice(0, drainBuffer.length)\n log.info(\"draining pending proxy calls into stream finish\", {\n sessionKey: sk,\n count: batch.length,\n toolCallIds: batch.map((c) => c.toolCallId),\n })\n finishWithToolCalls(batch)\n }\n\n const settleResultBoundary = () => {\n drainTimer = null\n const completeResult = pendingResultCompletion\n pendingResultCompletion = null\n if (!completeResult || controllerClosed) return\n if (drainBuffer.length > 0) {\n drainNow()\n return\n }\n completeResult()\n }\n\n const scheduleResultBoundary = (\n completeResult: () => void,\n delayMs: number,\n ) => {\n pendingResultCompletion = completeResult\n if (drainTimer) clearTimeout(drainTimer)\n drainTimer = setTimeout(settleResultBoundary, delayMs)\n }\n\n const noteResultBoundaryCall = (): boolean => {\n if (!pendingResultCompletion) return false\n if (drainTimer) clearTimeout(drainTimer)\n drainTimer = setTimeout(settleResultBoundary, DRAIN_QUIET_MS)\n return true\n }\n\n const noteVisibleText = (text: string) => {\n visibleTextSinceContinue += text\n lastVisibleTextSinceContinue += text\n }\n\n const resetLastVisibleTextBlock = () => {\n lastVisibleTextSinceContinue = \"\"\n }\n\n const noteReasoning = () => {\n hadReasoningSinceContinue = true\n }\n\n const noteToolActivity = () => {\n hadToolActivitySinceContinue = true\n }\n\n const noteProxyActivity = () => {\n hadProxyActivitySinceContinue = true\n }\n\n const resetAutoContinueWindow = () => {\n visibleTextSinceContinue = \"\"\n lastVisibleTextSinceContinue = \"\"\n hadReasoningSinceContinue = false\n hadToolActivitySinceContinue = false\n hadProxyActivitySinceContinue = false\n lastStopReason = null\n }\n\n const completeResult = (msg: ClaudeStreamMessage) => {\n if (controllerClosed) return\n // The socket may have closed after the tool-result prompt was matched,\n // or while the result-boundary grace timer was running.\n if (deliverPendingCompletions()) {\n if (drainBuffer.length > 0) drainNow()\n return\n }\n if (drainBuffer.length > 0) {\n drainNow()\n return\n }\n\n const pendingSiblings = getPendingProxyCalls(sk)\n if (pendingSiblings.length > 0) {\n log.info(\"leaving parallel proxy calls pending at result boundary\", {\n sessionKey: sk,\n count: pendingSiblings.length,\n })\n }\n\n activeProcess?.pendingProxyCompletions?.clear()\n\n const autoDecision = shouldAutoContinueIncompleteTurn(\n autoContinueState,\n {\n text: visibleTextSinceContinue,\n lastVisibleText: lastVisibleTextSinceContinue,\n hadReasoning: hadReasoningSinceContinue,\n hadToolActivity: hadToolActivitySinceContinue,\n hadProxyActivity: hadProxyActivitySinceContinue,\n isError: msg.is_error,\n stopReason: lastStopReason,\n },\n )\n if (autoDecision.continue) {\n const signature = continuationSignature({\n text: visibleTextSinceContinue,\n lastVisibleText: lastVisibleTextSinceContinue,\n hadReasoning: hadReasoningSinceContinue,\n hadToolActivity: hadToolActivitySinceContinue,\n hadProxyActivity: hadProxyActivitySinceContinue,\n isError: msg.is_error,\n })\n autoContinueState.noProgressCount =\n signature === autoContinueState.lastSignature\n ? autoContinueState.noProgressCount + 1\n : 0\n autoContinueState.lastSignature = signature\n autoContinueState.attempts++\n log.notice(\"auto-continuing incomplete claude result\", {\n sessionKey: sk,\n reason: autoDecision.reason,\n attempts: autoContinueState.attempts,\n textLength: visibleTextSinceContinue.length,\n lastTextLength: lastVisibleTextSinceContinue.length,\n hadReasoning: hadReasoningSinceContinue,\n hadToolActivity: hadToolActivitySinceContinue,\n hadProxyActivity: hadProxyActivitySinceContinue,\n })\n turnCompleted = false\n resetAutoContinueWindow()\n proc.stdin?.write(makeAutoContinueMessage() + \"\\n\")\n return\n }\n log.notice(\"auto-continuation stopped\", {\n sessionKey: sk,\n reason: autoDecision.reason,\n stopReason: lastStopReason,\n attempts: autoContinueState.attempts,\n textLength: visibleTextSinceContinue.length,\n lastTextLength: lastVisibleTextSinceContinue.length,\n hadReasoning: hadReasoningSinceContinue,\n hadToolActivity: hadToolActivitySinceContinue,\n hadProxyActivity: hadProxyActivitySinceContinue,\n })\n\n for (const [idx, reasoningId] of reasoningIds) {\n if (reasoningStarted.get(idx)) {\n controller.enqueue({\n type: \"reasoning-end\",\n id: reasoningId,\n } as any)\n }\n }\n\n controller.enqueue({\n type: \"finish\",\n finishReason: toFinishReason(\"stop\"),\n usage: toUsage(msg.usage),\n providerMetadata: {\n \"claude-code\": {\n ...resultMeta,\n ...(compactionMode\n ? { compactionModel: effectiveModelId }\n : {}),\n },\n ...(typeof msg.usage?.cache_creation_input_tokens === \"number\"\n ? {\n anthropic: {\n cacheCreationInputTokens:\n msg.usage.cache_creation_input_tokens,\n },\n }\n : {}),\n },\n })\n\n controllerClosed = true\n cleanupTurn()\n\n try {\n controller.close()\n } catch {}\n }\n\n // Set true once we observe a `stream_event` envelope. When on, the\n // top-level `assistant` message is a duplicate of what we already\n // streamed via content_block_* deltas — skip its content.\n let gotPartialEvents = false\n\n const lineHandler = (line: string) => {\n if (!line.trim()) return\n if (controllerClosed) return\n\n // Any line from the CLI counts as activity — reset the inactivity\n // watchdog so mid-turn pauses between blocks don't get killed.\n startResultFallback()\n\n try {\n const outer: ClaudeStreamMessage = JSON.parse(line)\n\n // Unwrap stream_event envelope (--include-partial-messages).\n // Inner event uses the same content_block_* / message_* shape.\n const msg: ClaudeStreamMessage =\n outer.type === \"stream_event\" && outer.event\n ? { ...outer.event, session_id: outer.session_id }\n : outer\n\n const modelProgress =\n (msg.type === \"assistant\" && !!msg.message?.content?.length) ||\n (msg.type === \"content_block_start\" && msg.content_block?.type === \"tool_use\") ||\n (msg.type === \"content_block_delta\" &&\n ((msg.delta?.type === \"text_delta\" && !!msg.delta.text) ||\n (msg.delta?.type === \"thinking_delta\" && !!msg.delta.thinking)))\n if (modelProgress) {\n hasReceivedProgress = true\n clearStartWatchdog()\n startResultFallback()\n }\n\n if (outer.type === \"stream_event\") {\n gotPartialEvents = true\n }\n\n if (handleControlRequest(msg, proc)) {\n return\n }\n\n log.debug(\"stream message\", {\n type: msg.type,\n subtype: msg.subtype,\n })\n\n // Handle system init\n if (msg.type === \"system\" && msg.subtype === \"init\") {\n if (msg.session_id) {\n setClaudeSessionId(sk, msg.session_id)\n log.info(\"session initialized\", {\n claudeSessionId: msg.session_id,\n })\n }\n reportFastModeState(msg, fastMode)\n }\n\n // content_block_start\n if (\n msg.type === \"content_block_start\" &&\n msg.content_block &&\n msg.index !== undefined\n ) {\n const block = msg.content_block\n const idx = msg.index\n\n if (block.type === \"thinking\") {\n noteReasoning()\n const reasoningId = generateId()\n reasoningIds.set(idx, reasoningId)\n }\n\n if (block.type === \"text\") {\n textBlockIndices.add(idx)\n // New text block — clear last-block buffer so final-answer\n // detection only considers this block's contents, not earlier\n // mid-task narration.\n resetLastVisibleTextBlock()\n if (block.text) {\n if (!currentTextId) startTextBlock()\n controller.enqueue({\n type: \"text-delta\",\n id: currentTextId!,\n delta: block.text,\n })\n noteVisibleText(block.text)\n hasReceivedContent = true\n }\n }\n\n if (block.type === \"tool_use\" && block.id && block.name) {\n noteToolActivity()\n const entry = {\n id: block.id,\n name: block.name,\n inputJson: \"\",\n started: false,\n }\n toolCallMap.set(idx, entry)\n\n if (\n block.name !== \"AskUserQuestion\" &&\n block.name !== \"ask_user_question\" &&\n block.name !== \"ExitPlanMode\" &&\n !block.name.startsWith(PROXY_TOOL_PREFIX)\n ) {\n const { name: mappedName, skip, executed } = mapTool(\n block.name,\n undefined,\n {\n webSearch: self.config.webSearch,\n sessionId: getClaudeSessionId(sk),\n toolUseId: block.id,\n },\n )\n if (!skip) {\n entry.started = true\n controller.enqueue({\n type: \"tool-input-start\",\n id: block.id,\n toolName: mappedName,\n providerExecuted: executed,\n } as any)\n log.info(\"tool started\", {\n name: block.name,\n mappedName,\n id: block.id,\n })\n }\n }\n }\n }\n\n // content_block_delta\n if (\n msg.type === \"content_block_delta\" &&\n msg.delta &&\n msg.index !== undefined\n ) {\n const delta = msg.delta\n const idx = msg.index\n\n if (delta.type === \"thinking_delta\" && delta.thinking) {\n noteReasoning()\n hadThinkingTextFromStream = true\n const reasoningId = reasoningIds.get(idx)\n if (reasoningId) {\n if (!reasoningStarted.get(idx)) {\n controller.enqueue({\n type: \"reasoning-start\",\n id: reasoningId,\n } as any)\n reasoningStarted.set(idx, true)\n }\n controller.enqueue({\n type: \"reasoning-delta\",\n id: reasoningId,\n delta: delta.thinking,\n } as any)\n }\n }\n\n if (delta.type === \"text_delta\" && delta.text) {\n if (!currentTextId) startTextBlock()\n controller.enqueue({\n type: \"text-delta\",\n id: currentTextId!,\n delta: delta.text,\n })\n noteVisibleText(delta.text)\n hasReceivedContent = true\n }\n\n if (delta.type === \"input_json_delta\" && delta.partial_json) {\n const tc = toolCallMap.get(idx)\n if (tc) {\n tc.inputJson += delta.partial_json\n // Only forward deltas for tool calls whose tool-input-start\n // was actually emitted. Skipped tools (CLAUDE_INTERNAL_TOOLS,\n // TaskCreate/TaskUpdate, CLI-internal WebSearch, AskUserQuestion,\n // ExitPlanMode, proxy tools) never get a named start part, so\n // forwarding their deltas makes opencode's AI SDK bridge fall\n // back to a nameless pending part rendered as `⚙ unknown`.\n if (tc.started) {\n controller.enqueue({\n type: \"tool-input-delta\",\n id: tc.id,\n delta: delta.partial_json,\n } as any)\n }\n }\n }\n\n if (!KNOWN_DELTA_TYPES.has(delta.type)) {\n log.debug(\"unrecognized content_block_delta type\", {\n type: delta.type,\n idx,\n keys: Object.keys(delta),\n })\n }\n }\n\n // content_block_stop\n if (\n msg.type === \"content_block_stop\" &&\n msg.index !== undefined\n ) {\n const idx = msg.index\n\n const reasoningId = reasoningIds.get(idx)\n if (reasoningId && reasoningStarted.get(idx)) {\n controller.enqueue({\n type: \"reasoning-end\",\n id: reasoningId,\n } as any)\n reasoningStarted.delete(idx)\n }\n\n if (textBlockIndices.has(idx)) {\n endTextBlock()\n textBlockIndices.delete(idx)\n }\n\n const tc = toolCallMap.get(idx)\n if (tc) {\n // Block indices restart at 0 on every assistant message, and a\n // turn can hold several (tool_use -> tool_result -> answer).\n // Without this delete the entry outlives its message, so the\n // next message's block at the same index re-emits a tool-call\n // for an id opencode already completed. That second part never\n // gets a result, opencode aborts it at stream end, and a\n // subagent's `task` call reports \"Tool execution aborted\"\n // even though the child answered correctly.\n toolCallMap.delete(idx)\n let parsedInput: any = {}\n try {\n parsedInput = JSON.parse(tc.inputJson || \"{}\")\n } catch {}\n\n if (isAskUserQuestionTool(tc.name)) {\n // Latch: the model handed control to the operator. Block any\n // auto-continue nudge for the rest of the turn so it can't\n // proceed on its own before the operator replies.\n autoContinueState.sawAskUserQuestion = true\n const askId = startTextBlock()\n controller.enqueue({\n type: \"text-delta\",\n id: askId,\n delta: formatAskUserQuestion(parsedInput),\n })\n endTextBlock()\n } else if (tc.name === \"ExitPlanMode\") {\n const plan = (parsedInput?.plan as string) || \"\"\n\n if (planModeQuestionActive) {\n // Approval bridge: render the plan, then hand the\n // yes/no back to opencode's own `question` tool and end\n // the turn on \"tool-calls\" so the outer loop runs it.\n const questionCall = createExitPlanModeQuestionCall(\n sk,\n tc.id,\n plan,\n )\n const planId = startTextBlock()\n controller.enqueue({\n type: \"text-delta\",\n id: planId,\n delta: questionCall.text,\n })\n finishWithExitPlanQuestion(questionCall)\n return\n }\n\n const planId = startTextBlock()\n controller.enqueue({\n type: \"text-delta\",\n id: planId,\n delta: `\\n\\n${plan}\\n\\n---\\n**Do you want to proceed with this plan?** (yes/no)\\n`,\n })\n endTextBlock()\n } else if (\n isWebSearchTool(tc.name) &&\n isWebSearchHandledByCli(self.config.webSearch)\n ) {\n // Claude CLI runs WebSearch internally. Forwarding the\n // \"WebSearch\" tool-call part would render an invalid tool\n // row in opencode (no registry entry), so show the query\n // as a text line instead. The result stays CLI-internal.\n const query =\n typeof parsedInput?.query === \"string\"\n ? parsedInput.query\n : JSON.stringify(parsedInput)\n const searchId = startTextBlock()\n controller.enqueue({\n type: \"text-delta\",\n id: searchId,\n delta: `\\n> **Web search:** ${query}\\n`,\n })\n endTextBlock()\n } else if (tc.name.startsWith(PROXY_TOOL_PREFIX)) {\n noteProxyActivity()\n log.debug(\"ignoring proxy tool_use block; broker handles it\", {\n name: tc.name,\n id: tc.id,\n })\n } else {\n const {\n name: mappedName,\n input: mappedInput,\n executed,\n skip,\n } = mapTool(tc.name, parsedInput, {\n webSearch: self.config.webSearch,\n sessionId: getClaudeSessionId(sk),\n toolUseId: tc.id,\n })\n\n if (!skip) {\n toolCallsById.set(tc.id, {\n id: tc.id,\n name: tc.name,\n input: parsedInput,\n })\n if (!executed) skipResultForIds.add(tc.id)\n\n controller.enqueue({\n type: \"tool-call\",\n toolCallId: tc.id,\n toolName: mappedName,\n input: JSON.stringify(mappedInput),\n providerExecuted: executed,\n } as any)\n }\n log.info(\"tool call complete\", {\n name: tc.name,\n mappedName,\n id: tc.id,\n executed,\n })\n }\n }\n }\n\n // Capture protocol-level stop_reason from the streaming\n // `message_delta` event (sent right before the final\n // `message_stop`). Any non-empty value is the source-of-truth\n // for why the turn ended — used to bypass the keyword heuristic.\n if (\n gotPartialEvents &&\n msg.type === \"message_delta\" &&\n typeof (msg as any).delta?.stop_reason === \"string\"\n ) {\n lastStopReason = (msg as any).delta.stop_reason\n }\n\n // assistant message (complete, not streaming).\n // When --include-partial-messages is on, this is a duplicate of\n // what we already streamed via content_block_* events. Skip it\n // for content, but still capture stop_reason from it for the\n // non-partial path.\n if (\n msg.type === \"assistant\" &&\n msg.message &&\n typeof (msg.message as any).stop_reason === \"string\"\n ) {\n lastStopReason = (msg.message as any).stop_reason\n }\n // Fallback: extract thinking from the complete assistant\n // message. opus-4-7's CLI strips thinking_delta from stream\n // events but may include thinking in the final message.\n if (\n msg.type === \"assistant\" &&\n msg.message?.content &&\n gotPartialEvents\n ) {\n const thinkingBlocks = (msg.message.content as any[]).filter(\n (b) => b.type === \"thinking\",\n )\n if (thinkingBlocks.length > 0) {\n log.info(\"assistant message thinking blocks\", {\n count: thinkingBlocks.length,\n hasText: thinkingBlocks.some(\n (b) => typeof b.thinking === \"string\" && b.thinking.length > 0,\n ),\n hadStreamThinking: hadThinkingTextFromStream,\n })\n if (!hadThinkingTextFromStream) {\n for (const block of thinkingBlocks) {\n if (block.thinking && block.thinking.length > 0) {\n noteReasoning()\n hadThinkingTextFromStream = true\n const thinkingId = generateId()\n controller.enqueue({\n type: \"reasoning-start\",\n id: thinkingId,\n } as any)\n controller.enqueue({\n type: \"reasoning-delta\",\n id: thinkingId,\n delta: block.thinking,\n } as any)\n controller.enqueue({\n type: \"reasoning-end\",\n id: thinkingId,\n } as any)\n }\n }\n }\n }\n }\n if (\n msg.type === \"assistant\" &&\n msg.message?.content &&\n !gotPartialEvents\n ) {\n const hasText = msg.message.content.some(\n (b: any) => b.type === \"text\" && b.text,\n )\n const hasToolUse = msg.message.content.some(\n (b: any) => b.type === \"tool_use\",\n )\n\n if (hasText) {\n hasReceivedContent = true\n }\n\n if (hasText && !hasToolUse) {\n startResultFallback()\n }\n if (hasToolUse) {\n clearFallbackTimer()\n }\n\n for (const block of msg.message.content) {\n if (block.type === \"text\" && block.text) {\n // New text block — keep only this block's text in the\n // last-block buffer for final-answer detection.\n resetLastVisibleTextBlock()\n const blockId = startTextBlock()\n controller.enqueue({\n type: \"text-delta\",\n id: blockId,\n delta: block.text,\n })\n endTextBlock()\n noteVisibleText(block.text)\n hasReceivedContent = true\n }\n\n if (block.type === \"thinking\" && block.thinking) {\n noteReasoning()\n const thinkingId = generateId()\n controller.enqueue({\n type: \"reasoning-start\",\n id: thinkingId,\n } as any)\n controller.enqueue({\n type: \"reasoning-delta\",\n id: thinkingId,\n delta: block.thinking,\n } as any)\n controller.enqueue({\n type: \"reasoning-end\",\n id: thinkingId,\n } as any)\n }\n\n if (block.type === \"tool_use\" && block.id && block.name) {\n noteToolActivity()\n const parsedInput = (block.input ?? {}) as Record<\n string,\n unknown\n >\n\n if (isAskUserQuestionTool(block.name)) {\n const askId = startTextBlock()\n controller.enqueue({\n type: \"text-delta\",\n id: askId,\n delta: formatAskUserQuestion(parsedInput),\n })\n endTextBlock()\n } else if (block.name === \"ExitPlanMode\") {\n const plan = (parsedInput?.plan as string) || \"\"\n\n if (planModeQuestionActive) {\n const questionCall = createExitPlanModeQuestionCall(\n sk,\n block.id,\n plan,\n )\n const planId = startTextBlock()\n controller.enqueue({\n type: \"text-delta\",\n id: planId,\n delta: questionCall.text,\n })\n finishWithExitPlanQuestion(questionCall)\n return\n }\n\n const planId = startTextBlock()\n controller.enqueue({\n type: \"text-delta\",\n id: planId,\n delta: `\\n\\n${plan}\\n\\n---\\n**Do you want to proceed with this plan?** (yes/no)\\n`,\n })\n endTextBlock()\n } else if (\n isWebSearchTool(block.name) &&\n isWebSearchHandledByCli(self.config.webSearch)\n ) {\n // CLI-internal WebSearch: render the query as text and\n // drop the call/result parts (no opencode registry entry\n // for \"WebSearch\" — would render as an invalid tool row).\n toolCallsById.delete(block.id)\n const query =\n typeof parsedInput?.query === \"string\"\n ? parsedInput.query\n : JSON.stringify(parsedInput)\n const searchId = startTextBlock()\n controller.enqueue({\n type: \"text-delta\",\n id: searchId,\n delta: `\\n> **Web search:** ${query}\\n`,\n })\n endTextBlock()\n } else if (block.name.startsWith(PROXY_TOOL_PREFIX)) {\n noteProxyActivity()\n log.debug(\"ignoring proxy tool_use from assistant message\", {\n name: block.name,\n id: block.id,\n })\n } else {\n const {\n name: mappedName,\n input: mappedInput,\n executed,\n skip,\n } = mapTool(block.name, parsedInput, {\n webSearch: self.config.webSearch,\n sessionId: getClaudeSessionId(sk),\n toolUseId: block.id,\n })\n\n if (!skip) {\n toolCallsById.set(block.id, {\n id: block.id,\n name: block.name,\n input: parsedInput,\n })\n if (!executed) skipResultForIds.add(block.id)\n controller.enqueue({\n type: \"tool-input-start\",\n id: block.id,\n toolName: mappedName,\n providerExecuted: executed,\n } as any)\n controller.enqueue({\n type: \"tool-call\",\n toolCallId: block.id,\n toolName: mappedName,\n input: JSON.stringify(mappedInput),\n providerExecuted: executed,\n } as any)\n }\n log.info(\"tool_use from assistant message\", {\n name: block.name,\n mappedName,\n id: block.id,\n executed,\n })\n }\n }\n\n if (block.type === \"tool_result\") {\n log.debug(\"tool_result\", {\n toolUseId: block.tool_use_id,\n })\n }\n }\n }\n\n // user message (tool results from Claude CLI)\n if (msg.type === \"user\" && msg.message?.content) {\n for (const block of msg.message.content) {\n if (block.type === \"tool_result\" && block.tool_use_id) {\n if (skipResultForIds.has(block.tool_use_id)) {\n log.debug(\"skipping tool-result (opencode runs it)\", {\n toolUseId: block.tool_use_id,\n })\n continue\n }\n\n let resultText = \"\"\n if (typeof block.content === \"string\") {\n resultText = block.content\n } else if (Array.isArray(block.content)) {\n resultText = block.content\n .filter(\n (\n c,\n ): c is { type: string; text: string } =>\n c.type === \"text\" &&\n typeof c.text === \"string\",\n )\n .map((c) => c.text)\n .join(\"\\n\")\n }\n\n // Ledger hook: commit pending TaskCreate to opencode's todo\n // panel via a synthetic todowrite emission. Pass-through —\n // returns null for non-TaskCreate ids, so cheap and silent.\n const claudeSessionId = getClaudeSessionId(sk)\n if (claudeSessionId) {\n const list = applyTaskCreateToolResult(\n claudeSessionId,\n block.tool_use_id,\n resultText,\n )\n if (list) {\n const synthId = `todowrite_${block.tool_use_id}`\n controller.enqueue({\n type: \"tool-input-start\",\n id: synthId,\n toolName: \"todowrite\",\n providerExecuted: false,\n } as any)\n controller.enqueue({\n type: \"tool-call\",\n toolCallId: synthId,\n toolName: \"todowrite\",\n input: JSON.stringify({\n todos: list.map((t) => ({\n id: t.id,\n content: t.content,\n status: t.status,\n priority: \"medium\",\n })),\n }),\n providerExecuted: false,\n } as any)\n noteToolActivity()\n }\n }\n\n const toolCall = toolCallsById.get(block.tool_use_id)\n if (toolCall) {\n controller.enqueue({\n type: \"tool-result\",\n toolCallId: block.tool_use_id,\n toolName: toolCall.name,\n result: {\n output: resultText,\n title: toolCall.name,\n metadata: {},\n },\n providerExecuted: true,\n } as any)\n noteToolActivity()\n log.info(\"tool result emitted\", {\n toolUseId: block.tool_use_id,\n name: toolCall.name,\n })\n toolCallsById.delete(block.tool_use_id)\n }\n }\n }\n }\n\n // result - end of conversation turn\n if (msg.type === \"result\") {\n clearFallbackTimer()\n\n if (msg.session_id) {\n setClaudeSessionId(sk, msg.session_id)\n }\n\n if (deliverPendingCompletions()) {\n // Finish the abandoned turn before submitting its late result.\n // Otherwise this result could close the stream for the new turn.\n return\n }\n\n // Some CLI failures only include user-readable text in\n // `result.result` (no prior assistant text blocks). Emit it so\n // opencode users don't see a blank turn.\n if (\n !currentTextId &&\n msg.is_error &&\n typeof msg.result === \"string\" &&\n msg.result.trim().length > 0\n ) {\n const errId = startTextBlock()\n controller.enqueue({\n type: \"text-delta\",\n id: errId,\n delta: msg.result,\n })\n }\n\n resultMeta = {\n sessionId: msg.session_id,\n costUsd: msg.total_cost_usd,\n durationMs: msg.duration_ms,\n usage: msg.usage,\n }\n\n log.info(\"conversation result\", {\n sessionId: msg.session_id,\n durationMs: msg.duration_ms,\n numTurns: msg.num_turns,\n isError: msg.is_error,\n })\n\n turnCompleted = true\n\n endTextBlock()\n\n const shouldDeferResult =\n !msg.is_error &&\n !autoContinueState.aborted &&\n !autoContinueState.sawAskUserQuestion\n\n if (drainBuffer.length > 0 && shouldDeferResult) {\n log.info(\n \"waiting for parallel proxy calls at turn-result boundary\",\n {\n sessionKey: sk,\n count: drainBuffer.length,\n },\n )\n scheduleResultBoundary(\n () => completeResult(msg),\n DRAIN_QUIET_MS,\n )\n return\n }\n\n if (\n drainBuffer.length === 0 &&\n hadProxyActivitySinceContinue &&\n shouldDeferResult\n ) {\n log.info(\n \"waiting for delayed proxy call at turn-result boundary\",\n {\n sessionKey: sk,\n graceMs: PROXY_RESULT_BOUNDARY_GRACE_MS,\n },\n )\n scheduleResultBoundary(\n () => completeResult(msg),\n PROXY_RESULT_BOUNDARY_GRACE_MS,\n )\n return\n }\n\n completeResult(msg)\n }\n } catch (e) {\n log.debug(\"failed to parse line\", {\n error:\n e instanceof Error ? e.message : String(e),\n })\n }\n }\n\n const closeHandler = () => {\n log.debug(\"readline closed\")\n if (controllerClosed) return\n // Claude CLI's stdio is gone. The proxy-mcp HTTP requests that\n // backed any pending tool calls have no one to answer them now —\n // reject so the handlers return errors rather than hang.\n if (drainBuffer.length > 0 || getPendingProxyCalls(sk).length > 0) {\n rejectAllPendingProxyCallsForSession(\n sk,\n new Error(\n \"Claude CLI subprocess closed before pending tool calls were resolved\",\n ),\n )\n drainBuffer.length = 0\n }\n controllerClosed = true\n cleanupTurn()\n endTextBlock()\n controller.enqueue({\n type: \"finish\",\n finishReason: toFinishReason(\"stop\"),\n usage: toUsage(),\n providerMetadata: {\n \"claude-code\": {\n ...resultMeta,\n ...(compactionMode\n ? { compactionModel: effectiveModelId }\n : {}),\n },\n },\n })\n try {\n controller.close()\n } catch {}\n }\n\n // Centralised per-turn teardown. Every exit path funnels through here\n // so we don't accumulate listeners across turns on a reused process.\n let cleanedUp = false\n const cleanupTurn = () => {\n if (cleanedUp) return\n cleanedUp = true\n clearFallbackTimer()\n pendingResultCompletion = null\n clearStartWatchdog()\n if (drainTimer) {\n clearTimeout(drainTimer)\n drainTimer = null\n }\n lineEmitter.off(\"line\", lineHandler)\n lineEmitter.off(\"close\", closeHandler)\n pendingProxyUnsubscribe?.()\n pendingProxyUnsubscribe = null\n asideSinkUnregister?.()\n asideSinkUnregister = null\n proc.off(\"error\", procErrorHandler)\n }\n\n const procErrorHandler = (err: Error) => {\n log.error(\"process error\", { error: err.message })\n deleteActiveProcess(sk)\n deleteClaudeSessionId(sk)\n if (controllerClosed) return\n // Subprocess failure invalidates every pending HTTP-bound tool\n // call for this session. Reject them so proxy-mcp returns errors\n // to Claude rather than letting the sockets stall.\n if (drainBuffer.length > 0 || getPendingProxyCalls(sk).length > 0) {\n rejectAllPendingProxyCallsForSession(\n sk,\n new Error(\n `Claude CLI subprocess error: ${err.message}`,\n ),\n )\n drainBuffer.length = 0\n }\n controllerClosed = true\n cleanupTurn()\n controller.enqueue({ type: \"error\", error: err })\n try {\n controller.close()\n } catch {}\n }\n\n // Whatever the child said while no turn was listening comes first:\n // the operator gets to see it, and a turn that already ended on the\n // CLI's side is known before this one decides what to send.\n if (activeProcess) {\n const unattended = takeUnattendedLines(activeProcess)\n if (unattended.lines.length > 0 || unattended.dropped > 0) {\n log.notice(\"replaying stdout the child emitted between turns\", {\n sessionKey: sk,\n lines: unattended.lines.length,\n dropped: unattended.dropped,\n })\n // Render narration only. Replaying actionable events could execute\n // old tools or close this new stream on a stale approval/result.\n let partialText = false\n {\n if (unattended.dropped > 0) {\n const id = startTextBlock()\n controller.enqueue({\n type: \"text-delta\",\n id,\n delta: `> _${unattended.dropped} lines of output emitted between turns were dropped._\\n\\n`,\n })\n }\n for (const line of unattended.lines) {\n try {\n const outer: ClaudeStreamMessage = JSON.parse(line)\n const msg = outer.type === \"stream_event\" && outer.event ? outer.event : outer\n let text = \"\"\n if (msg.type === \"content_block_delta\" && msg.delta?.type === \"text_delta\") {\n text = msg.delta.text ?? \"\"\n partialText = true\n } else if (msg.type === \"assistant\") {\n if (!partialText) text = (msg.message?.content ?? []).filter((part) => part.type === \"text\").map((part) => part.text ?? \"\").join(\"\")\n partialText = false\n } else if (msg.type === \"result\") {\n unattendedTurnEnded = true\n for (const entry of activeProcess.pendingProxyCompletions?.values() ?? []) {\n if (isPendingProxyCallChannelClosed(entry.call)) entry.recoveryRequired = true\n }\n if (outer.session_id) setClaudeSessionId(sk, outer.session_id)\n if (msg.is_error && msg.result) text = msg.result\n }\n if (text) controller.enqueue({ type: \"text-delta\", id: startTextBlock(), delta: text })\n } catch { /* Ignore incomplete or malformed buffered lines. */ }\n }\n }\n endTextBlock()\n // Replayed lines are history, not liveness: the watchdogs below\n // must judge the child on what it does from here on.\n clearFallbackTimer()\n hasReceivedContent = false\n }\n }\n\n if (activeProcess && !compactionMode) {\n activeProcess.opencodeSessionID = affinity\n activeProcess.asideTransport = asideTransportRef\n }\n if (!compactionMode) {\n // Lets a `/btw` answered while this turn runs land in the turn's own\n // reply instead of a toast (btw-command.ts). Its own text block, so\n // the marker stays at the start of a part and the block can be\n // stripped exactly when a transcript is rebuilt.\n asideSinkUnregister = registerAsideSink(affinity, (text) => {\n if (controllerClosed) return false\n const asideId = startTextBlock()\n controller.enqueue({ type: \"text-delta\", id: asideId, delta: text })\n endTextBlock()\n return true\n })\n }\n lineEmitter.on(\"line\", lineHandler)\n lineEmitter.on(\"close\", closeHandler)\n\n pendingProxyUnsubscribe = onPendingProxyCall(sk, (call) => {\n if (controllerClosed) {\n // Stream already closed (we already drained). Late arrival —\n // reject immediately so the proxy-mcp HTTP request returns\n // instead of hanging until its 10-min timeout.\n log.warn(\n \"pending proxy call arrived after stream close; rejecting\",\n {\n sessionKey: sk,\n toolCallId: call.toolCallId,\n toolName: call.toolName,\n },\n )\n rejectPendingProxyCallById(\n call.toolCallId,\n new Error(\n `Pending proxy call '${call.toolName}' arrived after the stream was already closed`,\n ),\n )\n return\n }\n log.info(\"received pending proxy call for session\", {\n sessionKey: sk,\n toolCallId: call.toolCallId,\n toolName: call.toolName,\n })\n noteProxyActivity()\n noteToolActivity()\n drainBuffer.push(call)\n if (noteResultBoundaryCall()) return\n if (drainTimer) clearTimeout(drainTimer)\n drainTimer = setTimeout(drainNow, DRAIN_QUIET_MS)\n })\n\n proc.on(\"error\", procErrorHandler)\n\n // On abort, keep process alive for next message\n if (options.abortSignal) {\n options.abortSignal.addEventListener(\"abort\", () => {\n autoContinueState.aborted = true\n if (turnCompleted || controllerClosed) return\n\n if (!hasReceivedContent) {\n log.info(\n \"abort signal received before content, closing stream immediately\",\n { cwd },\n )\n if (\n drainBuffer.length > 0 ||\n getPendingProxyCalls(sk).length > 0\n ) {\n rejectAllPendingProxyCallsForSession(\n sk,\n new Error(\n \"Provider stream was aborted before pending proxy calls were emitted\",\n ),\n )\n drainBuffer.length = 0\n }\n controllerClosed = true\n cleanupTurn()\n try {\n controller.close()\n } catch {}\n return\n }\n\n log.info(\n \"abort signal received mid-turn, starting grace period\",\n { cwd },\n )\n // Abort grace period — short, since the user already asked to stop.\n startResultFallback(5_000)\n })\n }\n\n if (hasMatchedPendingResults) {\n // Tool-result turn: the prompt carries opencode's results for the\n // proxy tool calls we drained on the previous turn. Resolve each\n // matched call (claude CLI's HTTP handlers wake up and continue).\n // Parallel tools may complete in separate opencode turns. Keep\n // unmatched siblings pending until their own result, an explicit\n // abort/new user turn, or the proxy deadline.\n for (const { call, result } of previousPendingProxyMatches) {\n if (result) {\n const channelClosed = isPendingProxyCallChannelClosed(call)\n log.info(\"resolving pending proxy call from tool result prompt\", {\n sessionKey: sk,\n toolCallId: call.toolCallId,\n toolName: call.toolName,\n channelClosed,\n })\n const completions = (activeProcess!.pendingProxyCompletions ??= new Map())\n if (!completions.has(call.toolCallId)) {\n completions.set(call.toolCallId, {\n call,\n result,\n recoveryRequired: channelClosed || unattendedTurnEnded,\n })\n }\n // With a closed channel this only clears the broker entry;\n // proxy-mcp drops the write and the result travels below.\n resolvePendingProxyCallById(call.toolCallId, result)\n } else {\n log.info(\n \"leaving unmatched parallel proxy call pending\",\n {\n sessionKey: sk,\n toolCallId: call.toolCallId,\n toolName: call.toolName,\n },\n )\n }\n }\n\n if (unattendedTurnEnded) deliverPendingCompletions()\n\n // Calls queued while no turn was attached were never handed to\n // opencode; the child is blocked on them right now.\n const unemitted = getPendingProxyCalls(sk).filter(\n (call) => !call.emitted,\n )\n if (unemitted.length > 0) {\n log.notice(\"draining proxy calls queued between turns\", {\n sessionKey: sk,\n toolCallIds: unemitted.map((call) => call.toolCallId),\n })\n drainBuffer.push(...unemitted)\n drainNow()\n return\n }\n\n if (getPendingProxyCalls(sk).length === 0) {\n armStartWatchdog()\n }\n return\n }\n\n // No pending calls had matching tool-results. If any pending calls\n // are still hanging around from a prior turn, reject them so the\n // HTTP handlers in proxy-mcp don't sit blocked forever while we\n // proceed with a brand new user message.\n if (previousPendingProxyCalls.length > 0) {\n for (const call of previousPendingProxyCalls) {\n rejectPendingProxyCallById(\n call.toolCallId,\n new Error(\n `Pending proxy call '${call.toolName}' (${call.toolCallId}) was orphaned by a new user turn; rejecting`,\n ),\n )\n }\n }\n\n // Send the user message for a fresh turn.\n proc.stdin?.write(userMsg + \"\\n\")\n log.debug(\"sent user message\", { textLength: userMsg.length })\n // Arm the start watchdog so a reused child that goes silent after\n // the envelope write (seen after a long proxy-blocked tool call)\n // is respawned with --session-id instead of hanging the turn.\n armStartWatchdog()\n }\n\n void setup().catch((err) => {\n log.error(\"failed to set up doStream\", {\n error: err instanceof Error ? err.message : String(err),\n })\n controller.enqueue({\n type: \"error\",\n error: err instanceof Error ? err : new Error(String(err)),\n })\n try {\n controller.close()\n } catch {}\n })\n },\n cancel() {\n // Consumer cancelled the stream\n },\n })\n\n return {\n stream,\n request: { body: { text: userMsg } },\n response: { headers: {} },\n }\n }\n}\n","import { appendFileSync, mkdirSync, renameSync, statSync } from \"node:fs\"\nimport { homedir } from \"node:os\"\nimport { dirname, join } from \"node:path\"\n\nexport type LogLevel = \"debug\" | \"info\" | \"notice\" | \"warn\" | \"error\"\nexport type LogMode = \"silent\" | \"debug\"\n\nexport interface LoggerConfig {\n file: boolean\n dir: string | null\n mode: LogMode\n level: LogLevel\n}\n\nconst LEVEL_RANK: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n notice: 2,\n warn: 3,\n error: 4,\n}\n\nconst MAX_LOG_BYTES = 5 * 1024 * 1024 // 5 MB\nconst DEFAULT_DIR = join(homedir(), \".local\", \"share\", \"opencode-claude-code\")\n\nconst DEFAULT_CONFIG: LoggerConfig = {\n file: false,\n dir: null,\n mode: \"silent\",\n level: \"info\",\n}\n\nfunction parseBoolEnv(v: string | undefined): boolean | undefined {\n if (v == null) return undefined\n const s = v.toLowerCase().trim()\n if (s === \"\") return undefined\n if (s === \"0\" || s === \"false\" || s === \"no\" || s === \"off\") return false\n return true\n}\n\nfunction parseLevelEnv(v: string | undefined): LogLevel | undefined {\n if (v == null) return undefined\n const s = v.toLowerCase().trim()\n if (s === \"\") return undefined\n if (s === \"debug\" || s === \"info\" || s === \"notice\" || s === \"warn\" || s === \"error\") {\n return s\n }\n return undefined\n}\n\nfunction parseModeFromDebugEnv(v: string | undefined): LogMode | undefined {\n if (v == null || v === \"\") return undefined\n return v.includes(\"opencode-claude-code\") ? \"debug\" : undefined\n}\n\nfunction withEnvOverrides(base: LoggerConfig): LoggerConfig {\n const result: LoggerConfig = { ...base }\n const envFile = parseBoolEnv(process.env.OPENCODE_CLAUDE_CODE_LOG_FILE)\n if (envFile !== undefined) result.file = envFile\n const envDir = process.env.OPENCODE_CLAUDE_CODE_LOG_DIR\n if (envDir !== undefined && envDir !== \"\") result.dir = envDir\n const envMode = parseModeFromDebugEnv(process.env.DEBUG)\n if (envMode !== undefined) result.mode = envMode\n const envLevel = parseLevelEnv(process.env.OPENCODE_CLAUDE_CODE_LOG_LEVEL)\n if (envLevel !== undefined) result.level = envLevel\n return result\n}\n\nlet activeConfig: LoggerConfig = withEnvOverrides(DEFAULT_CONFIG)\nlet fileLoggingDisabled = false\n\n/**\n * Configure the logger from plugin settings. Env vars override the supplied\n * config when explicitly set, so a developer can flip behavior for a single\n * process without editing opencode.jsonc.\n *\n * `OPENCODE_CLAUDE_CODE_LOG_FILE` → `file` (1/true/on/yes vs 0/false/no/off)\n * `OPENCODE_CLAUDE_CODE_LOG_DIR` → `dir`\n * `DEBUG=opencode-claude-code` → `mode: \"debug\"`\n * `OPENCODE_CLAUDE_CODE_LOG_LEVEL` → `level` (debug | info | notice | warn | error)\n */\nexport function configureLogger(input: Partial<LoggerConfig>): void {\n const merged: LoggerConfig = { ...DEFAULT_CONFIG, ...input }\n activeConfig = withEnvOverrides(merged)\n fileLoggingDisabled = false\n}\n\nexport function getLoggerConfig(): LoggerConfig {\n return { ...activeConfig }\n}\n\n/** Test-only helper. Resets to defaults+env so tests are deterministic. */\nexport function _resetLoggerForTests(): void {\n activeConfig = withEnvOverrides(DEFAULT_CONFIG)\n fileLoggingDisabled = false\n}\n\nfunction resolvedLogFile(): string {\n return join(activeConfig.dir ?? DEFAULT_DIR, \"plugin.log\")\n}\n\nfunction rotateIfNeeded(logFile: string): void {\n try {\n const stat = statSync(logFile)\n if (stat.size > MAX_LOG_BYTES) {\n renameSync(logFile, `${logFile}.1`)\n }\n } catch {\n // file does not exist yet — nothing to rotate\n }\n}\n\nfunction writeToFile(line: string): void {\n if (!activeConfig.file) return\n if (fileLoggingDisabled) return\n try {\n const logFile = resolvedLogFile()\n mkdirSync(dirname(logFile), { recursive: true })\n rotateIfNeeded(logFile)\n appendFileSync(logFile, line + \"\\n\", \"utf8\")\n } catch {\n // Disable on first failure to avoid spamming errors on a read-only FS.\n fileLoggingDisabled = true\n }\n}\n\nfunction fmt(level: string, msg: string, data?: Record<string, unknown>): string {\n const ts = new Date().toISOString()\n const base = `[${ts}] [opencode-claude-code] ${level}: ${msg}`\n if (data && Object.keys(data).length > 0) {\n return `${base} ${JSON.stringify(data)}`\n }\n return base\n}\n\nfunction shouldEmit(level: LogLevel): boolean {\n return LEVEL_RANK[level] >= LEVEL_RANK[activeConfig.level]\n}\n\nfunction shouldTui(level: LogLevel): boolean {\n // warn/error are alwaysStderr: a developer who passes the level threshold\n // should still see real problems in the TUI regardless of mode. Below-\n // threshold entries are filtered earlier by shouldEmit().\n if (level === \"warn\" || level === \"error\") return true\n return activeConfig.mode === \"debug\"\n}\n\nfunction emit(level: LogLevel, msg: string, data?: Record<string, unknown>): void {\n if (!shouldEmit(level)) return\n const line = fmt(level.toUpperCase(), msg, data)\n if (shouldTui(level)) {\n console.error(line)\n }\n writeToFile(line)\n}\n\nexport const log = {\n debug(msg: string, data?: Record<string, unknown>) {\n emit(\"debug\", msg, data)\n },\n info(msg: string, data?: Record<string, unknown>) {\n emit(\"info\", msg, data)\n },\n notice(msg: string, data?: Record<string, unknown>) {\n emit(\"notice\", msg, data)\n },\n warn(msg: string, data?: Record<string, unknown>) {\n emit(\"warn\", msg, data)\n },\n error(msg: string, data?: Record<string, unknown>) {\n emit(\"error\", msg, data)\n },\n}\n","import { log } from \"./logger.js\"\n\nexport type TodoStatus = \"pending\" | \"in_progress\" | \"completed\"\n\nexport interface TodoEntry {\n id: string\n content: string\n status: TodoStatus\n}\n\ninterface PendingCreate {\n subject: string\n createdAt: number\n}\n\ninterface SessionLedger {\n todos: Map<string, TodoEntry>\n pendingCreates: Map<string, PendingCreate>\n}\n\nconst ledgers = new Map<string, SessionLedger>()\n\nconst PENDING_CREATE_TTL_MS = 60_000\nconst TASK_CREATED_PATTERN = /Task\\s*#?\\s*(\\d+)\\s+created/i\nconst VALID_STATUSES: ReadonlySet<TodoStatus> = new Set([\"pending\", \"in_progress\", \"completed\"])\n\nfunction getOrCreate(sessionId: string): SessionLedger {\n let ledger = ledgers.get(sessionId)\n if (!ledger) {\n ledger = { todos: new Map(), pendingCreates: new Map() }\n ledgers.set(sessionId, ledger)\n }\n return ledger\n}\n\nfunction prunePending(ledger: SessionLedger): void {\n const cutoff = Date.now() - PENDING_CREATE_TTL_MS\n for (const [id, pending] of ledger.pendingCreates) {\n if (pending.createdAt < cutoff) ledger.pendingCreates.delete(id)\n }\n}\n\nfunction materialize(ledger: SessionLedger): TodoEntry[] {\n return Array.from(ledger.todos.values())\n}\n\nfunction resolveSubject(input: { subject?: unknown; description?: unknown } | undefined): string {\n const subject = typeof input?.subject === \"string\" ? input.subject.trim() : \"\"\n if (subject) return subject\n const description = typeof input?.description === \"string\" ? input.description.trim() : \"\"\n if (description) return description\n return \"(no subject)\"\n}\n\nexport function applyTaskCreateToolUse(\n sessionId: string,\n toolUseId: string,\n input: { subject?: unknown; description?: unknown } | undefined,\n): void {\n if (!sessionId || !toolUseId) return\n const ledger = getOrCreate(sessionId)\n prunePending(ledger)\n ledger.pendingCreates.set(toolUseId, {\n subject: resolveSubject(input),\n createdAt: Date.now(),\n })\n}\n\nexport function applyTaskCreateToolResult(\n sessionId: string,\n toolUseId: string,\n resultText: string,\n): TodoEntry[] | null {\n if (!sessionId || !toolUseId) return null\n const ledger = ledgers.get(sessionId)\n if (!ledger) return null\n const pending = ledger.pendingCreates.get(toolUseId)\n if (!pending) return null\n ledger.pendingCreates.delete(toolUseId)\n const match = typeof resultText === \"string\" ? resultText.match(TASK_CREATED_PATTERN) : null\n if (!match) {\n log.debug(\"TaskCreate result did not match expected format\", { sessionId, toolUseId, resultText })\n return null\n }\n const claudeId = match[1]\n if (ledger.todos.has(claudeId)) {\n log.debug(\"TaskCreate result for already-known claude id; overwriting\", { sessionId, claudeId })\n }\n ledger.todos.set(claudeId, { id: claudeId, content: pending.subject, status: \"pending\" })\n return materialize(ledger)\n}\n\nexport function applyTaskUpdate(\n sessionId: string,\n input: { taskId?: unknown; subject?: unknown; status?: unknown } | undefined,\n): TodoEntry[] | null {\n if (!sessionId) return null\n const taskId = typeof input?.taskId === \"string\" ? input.taskId : null\n if (!taskId) return null\n const ledger = ledgers.get(sessionId)\n if (!ledger) return null\n const entry = ledger.todos.get(taskId)\n if (!entry) {\n log.debug(\"TaskUpdate for unknown task id\", { sessionId, taskId })\n return null\n }\n if (input?.status === \"deleted\") {\n ledger.todos.delete(taskId)\n return materialize(ledger)\n }\n if (typeof input?.status === \"string\" && VALID_STATUSES.has(input.status as TodoStatus)) {\n entry.status = input.status as TodoStatus\n }\n if (typeof input?.subject === \"string\" && input.subject.trim().length > 0) {\n entry.content = input.subject.trim()\n }\n return materialize(ledger)\n}\n\nexport function clearLedger(sessionId: string): void {\n if (!sessionId) return\n ledgers.delete(sessionId)\n}\n\nexport function getLedger(sessionId: string): TodoEntry[] {\n const ledger = ledgers.get(sessionId)\n if (!ledger) return []\n return materialize(ledger)\n}\n\nexport function _resetAllLedgersForTests(): void {\n ledgers.clear()\n}\n","import { log } from \"./logger.js\"\nimport { applyTaskCreateToolUse, applyTaskUpdate, type TodoEntry } from \"./todo-ledger.js\"\nimport type { WebSearchRouting } from \"./types.js\"\n\nexport interface MapToolOptions {\n webSearch?: WebSearchRouting\n sessionId?: string\n toolUseId?: string\n}\n\n/** Claude CLI's built-in web search tool (name varies by CLI version). */\nexport function isWebSearchTool(name: string): boolean {\n return name === \"WebSearch\" || name === \"web_search\"\n}\n\n/**\n * True when WebSearch runs inside Claude CLI (default) rather than being\n * forwarded to an opencode tool. In that case the tool-call part must not\n * reach opencode — \"WebSearch\" has no registry entry there and renders as\n * an invalid tool row. Callers show the query as a text line instead.\n */\nexport function isWebSearchHandledByCli(route?: WebSearchRouting): boolean {\n return !route || route === \"claude\" || route === \"disabled\"\n}\n\n/**\n * Map Claude CLI tool input (snake_case) to OpenCode tool input (camelCase)\n */\nfunction mapToolInput(name: string, input: any): any {\n if (!input) return input\n\n switch (name) {\n case \"Write\":\n return {\n filePath: input.file_path ?? input.filePath,\n content: input.content,\n }\n case \"Edit\":\n return {\n filePath: input.file_path ?? input.filePath,\n oldString: input.old_string ?? input.oldString,\n newString: input.new_string ?? input.newString,\n replaceAll: input.replace_all ?? input.replaceAll,\n }\n case \"Read\":\n return {\n filePath: input.file_path ?? input.filePath,\n offset: input.offset,\n limit: input.limit,\n }\n case \"Bash\":\n return {\n command: input.command,\n description:\n input.description ||\n `Execute: ${String(input.command || \"\").slice(0, 50)}${String(input.command || \"\").length > 50 ? \"...\" : \"\"}`,\n timeout: input.timeout,\n }\n case \"NotebookEdit\":\n return {\n notebookPath: input.notebook_path ?? input.notebookPath,\n cellNumber: input.cell_number ?? input.cellNumber,\n newSource: input.new_source ?? input.newSource,\n cellType: input.cell_type ?? input.cellType,\n editMode: input.edit_mode ?? input.editMode,\n }\n case \"Glob\":\n return {\n pattern: input.pattern,\n path: input.path,\n }\n case \"Grep\":\n return {\n pattern: input.pattern,\n path: input.path,\n include: input.include,\n }\n case \"TodoWrite\":\n if (Array.isArray(input.todos)) {\n const mappedTodos = input.todos.map((todo: any, index: number) => ({\n content: todo.content,\n status: todo.status || \"pending\",\n priority: todo.priority || \"medium\",\n id: todo.id || `todo_${Date.now()}_${index}`,\n }))\n return { todos: mappedTodos }\n }\n return input\n default:\n return input\n }\n}\n\n// Tools that Claude CLI executes internally but we report to opencode for UI display\nconst OPENCODE_HANDLED_TOOLS = new Set([\n \"Edit\",\n \"Write\",\n \"Bash\",\n \"NotebookEdit\",\n \"Read\",\n \"Glob\",\n \"Grep\",\n])\n\n// Claude CLI internal tools that should not be forwarded to opencode.\n// These are part of Claude Code's own system and have no opencode equivalent.\n// Tools the Claude CLI emits for its own internal bookkeeping (sub-agents,\n// task tracking, search). opencode has no matching tool registry entry, so\n// forwarding them surfaces as `⚙ invalid` rows in the UI. Skip them.\n// TaskOutput is intentionally NOT here — it has an explicit bash-echo mapping\n// below so the result stays visible.\nconst CLAUDE_INTERNAL_TOOLS = new Set([\n \"ToolSearch\",\n \"Agent\",\n \"AskFollowupQuestion\",\n \"TaskList\",\n \"TaskGet\",\n \"TaskStop\",\n])\n\n/**\n * Wrap model-controlled text as one shell single-quoted word.\n *\n * `TaskOutput` is displayed by running a real `bash` call, so its payload\n * reaches a shell. Double quotes are not enough: inside them `$(…)`,\n * backticks and `${…}` still expand, so `TaskOutput({content: \"X$(id -u)Y\"})`\n * executed `id` while the operator saw a command that read like a print\n * (issue #27). Single quotes suppress every expansion; the only character\n * needing care is `'` itself, closed and reopened around an escaped one.\n */\nexport function singleQuoteForShell(value: string): string {\n return `'${value.replace(/'/g, `'\\\\''`)}'`\n}\n\nfunction emitTodoWrite(todos: TodoEntry[]) {\n return {\n name: \"todowrite\",\n input: {\n todos: todos.map((todo) => ({\n id: todo.id,\n content: todo.content,\n status: todo.status,\n priority: \"medium\",\n })),\n },\n executed: false,\n }\n}\n\nexport function mapTool(\n name: string,\n input?: any,\n opts?: MapToolOptions,\n): { name: string; input?: any; executed: boolean; skip?: boolean } {\n // Claude CLI internal tools — skip entirely\n if (CLAUDE_INTERNAL_TOOLS.has(name)) {\n log.debug(\"skipping Claude CLI internal tool\", { name })\n return { name, input, executed: true, skip: true }\n }\n\n // TaskCreate: stash subject keyed by tool_use_id; emission happens on tool_result.\n // Without sessionId+toolUseId we cannot maintain the ledger, so fall back to skip\n // (preserves old behavior for callers that haven't been threaded yet).\n if (name === \"TaskCreate\") {\n if (opts?.sessionId && opts?.toolUseId) {\n applyTaskCreateToolUse(opts.sessionId, opts.toolUseId, input)\n }\n return { name, input, executed: true, skip: true }\n }\n\n // TaskUpdate: mutate ledger and emit full list as opencode todowrite. Without\n // sessionId, fall back to skip. Unknown task ids return null from the ledger\n // and we drop the event.\n if (name === \"TaskUpdate\") {\n if (opts?.sessionId) {\n const list = applyTaskUpdate(opts.sessionId, input)\n if (list !== null) return emitTodoWrite(list)\n }\n return { name, input, executed: true, skip: true }\n }\n\n // Plan mode tools\n if (name === \"EnterPlanMode\") return { name: \"plan_enter\", input: {}, executed: false }\n if (name === \"ExitPlanMode\") return { name: \"plan_exit\", input, executed: false }\n\n // TodoWrite needs opencode to run it locally so Todo.Service (and the UI\n // widget backed by it) gets populated. Reporting as provider-executed would\n // short-circuit opencode's own execute and leave the todo panel empty.\n if (name === \"TodoWrite\") {\n const mappedInput = mapToolInput(name, input)\n return { name: \"todowrite\", input: mappedInput, executed: false }\n }\n\n // WebSearch — routing controlled by config.webSearch\n if (isWebSearchTool(name)) {\n const mappedInput = input?.query ? { query: input.query } : input\n const route = opts?.webSearch\n if (route && route !== \"claude\" && route !== \"disabled\") {\n log.debug(\"routing WebSearch to opencode tool\", { target: route, mappedInput })\n return { name: route, input: mappedInput, executed: false }\n }\n // Claude CLI runs WebSearch internally; \"WebSearch\" has no opencode\n // registry entry, so forwarding the tool-call part surfaces a\n // \"Model tried to call unavailable tool\" invalid row in opencode.\n // Skip the part — callers render the query as a text line instead.\n log.debug(\"WebSearch executed by Claude CLI\", { mappedInput })\n return { name: \"WebSearch\", input: mappedInput, executed: true, skip: true }\n }\n\n // TaskOutput -> bash printf\n if (name === \"TaskOutput\") {\n if (!input) return { name: \"bash\", executed: false }\n const output = input?.content || input?.output || JSON.stringify(input)\n return {\n name: \"bash\",\n input: {\n command: `printf '%s\\\\n' ${singleQuoteForShell(`TASK OUTPUT: ${String(output)}`)}`,\n description: \"Displaying task output\",\n },\n executed: false,\n }\n }\n\n // Third-party MCP tools: mcp__<server>__<tool> -> <server>_<tool>.\n // Marked provider-executed because Claude CLI runs these internally via\n // its own --mcp-config; the tool-result is already in the stream. If we\n // reported executed:false, opencode would look up the tool in its own\n // registry, fail to find it, and emit an `invalid` tool error that\n // shadows the real result.\n //\n // Our own proxy tools (`mcp__opencode_proxy__*`) are filtered out by\n // callers before reaching here, so this branch only ever sees user MCP\n // servers configured in Claude CLI's settings.\n if (name.startsWith(\"mcp__\")) {\n const parts = name.slice(5).split(\"__\")\n if (parts.length >= 2) {\n const serverName = parts[0]\n const toolName = parts.slice(1).join(\"_\")\n const openCodeName = `${serverName}_${toolName}`\n log.debug(\"mapping MCP tool\", { original: name, mapped: openCodeName })\n return { name: openCodeName, input, executed: true }\n }\n }\n\n // Tools executed by Claude CLI internally - map to lowercase for opencode\n if (OPENCODE_HANDLED_TOOLS.has(name)) {\n const mappedInput = mapToolInput(name, input)\n const openCodeName = name.toLowerCase()\n log.debug(\"mapping CLI-executed tool\", { name, openCodeName })\n return { name: openCodeName, input: mappedInput, executed: true }\n }\n\n // Unknown tools - treated as provider-executed\n return { name, input, executed: true }\n}\n","import { execFile } from \"node:child_process\"\nimport { promisify } from \"node:util\"\nimport { log } from \"./logger.js\"\n\nconst execFileAsync = promisify(execFile)\n\nexport interface CliVersion {\n major: number\n minor: number\n patch: number\n raw: string\n}\n\nconst cache = new Map<string, Promise<CliVersion | null>>()\n\n/**\n * Run `claude --version` once per cliPath and parse the leading semver.\n * Returns null on any failure (binary missing, unparseable output, etc.)\n * so callers can fall back to the most conservative flag set.\n */\nexport function detectCliVersion(cliPath: string): Promise<CliVersion | null> {\n const cached = cache.get(cliPath)\n if (cached) return cached\n const promise = (async (): Promise<CliVersion | null> => {\n try {\n const { stdout } = await execFileAsync(cliPath, [\"--version\"], {\n timeout: 5000,\n })\n const match = /(\\d+)\\.(\\d+)\\.(\\d+)/.exec(stdout.trim())\n if (!match) {\n log.warn(\"claude --version output unparseable\", { stdout: stdout.trim() })\n return null\n }\n const v: CliVersion = {\n major: Number(match[1]),\n minor: Number(match[2]),\n patch: Number(match[3]),\n raw: stdout.trim(),\n }\n log.info(\"detected claude cli version\", { cliPath, version: v.raw })\n if (!cliSupportsThinkingDisplay(v)) {\n log.notice(\n \"claude cli < 2.1.142 detected; Opus 4.7 thinking summaries unavailable. Run `npm i -g @anthropic-ai/claude-code` to upgrade.\",\n { version: v.raw },\n )\n }\n return v\n } catch (err) {\n log.warn(\"failed to detect claude cli version\", {\n cliPath,\n error: err instanceof Error ? err.message : String(err),\n })\n return null\n }\n })()\n cache.set(cliPath, promise)\n return promise\n}\n\nfunction gte(v: CliVersion, target: { major: number; minor: number; patch: number }): boolean {\n if (v.major !== target.major) return v.major > target.major\n if (v.minor !== target.minor) return v.minor > target.minor\n return v.patch >= target.patch\n}\n\n/**\n * `--thinking-display` was introduced in Claude Code 2.1.142 alongside\n * Opus 4.7's \"omitted by default\" thinking behavior. Older CLIs reject\n * the flag with a parse error, so we gate it. Unknown version → return\n * false so we don't risk crashing the spawn.\n */\nexport function cliSupportsThinkingDisplay(v: CliVersion | null): boolean {\n if (!v) return false\n return gte(v, { major: 2, minor: 1, patch: 142 })\n}\n\n/**\n * Fast mode's headless opt-in. In print mode the CLI reports\n * `fast_mode_disabled_reason: \"sdk_opt_in_required\"` unless the *flag* settings\n * layer carries `fastMode: true`, which only `--settings` populates (there is\n * no `--fast` flag, and no fast-mode model name the CLI still accepts).\n *\n * 2.1.220 is the floor because it is the oldest binary the opt-in path was\n * confirmed present in, not because 2.1.219 is known to lack it. An unknown\n * settings key is ignored rather than fatal, so the downside of gating too\n * high is only that fast mode stays off.\n */\nexport function cliSupportsFastMode(v: CliVersion | null): boolean {\n if (!v) return false\n return gte(v, { major: 2, minor: 1, patch: 220 })\n}\n\n/** 2.1.258 is the oldest verified side_question control protocol, not its introduction date. */\nexport function cliSupportsSideQuestion(v: CliVersion | null): boolean {\n if (!v) return false\n return gte(v, { major: 2, minor: 1, patch: 258 })\n}\n\n/**\n * `--thinking` has been part of Claude Code's CLI since the 2.x line.\n * We require a detected 2.0.0+ before passing it; unknown version → skip\n * to avoid crashing a pre-flag binary. Anyone on the 1.x line should\n * upgrade.\n */\nexport function cliSupportsThinking(v: CliVersion | null): boolean {\n if (!v) return false\n return gte(v, { major: 2, minor: 0, patch: 0 })\n}\n\n/** For tests. */\nexport function _clearCache(): void {\n cache.clear()\n}\n","import { spawn, type ChildProcess } from \"node:child_process\"\nimport { createInterface } from \"node:readline\"\nimport { EventEmitter } from \"node:events\"\nimport { unlink } from \"node:fs/promises\"\nimport { log } from \"./logger.js\"\nimport type { ProxyMcpServer, ProxyToolResult } from \"./proxy-mcp.js\"\nimport { getPendingProxyCalls, type PendingProxyCall } from \"./proxy-broker.js\"\nimport { clearLedger } from \"./todo-ledger.js\"\nimport { clearExitPlanModeQuestions, hasExitPlanModeQuestions } from \"./plan-mode-question.js\"\nimport { clearCompression } from \"./compression-store.js\"\nimport {\n cliSupportsFastMode,\n cliSupportsThinking,\n cliSupportsThinkingDisplay,\n type CliVersion,\n} from \"./cli-version.js\"\nimport type { ReasoningEffort } from \"./types.js\"\nimport { dispatchSideQuestionResponse, isSideQuestionPending } from \"./side-question.js\"\n\nexport interface ActiveProcess {\n proc: ChildProcess\n lineEmitter: EventEmitter\n proxyServer?: ProxyMcpServer | null\n /**\n * Hash of the bridged opencode MCP config the process was spawned with.\n * `null` when the bridge produced nothing (no MCP servers). `undefined`\n * when the bridge was disabled. Used to detect mid-session config drift\n * and force a respawn.\n */\n mcpHash?: string | null\n /** Temp file holding `--append-system-prompt-file` content; unlinked on exit. */\n systemPromptFile?: string\n /** Effort the process was spawned with, so a respawn keeps it. */\n effort?: ReasoningEffort\n cliArgs?: string[]\n // Retain resolved calls until continuation settles, including late channel closure.\n pendingProxyCompletions?: Map<string, {\n call: PendingProxyCall\n result: ProxyToolResult\n recoveryRequired: boolean\n }>\n /**\n * stdout lines the child emitted while no turn had a line listener\n * attached (between opencode turns). Bounded; see `bufferUnattendedLine`.\n * Absent on the interactive shim, which has no unattended window.\n */\n unattendedLines?: string[]\n /** Lines evicted from `unattendedLines` because the cap was hit. */\n unattendedDropped?: number\n /**\n * opencode session this process last served, tagged by doStream each turn.\n * `/btw` runs from a command hook that only knows the session id, so this is\n * how it finds the process to ask (see `findActiveProcessBySessionId`).\n */\n opencodeSessionID?: string\n /** What the /btw command hook needs to send a side question to this process early. */\n asideTransport?: { cliPath: string; interactive: boolean }\n}\n\n/** Most recently used process serving an opencode session id, if any. */\nexport function findActiveProcessBySessionId(sessionID: string): ActiveProcess | undefined {\n let found: ActiveProcess | undefined\n // Map order is LRU (see `touch`), so the last match is the freshest.\n for (const ap of activeProcesses.values()) {\n if (ap.opencodeSessionID === sessionID) found = ap\n }\n return found\n}\n\n// A child normally only speaks while a doStream turn is listening. The one\n// exception is a turn that ended on the CLI's side while opencode was still\n// waiting on a proxy call (Claude's MCP client gave up on the request and\n// the model carried on alone). Keep what it said so the next turn can show\n// it instead of losing it; cap it so a runaway child cannot grow the heap.\nconst UNATTENDED_LINE_CAP = 500\nconst UNATTENDED_BYTE_CAP = 2 * 1024 * 1024\n\nexport function bufferUnattendedLine(ap: ActiveProcess, line: string): void {\n const lines = (ap.unattendedLines ??= [])\n lines.push(line)\n let bytes = 0\n for (const kept of lines) bytes += Buffer.byteLength(kept)\n while (\n lines.length > 0 &&\n (lines.length > UNATTENDED_LINE_CAP || bytes > UNATTENDED_BYTE_CAP)\n ) {\n bytes -= Buffer.byteLength(lines.shift()!)\n ap.unattendedDropped = (ap.unattendedDropped ?? 0) + 1\n }\n}\n\n/** Hand over and clear everything the child said while nobody listened. */\nexport function takeUnattendedLines(ap: ActiveProcess): {\n lines: string[]\n dropped: number\n} {\n const lines = ap.unattendedLines ?? []\n const dropped = ap.unattendedDropped ?? 0\n ap.unattendedLines = []\n ap.unattendedDropped = 0\n return { lines, dropped }\n}\n\n// One active CLI process per session key. Keyed by a composite\n// (cwd + model + opencode session-affinity) so two chats don't race.\n// Iteration order is insertion order, which we refresh on access to\n// make this a poor-man's LRU; see `touch()` below.\nconst activeProcesses = new Map<string, ActiveProcess>()\nconst claudeSessions = new Map<string, string>()\n\n// Cap on live CLI subprocesses. Session-affinity-keyed entries accumulate\n// one-per-chat, so an unbounded map would leak processes as users open new\n// chats. This caps at a reasonable working-set and evicts the oldest.\nconst MAX_ACTIVE_PROCESSES = 16\nconst PROCESS_EXIT_TIMEOUT_MS = 1_500\nconst PROCESS_FORCE_EXIT_TIMEOUT_MS = 500\n\nfunction envFlagEnabled(value: string | undefined): boolean {\n if (value === undefined) return false\n const normalized = value.trim().toLowerCase()\n if (!normalized) return false\n return ![\"0\", \"false\", \"no\", \"off\"].includes(normalized)\n}\n\nexport function isClaudeThinkingDisabled(): boolean {\n return (\n envFlagEnabled(process.env.CLAUDE_CODE_DISABLE_THINKING) ||\n envFlagEnabled(process.env.CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING)\n )\n}\n\n/**\n * The CLI's effort vocabulary is low | medium | high | xhigh | max. `minimal`\n * is this provider's own lowest step with no CLI counterpart, so it lands on\n * `low`.\n */\nexport function cliEffortLevel(effort: ReasoningEffort): string {\n return effort === \"minimal\" ? \"low\" : effort\n}\n\nexport function claudeSpawnEnv(opts?: {\n ignoreAnthropicApiKey?: boolean\n /** Reasoning effort for this spawn; wins over a shell-level override. */\n effort?: ReasoningEffort\n}): Record<string, string | undefined> {\n const env: Record<string, string | undefined> = {\n ...process.env,\n TERM: \"xterm-256color\",\n }\n\n // Effort travels as CLAUDE_CODE_EFFORT_LEVEL, which the CLI treats as the\n // session-wide override (it beats settings.json and `/effort`). An env var\n // rather than `--effort` because a CLI too old to know it ignores it\n // instead of refusing to start. Unlike the thinking vars below, an explicit\n // effort from the request wins over the shell: the variant picker and an\n // agent's `reasoningEffort` are per-request choices, a shell export is not.\n if (opts?.effort) {\n env.CLAUDE_CODE_EFFORT_LEVEL = cliEffortLevel(opts.effort)\n }\n\n // Force subscription auth: with an API key in the env, Claude Code bills\n // pay-as-you-go (Console) instead of the logged-in plan, bypassing the\n // Agent SDK credit. Opt-in via `ignoreAnthropicApiKey`.\n if (opts?.ignoreAnthropicApiKey) {\n delete env.ANTHROPIC_API_KEY\n delete env.ANTHROPIC_AUTH_TOKEN\n }\n\n // Default-on thinking summaries for opus-4-7 (which omits thinking by\n // default on the CLI side). Any var the user has explicitly set in their\n // shell is passed through untouched; the plugin only fills in the default.\n if (\n !isClaudeThinkingDisabled() &&\n process.env.CLAUDE_CODE_SHOW_THINKING_SUMMARIES === undefined\n ) {\n env.CLAUDE_CODE_SHOW_THINKING_SUMMARIES = \"1\"\n }\n\n return env\n}\n\nfunction touch(key: string): void {\n const existing = activeProcesses.get(key)\n if (existing) {\n activeProcesses.delete(key)\n activeProcesses.set(key, existing)\n }\n}\n\nfunction evictIfNeeded(): void {\n while (activeProcesses.size >= MAX_ACTIVE_PROCESSES) {\n const oldestKey = activeProcesses.keys().next().value\n if (!oldestKey) break\n log.info(\"evicting LRU claude process\", { sessionKey: oldestKey })\n deleteActiveProcess(oldestKey)\n }\n}\n\nexport function getActiveProcess(key: string): ActiveProcess | undefined {\n const ap = activeProcesses.get(key)\n if (ap) touch(key)\n return ap\n}\n\nexport function setActiveProcess(key: string, ap: ActiveProcess): void {\n activeProcesses.set(key, ap)\n}\n\nfunction detachActiveProcess(key: string): ActiveProcess | undefined {\n const ap = activeProcesses.get(key)\n if (!ap) return undefined\n activeProcesses.delete(key)\n void ap.proxyServer?.close()\n return ap\n}\n\nexport function deleteActiveProcess(key: string): void {\n const ap = detachActiveProcess(key)\n ap?.proc.kill()\n}\n\nfunction hasProcessExited(proc: ChildProcess): boolean {\n return proc.exitCode !== null || proc.signalCode !== null\n}\n\nfunction waitForProcessExit(\n proc: ChildProcess,\n timeoutMs: number,\n): Promise<boolean> {\n if (hasProcessExited(proc)) return Promise.resolve(true)\n\n return new Promise((resolve) => {\n const onExit = () => {\n clearTimeout(timer)\n resolve(true)\n }\n const timer = setTimeout(() => {\n proc.off(\"exit\", onExit)\n resolve(hasProcessExited(proc))\n }, timeoutMs)\n proc.once(\"exit\", onExit)\n })\n}\n\nexport async function deleteActiveProcessAndWait(\n key: string,\n options: {\n exitTimeoutMs?: number\n forceExitTimeoutMs?: number\n } = {},\n): Promise<boolean> {\n const ap = detachActiveProcess(key)\n if (!ap || hasProcessExited(ap.proc)) return true\n\n const gracefulExit = waitForProcessExit(\n ap.proc,\n options.exitTimeoutMs ?? PROCESS_EXIT_TIMEOUT_MS,\n )\n ap.proc.kill()\n if (await gracefulExit) return true\n\n const forcedExit = waitForProcessExit(\n ap.proc,\n options.forceExitTimeoutMs ?? PROCESS_FORCE_EXIT_TIMEOUT_MS,\n )\n ap.proc.kill(\"SIGKILL\")\n if (await forcedExit) return true\n\n log.warn(\"claude process did not exit; starting a fresh session\", {\n sessionKey: key,\n })\n deleteClaudeSessionId(key)\n return false\n}\n\nexport function getClaudeSessionId(key: string): string | undefined {\n return claudeSessions.get(key)\n}\n\nexport function setClaudeSessionId(key: string, sessionId: string): void {\n claudeSessions.set(key, sessionId)\n}\n\nexport function deleteClaudeSessionId(key: string): void {\n clearExitPlanModeQuestions(key)\n const claudeSessionId = claudeSessions.get(key)\n if (claudeSessionId) clearLedger(claudeSessionId)\n claudeSessions.delete(key)\n}\n\nexport function effortSessionKey(baseKey: string, effort?: ReasoningEffort): string {\n return effort ? `${baseKey}::effort=${effort}` : baseKey\n}\n\n/** Retire sibling effort sessions before deciding whether to replay history. */\nexport function invalidateOtherEffortSessions(\n baseKey: string,\n effort?: ReasoningEffort,\n): void {\n const levels: (ReasoningEffort | undefined)[] = [\n undefined, \"minimal\", \"low\", \"medium\", \"high\", \"xhigh\", \"max\",\n ]\n const staleKeys = levels\n .filter((level) => level !== effort)\n .map((level) => effortSessionKey(baseKey, level))\n\n // Refuse the transition atomically. Tool results and recovery completions\n // still belong to the old process; they must finish at its original effort.\n for (const key of staleKeys) {\n const active = activeProcesses.get(key)\n if (\n getPendingProxyCalls(key).length ||\n hasExitPlanModeQuestions(key) ||\n active?.pendingProxyCompletions?.size ||\n (active && (active.lineEmitter.listenerCount(\"line\") > 0 || isSideQuestionPending(active)))\n ) {\n throw new Error(\n \"Cannot change reasoning effort while the previous effort session has pending work. Finish that work at its original effort first.\",\n )\n }\n }\n for (const key of staleKeys) {\n deleteActiveProcess(key)\n deleteClaudeSessionId(key)\n clearCompression(key)\n }\n}\n\nexport function spawnClaudeProcess(\n cliPath: string,\n cliArgs: string[],\n cwd: string,\n sessionKey: string,\n proxyServer?: ProxyMcpServer | null,\n mcpHash?: string | null,\n systemPromptFile?: string,\n ignoreAnthropicApiKey?: boolean,\n effort?: ReasoningEffort,\n): ActiveProcess {\n evictIfNeeded()\n log.info(\"spawning new claude process\", {\n cliPath,\n cliArgs,\n cwd,\n sessionKey,\n effort,\n })\n\n const proc = spawn(cliPath, cliArgs, {\n cwd,\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n env: claudeSpawnEnv({ ignoreAnthropicApiKey, effort }),\n shell: process.platform === \"win32\",\n })\n\n const lineEmitter = new EventEmitter()\n\n const ap: ActiveProcess = {\n proc,\n lineEmitter,\n proxyServer: proxyServer ?? null,\n mcpHash,\n systemPromptFile,\n effort,\n cliArgs: [...cliArgs],\n unattendedLines: [],\n unattendedDropped: 0,\n }\n\n const rl = createInterface({ input: proc.stdout! })\n rl.on(\"line\", (line: string) => {\n if (dispatchSideQuestionResponse(ap, line)) return\n if (lineEmitter.listenerCount(\"line\") === 0) {\n bufferUnattendedLine(ap, line)\n return\n }\n lineEmitter.emit(\"line\", line)\n })\n rl.on(\"close\", () => {\n lineEmitter.emit(\"close\")\n })\n activeProcesses.set(sessionKey, ap)\n\n // Baseline 'error' listener so Node doesn't throw when the process emits\n // an error between stream turns (no per-stream listener attached then).\n proc.on(\"error\", (err) => {\n log.error(\"claude process error\", { sessionKey, error: err.message })\n })\n\n proc.on(\"exit\", (code, signal) => {\n log.info(\"claude process exited\", { code, signal, sessionKey })\n void proxyServer?.close()\n if (systemPromptFile) {\n void unlink(systemPromptFile).catch(() => {})\n }\n const ownsSessionKey = activeProcesses.get(sessionKey) === ap\n if (ownsSessionKey) activeProcesses.delete(sessionKey)\n if (ownsSessionKey && code !== 0 && code !== null) {\n log.info(\"process exited with error, clearing session\", {\n code,\n sessionKey,\n })\n claudeSessions.delete(sessionKey)\n }\n })\n\n proc.stderr?.on(\"data\", (data: Buffer) => {\n const stderr = data.toString()\n log.debug(\"stderr\", { data: stderr.slice(0, 200) })\n\n // \"No conversation found with session ID: <uuid>\" is what `--resume`\n // prints for a purged transcript — note the lowercase \"session ID\",\n // which the capitalized match below does not catch.\n if (\n stderr.includes(\"No conversation found\") ||\n (stderr.includes(\"Session ID\") &&\n (stderr.includes(\"already in use\") ||\n stderr.includes(\"not found\") ||\n stderr.includes(\"invalid\")))\n ) {\n if (activeProcesses.get(sessionKey) === ap) {\n log.warn(\"claude session ID error, clearing session\", {\n sessionKey,\n error: stderr.slice(0, 200),\n })\n claudeSessions.delete(sessionKey)\n } else {\n log.debug(\"ignoring session ID error from stale claude process\", {\n sessionKey,\n })\n }\n }\n })\n\n return ap\n}\n\n/**\n * Append `--resume <id>` to an already-built args vector when a Claude\n * conversation id is known for the session and the args don't already carry\n * a session flag. Used by `respawnActiveProcess` to resume the conversation\n * in a fresh child without rebuilding the whole (version-gated) args vector.\n * `--resume`, not `--session-id`: the latter means \"create a NEW session\n * with this UUID\" and the CLI rejects it with \"Session ID ... is already in\n * use\" whenever a transcript exists on disk — which is exactly the state a\n * mid-conversation respawn is in. If the wedged child died before writing\n * any transcript, `--resume` fails with \"No conversation found with session\n * ID\", which the stderr recovery matcher already catches (fresh-session\n * fallback).\n */\nexport function appendResumeIfNeeded(\n sessionKey: string,\n cliArgs: string[],\n): string[] {\n if (cliArgs.includes(\"--resume\") || cliArgs.includes(\"--session-id\")) {\n return cliArgs\n }\n const sid = claudeSessions.get(sessionKey)\n if (!sid) return cliArgs\n return [...cliArgs, \"--resume\", sid]\n}\n\n/**\n * Replace a wedged reused process with a fresh one, resuming the same\n * Claude conversation. Used by the doStream start-watchdog when a reused\n * process produces no stdout within a grace window after a fresh-turn\n * envelope write — observed after a very long proxy-blocked tool call\n * (e.g. a multi-minute `task` subagent). Before the per-tool proxy timeout\n * fix this was masked because the flat 10-minute ceiling ended the turn\n * first; now that the task proxy blocks and returns successfully, resuming\n * a reused child after such a long wait can leave it silent on stdout.\n *\n * Reuses the existing proxy server, system-prompt file, and MCP hash (their\n * handles are already baked into `cliArgs`' `--mcp-config`/append-prompt\n * paths), so this only swaps the child process. The old child's exit\n * handler is silenced before kill so it doesn't close the proxy server we\n * are reusing; the new child gets its own exit handler from\n * `spawnClaudeProcess`. `claudeSessions` is left intact so the respawn can\n * add `--resume` (see `appendResumeIfNeeded`).\n *\n * Returns the new `ActiveProcess`, or `undefined` if there was no active\n * process for the key (caller should treat that as \"nothing to respawn\").\n */\nexport function respawnActiveProcess(\n sessionKey: string,\n cliPath: string,\n cliArgs: string[],\n cwd: string,\n ignoreAnthropicApiKey?: boolean,\n): ActiveProcess | undefined {\n const old = activeProcesses.get(sessionKey)\n if (!old) return undefined\n activeProcesses.delete(sessionKey)\n // Silence the old exit handler so it doesn't close the proxy server,\n // unlink the system-prompt file, or touch claudeSessions on its way out\n // — those handles are reused by the new child. spawnClaudeProcess wires\n // a fresh exit handler for the respawned child.\n old.proc.removeAllListeners(\"exit\")\n try {\n old.proc.kill()\n } catch {}\n const replacement = spawnClaudeProcess(\n cliPath,\n appendResumeIfNeeded(sessionKey, old.cliArgs ?? cliArgs),\n cwd,\n sessionKey,\n old.proxyServer,\n old.mcpHash,\n old.systemPromptFile,\n ignoreAnthropicApiKey,\n old.effort,\n )\n replacement.pendingProxyCompletions = old.pendingProxyCompletions\n delete old.pendingProxyCompletions\n return replacement\n}\n\nexport function buildCliArgs(opts: {\n sessionKey: string\n skipPermissions: boolean\n includeSessionId?: boolean\n model?: string\n permissionMode?: string\n mcpConfig?: string | string[]\n strictMcpConfig?: boolean\n disallowedTools?: string[]\n appendSystemPromptFile?: string\n thinking?: \"enabled\" | \"disabled\"\n thinkingDisplay?: \"summarized\" | \"omitted\"\n fastMode?: boolean\n cliVersion?: CliVersion | null\n}): string[] {\n const {\n sessionKey,\n skipPermissions,\n includeSessionId = true,\n model,\n permissionMode,\n mcpConfig,\n strictMcpConfig,\n disallowedTools,\n appendSystemPromptFile,\n thinking,\n thinkingDisplay,\n fastMode,\n cliVersion,\n } = opts\n const args = [\n \"--print\",\n \"--output-format\",\n \"stream-json\",\n \"--input-format\",\n \"stream-json\",\n \"--include-partial-messages\",\n \"--verbose\",\n ]\n\n if (model) {\n args.push(\"--model\", model)\n }\n\n if (permissionMode) {\n args.push(\"--permission-mode\", permissionMode)\n }\n\n // `--session-id` means \"create a NEW session with this UUID\" and the CLI\n // exits with \"Session ID ... is already in use\" whenever a transcript for\n // that ID already exists on disk. Continuing an existing session requires\n // `--resume` (which keeps the same session ID in print mode).\n if (includeSessionId) {\n const sessionId = claudeSessions.get(sessionKey)\n if (sessionId && !activeProcesses.has(sessionKey)) {\n args.push(\"--resume\", sessionId)\n }\n }\n\n if (mcpConfig) {\n const configs = Array.isArray(mcpConfig) ? mcpConfig : [mcpConfig]\n const filtered = configs.filter((c) => typeof c === \"string\" && c.length > 0)\n if (filtered.length > 0) {\n args.push(\"--mcp-config\", ...filtered)\n }\n }\n\n if (strictMcpConfig) {\n args.push(\"--strict-mcp-config\")\n }\n\n if (disallowedTools && disallowedTools.length > 0) {\n args.push(\"--disallowedTools\", ...disallowedTools)\n }\n\n // `--thinking` is only present from Claude Code 2.x onward; gate so\n // pre-2.x binaries don't crash with a parse error. Unknown version →\n // skip (the spawn still works, the user just doesn't get extended\n // thinking until they upgrade).\n if (thinking && cliSupportsThinking(cliVersion ?? null)) {\n args.push(\"--thinking\", thinking)\n }\n\n // `--thinking-display` was added in Claude Code 2.1.142. Older CLIs\n // reject it with a parse error, so gate on detected version. When\n // version is unknown (detection failed), be conservative and skip.\n if (thinkingDisplay && cliSupportsThinkingDisplay(cliVersion ?? null)) {\n args.push(\"--thinking-display\", thinkingDisplay)\n }\n\n if (appendSystemPromptFile) {\n args.push(\"--append-system-prompt-file\", appendSystemPromptFile)\n }\n\n // Fast mode's only headless opt-in. `--settings` feeds the CLI's\n // `flagSettings` layer, which is the one its SDK gate checks; a `fastMode`\n // in the user's own settings.json is NOT enough for a `--print` run.\n // Built as one object so later flag-settings keys merge here instead of\n // adding a second `--settings` (the CLI takes the flag once).\n if (fastMode && cliSupportsFastMode(cliVersion ?? null)) {\n args.push(\"--settings\", JSON.stringify({ fastMode: true }))\n }\n\n if (skipPermissions) {\n args.push(\"--dangerously-skip-permissions\")\n }\n\n return args\n}\n\n/**\n * Build a session key that includes both cwd and model,\n * so different models get separate processes.\n */\nexport function sessionKey(cwd: string, modelId: string): string {\n return `${cwd}::${modelId}`\n}\n","import { EventEmitter } from \"node:events\"\nimport {\n buildProxyTimeoutError,\n resolveProxyCallTimeoutMs,\n type ProxyCallChannel,\n type ProxyToolCall,\n type ProxyToolResult,\n} from \"./proxy-mcp.js\"\nimport { log } from \"./logger.js\"\n\nexport interface PendingProxyCall {\n sessionKey: string\n toolCallId: string\n toolName: string\n input: Record<string, unknown>\n /**\n * Liveness of Claude's HTTP request for this call. Once `closed`, a\n * result written to it is lost; the language model then delivers the\n * result as a user message instead. Absent means open.\n */\n channel?: ProxyCallChannel\n /**\n * True once the language model has handed this call to opencode as a\n * tool-call part. A call that is still pending without it was queued\n * while no turn was attached and has to be drained by the next one.\n */\n emitted?: boolean\n}\n\ntype InternalPending = PendingProxyCall & {\n createdAt: number\n timer: ReturnType<typeof setTimeout>\n resolve(result: ProxyToolResult): void\n reject(error: Error): void\n}\n\n// Primary index: callId -> pending. Tool call IDs are UUIDs produced by\n// proxy-mcp, so they are globally unique across sessions.\nconst pendingByCallId = new Map<string, InternalPending>()\n// Reverse index: sessionKey -> set of callIds, so the language model can\n// drain or reject every pending call for one Claude subprocess at once.\nconst callIdsBySession = new Map<string, Set<string>>()\n\nconst emitter = new EventEmitter()\n\nfunction eventName(sessionKey: string) {\n return `pending:${sessionKey}`\n}\n\nfunction indexAdd(sessionKey: string, callId: string) {\n let s = callIdsBySession.get(sessionKey)\n if (!s) {\n s = new Set()\n callIdsBySession.set(sessionKey, s)\n }\n s.add(callId)\n}\n\nfunction indexRemove(sessionKey: string, callId: string) {\n const s = callIdsBySession.get(sessionKey)\n if (!s) return\n s.delete(callId)\n if (s.size === 0) callIdsBySession.delete(sessionKey)\n}\n\nexport function onPendingProxyCall(\n sessionKey: string,\n handler: (call: PendingProxyCall) => void,\n): () => void {\n const name = eventName(sessionKey)\n emitter.on(name, handler)\n return () => emitter.off(name, handler)\n}\n\nexport function queuePendingProxyCall(\n sessionKey: string,\n call: ProxyToolCall,\n timeoutOverrides?: Record<string, number>,\n): PendingProxyCall {\n // Defensive: if this exact callId is somehow already pending (UUID\n // collision or retry storm), replace it cleanly so we never leak two\n // entries for the same id.\n const previous = pendingByCallId.get(call.id)\n if (previous) {\n clearTimeout(previous.timer)\n previous.reject(\n new Error(`Replaced pending proxy call ${call.id} with a fresh one`),\n )\n pendingByCallId.delete(call.id)\n indexRemove(previous.sessionKey, call.id)\n }\n\n const deadlineMs = resolveProxyCallTimeoutMs(\n call.toolName,\n call.input,\n timeoutOverrides,\n )\n\n const timer = setTimeout(() => {\n const current = pendingByCallId.get(call.id)\n if (!current) return\n pendingByCallId.delete(call.id)\n indexRemove(current.sessionKey, call.id)\n current.reject(buildProxyTimeoutError(call.toolName, deadlineMs))\n // v0.4.13: demoted from warn to notice. AFK-permission-pending\n // sessions can stack many of these; demoting keeps the UI quiet on\n // return while preserving the audit trail in plugin.log.\n log.notice(\"timed out pending proxy call\", {\n sessionKey: current.sessionKey,\n toolCallId: call.id,\n toolName: call.toolName,\n deadlineMs,\n })\n }, deadlineMs)\n\n const pending: InternalPending = {\n sessionKey,\n toolCallId: call.id,\n toolName: call.toolName,\n input: call.input,\n channel: call.channel,\n createdAt: Date.now(),\n timer,\n resolve: call.resolve,\n reject: call.reject,\n }\n pendingByCallId.set(call.id, pending)\n indexAdd(sessionKey, call.id)\n emitter.emit(eventName(sessionKey), pending)\n log.info(\"queued pending proxy call\", {\n sessionKey,\n toolCallId: call.id,\n toolName: call.toolName,\n })\n return pending\n}\n\n/** Record that opencode has been given this call as a tool-call part. */\nexport function markPendingProxyCallEmitted(toolCallId: string): void {\n const pending = pendingByCallId.get(toolCallId)\n if (pending) pending.emitted = true\n}\n\n/** True when Claude's request for this call is gone (see `channel`). */\nexport function isPendingProxyCallChannelClosed(\n call: PendingProxyCall,\n): boolean {\n return call.channel?.closed === true\n}\n\nexport function getPendingProxyCalls(sessionKey: string): PendingProxyCall[] {\n const s = callIdsBySession.get(sessionKey)\n if (!s || s.size === 0) return []\n const out: PendingProxyCall[] = []\n for (const id of s) {\n const p = pendingByCallId.get(id)\n if (p) out.push(p)\n }\n return out\n}\n\nexport function resolvePendingProxyCallById(\n toolCallId: string,\n result: ProxyToolResult,\n): boolean {\n const pending = pendingByCallId.get(toolCallId)\n if (!pending) return false\n pendingByCallId.delete(toolCallId)\n indexRemove(pending.sessionKey, toolCallId)\n clearTimeout(pending.timer)\n pending.resolve(result)\n log.info(\"resolved pending proxy call\", {\n sessionKey: pending.sessionKey,\n toolCallId: pending.toolCallId,\n toolName: pending.toolName,\n })\n return true\n}\n\nexport function rejectPendingProxyCallById(\n toolCallId: string,\n error: Error,\n): boolean {\n const pending = pendingByCallId.get(toolCallId)\n if (!pending) return false\n pendingByCallId.delete(toolCallId)\n indexRemove(pending.sessionKey, toolCallId)\n clearTimeout(pending.timer)\n pending.reject(error)\n // Rejection is the broker's cleanup mechanism — fires on timeouts, orphans,\n // stream closes, etc. None are user-actionable. File-log them at NOTICE so\n // the audit trail is intact; rely on caller sites to decide TUI visibility.\n log.notice(\"rejected pending proxy call\", {\n sessionKey: pending.sessionKey,\n toolCallId: pending.toolCallId,\n toolName: pending.toolName,\n error: error.message,\n })\n return true\n}\n\nexport function rejectAllPendingProxyCallsForSession(\n sessionKey: string,\n error: Error,\n): number {\n const s = callIdsBySession.get(sessionKey)\n if (!s) return 0\n const ids = [...s]\n let count = 0\n for (const id of ids) {\n if (rejectPendingProxyCallById(id, error)) count++\n }\n return count\n}\n","import { createServer, type IncomingMessage, type ServerResponse } from \"node:http\"\nimport type { AddressInfo } from \"node:net\"\nimport * as fs from \"node:fs\"\nimport * as path from \"node:path\"\nimport * as crypto from \"node:crypto\"\nimport { EventEmitter } from \"node:events\"\nimport { log } from \"./logger.js\"\nimport { pluginTmpDir } from \"./tmp.js\"\n\n/**\n * Minimal MCP HTTP server embedded in-process. Exposes a set of \"proxy\"\n * tools (Bash, Edit, Write, etc.) that Claude CLI calls when its built-in\n * equivalents are disabled via --disallowedTools. Our handler blocks until\n * an external broker resolves the call, then responds to Claude.\n *\n * Wire protocol: JSON-RPC 2.0 over plain HTTP POST to `/mcp`. MCP spec\n * also supports SSE streaming, but Claude's HTTP transport accepts single\n * JSON responses for short-lived tool calls, so we keep it simple.\n */\n\nexport interface ProxyMcpServer {\n url: string\n serverName: string\n tools: ProxyToolDef[]\n /** Per-server bearer secret. Minted on start, handed to Claude via the\n * `headers` block of the generated MCP config, and required on every\n * request. Exposed so callers (and tests) can authenticate; MUST NOT be\n * logged or placed in the URL. */\n authToken: string\n /** Fires when Claude invokes one of our proxy tools. The handler resolves\n * the returned pending call once a result is available. */\n calls: EventEmitter\n /** Write `--mcp-config <path>`-compatible scratch file and return its path. */\n configPath(): string\n close(): Promise<void>\n}\n\nexport interface ProxyToolDef {\n /** Raw name as seen by Claude once proxied: the MCP exposed tool name. */\n name: string\n description: string\n inputSchema: Record<string, unknown>\n}\n\n/**\n * Liveness of the HTTP reply channel behind one proxy call. Shared by\n * reference between proxy-mcp (which flips `closed` when Claude's request\n * goes away) and the broker / language model (which read it before\n * answering), so the two never need to import each other.\n */\nexport interface ProxyCallChannel {\n closed: boolean\n}\n\nexport interface ProxyToolCall {\n id: string\n toolName: string\n input: Record<string, unknown>\n resolve: (result: ProxyToolResult) => void\n reject: (err: Error) => void\n /** Absent for calls built by hand in tests; treated as open. */\n channel?: ProxyCallChannel\n}\n\n/**\n * Keep unanswered HTTP calls active independently of the tool deadline.\n * A held call timed out before delivery on CLI 2.1.258; with immediate\n * headers and these comments, the same 390-second hold completed.\n */\nexport const SSE_KEEPALIVE_MS = 15_000\n\n/** True when the client advertised `text/event-stream` in Accept. */\nexport function acceptsEventStream(acceptHeader: unknown): boolean {\n return (\n typeof acceptHeader === \"string\" &&\n acceptHeader.toLowerCase().includes(\"text/event-stream\")\n )\n}\n\nexport type ProxyToolResult =\n | { kind: \"text\"; text: string; isError?: boolean }\n | { kind: \"error\"; message: string }\n\n/**\n * Handler that answers a `tools/call` inside this process instead of\n * queueing it for opencode. Used by tools that act on plugin state rather\n * than on the workspace (currently only `compress`), so they never reach\n * the broker, never block on a human, and have no deadline.\n */\nexport type ProxyToolInterceptor = (\n input: Record<string, unknown>,\n) => Promise<ProxyToolResult> | ProxyToolResult\n\nexport const SERVER_CLOSED_MESSAGE = \"proxy MCP server closed\"\n\n/** Rejections that fire on normal lifecycle transitions: AFK-permission\n * timeouts, orphan rejections at turn boundaries, stream aborts, and server\n * close while its owning Claude process exits or is replaced. None are\n * user-actionable — file-log them at NOTICE. Anything else stays WARN so\n * genuine bugs remain visible in the TUI. */\nexport function isExpectedCleanupError(message: string): boolean {\n return (\n (message.includes(\"timed out after\") &&\n message.includes(\"waiting for opencode to resolve\")) ||\n message.includes(\"rejecting as orphaned\") ||\n message.includes(\"was orphaned by a new user turn\") ||\n message.includes(\"stream was aborted\") ||\n message.includes(SERVER_CLOSED_MESSAGE)\n )\n}\n\nconst PROTOCOL_VERSION = \"2024-11-05\"\nconst SERVER_NAME = \"opencode_proxy\"\nexport const PROXY_TOOL_PREFIX = `mcp__${SERVER_NAME}__`\n\n// Flat fallback cap on how long a proxy tool call may wait for opencode to\n// resolve it. Matches Claude CLI's hard upper bound for Bash (10 min). The\n// effective deadline is resolved per tool — see `resolveProxyCallTimeoutMs`.\nexport const PROXY_DEFAULT_TIMEOUT_MS = 10 * 60 * 1000\n\n// Per-tool default deadlines, keyed by lowercase proxy tool name. `task`\n// dispatches an opencode subagent that routinely runs 20-40 min; the old\n// flat ceiling fired mid-subagent, made Claude believe its dispatch had\n// failed, and (because the proxy had already returned a timeout error) the\n// late subagent result was dropped on the floor -- the operator had to\n// nudge \"please check now, it seems the task succeeded\" (@jknlsn, live\n// session ses_0cfc0da6, 2026-07-05).\n//\n// `question` blocks on a human reading a TUI form, so the flat ceiling is\n// the wrong unit entirely: a question posed just before the operator steps\n// away would be rejected mid-answer. 30 min is jknlsn's original figure and\n// matches the \"prefer fewer, high-signal questions\" guidance in the def.\nexport const PROXY_PER_TOOL_DEFAULT_TIMEOUT_MS: Record<string, number> = {\n task: 60 * 60 * 1000, // 60 min\n question: 30 * 60 * 1000, // 30 min\n}\n\n// Node's setTimeout delay is a signed 32-bit int; values above 2^31-1 ms\n// (~24.85 days) trigger TimeoutOverflowWarning and fire at ~1ms instead.\n// Clamp absurd overrides / input.timeouts so a misconfigured deadline\n// can't collapse to \"fires immediately\".\nexport const MAX_PROXY_TIMEOUT_MS = 2 ** 31 - 1\n\n/**\n * Resolve the proxy deadline for a tool call. Layers, most-specific last:\n * 1. flat default (`PROXY_DEFAULT_TIMEOUT_MS`, 10 min)\n * 2. per-tool default (`PROXY_PER_TOOL_DEFAULT_TIMEOUT_MS`)\n * 3. user override via `proxyToolTimeoutMs` config (case-insensitive key)\n * 4. for `bash`, the call's own `input.timeout` -- the proxy must never\n * undercut a build the caller explicitly asked to run long. The bash\n * proxy def advertises a `timeout` field; before this fix the proxy\n * ignored it and killed the call at the flat ceiling anyway.\n * Finally clamped to `MAX_PROXY_TIMEOUT_MS` to stay within Node's timer range.\n */\nexport function resolveProxyCallTimeoutMs(\n toolName: string,\n input: Record<string, unknown> | undefined,\n overrides: Record<string, number> | undefined,\n): number {\n const key = toolName.toLowerCase()\n let ms = PROXY_PER_TOOL_DEFAULT_TIMEOUT_MS[key] ?? PROXY_DEFAULT_TIMEOUT_MS\n if (overrides) {\n const ov = lookupCaseInsensitive(overrides, key)\n if (typeof ov === \"number\" && ov > 0) ms = ov\n }\n if (key === \"bash\") {\n const requested = input?.timeout\n if (typeof requested === \"number\" && requested > ms) ms = requested\n }\n return Math.min(ms, MAX_PROXY_TIMEOUT_MS)\n}\n\nfunction lookupCaseInsensitive(\n map: Record<string, number>,\n key: string,\n): number | undefined {\n if (Object.prototype.hasOwnProperty.call(map, key)) return map[key]\n for (const k of Object.keys(map)) {\n if (k.toLowerCase() === key) return map[k]\n }\n return undefined\n}\n\n/**\n * Client-side abort ceiling written into Claude's `--mcp-config` entry for\n * the proxy server. Without a `timeout` there, Claude CLI's remote-HTTP MCP\n * client aborts each call at its 60-second default even while an opencode\n * subagent is still running (@broskees, PR #18). It must be >= the largest\n * server-side deadline or the client gives up before the broker does, so it\n * tracks the max of the flat default, per-tool defaults, and user overrides.\n * (A bash call raising its own `input.timeout` above this ceiling is a known\n * edge; Claude CLI caps bash at 10 min anyway.)\n */\nexport function resolveProxyClientCeilingMs(\n overrides: Record<string, number> | undefined,\n): number {\n let ms = PROXY_DEFAULT_TIMEOUT_MS\n for (const v of Object.values(PROXY_PER_TOOL_DEFAULT_TIMEOUT_MS)) {\n if (v > ms) ms = v\n }\n if (overrides) {\n for (const v of Object.values(overrides)) {\n if (typeof v === \"number\" && v > ms) ms = v\n }\n }\n return Math.min(ms, MAX_PROXY_TIMEOUT_MS)\n}\n\n/**\n * Build the timeout error surfaced to Claude. Keeps the substrings\n * `\"timed out after\"` and `\"waiting for opencode to resolve\"` that the\n * proxy-mcp catch block classifies as expected cleanup (notice, not warn).\n * For `task` we append guidance: a Task timeout means the subagent may\n * still be running but its result is now unreachable, and the model must\n * neither declare the dispatch failed nor \"schedule a wake-up\" -- that is a\n * Claude Code affordance which cannot fire in this headless/proxy context,\n * so deferring silently drops the work.\n */\nexport function buildProxyTimeoutError(toolName: string, ms: number): Error {\n const key = toolName.toLowerCase()\n const base = `Proxy tool '${toolName}' timed out after ${ms}ms waiting for opencode to resolve the call`\n if (key === \"task\") {\n return new Error(\n base +\n \" (the subagent). The subagent may still be running but its result\" +\n \" is no longer reachable in this session. Do not declare the dispatch\" +\n \" failed, and do not 'schedule a wake-up' or defer -- that mechanism\" +\n \" does not apply here. If the result is required, re-dispatch or\" +\n \" verify it directly now.\",\n )\n }\n return new Error(base)\n}\n\n/**\n * Disambiguation appended to the `task` proxy def (both the static\n * fallback and the live overlay). Models routinely resolve opencode's\n * \"call the task tool with subagent: X\" mention hint to Claude Code's\n * native TaskCreate (a todo tool) — creating a todo, dispatching nothing,\n * and then narrating a successful dispatch. Others burn turns grepping\n * config files to verify a subagent exists before daring to call it.\n * Both failure modes are addressed here, at the tool the model reads.\n */\nexport const TASK_PROXY_NOTE =\n \"This is the ONLY tool that dispatches opencode subagents (including\" +\n \" user @-mentions). Claude Code's built-in TaskCreate/TaskUpdate manage\" +\n \" a local todo list and cannot dispatch subagents. Do not search config\" +\n \" files to verify a subagent type exists — invalid types fail fast with\" +\n \" a clear error. Foreground calls block until the subagent finishes; set\" +\n \" `background` to request opencode's background execution mode. Task calls\" +\n \" get a 60-minute proxy deadline by default (configurable via\" +\n \" proxyToolTimeoutMs).\"\n\nconst AGENT_TYPES_HEADING = \"Available agent types\"\n\n/** Longest per-agent blurb we keep; enough to choose, short enough to survive. */\nconst AGENT_BLURB_LIMIT = 140\n\n/**\n * Disambiguation appended to the `question` proxy def. Claude Code ships\n * a built-in `AskUserQuestion` that, when proxied, is disabled via\n * `--disallowedTools`; without an explicit hand-off note models keep\n * reaching for the disabled built-in or fall back to plain text. This\n * states that the proxy is the structured-questions path and summarises\n * the answer shape so the model can act on the result without a second\n * round-trip.\n */\nexport const QUESTION_PROXY_NOTE =\n \"This routes structured questions through opencode's native `question`\" +\n \" tool, which renders a TUI form with the options you provide and\" +\n \" blocks until the operator answers. Claude Code's built-in\" +\n \" AskUserQuestion is disabled in this environment; this proxy is the\" +\n \" ONLY way to ask the operator for a decision or clarification.\" +\n \" Answers come back as arrays of selected labels (set `multiple: true`\" +\n \" to allow more than one). If the operator dismisses the form the call\" +\n \" returns an error — treat that as 'no answer' and stop, do not guess.\" +\n \" Question calls get a 30-minute proxy deadline by default (configurable\" +\n \" via proxyToolTimeoutMs); for long-AFK scenarios prefer fewer,\" +\n \" high-signal questions.\"\n\n/**\n * Disambiguation appended to the `compress` proxy def. Two things the\n * model gets wrong without it: when the reset happens (not mid-turn, so\n * it can keep working after the call), and how much survives it (only\n * the summary, because the fresh spawn is not given the prior transcript).\n */\nexport const COMPRESS_PROXY_NOTE =\n \"The current turn continues normally after this call — finish what you\" +\n \" are doing. The reset happens at the START of the next turn: the\" +\n \" Claude Code session is discarded and a fresh one begins with your\" +\n \" summary as its only prior context. Everything else, including tool\" +\n \" output and files you read, is gone, so write the summary as the\" +\n \" authoritative record. Call this once per compression, when older\" +\n \" resolved work no longer needs full detail.\"\n\n/**\n * Pull *only* the agent-type list out of opencode's live `task` description.\n *\n * jknlsn's original overlaid the whole live description (2.8 KB here) in front\n * of the static def. Live check 2026-07-26 showed that backfires: Claude Code\n * truncates long MCP tool descriptions, and opencode puts the agent list at\n * the *end* (char 2306 of 2858), so the one part the model needs is exactly\n * what gets cut — haiku then guessed `general-purpose`, `default`, and\n * `code-reviewer` (Claude Code's own agent names) and every dispatch failed\n * with \"Unknown agent type\". So: keep the list, drop opencode's preamble\n * (generic delegation advice the model already has), trim each blurb, and let\n * the caller put it first.\n *\n * Returns undefined when the description carries no parsable list, so callers\n * leave the static def alone.\n */\nexport function extractAgentTypeList(\n liveDescription: string | undefined,\n): string | undefined {\n const live = liveDescription?.trim()\n if (!live) return undefined\n const start = live.indexOf(AGENT_TYPES_HEADING)\n if (start === -1) return undefined\n const entries: string[] = []\n for (const raw of live.slice(start).split(\"\\n\")) {\n const match = /^-\\s*([^:]+):\\s*(.+)$/.exec(raw.trim())\n if (!match) continue\n const name = match[1].trim()\n const blurb = match[2].trim()\n entries.push(\n `- ${name}: ${\n blurb.length > AGENT_BLURB_LIMIT\n ? `${blurb.slice(0, AGENT_BLURB_LIMIT).trimEnd()}…`\n : blurb\n }`,\n )\n }\n if (entries.length === 0) return undefined\n return `Valid subagent_type values, from opencode's live registry — anything else fails:\\n${entries.join(\"\\n\")}`\n}\n\n/**\n * Front-load opencode's live agent-type list onto the static `task` proxy def\n * so the model picks a real `subagent_type` instead of guessing a Claude Code\n * name. First, not last: see `extractAgentTypeList` for why position matters.\n * No-op when no list can be extracted (SDK client missing, older opencode) or\n * the `task` def is not among the tools.\n */\nexport function overlayTaskProxyDescription(\n tools: ProxyToolDef[],\n liveDescription: string | undefined,\n): ProxyToolDef[] {\n const agentTypes = extractAgentTypeList(liveDescription)\n if (!agentTypes) return tools\n return tools.map((t) =>\n t.name === \"task\"\n ? { ...t, description: `${agentTypes}\\n\\n${t.description}` }\n : t,\n )\n}\n\n/**\n * Overlay opencode's live `question` tool description onto the static\n * proxy def, then append the disambiguation note. No-op when the live\n * description is unavailable (older opencode, SDK client missing) — the\n * static def + note stands. Mirrors `overlayTaskProxyDescription`.\n */\nexport function overlayQuestionProxyDescription(\n tools: ProxyToolDef[],\n liveDescription: string | undefined,\n): ProxyToolDef[] {\n const live = liveDescription?.trim()\n if (!live) return tools\n return tools.map((t) =>\n t.name === \"question\"\n ? { ...t, description: `${live}\\n\\n${QUESTION_PROXY_NOTE}` }\n : t,\n )\n}\n\n/**\n * Version gate for the `question` proxy. opencode added a built-in\n * `question` tool (registry id `question`) — on older builds that entry\n * is absent and a forwarded `mcp__opencode_proxy__question` call would\n * resolve to `⚙ invalid` in opencode. Drop the def silently when the\n * live registry does not contain it so the model never sees a dead tool.\n */\nexport function filterQuestionProxyByOpencodeSupport(\n tools: ProxyToolDef[],\n opencodeHasQuestion: boolean,\n): ProxyToolDef[] {\n if (opencodeHasQuestion) return tools\n return tools.filter((t) => t.name !== \"question\")\n}\n\nexport const DEFAULT_PROXY_TOOLS: ProxyToolDef[] = [\n {\n name: \"bash\",\n description:\n \"Execute a shell command. Routed through opencode's bash tool so\" +\n \" permission prompts flow through opencode's UI.\",\n inputSchema: {\n type: \"object\",\n properties: {\n command: {\n type: \"string\",\n description: \"The shell command to execute.\",\n },\n description: {\n type: \"string\",\n description: \"Short human-readable description of what the command does.\",\n },\n timeout: {\n type: \"number\",\n description: \"Optional timeout in milliseconds.\",\n },\n },\n required: [\"command\"],\n },\n },\n {\n name: \"write\",\n description:\n \"Write a file. Routed through opencode's write tool so permission prompts flow through opencode's UI.\",\n inputSchema: {\n type: \"object\",\n properties: {\n filePath: {\n type: \"string\",\n description: \"The file to write. Absolute paths are preferred.\",\n },\n content: {\n type: \"string\",\n description: \"The full content to write to the file.\",\n },\n },\n required: [\"filePath\", \"content\"],\n },\n },\n {\n name: \"edit\",\n description:\n \"Replace text in an existing file. Routed through opencode's edit tool so permission prompts flow through opencode's UI.\",\n inputSchema: {\n type: \"object\",\n properties: {\n filePath: {\n type: \"string\",\n description: \"The file to edit. Absolute paths are preferred.\",\n },\n oldString: {\n type: \"string\",\n description: \"The exact text to replace.\",\n },\n newString: {\n type: \"string\",\n description: \"The replacement text.\",\n },\n replaceAll: {\n type: \"boolean\",\n description: \"Replace all occurrences instead of just the first one.\",\n },\n },\n required: [\"filePath\", \"oldString\", \"newString\"],\n },\n },\n {\n name: \"webfetch\",\n description:\n \"Fetch content from a URL. Routed through opencode's webfetch tool so\" +\n \" permission prompts flow through opencode's UI. Returns the page\" +\n \" content in the requested format.\",\n inputSchema: {\n type: \"object\",\n properties: {\n url: {\n type: \"string\",\n description: \"The URL to fetch content from. Must start with http:// or https://.\",\n },\n format: {\n type: \"string\",\n enum: [\"text\", \"markdown\", \"html\"],\n description:\n \"The format to return the content in. Defaults to markdown.\",\n },\n timeout: {\n type: \"number\",\n description: \"Optional timeout in seconds (max 120).\",\n },\n },\n required: [\"url\"],\n },\n },\n {\n name: \"task\",\n description:\n \"Launch an opencode subagent to handle a complex multi-step task\" +\n \" autonomously. Routed through opencode's task tool so subagent\" +\n \" orchestration, permission, and lifecycle are handled by opencode.\" +\n \" Use `subagent_type` to pick which configured subagent runs (e.g.\" +\n \" `build`, `general`, `explore`, or any custom subagent declared in\" +\n \" opencode.json). \" +\n TASK_PROXY_NOTE,\n inputSchema: {\n type: \"object\",\n properties: {\n description: {\n type: \"string\",\n description: \"A short (3-5 words) description of the task\",\n },\n prompt: {\n type: \"string\",\n description: \"The task for the agent to perform\",\n },\n subagent_type: {\n type: \"string\",\n description: \"The type of specialized agent to use for this task\",\n },\n task_id: {\n type: \"string\",\n description:\n \"Set this only if you mean to resume a previous task — pass the\" +\n \" prior task_id to continue the same subagent session instead of\" +\n \" creating a fresh one.\",\n },\n command: {\n type: \"string\",\n description: \"The command that triggered this task\",\n },\n background: {\n type: \"boolean\",\n description:\n \"Run the task in the background when supported by opencode\",\n },\n },\n required: [\"description\", \"prompt\", \"subagent_type\"],\n },\n },\n {\n name: \"question\",\n description:\n \"Ask the operator structured questions with options and receive\" +\n \" their answers back. Routed through opencode's native `question`\" +\n \" tool so the prompt renders as a real TUI form (with options and a\" +\n \" custom-answer field) instead of a plain text turn. Use this when\" +\n \" you need a decision, clarification, or preference from the\" +\n \" operator mid-task. \" +\n QUESTION_PROXY_NOTE,\n inputSchema: {\n type: \"object\",\n properties: {\n questions: {\n type: \"array\",\n description: \"Questions to ask.\",\n items: {\n type: \"object\",\n properties: {\n question: {\n type: \"string\",\n description: \"Complete question.\",\n },\n header: {\n type: \"string\",\n description: \"Very short label (max 30 chars).\",\n },\n options: {\n type: \"array\",\n description: \"Available choices.\",\n items: {\n type: \"object\",\n properties: {\n label: {\n type: \"string\",\n description: \"Display text (1-5 words, concise).\",\n },\n description: {\n type: \"string\",\n description: \"Explanation of choice.\",\n },\n },\n required: [\"label\", \"description\"],\n },\n },\n multiple: {\n type: \"boolean\",\n description:\n \"Allow selecting multiple choices. Defaults to false.\",\n },\n },\n required: [\"question\", \"header\", \"options\"],\n },\n },\n },\n required: [\"questions\"],\n },\n },\n {\n name: \"compress\",\n description:\n \"Replace older conversation detail with a summary you write, then\" +\n \" continue in a fresh Claude Code session. Handled inside the plugin,\" +\n \" so it never prompts the operator. \" +\n COMPRESS_PROXY_NOTE,\n inputSchema: {\n type: \"object\",\n properties: {\n summary: {\n type: \"string\",\n description:\n \"Dense technical summary of the work being compressed: decisions\" +\n \" made, files changed, commands run and their outcomes, and what\" +\n \" is still open. This is the ONLY prior context that survives, so\" +\n \" anything omitted is lost.\",\n },\n },\n required: [\"summary\"],\n },\n },\n]\n\nexport async function createProxyMcpServer(\n tools: ProxyToolDef[] = DEFAULT_PROXY_TOOLS,\n timeoutOverrides?: Record<string, number>,\n interceptors?: Map<string, ProxyToolInterceptor>,\n): Promise<ProxyMcpServer> {\n const calls = new EventEmitter()\n const pending = new Map<string, ProxyToolCall>()\n\n // Per-server bearer secret (256 bits). This endpoint executes Bash/Edit/\n // Write through opencode's executor, so an unauthenticated caller on\n // loopback would have arbitrary command execution. The token lives only\n // in this process and in the 0600 MCP config file Claude reads; it is\n // deliberately kept out of the URL, because query strings leak into logs\n // and process listings.\n const authToken = crypto.randomBytes(32).toString(\"hex\")\n const expectedAuth = Buffer.from(`Bearer ${authToken}`)\n // The exact authority we hand to Claude. Set once the ephemeral port is\n // known; compared against the Host header to defeat DNS rebinding.\n let boundAuthority = \"\"\n\n function authOk(req: IncomingMessage): boolean {\n const got = req.headers.authorization\n if (typeof got !== \"string\") return false\n const candidate = Buffer.from(got)\n // timingSafeEqual throws on length mismatch, so length-check first.\n // Length is not secret (the token is fixed-width).\n if (candidate.length !== expectedAuth.length) return false\n return crypto.timingSafeEqual(candidate, expectedAuth)\n }\n\n /**\n * Reject a request without leaving the connection usable.\n *\n * Ending the response alone is not enough. A peer can declare a large\n * Content-Length, send a single byte, take the rejection, and leave the\n * request still arriving — and `server.close()` does not reap connections\n * that are still sending, so a shutdown would hang behind it. Node's\n * default whole-request timeout is five minutes, which is five minutes of\n * a socket held by an unauthenticated caller.\n *\n * `Connection: close` tells Node to close once the response is flushed;\n * destroying the socket on `finish` covers the case where the peer never\n * finishes its body.\n */\n function reject(\n req: IncomingMessage,\n res: ServerResponse,\n statusCode: number,\n reason: string,\n ): void {\n // Every guard below is a measured property of the client we spawn, not a\n // guarantee about future ones. If a later Claude CLI starts sending an\n // Origin header, or a different Content-Type, every proxy call would\n // 403/415 with no other symptom than tools mysteriously not working — so\n // say why, here, once per rejected request. Header VALUES are omitted:\n // this line must never carry the bearer token.\n log.notice(\"proxy-mcp rejected a request\", {\n statusCode,\n reason,\n method: req.method,\n hasAuthorization: typeof req.headers.authorization === \"string\",\n })\n res.statusCode = statusCode\n res.setHeader(\"Connection\", \"close\")\n res.on(\"finish\", () => {\n req.socket?.destroy()\n })\n res.end()\n }\n\n const server = createServer(async (req, res) => {\n if (req.method !== \"POST\" || !req.url?.startsWith(\"/mcp\")) {\n reject(req, res, 404, \"not a POST to /mcp\")\n return\n }\n // Everything below runs BEFORE readBody: an unauthenticated peer must\n // not be able to stream an unbounded body into memory.\n //\n // DNS rebinding: a browser rebound onto this port via an attacker\n // hostname sends that hostname in Host, never the loopback authority we\n // generated. This does NOT block a page posting directly to\n // 127.0.0.1:<port> — such a request carries exactly the expected Host —\n // so it is a rebinding defense specifically, not a browser defense. The\n // Origin and Content-Type guards below, and the token, cover that case.\n if (req.headers.host !== boundAuthority) {\n reject(req, res, 403, \"host header is not the bound authority\")\n return\n }\n // Claude Code 2.1.226 sends no Origin on MCP requests (verified). The MCP\n // transport spec obliges SERVERS to validate Origin; it does not oblige\n // clients to omit it, so this is a measured property of the client we\n // spawn rather than a guarantee about all conforming clients.\n if (req.headers.origin !== undefined) {\n reject(req, res, 403, \"origin header present\")\n return\n }\n // Requiring application/json forces a CORS preflight for cross-origin\n // callers (which then fails), closing the text/plain \"simple request\"\n // bypass that would otherwise allow blind cross-site POSTs.\n const contentType = String(req.headers[\"content-type\"] ?? \"\")\n .split(\";\")[0]\n .trim()\n .toLowerCase()\n if (contentType !== \"application/json\") {\n reject(req, res, 415, \"content-type is not application/json\")\n return\n }\n if (!authOk(req)) {\n reject(req, res, 401, \"missing or invalid bearer token\")\n return\n }\n // Hoist the request id and method so the catch block can echo them\n // in error responses. Without this, a broker rejection (timeout /\n // orphan) on a tools/call lands in the catch with no visible id, and\n // the response goes back with `id: null` which Claude CLI cannot\n // match to the original request. The method is also needed because\n // tools/call errors must be returned as MCP results with isError\n // (not JSON-RPC errors) or Claude CLI rejects them as a \"malformed\n // result that failed schema validation\" (seen live 2026-07-04).\n let requestId: number | string | null = null\n let requestMethod: string | null = null\n // Hoisted for the same reason: once SSE headers are out, an error must\n // travel down the stream instead of through writeJson (which would try\n // to set headers again and throw inside the catch).\n let sse: EventStream | null = null\n try {\n const body = await readBody(req)\n const request = JSON.parse(body) as {\n jsonrpc?: string\n id?: number | string | null\n method?: string\n params?: Record<string, unknown>\n }\n requestId = request?.id ?? null\n requestMethod = typeof request?.method === \"string\" ? request.method : null\n\n if (request?.jsonrpc !== \"2.0\" || typeof request.method !== \"string\") {\n writeJson(res, {\n jsonrpc: \"2.0\",\n id: requestId,\n error: { code: -32600, message: \"Invalid request\" },\n })\n return\n }\n\n log.debug(\"proxy-mcp request\", {\n method: request.method,\n id: request.id,\n })\n\n if (request.method === \"initialize\") {\n writeJson(res, {\n jsonrpc: \"2.0\",\n id: requestId,\n result: {\n protocolVersion: PROTOCOL_VERSION,\n capabilities: { tools: {} },\n serverInfo: {\n name: SERVER_NAME,\n version: \"0.1.0\",\n },\n },\n })\n return\n }\n\n if (request.method === \"notifications/initialized\") {\n res.statusCode = 204\n res.end()\n return\n }\n\n if (request.method === \"tools/list\") {\n writeJson(res, {\n jsonrpc: \"2.0\",\n id: requestId,\n result: {\n tools: tools.map((t) => ({\n name: t.name,\n description: t.description,\n inputSchema: t.inputSchema,\n })),\n },\n })\n return\n }\n\n if (request.method === \"tools/call\") {\n const params = request.params ?? {}\n const toolName = String(params.name ?? \"\")\n const input = (params.arguments ?? {}) as Record<string, unknown>\n\n if (!tools.some((t) => t.name === toolName)) {\n // tools/call failures MUST be MCP results with isError, never\n // JSON-RPC error envelopes: Claude CLI validates every tools/call\n // response against the MCP result schema and rejects JSON-RPC\n // errors as malformed (@jknlsn, seen live 2026-07-04).\n writeJson(res, {\n jsonrpc: \"2.0\",\n id: requestId,\n result: {\n content: [{ type: \"text\", text: `Unknown proxy tool: ${toolName}` }],\n isError: true,\n },\n })\n return\n }\n\n // Intercepted tools act on plugin state, not on the workspace, so\n // they are answered here and never queued for opencode. The result\n // still goes through the shared MCP envelope below — a JSON-RPC\n // error here would be rejected by Claude CLI exactly like any other\n // tools/call error envelope.\n const interceptor = interceptors?.get(toolName)\n if (interceptor) {\n let intercepted: ProxyToolResult\n try {\n intercepted = await interceptor(input)\n } catch (interceptorError) {\n const message =\n interceptorError instanceof Error\n ? interceptorError.message\n : String(interceptorError)\n log.warn(\"proxy-mcp interceptor failed\", { toolName, error: message })\n intercepted = { kind: \"error\", message }\n }\n writeToolCallResult(res, requestId, intercepted)\n return\n }\n\n const callId = crypto.randomUUID()\n log.info(\"proxy-mcp tool call received\", {\n callId,\n toolName,\n hasInput: input != null,\n sse: acceptsEventStream(req.headers.accept),\n })\n\n // Broker-backed calls can block for an hour on a subagent. Use SSE when the\n // client accepts one: headers and a comment go out now, keepalive\n // comments follow, and the JSON-RPC result is the final event. A\n // client that only accepts JSON gets the old single-shot reply.\n const channel: ProxyCallChannel = { closed: false }\n if (acceptsEventStream(req.headers.accept)) {\n sse = openEventStream(res)\n }\n res.once(\"close\", () => {\n sse?.stop()\n if (res.writableFinished) return\n channel.closed = true\n log.notice(\"proxy-mcp client closed a tool call before its result\", {\n callId,\n toolName,\n })\n })\n\n let timer: ReturnType<typeof setTimeout> | null = null\n const result = await new Promise<ProxyToolResult>(\n (resolve, reject) => {\n const entry: ProxyToolCall = {\n id: callId,\n toolName,\n input,\n resolve,\n reject,\n channel,\n }\n pending.set(callId, entry)\n const deadlineMs = resolveProxyCallTimeoutMs(\n toolName,\n input,\n timeoutOverrides,\n )\n timer = setTimeout(() => {\n if (!pending.has(callId)) return\n pending.delete(callId)\n // v0.4.13: demoted from warn to notice. Timeouts are usually\n // permission-pending while the user is AFK — surfacing each as\n // a yellow UI bubble produces a wall of noise on return. The\n // file log still captures the event for diagnostics.\n log.notice(\"proxy-mcp tool call timed out\", {\n callId,\n toolName,\n deadlineMs,\n })\n reject(buildProxyTimeoutError(toolName, deadlineMs))\n }, deadlineMs)\n calls.emit(\"call\", entry)\n },\n ).finally(() => {\n if (timer) clearTimeout(timer)\n pending.delete(callId)\n })\n\n if (channel.closed) {\n // Nobody is reading. The language model already saw the closed\n // channel and hands the result to Claude another way.\n log.notice(\"proxy-mcp dropping result for a closed tool call\", {\n callId,\n toolName,\n })\n return\n }\n writeToolCallResult(res, requestId, result, sse)\n return\n }\n\n writeJson(res, {\n jsonrpc: \"2.0\",\n id: requestId,\n error: { code: -32601, message: `Unknown method: ${request.method}` },\n })\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error)\n const logFn = isExpectedCleanupError(errorMessage) ? log.notice : log.warn\n logFn(\"proxy-mcp error handling request\", {\n error: errorMessage,\n })\n // Broker rejections (timeouts, orphans, server close) surface here for\n // tools/call requests. Same rule as above: respond with an MCP result\n // carrying isError, never a JSON-RPC error envelope, or Claude CLI\n // rejects the response as schema-invalid.\n if (requestMethod === \"tools/call\") {\n try {\n writeToolCallResult(\n res,\n requestId,\n { kind: \"error\", message: errorMessage },\n sse,\n )\n } catch {\n try {\n res.statusCode = 500\n res.end()\n } catch {}\n }\n return\n }\n try {\n // tools/call already returned above with an MCP result; anything\n // reaching here is a protocol-level method (initialize, tools/list)\n // where a JSON-RPC error is the correct shape.\n writeJson(res, {\n jsonrpc: \"2.0\",\n id: requestId,\n error: {\n code: -32603,\n message: error instanceof Error ? error.message : \"Internal error\",\n },\n })\n } catch {\n try {\n res.statusCode = 500\n res.end()\n } catch {}\n }\n }\n })\n\n await new Promise<void>((resolve, reject) => {\n server.once(\"error\", reject)\n server.listen(0, \"127.0.0.1\", () => {\n server.off(\"error\", reject)\n resolve()\n })\n })\n\n const addr = server.address() as AddressInfo | null\n if (!addr) {\n server.close()\n throw new Error(\"Failed to bind proxy MCP server\")\n }\n\n boundAuthority = `127.0.0.1:${addr.port}`\n const url = `http://${boundAuthority}/mcp`\n\n // NOTE: authToken is deliberately absent from this line and every other\n // log call. The plugin log is written to disk and echoed to the TUI in\n // debug mode; a leaked token there would defeat the whole mechanism.\n log.info(\"proxy-mcp server started\", {\n url,\n tools: tools.map((t) => t.name),\n })\n\n let configFilePath: string | null = null\n\n const api: ProxyMcpServer = {\n url,\n serverName: SERVER_NAME,\n tools,\n authToken,\n calls,\n configPath() {\n if (configFilePath) return configFilePath\n const body = JSON.stringify(\n {\n mcpServers: {\n [SERVER_NAME]: {\n type: \"http\",\n url,\n // Claude CLI replays these headers on every request to this\n // server, which is what lets the handler above reject anyone\n // who did not read this 0600 file.\n headers: { Authorization: `Bearer ${authToken}` },\n timeout: resolveProxyClientCeilingMs(timeoutOverrides),\n },\n },\n },\n null,\n 2,\n )\n const hash = crypto\n .createHash(\"sha256\")\n .update(body)\n .digest(\"hex\")\n .slice(0, 12)\n const outPath = path.join(\n pluginTmpDir(),\n `proxy-${hash}.json`,\n )\n fs.writeFileSync(outPath, body, { encoding: \"utf8\", mode: 0o600 })\n configFilePath = outPath\n return outPath\n },\n async close() {\n for (const entry of pending.values()) {\n entry.reject(new Error(SERVER_CLOSED_MESSAGE))\n }\n pending.clear()\n await new Promise<void>((resolve) => {\n server.close(() => resolve())\n })\n if (configFilePath) {\n try {\n fs.unlinkSync(configFilePath)\n } catch {}\n configFilePath = null\n }\n },\n }\n\n return api\n}\n\n/** CLI-ready list of Claude tool names to disable, for each proxied tool. */\nexport function disallowedToolFlags(tools: ProxyToolDef[]): string[] {\n // Map our lowercase MCP tool names to the Claude tool name(s) they replace.\n // `edit` covers both `Edit` and `MultiEdit` because opencode has no\n // MultiEdit equivalent; without disabling MultiEdit, Claude can batch\n // file changes through it and bypass opencode's permission UI.\n // `task` disables Claude CLI's `Agent` tool (its built-in subagent\n // dispatcher) so subagent calls flow through opencode's `task` tool\n // instead — which lets opencode's configured subagent set (`build`,\n // `general`, custom subagents in opencode.json) execute the work\n // under opencode's permission/lifecycle, rather than Claude's\n // internal-only general-purpose / Explore / Plan options.\n const nameMap: Record<string, string[]> = {\n bash: [\"Bash\"],\n read: [\"Read\"],\n write: [\"Write\"],\n edit: [\"Edit\", \"MultiEdit\"],\n glob: [\"Glob\"],\n grep: [\"Grep\"],\n webfetch: [\"WebFetch\"],\n task: [\"Agent\"],\n // `question` disables Claude Code's built-in `AskUserQuestion` so the\n // structured-questions path flows through opencode's native `question`\n // tool instead — same UI/permission/audit benefits as the other\n // proxies. Without this, the model can call both and the two paths\n // diverge (opencode's form vs the headless deny-and-render fallback).\n question: [\"AskUserQuestion\"],\n }\n const out: string[] = []\n const seen = new Set<string>()\n for (const t of tools) {\n const mapped = nameMap[t.name.toLowerCase()]\n if (!mapped) continue\n for (const claudeTool of mapped) {\n if (seen.has(claudeTool)) continue\n seen.add(claudeTool)\n out.push(claudeTool)\n }\n }\n return out\n}\n\n/**\n * Everything that goes to `--disallowedTools` for one spawn: the built-ins\n * the proxied tools replace, plus the ones the operator named directly.\n *\n * `disallowedToolFlags` can only cover tools the plugin has a proxy for, so\n * a built-in with no equivalent (`NotebookEdit`, and anything Claude Code\n * ships next) is unreachable without `extraDisallowedTools` — issue #26.\n */\nexport function resolveDisallowedTools(options: {\n proxyTools?: ProxyToolDef[] | null\n extraDisallowedTools?: string[]\n disableWebSearch?: boolean\n}): string[] {\n const out: string[] = []\n const seen = new Set<string>()\n const push = (name: string) => {\n const trimmed = name.trim()\n if (!trimmed || seen.has(trimmed)) return\n seen.add(trimmed)\n out.push(trimmed)\n }\n\n for (const name of disallowedToolFlags(options.proxyTools ?? [])) push(name)\n for (const name of options.extraDisallowedTools ?? []) push(String(name))\n if (options.disableWebSearch) push(\"WebSearch\")\n return out\n}\n\nfunction readBody(req: IncomingMessage): Promise<string> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = []\n req.on(\"data\", (chunk: Buffer) => chunks.push(chunk))\n req.on(\"end\", () => resolve(Buffer.concat(chunks).toString(\"utf8\")))\n req.on(\"error\", reject)\n })\n}\n\n/**\n * The single exit for every `tools/call`, broker-backed or intercepted.\n * Success and failure share one MCP result envelope: a JSON-RPC error for\n * `kind: \"error\"` was rejected by Claude CLI as a \"malformed result that\n * failed schema validation\", so tool failures must surface as\n * `isError: true` instead.\n */\nfunction writeToolCallResult(\n res: ServerResponse,\n requestId: unknown,\n result: ProxyToolResult,\n sse: EventStream | null = null,\n): void {\n const text = result.kind === \"error\" ? result.message : result.text\n const isError = result.kind === \"error\" || result.isError === true\n const envelope = {\n jsonrpc: \"2.0\",\n id: requestId ?? null,\n result: {\n content: [{ type: \"text\", text }],\n isError,\n },\n }\n if (sse) {\n sse.finish(envelope)\n return\n }\n writeJson(res, envelope)\n}\n\n/**\n * An in-flight SSE reply. `finish` writes the JSON-RPC response as the\n * single `message` event and ends the stream, which is what the MCP\n * Streamable HTTP client expects for a request answered over SSE.\n */\ninterface EventStream {\n finish(envelope: unknown): void\n stop(): void\n}\n\nfunction openEventStream(res: ServerResponse): EventStream {\n res.statusCode = 200\n res.setHeader(\"Content-Type\", \"text/event-stream\")\n res.setHeader(\"Cache-Control\", \"no-cache, no-transform\")\n res.setHeader(\"Connection\", \"keep-alive\")\n res.flushHeaders()\n // Start the response body without waiting for the tool result.\n res.write(\": open\\n\\n\")\n let timer: ReturnType<typeof setInterval> | null = setInterval(() => {\n if (res.writableEnded || res.destroyed) {\n stop()\n return\n }\n res.write(\": keepalive\\n\\n\")\n }, SSE_KEEPALIVE_MS)\n // Never keep the host process alive for a keepalive alone.\n timer.unref?.()\n const stop = () => {\n if (timer) {\n clearInterval(timer)\n timer = null\n }\n }\n return {\n stop,\n finish(envelope) {\n stop()\n if (res.writableEnded || res.destroyed) return\n res.end(`event: message\\ndata: ${JSON.stringify(envelope)}\\n\\n`)\n },\n }\n}\n\nfunction writeJson(res: ServerResponse, body: unknown): void {\n if (res.destroyed || res.writableEnded) return\n const payload = JSON.stringify(body)\n res.statusCode = 200\n res.setHeader(\"Content-Type\", \"application/json\")\n res.setHeader(\"Content-Length\", Buffer.byteLength(payload).toString())\n res.end(payload)\n}\n","import * as fs from \"node:fs\"\nimport * as os from \"node:os\"\nimport * as path from \"node:path\"\n\n/**\n * Per-process scratch directory for plugin tmp files (bridged MCP config,\n * proxy server config, etc.). Created lazily on first use and rm'd on\n * normal process exit so we don't leak across runs. PID-isolated so two\n * concurrent opencode processes don't race on the same files.\n *\n * Caveat: `process.on(\"exit\")` does not fire for SIGKILL or unhandled\n * external signals, so abnormal terminations still leak. OS-level tmpdir\n * cleanup (`systemd-tmpfiles`, macOS periodic) handles those eventually.\n */\nconst PLUGIN_TMP_DIR = path.join(\n os.tmpdir(),\n `opencode-claude-code-${process.pid}`,\n)\n\nlet registered = false\n\nexport function pluginTmpDir(): string {\n if (!fs.existsSync(PLUGIN_TMP_DIR)) {\n fs.mkdirSync(PLUGIN_TMP_DIR, { recursive: true })\n }\n if (!registered) {\n registered = true\n process.on(\"exit\", () => {\n try {\n fs.rmSync(PLUGIN_TMP_DIR, { recursive: true, force: true })\n } catch {}\n })\n }\n return PLUGIN_TMP_DIR\n}\n","export const QUESTION_TOOL_NAME = \"question\"\n\nexport const APPROVED_EXIT_PLAN_MODE_MESSAGE =\n \"User has approved your plan. You can now start coding. Start with updating your todo list if applicable.\"\n\nconst REJECTED_EXIT_PLAN_MODE_PREFIX =\n \"The user doesn't want to proceed with this tool use. The tool use was rejected. To tell you how to proceed, the user said:\"\n\nconst PLAN_MODE_APPROVAL_QUESTION = \"Do you want to proceed with this plan?\"\nconst OPENCODE_QUESTION_RESULT_PREFIX =\n `User has answered your questions: \"${PLAN_MODE_APPROVAL_QUESTION}\"=\"`\nconst OPENCODE_QUESTION_RESULT_SUFFIX =\n `\". You can now continue with the user's answers in mind.`\n\nconst KEY_SEPARATOR = \"\\u0000\"\n\nexport interface ExitPlanModeQuestionCall {\n toolCallId: string\n toolName: typeof QUESTION_TOOL_NAME\n input: {\n questions: Array<{\n header: string\n question: string\n options: Array<{ label: string; description: string }>\n multiple: boolean\n custom: boolean\n }>\n }\n text: string\n}\n\n/**\n * Whether to bridge `ExitPlanMode` into opencode's native `question` tool\n * this turn.\n *\n * Opt-in (`planModeQuestion`) because opencode's question form does not\n * currently render (anomalyco/opencode#36604), so an enabled bridge hangs the\n * turn until the operator interrupts, where the text path still works.\n * Gated on the live registry because emitting a `question` tool-call on a\n * build without that entry renders `⚙ invalid` and wedges the turn just the\n * same. Never bridged during compaction: that turn is text-only and its\n * answer would have nowhere to go.\n */\nexport function isPlanModeQuestionActive(input: {\n configured: boolean | undefined\n opencodeHasQuestion: boolean\n compactionMode: boolean\n}): boolean {\n if (input.compactionMode) return false\n if (input.configured !== true) return false\n return input.opencodeHasQuestion\n}\n\nconst pendingQuestions = new Map<string, string>()\n\nfunction pendingKey(sessionKey: string, questionToolCallId: string): string {\n return `${sessionKey}${KEY_SEPARATOR}${questionToolCallId}`\n}\n\nexport function clearExitPlanModeQuestions(sessionKey: string): void {\n const prefix = `${sessionKey}${KEY_SEPARATOR}`\n for (const key of pendingQuestions.keys()) {\n if (key.startsWith(prefix)) pendingQuestions.delete(key)\n }\n}\n\nexport function hasExitPlanModeQuestions(sessionKey: string): boolean {\n const prefix = `${sessionKey}${KEY_SEPARATOR}`\n return [...pendingQuestions.keys()].some((key) => key.startsWith(prefix))\n}\n\nexport function createExitPlanModeQuestionCall(\n sessionKey: string,\n exitPlanModeToolUseId: string,\n plan: string,\n questionToolCallId = `exit_plan_question_${exitPlanModeToolUseId}`,\n): ExitPlanModeQuestionCall {\n pendingQuestions.set(pendingKey(sessionKey, questionToolCallId), exitPlanModeToolUseId)\n\n return {\n toolCallId: questionToolCallId,\n toolName: QUESTION_TOOL_NAME,\n input: {\n questions: [\n {\n header: \"Plan approval\",\n question: PLAN_MODE_APPROVAL_QUESTION,\n options: [\n { label: \"yes\", description: \"\" },\n { label: \"no\", description: \"\" },\n ],\n multiple: false,\n custom: true,\n },\n ],\n },\n text: plan ? `\\n\\n${plan}\\n` : \"\\n\\n\",\n }\n}\n\nfunction buildToolResultMessage(input: {\n toolUseId: string\n approved: boolean\n feedback: string\n}): string {\n return JSON.stringify({\n type: \"user\",\n message: {\n role: \"user\",\n content: [\n input.approved\n ? {\n type: \"tool_result\",\n tool_use_id: input.toolUseId,\n content: APPROVED_EXIT_PLAN_MODE_MESSAGE,\n }\n : {\n type: \"tool_result\",\n tool_use_id: input.toolUseId,\n content: `${REJECTED_EXIT_PLAN_MODE_PREFIX}\\n${input.feedback || \"no\"}`,\n is_error: true,\n },\n ],\n },\n })\n}\n\nfunction tryParseJson(text: string): unknown {\n try {\n return JSON.parse(text)\n } catch {\n return text\n }\n}\n\nfunction unwrapToolOutput(part: any): unknown {\n const output = part?.output ?? part?.result\n if (typeof output === \"string\") return tryParseJson(output)\n if (!output || typeof output !== \"object\") return output\n\n switch (output.type) {\n case \"json\":\n case \"error-json\":\n return output.value\n case \"text\":\n case \"error-text\":\n return tryParseJson(String(output.value ?? \"\"))\n case \"execution-denied\":\n return {\n denied: true,\n reason: String(output.reason ?? \"question rejected\"),\n }\n case \"content\":\n return Array.isArray(output.value)\n ? output.value\n .map((item: any) => {\n if (item?.type === \"text\") return item.text\n return JSON.stringify(item)\n })\n .join(\"\\n\")\n : output.value\n default:\n return output\n }\n}\n\nfunction unwrapOpencodeQuestionResult(value: string): string {\n if (\n value.startsWith(OPENCODE_QUESTION_RESULT_PREFIX) &&\n value.endsWith(OPENCODE_QUESTION_RESULT_SUFFIX)\n ) {\n return value.slice(\n OPENCODE_QUESTION_RESULT_PREFIX.length,\n -OPENCODE_QUESTION_RESULT_SUFFIX.length,\n )\n }\n return value\n}\n\nfunction collectAnswerStrings(value: unknown): string[] {\n if (typeof value === \"string\") return [unwrapOpencodeQuestionResult(value)]\n if (Array.isArray(value)) return value.flatMap(collectAnswerStrings)\n if (!value || typeof value !== \"object\") return []\n\n const obj = value as Record<string, unknown>\n if (obj.denied === true) return [String(obj.reason ?? \"question rejected\")]\n\n for (const key of [\"answers\", \"answer\", \"selected\", \"selection\", \"value\"]) {\n if (key in obj) return collectAnswerStrings(obj[key])\n }\n\n return []\n}\n\nfunction classifyQuestionResult(part: any): { approved: boolean; feedback: string } {\n const output = unwrapToolOutput(part)\n const answers = collectAnswerStrings(output)\n .map((answer) => answer.trim())\n .filter(Boolean)\n\n if (answers.length === 1 && answers[0].toLowerCase() === \"yes\") {\n return { approved: true, feedback: \"\" }\n }\n\n return {\n approved: false,\n feedback: answers.length > 0 ? answers.join(\"\\n\") : \"no\",\n }\n}\n\nexport function consumeExitPlanModeQuestionResult(\n sessionKey: string,\n prompt: Array<{ role: string; content?: unknown }>,\n): string | null {\n for (let i = prompt.length - 1; i >= 0; i--) {\n const msg = prompt[i]\n if (!Array.isArray(msg.content)) continue\n\n for (const part of msg.content as any[]) {\n if (part?.type !== \"tool-result\" || typeof part.toolCallId !== \"string\") {\n continue\n }\n\n const key = pendingKey(sessionKey, part.toolCallId)\n const exitPlanModeToolUseId = pendingQuestions.get(key)\n if (!exitPlanModeToolUseId) continue\n\n pendingQuestions.delete(key)\n const result = classifyQuestionResult(part)\n return buildToolResultMessage({\n toolUseId: exitPlanModeToolUseId,\n approved: result.approved,\n feedback: result.feedback,\n })\n }\n }\n\n return null\n}\n","/**\n * Per-session state for the opt-in `compress` proxy tool.\n *\n * Keyed by session key (the same `cwd::modelId::scope::affinity` string\n * session-manager uses). When Claude calls the intercepted `compress` tool\n * the summary is stored here and the session is marked for restart. The\n * next `doStream` turn consumes that mark, evicts the running child and its\n * Claude session id, and the fresh spawn gets the summary prepended to its\n * appended system prompt.\n *\n * The summary deliberately survives `deleteClaudeSessionId()`: the restart\n * path calls it, so clearing there would wipe the summary microseconds\n * before the new spawn reads it (the original fork version did exactly\n * that, which made the whole feature a no-op). It is dropped when a new\n * opencode conversation starts on the same key, and by the entry cap below.\n */\n\nimport { log } from \"./logger.js\"\n\ninterface CompressionState {\n summary: string\n restartPending: boolean\n}\n\n/**\n * Session keys are bounded in practice by workspaces × models, and each\n * entry is one summary string, but a long-lived opencode process that\n * hops workspaces should not accumulate them forever.\n */\nconst MAX_COMPRESSION_ENTRIES = 32\n\nconst compressions = new Map<string, CompressionState>()\n\n/**\n * Record a summary and mark the session for restart. Storing and marking\n * are one event on purpose: a stored summary that never resets the session\n * would silently do nothing.\n */\nexport function storeCompressionSummary(sessionKey: string, summary: string): void {\n compressions.set(sessionKey, { summary, restartPending: true })\n while (compressions.size > MAX_COMPRESSION_ENTRIES) {\n const oldest = compressions.keys().next()\n if (oldest.done) break\n compressions.delete(oldest.value)\n log.info(\"compression store evicted oldest entry\", { sessionKey: oldest.value })\n }\n}\n\nexport function getCompressionSummary(sessionKey: string): string | undefined {\n return compressions.get(sessionKey)?.summary\n}\n\n/**\n * True once per compress call, for the turn that performs the reset. The\n * summary is kept: it is the prior context for every spawn that follows,\n * until a new conversation clears it.\n */\nexport function consumeCompressionRestart(sessionKey: string): boolean {\n const state = compressions.get(sessionKey)\n if (!state?.restartPending) return false\n state.restartPending = false\n return true\n}\n\nexport function clearCompression(sessionKey: string): void {\n compressions.delete(sessionKey)\n}\n","import { randomUUID } from \"node:crypto\"\nimport type { ChildProcess } from \"node:child_process\"\nimport { cliSupportsSideQuestion, type CliVersion } from \"./cli-version.js\"\nimport type { ActiveProcess } from \"./session-manager.js\"\n\ntype SideQuestionProcess = Pick<ActiveProcess, \"proc\" | \"lineEmitter\">\n\nexport interface SideQuestionResult {\n response: string\n synthetic: boolean\n}\n\nexport interface SideQuestionOptions {\n cliVersion: CliVersion | null\n interactive?: boolean\n abortSignal?: AbortSignal\n timeoutMs?: number\n history?: readonly { question: string; response: string }[]\n}\n\nexport interface SideQuestionExchange {\n question: string\n response: string\n}\n\nconst MAX_HISTORY_EXCHANGES = 20\n\nexport const SIDE_QUESTION_USAGE =\n \"Usage: /btw <question>. Ask a side question about the current conversation without adding it to the main context.\"\n\nconst pendingProcesses = new WeakSet<ChildProcess>()\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value)\n}\n\n/**\n * opencode appends its own `<system-reminder>` blocks to the user message, as\n * extra text parts on the same message. They instruct a normal turn and are not\n * part of what the operator typed after `/btw`, so they must not travel with the\n * aside: a plan-mode reminder alone is over 1.5 KB, and measured live it both\n * steered the answer and kept a bare `/btw` from ever looking empty.\n *\n * Blocks are removed wherever they sit rather than by matching a whole part,\n * because a harness may append its own trailing metadata after one (opencode-dcp\n * adds a `<dcp-message-id>` marker), which an end-anchored check would miss.\n */\nconst SYSTEM_REMINDER_BLOCK = /<system-reminder>[\\s\\S]*?<\\/system-reminder>/g\n\nexport function parseSideQuestionContent(content: unknown): { question: string } | null {\n let text: string\n if (typeof content === \"string\") {\n text = content\n } else if (Array.isArray(content)) {\n const parts: string[] = []\n for (const part of content) {\n if (!isRecord(part) || part.type !== \"text\" || typeof part.text !== \"string\") return null\n parts.push(part.text)\n }\n text = parts.join(\"\\n\")\n } else {\n return null\n }\n const match = /^\\/btw(?:\\s+([\\s\\S]*))?$/.exec(text.replace(SYSTEM_REMINDER_BLOCK, \"\").trim())\n return match ? { question: (match[1] ?? \"\").trim() } : null\n}\n\n/** Do not replay a historical /btw during an assistant/tool continuation. */\nexport function parseSideQuestion(\n prompt: readonly { role: string; content: unknown }[],\n): { question: string } | null {\n const latest = prompt.at(-1)\n return latest?.role === \"user\" ? parseSideQuestionContent(latest.content) : null\n}\n\nfunction assistantText(content: unknown): string {\n if (typeof content === \"string\") return content.trim()\n if (!Array.isArray(content)) return \"\"\n const parts: string[] = []\n for (const part of content) {\n if (isRecord(part) && part.type === \"text\" && typeof part.text === \"string\") parts.push(part.text)\n }\n return parts.join(\"\\n\").trim()\n}\n\n/**\n * Earlier `/btw` exchanges in this conversation, oldest first, for the\n * control request's `history` so follow-ups can refer to previous asides.\n * The final user message is the current question and is left out.\n */\nexport function collectSideQuestionHistory(\n prompt: readonly { role: string; content: unknown }[],\n): SideQuestionExchange[] {\n const history: SideQuestionExchange[] = []\n for (let index = 0; index < prompt.length - 1; index++) {\n const message = prompt[index]\n if (message.role !== \"user\") continue\n const aside = parseSideQuestionContent(message.content)\n if (!aside?.question) continue\n const reply = prompt[index + 1]\n if (reply.role !== \"assistant\") continue\n const response = assistantText(reply.content)\n if (!response || response === SIDE_QUESTION_USAGE) continue\n history.push({ question: aside.question, response })\n }\n return history.slice(-MAX_HISTORY_EXCHANGES)\n}\n\nexport function isSideQuestionPending(activeProcess: SideQuestionProcess): boolean {\n return pendingProcesses.has(activeProcess.proc)\n}\n\n/**\n * Call before the normal stdout line/buffer dispatch. Only a response with an\n * active request-ID listener is consumed. Progress and unrelated lines retain\n * their existing routing; the helper never subscribes to the shared `line` event.\n */\nexport function dispatchSideQuestionResponse(\n activeProcess: SideQuestionProcess,\n line: string,\n): boolean {\n if (!pendingProcesses.has(activeProcess.proc)) return false\n let message: unknown\n try {\n message = JSON.parse(line)\n } catch {\n return false\n }\n if (!isRecord(message) || message.type !== \"control_response\") return false\n const response = message.response\n if (!isRecord(response) || typeof response.request_id !== \"string\") return false\n return activeProcess.lineEmitter.emit(`side-question:${response.request_id}`, response)\n}\n\n/**\n * Uses an existing headless process, never a user envelope or a new spawn.\n * The process may be mid-turn: Claude Code answers `side_question` on a\n * separate advisor call while the main loop keeps running (measured live on\n * 2.1.258 with the turn blocked on a held MCP tool). Only one aside per\n * process is in flight at a time; responses are matched by request id ahead\n * of the normal stdout routing, so a streaming turn never sees them.\n */\nexport async function requestSideQuestion(\n activeProcess: SideQuestionProcess,\n question: string,\n options: SideQuestionOptions,\n): Promise<SideQuestionResult> {\n question = question.trim()\n if (!question) return { response: SIDE_QUESTION_USAGE, synthetic: true }\n options.abortSignal?.throwIfAborted()\n const { proc, lineEmitter } = activeProcess\n if (options.interactive || !proc.stdout) {\n throw new Error(\"/btw requires the headless Claude Code transport; interactive sessions are not supported.\")\n }\n if (!cliSupportsSideQuestion(options.cliVersion)) {\n throw new Error(\"/btw requires Claude Code CLI 2.1.258 or newer (the oldest verified version).\")\n }\n if (pendingProcesses.has(proc)) {\n throw new Error(\"Wait for the current /btw to finish before asking another.\")\n }\n const stdin = proc.stdin\n if (proc.killed || proc.exitCode != null || proc.signalCode != null ||\n !stdin || stdin.destroyed || stdin.writableEnded || !stdin.writable) {\n throw new Error(\"/btw requires a live Claude Code session with writable stdin.\")\n }\n const timeoutMs = options.timeoutMs ?? 120_000\n if (!Number.isInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2_147_483_647) {\n throw new Error(\"/btw timeoutMs must be a positive 32-bit integer.\")\n }\n const requestId = randomUUID()\n const request = JSON.stringify({\n type: \"control_request\",\n request_id: requestId,\n request: {\n subtype: \"side_question\",\n question,\n ...(options.history === undefined ? {} : { history: options.history }),\n },\n })\n\n pendingProcesses.add(proc)\n return new Promise<SideQuestionResult>((resolve, reject) => {\n const event = `side-question:${requestId}`\n let settled = false\n let sent = false\n let cancelPending = false\n\n const cleanup = (): void => {\n clearTimeout(timer)\n lineEmitter.off(event, onResponse)\n lineEmitter.off(\"close\", onClose)\n lineEmitter.off(\"error\", onError)\n proc.off(\"exit\", onClose)\n proc.off(\"close\", onClose)\n proc.off(\"error\", onError)\n if (!cancelPending) stdin.off(\"error\", onError)\n options.abortSignal?.removeEventListener(\"abort\", onAbort)\n pendingProcesses.delete(proc)\n }\n const fail = (error: unknown, cancel = false): void => {\n if (settled) return\n settled = true\n if (cancel && sent && !stdin.destroyed && !stdin.writableEnded && stdin.writable) {\n try {\n cancelPending = true\n stdin.write(\n JSON.stringify({ type: \"control_cancel_request\", request_id: requestId }) + \"\\n\",\n () => {\n // A failed write emits `error` after its callback. Keep the pipe\n // listener through that event without delaying abort/timeout.\n queueMicrotask(() => stdin.off(\"error\", onError))\n },\n )\n } catch {\n cancelPending = false\n // Preserve the original abort/timeout even if the child has gone away.\n }\n }\n cleanup()\n reject(error)\n }\n const onClose = (): void => fail(new Error(\"Claude Code closed before answering /btw.\"))\n const onError = (error: Error): void => fail(error)\n const onAbort = (): void => fail(\n options.abortSignal?.reason ?? new DOMException(\"/btw was aborted.\", \"AbortError\"),\n true,\n )\n const onResponse = (response: Record<string, unknown>): void => {\n if (settled || response.request_id !== requestId) return\n if (response.subtype === \"error\") {\n fail(new Error(typeof response.error === \"string\" ? response.error : \"Claude Code rejected /btw.\"))\n return\n }\n const result = response.response\n if (response.subtype !== \"success\" || !isRecord(result) ||\n typeof result.response !== \"string\" || typeof result.synthetic !== \"boolean\") {\n fail(new Error(\"Claude Code returned an invalid /btw response.\"))\n return\n }\n settled = true\n cleanup()\n resolve({ response: result.response, synthetic: result.synthetic })\n }\n const timer = setTimeout(() => {\n fail(new Error(`/btw timed out after ${timeoutMs}ms.`), true)\n }, timeoutMs)\n\n lineEmitter.on(event, onResponse)\n lineEmitter.on(\"close\", onClose)\n lineEmitter.on(\"error\", onError)\n proc.on(\"exit\", onClose)\n proc.on(\"close\", onClose)\n proc.on(\"error\", onError)\n stdin.on(\"error\", onError)\n options.abortSignal?.addEventListener(\"abort\", onAbort, { once: true })\n if (options.abortSignal?.aborted) {\n onAbort()\n return\n }\n try {\n sent = true\n stdin.write(request + \"\\n\")\n } catch (error) {\n fail(error)\n }\n })\n}\n","import { detectCliVersion } from \"./cli-version.js\"\nimport { log } from \"./logger.js\"\nimport { getOpencodeClient } from \"./runtime-status.js\"\nimport { findActiveProcessBySessionId, type ActiveProcess } from \"./session-manager.js\"\nimport {\n collectSideQuestionHistory,\n isSideQuestionPending,\n requestSideQuestion,\n SIDE_QUESTION_USAGE,\n type SideQuestionExchange,\n type SideQuestionResult,\n} from \"./side-question.js\"\n\n/**\n * `/btw`: a side question that is answered while the main turn keeps running,\n * and whose exchange is kept in the conversation where it was asked.\n *\n * opencode's TUI sends every slash command to the server the moment it is\n * typed, busy or not (`tui/component/prompt/index.tsx`), so the\n * `command.execute.before` hook fires immediately. The user message the\n * command produces is what gets held back (\"Queued\") until the running turn\n * ends, and opencode's loop then runs it as a step of its own: the loop only\n * exits when the newest assistant message answers the newest user message\n * (`session/prompt.ts`, `lastAssistant.parentID === lastUser.id`).\n *\n * So the hook sends the question to the conversation's live `claude` process\n * as a `side_question` control request right away (Claude Code answers those\n * on a separate advisor call, concurrently with a running turn, from the\n * conversation's context) and remembers the pending answer per session. Where\n * the answer lands then depends on what is open when it arrives:\n * 1. a turn is streaming, so the answer is written into that turn's own\n * reply as its own text block and the `/btw` message is dropped. The\n * operator reads it in place, the moment it is ready, and it stays;\n * 2. nothing is open to write to, so the `/btw` message is held until the\n * turn ends. It then reaches the aside branch in\n * `claude-code-language-model.ts`, which takes the remembered answer and\n * emits it as that message's reply, at no cost;\n * 3. the conversation was idle all along, so the message runs at once and\n * case 2 is all that happens.\n * Every one of those lands in the conversation, so none of them toasts: a\n * toast expires and the operator asked for the answer to stay. The two that\n * remain are the paths where nothing reaches the conversation at all, a bare\n * `/btw` and a turn that never ended, where a toast is the only feedback left.\n * `filterSideQuestionHistory` keeps every `/btw` pair out of Claude's prompt,\n * `INLINE_ASIDE_MARKER` does the same for case 1's block, and the control\n * request never touches Claude's own transcript, so an aside is persisted for\n * the operator only.\n */\n\ntype SdkResult<T = unknown> = Promise<{ data?: T; error?: unknown }>\n\nexport interface BtwToast {\n title?: string\n message: string\n variant: \"info\" | \"success\" | \"warning\" | \"error\"\n duration?: number\n}\n\nexport interface BtwSdkMessage {\n info?: { role?: string }\n parts?: unknown[]\n}\n\nexport interface BtwSdkClient {\n session?: {\n messages?: (options: { path: { id: string } }) => SdkResult<BtwSdkMessage[]>\n /** `GET /session/status`: sessions missing from the map are idle. */\n status?: () => SdkResult<Record<string, { type: string }>>\n }\n tui?: {\n showToast?: (options: { body: BtwToast }) => SdkResult\n }\n}\n\nexport interface BtwCommandInput {\n command: string\n sessionID: string\n arguments: string\n}\n\n/** Every wait the hook can make, so tests do not have to sit through them. */\nexport interface BtwWaitOptions {\n /** How often to re-read opencode's session status. */\n pollMs?: number\n /** Cap on holding the `/btw` message back while a turn runs. */\n timeoutMs?: number\n /** Cap on treating an idle-looking status as not yet registered. */\n settleMs?: number\n /** Cap on waiting for the running turn's `claude` process to be tagged. */\n spawnWaitMs?: number\n /** How often to retry writing the answer into the running turn. */\n inlinePollMs?: number\n /** Cap on waiting for a stream to write the answer into. */\n inlineWaitMs?: number\n}\n\n/** Thrown to make opencode drop the prompt when there is nothing worth keeping. */\nexport class BtwHandledError extends Error {\n override readonly name = \"BtwHandledError\"\n constructor(message = \"/btw was handled by the claude-code plugin; nothing to add to this conversation.\") {\n super(message)\n }\n}\n\nexport const BTW_NO_SESSION_MESSAGE =\n \"/btw needs a live Claude Code session in this conversation. Send a normal message with a Claude Code model first, then ask again.\"\n\nexport const BTW_INLINE_HANDLED_MESSAGE =\n \"/btw was answered inside the running turn; nothing to add to this conversation.\"\n\nexport const BTW_TURN_TOO_LONG_MESSAGE =\n \"/btw gave up waiting for this turn to end. Ask again once it is over.\"\n\nconst IDLE_POLL_MS = 500\nconst IDLE_WAIT_MAX_MS = 30 * 60_000\n/**\n * How long a single status read is allowed to be wrong. opencode registers\n * the turn a moment after the TUI sends the command, and a session missing\n * from `GET /session/status` reads as idle, so a `/btw` typed inside that gap\n * would decide the conversation is free and let its message queue.\n */\nconst BUSY_SETTLE_MS = 1_500\n/**\n * How long to wait for the turn's `claude` process to appear. doStream tags\n * the process only once it attaches its line listener, which is after the\n * whole spawn path, so the first `/btw` of a conversation regularly arrives\n * before there is anything to ask. Bounded, because the running turn may\n * belong to another provider and then no process is ever coming.\n */\nconst SPAWN_WAIT_MAX_MS = 30_000\n\nconst INLINE_POLL_MS = 200\n/**\n * How long to keep trying to write into the turn. A turn is a run of streams,\n * not one: every proxy tool call ends the current stream and opencode opens\n * the next one with the tool's result, so an answer that arrives inside that\n * gap has nothing to write to yet and has to wait for the next stream.\n */\nconst INLINE_WAIT_MAX_MS = 20_000\n\nconst PENDING_ANSWER_TTL_MS = 10 * 60_000\nconst PENDING_ANSWER_CAP = 32\n\ninterface PendingAnswer {\n question: string\n answer: Promise<SideQuestionResult>\n at: number\n}\n\n/** Answers the hook requested ahead of the queued prompt, one per opencode session. */\nconst pendingAnswers = new Map<string, PendingAnswer>()\n\nexport function rememberSideQuestionAnswer(\n sessionID: string,\n question: string,\n answer: Promise<SideQuestionResult>,\n now = Date.now(),\n): void {\n for (const [id, entry] of pendingAnswers) {\n if (now - entry.at > PENDING_ANSWER_TTL_MS) pendingAnswers.delete(id)\n }\n pendingAnswers.delete(sessionID)\n while (pendingAnswers.size >= PENDING_ANSWER_CAP) {\n const oldest = pendingAnswers.keys().next().value\n if (oldest === undefined) break\n pendingAnswers.delete(oldest)\n }\n pendingAnswers.set(sessionID, { question: question.trim(), answer, at: now })\n}\n\n/**\n * The answer the hook already requested for this session, if it was for this\n * question and is still fresh. Taking it consumes it: a later `/btw` with the\n * same text asks again rather than replaying a stale answer.\n *\n * The question the turn parses may be longer than what the hook saw: a\n * harness can append trailing metadata to the message text (opencode-dcp adds\n * a `<dcp-message-id>` marker), so the hook's question only has to be a prefix.\n * Measured live: an exact match missed, the turn asked again, and the\n * single-flight guard refused it as a second concurrent aside.\n */\nexport function takeSideQuestionAnswer(\n sessionID: string,\n question: string,\n now = Date.now(),\n): Promise<SideQuestionResult> | undefined {\n const entry = pendingAnswers.get(sessionID)\n if (!entry) return undefined\n pendingAnswers.delete(sessionID)\n if (!question.trim().startsWith(entry.question) || now - entry.at > PENDING_ANSWER_TTL_MS) return undefined\n return entry.answer\n}\n\n/** Test seam. */\nexport function clearPendingSideQuestionAnswers(): void {\n pendingAnswers.clear()\n}\n\n/**\n * Header of the block an aside writes into the running turn's own reply, and\n * the marker `message-builder` strips by when a transcript has to be rebuilt\n * for a fresh Claude process. Kept as the first characters of its own text\n * part so the strip is exact rather than a guess at where the block ends.\n */\nexport const INLINE_ASIDE_MARKER = \"▌ **btw:**\"\n\n/**\n * Markers of blocks written before the bar replaced the blockquote. Only the\n * strip reads these: a conversation that already holds an old aside still has\n * to keep it out of a rebuilt transcript.\n */\nexport const LEGACY_INLINE_ASIDE_MARKERS = [\"> **btw:**\"]\n\n/**\n * A literal bar on every line, blank ones included, so the aside reads as one\n * block down its whole height.\n *\n * The obvious alternative, a markdown blockquote, was tried first and is why\n * this exists: opencode renders assistant text with OpenTUI's markdown, which\n * draws a blockquote's left border in the `conceal` scope's colour, not the\n * theme's `markdownBlockQuote`. That border is dim by design and there is no\n * per-block way to change it, so the bar has to be text the plugin emits.\n * Line breaks survive because OpenTUI renders a paragraph from `token.raw`,\n * verbatim, rather than reflowing it.\n */\nfunction barEveryLine(text: string): string {\n return text\n .split(\"\\n\")\n .map((line) => (line.trim() === \"\" ? \"▌\" : `▌ ${line}`))\n .join(\"\\n\")\n}\n\nfunction oneLine(question: string): string {\n return question.replace(/\\s+/g, \" \").trim()\n}\n\nfunction asideHeader(question: string): string {\n return `${INLINE_ASIDE_MARKER} ${oneLine(question)}`\n}\n\nexport function formatInlineAside(question: string, answer: string): string {\n return `\\n${asideHeader(question)}\\n▌\\n${barEveryLine(answer.trim())}\\n`\n}\n\n/**\n * The receipt's trailing note. Past tense, because the block stays in the\n * conversation and an \"answering...\" would read as stale the moment the\n * answer lands.\n */\nexport const INLINE_ASIDE_SENT_NOTE = \"*sent to Claude on the side*\"\n\n/**\n * A receipt written into the running turn the moment the question goes out, so\n * a `/btw` typed mid-turn shows as taken instead of looking swallowed until\n * the answer arrives.\n *\n * It quotes the question back **in full**, which is what the operator asked\n * for: the prompt box clears on submit and no `/btw` message is ever created,\n * so this is the only place the question can be read back. It was briefly\n * capped at 240 characters and that was wrong for the same reason, since a\n * long aside would then be unreadable everywhere. The note goes on its own bar\n * line so the question is never crowded by it.\n *\n * The answer block repeats the question rather than dropping it, because the\n * model keeps streaming its own text between the two and a headerless answer\n * arriving after that reads as orphaned.\n */\nexport function formatInlineAsideAsk(question: string): string {\n return `\\n${asideHeader(question)}\\n▌ ${INLINE_ASIDE_SENT_NOTE}\\n`\n}\n\n/**\n * Writes one finished text block into a stream that is open right now.\n * Returns false when there is nothing to write to, which is the whole reason\n * the held-message path is still here.\n */\nexport type AsideSink = (text: string) => boolean\n\n/** At most one open stream per conversation, so a plain map is enough. */\nconst asideSinks = new Map<string, AsideSink>()\n\nexport function registerAsideSink(sessionID: string, sink: AsideSink): () => void {\n asideSinks.set(sessionID, sink)\n return () => {\n // Only the stream that registered may unregister: a later turn's sink\n // must survive the earlier turn's cleanup.\n if (asideSinks.get(sessionID) === sink) asideSinks.delete(sessionID)\n }\n}\n\nexport function emitAsideInline(sessionID: string, text: string): boolean {\n const sink = asideSinks.get(sessionID)\n if (!sink) return false\n try {\n return sink(text)\n } catch (error) {\n log.debug(\"btw: could not write the aside into the running turn\", { sessionID, error: errorText(error) })\n return false\n }\n}\n\n/** Test seam. */\nexport function clearAsideSinks(): void {\n asideSinks.clear()\n}\n\nexport function showToast(client: BtwSdkClient | null, body: BtwToast): void {\n // Keep the receiver: the SDK's namespace methods read `this._client`, so a\n // detached `const show = client.tui.showToast` throws at call time.\n try {\n void client?.tui?.showToast?.({ body })?.catch((error: unknown) => {\n log.debug(\"btw toast failed\", { error: errorText(error) })\n })\n } catch (error) {\n log.debug(\"btw toast failed\", { error: errorText(error) })\n }\n}\n\n/** A turn is streaming from this process, so its transcript cannot show an answer yet. */\nexport function isProcessBusy(active: Pick<ActiveProcess, \"lineEmitter\">): boolean {\n return active.lineEmitter.listenerCount(\"line\") > 0\n}\n\n/**\n * opencode's own view of the session: `busy` for the whole turn, including\n * the gaps where opencode runs a tool and no stream is attached to the\n * process, which `isProcessBusy` cannot see. `unknown` when the SDK has no\n * status route or it fails.\n */\nexport async function sessionStatus(\n client: BtwSdkClient | null,\n sessionID: string,\n): Promise<\"busy\" | \"idle\" | \"unknown\"> {\n const status = client?.session?.status\n if (!status) return \"unknown\"\n try {\n const result = await status.call(client!.session)\n const entry = result.data?.[sessionID]\n return entry && entry.type !== \"idle\" ? \"busy\" : \"idle\"\n } catch (error) {\n log.debug(\"btw: could not read session status\", { sessionID, error: errorText(error) })\n return \"unknown\"\n }\n}\n\n/**\n * Resolves once the session is no longer busy. Returns false on timeout. A\n * client without a status route resolves at once, since there is nothing to\n * wait on.\n */\nexport async function waitForSessionIdle(\n client: BtwSdkClient | null,\n sessionID: string,\n options: { pollMs?: number; timeoutMs?: number; stop?: () => boolean } = {},\n): Promise<boolean> {\n const pollMs = options.pollMs ?? IDLE_POLL_MS\n const timeoutMs = options.timeoutMs ?? IDLE_WAIT_MAX_MS\n const started = Date.now()\n for (;;) {\n if (options.stop?.()) return true\n if ((await sessionStatus(client, sessionID)) !== \"busy\") return true\n if (Date.now() - started >= timeoutMs) return false\n await new Promise((resolve) => setTimeout(resolve, pollMs))\n }\n}\n\n/**\n * Puts the answer in the conversation while the turn that prompted it is\n * still running, by writing it as its own text block into that turn's live\n * stream. It lands in the assistant reply the operator is already watching:\n * full markdown, scrollable, kept by opencode, and readable long after a\n * toast would have gone.\n *\n * Retries while the conversation stays busy, because a turn is a run of\n * streams rather than one and the gap between two of them is short. Gives up\n * once the turn ends, leaving the message to carry the answer instead.\n */\nexport async function deliverAsideInline(\n client: BtwSdkClient | null,\n sessionID: string,\n text: string,\n options: BtwWaitOptions = {},\n): Promise<boolean> {\n const pollMs = options.inlinePollMs ?? INLINE_POLL_MS\n const timeoutMs = options.inlineWaitMs ?? INLINE_WAIT_MAX_MS\n const started = Date.now()\n for (;;) {\n if (emitAsideInline(sessionID, text)) return true\n if (Date.now() - started >= timeoutMs) return false\n if ((await sessionStatus(client, sessionID)) !== \"busy\") return false\n await new Promise((resolve) => setTimeout(resolve, pollMs))\n }\n}\n\n/**\n * The `claude` process serving this conversation, waiting for it when a turn\n * is already running but has not yet reached the point where doStream tags it\n * (`claude-code-language-model.ts`, where the line listener attaches). That\n * gap is the whole spawn path on a conversation's first turn, and a `/btw`\n * typed inside it used to fall straight through, which is exactly what leaves\n * a \"Queued\" bubble in the transcript: measured live on 2026-09-06, a `/btw`\n * logged \"no live claude process for session\" and the same question 22 s\n * later found one and was answered concurrently.\n */\nexport async function waitForAsideProcess(\n client: BtwSdkClient | null,\n sessionID: string,\n options: BtwWaitOptions = {},\n): Promise<ActiveProcess | undefined> {\n const pollMs = options.pollMs ?? IDLE_POLL_MS\n const settleMs = options.settleMs ?? BUSY_SETTLE_MS\n const spawnWaitMs = options.spawnWaitMs ?? SPAWN_WAIT_MAX_MS\n const started = Date.now()\n for (;;) {\n const active = findActiveProcessBySessionId(sessionID)\n if (active) return active\n const busy = (await sessionStatus(client, sessionID)) === \"busy\"\n const waitedMs = Date.now() - started\n if (!busy && waitedMs >= settleMs) {\n // Nothing is running, so no process is on its way either.\n log.info(\"btw: no live claude process for session, leaving it to the turn\", { sessionID, waitedMs })\n return undefined\n }\n if (busy && waitedMs >= spawnWaitMs) {\n // A turn is running but it never produced a process of ours: it belongs\n // to another provider, or the spawn failed. Do not hold the message for\n // the rest of it.\n log.warn(\"btw: a turn is running but no claude process appeared for it\", { sessionID, waitedMs })\n return undefined\n }\n await new Promise((resolve) => setTimeout(resolve, pollMs))\n }\n}\n\n/**\n * Whether a turn is running, tolerant of the same registration lag: a status\n * read taken the instant `/btw` is typed can still say idle while opencode is\n * starting the turn, and skipping the hold on that reading is what queues the\n * message behind the turn instead of releasing it afterwards.\n */\nexport async function settleSessionBusy(\n client: BtwSdkClient | null,\n sessionID: string,\n active: Pick<ActiveProcess, \"lineEmitter\">,\n options: BtwWaitOptions = {},\n): Promise<boolean> {\n const pollMs = options.pollMs ?? IDLE_POLL_MS\n const settleMs = options.settleMs ?? BUSY_SETTLE_MS\n const started = Date.now()\n for (;;) {\n const status = await sessionStatus(client, sessionID)\n if (status === \"busy\") return true\n // No status route to poll: the process's own stream is all there is.\n if (status === \"unknown\") return isProcessBusy(active)\n if (Date.now() - started >= settleMs) return false\n await new Promise((resolve) => setTimeout(resolve, pollMs))\n }\n}\n\nfunction errorText(error: unknown): string {\n if (error instanceof Error) return error.message\n if (error && typeof error === \"object\" && \"message\" in error && typeof (error as { message: unknown }).message === \"string\") {\n return (error as { message: string }).message\n }\n return String(error)\n}\n\nfunction isTextPart(part: unknown): part is { type: \"text\"; text: string } {\n return (\n part !== null &&\n typeof part === \"object\" &&\n (part as { type?: unknown }).type === \"text\" &&\n typeof (part as { text?: unknown }).text === \"string\"\n )\n}\n\n/**\n * Earlier `/btw` exchanges in this conversation, read back from opencode\n * because the hook runs before the current question exists as a message.\n * Best effort: a follow-up without history still gets an answer, just one\n * that cannot refer to previous asides.\n */\nexport async function fetchAsideHistory(\n client: BtwSdkClient | null,\n sessionID: string,\n question: string,\n): Promise<SideQuestionExchange[]> {\n const messages = client?.session?.messages\n if (!messages) return []\n try {\n const result = await messages.call(client!.session, { path: { id: sessionID } })\n const prompt: { role: string; content: unknown }[] = []\n for (const message of result.data ?? []) {\n const role = message.info?.role\n if (role !== \"user\" && role !== \"assistant\") continue\n prompt.push({ role, content: (message.parts ?? []).filter(isTextPart) })\n }\n // collectSideQuestionHistory skips the final message as the question being\n // asked; stand in for the one opencode has not created yet.\n prompt.push({ role: \"user\", content: `/btw ${question}` })\n return collectSideQuestionHistory(prompt)\n } catch (error) {\n log.debug(\"btw: could not read aside history\", { sessionID, error: errorText(error) })\n return []\n }\n}\n\n/**\n * `command.execute.before` handler for `btw`. Returns normally so opencode\n * creates the `/btw` message in this conversation; throws only when there is\n * nothing to keep (a bare `/btw`, or a turn that never ended).\n *\n * While the session is busy the return is delayed until it is idle. opencode\n * would otherwise queue the message behind the running turn and run it as\n * that turn's next step, which is also the step that carries the results of\n * the tools opencode just ran: answering the aside there would swallow the\n * turn's own continuation (measured live: the main answer never appeared).\n * opencode already keeps the command route open for a queued prompt, so\n * holding it here changes nothing on the wire, and the TUI's call is\n * fire-and-forget.\n *\n * Both waits before that hold exist because a `/btw` typed early in a turn\n * used to be seen as belonging to an idle conversation with no process, and\n * was let through to be queued: `waitForAsideProcess` covers the spawn gap,\n * `settleSessionBusy` covers opencode registering the turn.\n */\nexport async function handleBtwCommand(\n client: BtwSdkClient | null,\n input: BtwCommandInput,\n options: BtwWaitOptions = {},\n): Promise<void> {\n const question = input.arguments.trim()\n if (!question) {\n showToast(client, { title: \"btw\", message: SIDE_QUESTION_USAGE, variant: \"warning\", duration: 6_000 })\n throw new BtwHandledError(\"/btw needs a question.\")\n }\n const active = await waitForAsideProcess(client, input.sessionID, options)\n const transport = active?.asideTransport\n if (!active || !transport) {\n // The message still goes through: the aside branch answers it with an\n // explanation that stays readable in the conversation.\n if (active) log.info(\"btw: process has no aside transport, leaving it to the turn\", { sessionID: input.sessionID })\n return\n }\n let busy = false\n let inlineDone = false\n let markInlineDelivered = (): void => {}\n const inlineDelivered = new Promise<\"inline\">((resolve) => {\n markInlineDelivered = () => {\n inlineDone = true\n resolve(\"inline\")\n }\n })\n if (isSideQuestionPending(active)) {\n // One aside per process at a time. Leave the earlier answer in place for\n // its own message; this one asks when its turn comes.\n busy = await settleSessionBusy(client, input.sessionID, active, options)\n log.info(\"btw: an aside is already in flight, leaving this one to the turn\", { sessionID: input.sessionID, busy })\n } else {\n // Settled alongside the request rather than before it: an aside asked\n // while the conversation is idle must not wait out the settle window\n // before it is even sent.\n const settling = settleSessionBusy(client, input.sessionID, active, options)\n const history = await fetchAsideHistory(client, input.sessionID, question)\n const answer = requestSideQuestion(active, question, {\n cliVersion: await detectCliVersion(transport.cliPath),\n interactive: transport.interactive,\n ...(history.length ? { history } : {}),\n })\n // Handled from this tick on. The settle below can span several timer\n // ticks, and an aside that fails immediately (a dead process, an\n // interactive transport) would otherwise raise an unhandled rejection in\n // the host before the real handlers further down are attached.\n answer.catch(() => undefined)\n rememberSideQuestionAnswer(input.sessionID, question, answer)\n busy = await settling\n log.info(\"btw: aside sent ahead of its message\", {\n sessionID: input.sessionID,\n busy,\n questionLength: question.length,\n history: history.length,\n })\n // Written before the answer exists, so a `/btw` typed mid-turn shows up in\n // the turn straight away rather than looking swallowed until the answer\n // arrives. Only while a turn is running: an idle conversation gets the\n // whole pair as its own message a moment later anyway.\n const asked = busy\n ? deliverAsideInline(client, input.sessionID, formatInlineAsideAsk(question), options).catch(() => false)\n : Promise.resolve(false)\n answer.then(\n async (result) => {\n log.info(\"btw: early answer arrived\", { sessionID: input.sessionID, busy, responseLength: result.response.length })\n if (!busy || result.synthetic) return\n // Awaited, not raced: a receipt that landed after the answer it\n // announces would read backwards. In the common case it was written\n // long before this and the await is already settled.\n await asked\n const inline = await deliverAsideInline(\n client,\n input.sessionID,\n formatInlineAside(question, result.response),\n options,\n )\n if (inline) {\n // The answer is in the conversation already, so the `/btw` message\n // has nothing left to carry. The remembered answer is deliberately\n // left in place: if the drop below does not take, the message\n // replays this answer instead of paying for a second one.\n log.info(\"btw: answer written into the running turn\", { sessionID: input.sessionID })\n markInlineDelivered()\n return\n }\n // Nothing was open to write to. The held `/btw` message carries this\n // same answer into the conversation once the turn ends, which is the\n // durable copy, so there is nothing to announce here.\n log.info(\"btw: no open stream for the answer; the held message will carry it\", {\n sessionID: input.sessionID,\n })\n },\n (error: unknown) => {\n // The message asks again once its turn runs.\n log.warn(\"btw: early aside failed; the message will ask again\", {\n sessionID: input.sessionID,\n error: errorText(error),\n })\n },\n )\n }\n if (!busy) return\n const started = Date.now()\n const outcome = await Promise.race([\n inlineDelivered,\n waitForSessionIdle(client, input.sessionID, { ...options, stop: () => inlineDone }).then((idle) =>\n idle ? (\"idle\" as const) : (\"timeout\" as const),\n ),\n ])\n if (outcome === \"inline\") {\n log.info(\"btw: answered inside the running turn, dropping the /btw message\", {\n sessionID: input.sessionID,\n waitedMs: Date.now() - started,\n })\n throw new BtwHandledError(BTW_INLINE_HANDLED_MESSAGE)\n }\n log.info(\"btw: turn over, releasing the /btw message\", {\n sessionID: input.sessionID,\n idle: outcome === \"idle\",\n waitedMs: Date.now() - started,\n })\n if (outcome === \"timeout\") {\n showToast(client, { title: \"btw\", message: BTW_TURN_TOO_LONG_MESSAGE, variant: \"warning\", duration: 8_000 })\n throw new BtwHandledError(BTW_TURN_TOO_LONG_MESSAGE)\n }\n}\n","import type { LanguageModelV3 } from \"@ai-sdk/provider\"\nimport { INLINE_ASIDE_MARKER, LEGACY_INLINE_ASIDE_MARKERS } from \"./btw-command.js\"\nimport { log } from \"./logger.js\"\nimport { parseSideQuestionContent } from \"./side-question.js\"\n\ntype Prompt = Parameters<LanguageModelV3[\"doGenerate\"]>[0][\"prompt\"]\n\nconst ASIDE_MARKERS = [INLINE_ASIDE_MARKER, ...LEGACY_INLINE_ASIDE_MARKERS]\n\nfunction isInlineAside(part: any): boolean {\n if (!part || part.type !== \"text\" || typeof part.text !== \"string\") return false\n const text = part.text.trimStart()\n return ASIDE_MARKERS.some((marker) => text.startsWith(marker))\n}\n\n/**\n * An aside answered while a turn was running was written into that turn's\n * reply as its own text part (btw-command.ts). It was never Claude's own\n * output and was never in Claude's context, so a rebuilt transcript must not\n * hand it back as something Claude said.\n */\nfunction stripInlineAsides(content: unknown): unknown {\n if (!Array.isArray(content)) return content\n const kept = content.filter((part: any) => !isInlineAside(part))\n return kept.length === content.length ? content : kept\n}\n\nexport function filterSideQuestionHistory(prompt: Prompt): Prompt {\n let aside = false\n const kept = prompt.filter((message) => {\n if (message.role === \"user\") {\n aside = parseSideQuestionContent(message.content) !== null\n return !aside\n }\n return message.role !== \"assistant\" || !aside\n })\n return kept.map((message) =>\n message.role === \"assistant\" ? ({ ...message, content: stripInlineAsides(message.content) } as typeof message) : message,\n )\n}\n\nconst SUPPORTED_IMAGE_TYPES = new Set([\n \"image/jpeg\",\n \"image/png\",\n \"image/gif\",\n \"image/webp\",\n])\n\nfunction toImageBlock(part: any): any | null {\n const raw: unknown = part.image ?? part.data ?? part.url ?? part.source?.data\n if (!raw) {\n log.warn(\"file part without data, skipping\")\n return null\n }\n\n let resolvedMediaType: string = part.mediaType || part.mimeType || part.mime || \"\"\n let base64: string | null = null\n\n if (typeof raw === \"string\") {\n if (raw.startsWith(\"data:\")) {\n const match = /^data:([^;,]+)(?:;[^,]*)*(?:;base64)?,(.*)$/s.exec(raw)\n if (!match) {\n log.warn(\"malformed data URI, skipping file part\")\n return null\n }\n resolvedMediaType = resolvedMediaType || match[1]\n base64 = match[2]\n } else if (/^https?:\\/\\//i.test(raw)) {\n log.warn(\"remote URL images are not supported by Claude CLI, skipping\")\n return null\n } else {\n base64 = raw\n }\n } else if (raw instanceof URL) {\n log.warn(\"remote URL images are not supported by Claude CLI, skipping\")\n return null\n } else if (raw instanceof Uint8Array || Buffer.isBuffer(raw)) {\n base64 = Buffer.from(raw as Uint8Array).toString(\"base64\")\n } else {\n log.warn(\"unsupported file part data type\", { dataType: typeof raw })\n return null\n }\n\n if (!resolvedMediaType || !SUPPORTED_IMAGE_TYPES.has(resolvedMediaType)) {\n log.warn(\"unsupported media type for Claude image block, skipping\", {\n mediaType: resolvedMediaType,\n })\n return null\n }\n\n return {\n type: \"image\",\n source: { type: \"base64\", media_type: resolvedMediaType, data: base64 },\n }\n}\n\nfunction getToolResultText(part: any): string {\n const value = part.output ?? part.result\n\n if (typeof value === \"string\") {\n return value\n }\n\n if (!value || typeof value !== \"object\") {\n return JSON.stringify(value)\n }\n\n switch (value.type) {\n case \"text\":\n case \"error-text\":\n return String(value.value)\n case \"json\":\n case \"error-json\":\n return JSON.stringify(value.value)\n case \"execution-denied\":\n return value.reason ? `Execution denied: ${value.reason}` : \"Execution denied\"\n case \"content\":\n return Array.isArray(value.value)\n ? value.value\n .map((item: any) => {\n if (item?.type === \"text\") return item.text\n return JSON.stringify(item)\n })\n .join(\"\\n\")\n : JSON.stringify(value.value)\n default:\n return JSON.stringify(value)\n }\n}\n\n// Compaction-mode caps. These are the only knobs that affect how much\n// transcript content reaches the model when opencode invokes /compact.\n// 180k chars ≈ 60k tokens worst-case — well under Haiku 4.5's 200k window\n// after accounting for system prompt + output budget.\nconst MAX_HISTORY_CHARS = 180_000\nconst MAX_TOOL_RESULT_CHARS = 10_000\nconst MAX_TOOL_INPUT_CHARS = 2_000\n\nfunction clipWithMarker(text: string, max: number): string {\n if (text.length <= max) return text\n return `${text.slice(0, max)}\\n…[truncated ${text.length - max} chars]`\n}\n\nfunction renderToolInput(input: unknown): string {\n let raw: string\n try {\n raw = typeof input === \"string\" ? input : JSON.stringify(input)\n } catch {\n raw = String(input)\n }\n return clipWithMarker(raw, MAX_TOOL_INPUT_CHARS)\n}\n\nfunction renderMessageContentForCompaction(\n msg: any,\n): { text: string; toolResultCount: number } {\n const lines: string[] = []\n let toolResultCount = 0\n\n if (typeof msg.content === \"string\") {\n return { text: msg.content, toolResultCount: 0 }\n }\n\n if (!Array.isArray(msg.content)) {\n return { text: \"\", toolResultCount: 0 }\n }\n\n for (const part of msg.content as any[]) {\n if (!part) continue\n switch (part.type) {\n case \"text\":\n if (part.text) lines.push(part.text)\n break\n case \"tool-call\":\n lines.push(\n `[tool_use:${part.toolName ?? \"unknown\"}(${renderToolInput(part.input)})]`,\n )\n break\n case \"tool-result\":\n toolResultCount++\n lines.push(\n `[tool_result:${part.toolName ?? part.toolCallId ?? \"unknown\"}]\\n${clipWithMarker(\n getToolResultText(part),\n MAX_TOOL_RESULT_CHARS,\n )}`,\n )\n break\n case \"image\":\n lines.push(\n `[image: ${part.mediaType ?? part.mimeType ?? \"unknown\"}]`,\n )\n break\n case \"file\":\n lines.push(\n `[file: ${part.mediaType ?? part.mimeType ?? \"unknown\"}]`,\n )\n break\n case \"reasoning\":\n // Skip reasoning blocks in compaction — they bloat input without\n // helping the summarizer.\n break\n }\n }\n\n return { text: lines.join(\"\\n\"), toolResultCount }\n}\n\n/**\n * Compact conversation history into a context summary.\n *\n * - mode \"fresh-session\" (default): includes user, assistant and tool roles,\n * renders each with the same serializer /compact uses so tool inputs and\n * result bodies survive, then clips each message at 2000 chars. Used when\n * starting a fresh CLI session that lost its prior session id. It used to\n * filter to user/assistant only and reduce tool content to\n * `[Called N tool(s)]` placeholders, which silently dropped subagent\n * output entirely (issue #29).\n * - mode \"compaction\": rich serializer for opencode /compact. Includes\n * tool roles, renders tool_use input and tool_result content (each\n * clipped at MAX_TOOL_RESULT_CHARS), and caps aggregate output at\n * MAX_HISTORY_CHARS by dropping oldest entries first.\n */\nexport function compactConversationHistory(\n prompt: Prompt,\n opts: { mode?: \"fresh-session\" | \"compaction\" } = {},\n): string | null {\n const mode = opts.mode ?? \"fresh-session\"\n prompt = filterSideQuestionHistory(prompt)\n\n if (mode === \"compaction\") {\n return buildCompactionHistory(prompt)\n }\n\n // `tool`-role messages carry the results of everything opencode ran itself,\n // so they belong in the transcript. Filtering them out (issue #29) meant a\n // subagent's whole answer vanished: the assistant message kept a\n // `[Called 1 tool(s): task]` placeholder and the result it referred to was\n // never rendered at all.\n const conversationMessages = prompt.filter(\n (m) => m.role === \"user\" || m.role === \"assistant\" || m.role === \"tool\",\n )\n\n if (conversationMessages.length <= 1) {\n return null\n }\n\n const historyParts: string[] = []\n\n for (let i = 0; i < conversationMessages.length - 1; i++) {\n const msg = conversationMessages[i]\n const role =\n msg.role === \"user\" ? \"User\" : msg.role === \"assistant\" ? \"Assistant\" : \"Tool\"\n\n // Same renderer the /compact transcript uses, so tool inputs and result\n // bodies survive instead of collapsing to counts. This path used to write\n // `[Called N tool(s): ...]` / `[Received N tool result(s)]` and discard\n // every byte of the payload, which is the second half of issue #29.\n const { text } = renderMessageContentForCompaction(msg)\n\n if (text.trim()) {\n const truncated =\n text.length > 2000 ? text.slice(0, 2000) + \"...\" : text\n historyParts.push(`${role}: ${truncated}`)\n }\n }\n\n if (historyParts.length === 0) {\n return null\n }\n\n return historyParts.join(\"\\n\\n\")\n}\n\nfunction buildCompactionHistory(prompt: Prompt): string | null {\n // Iterate newest-first, accumulate up to MAX_HISTORY_CHARS, then reverse\n // to chronological order. Oldest messages get dropped when the budget\n // is exhausted — they are the least relevant for a summary of recent\n // work.\n const entries: string[] = []\n let total = 0\n let totalToolResults = 0\n let droppedOldest = 0\n\n // Skip the trailing user message: opencode's /compact appends the\n // synthesis instruction as the final user turn. The instruction itself\n // is added by getClaudeUserMessage after the transcript block, so we\n // don't want it duplicated inside the transcript.\n const end = prompt.length > 0 && prompt[prompt.length - 1].role === \"user\"\n ? prompt.length - 1\n : prompt.length\n\n for (let i = end - 1; i >= 0; i--) {\n const msg = prompt[i] as any\n const roleLabel =\n msg.role === \"user\"\n ? \"User\"\n : msg.role === \"assistant\"\n ? \"Assistant\"\n : msg.role === \"tool\"\n ? \"Tool\"\n : msg.role\n\n const { text, toolResultCount } = renderMessageContentForCompaction(msg)\n if (!text.trim()) continue\n\n const entry = `${roleLabel}: ${text}`\n if (total + entry.length > MAX_HISTORY_CHARS) {\n droppedOldest = i + 1\n break\n }\n entries.push(entry)\n total += entry.length + 2 // +2 for the \"\\n\\n\" join\n totalToolResults += toolResultCount\n }\n\n if (entries.length === 0) return null\n\n entries.reverse()\n log.info(\"built compaction history\", {\n entries: entries.length,\n chars: total,\n toolResults: totalToolResults,\n droppedOldestBefore: droppedOldest,\n })\n\n return entries.join(\"\\n\\n\")\n}\n\n/**\n * Convert AI SDK prompt into a Claude CLI stream-json user message.\n *\n * `compactionMode` switches behavior for opencode /compact: the prior\n * transcript is rendered with rich tool content (not placeholders) and the\n * wrapper framing tells the model this is the authoritative thread.\n *\n * Reasoning effort is not part of the message. It used to ride here as a\n * thinking keyword (\"(ultrathink)\"), but Claude Code dropped every keyword\n * except that one, so effort now reaches the CLI as CLAUDE_CODE_EFFORT_LEVEL\n * at spawn time (see `claudeSpawnEnv`).\n */\nexport function getClaudeUserMessage(\n prompt: Prompt,\n includeHistoryContext: boolean = false,\n opts: { compactionMode?: boolean; cliToolCallIds?: ReadonlySet<string> } = {},\n): string {\n const compactionMode = opts.compactionMode === true\n const cliToolCallIds = opts.cliToolCallIds\n const content: any[] = []\n\n /**\n * A `tool_result` block is only meaningful to a resumed CLI session when\n * that session issued the matching `tool_use`. Anything opencode ran on its\n * own behalf (a `subtask: true` command's `task` call, issue #29) has an id\n * the CLI never emitted, so the block is orphaned: Claude cannot resolve it\n * and the payload, which is right there in the envelope, is unreachable.\n * Those are rendered as plain text instead, which keeps the content and\n * loses only the pairing the CLI could not have honoured anyway.\n *\n * `cliToolCallIds` is the set of calls this CLI process is waiting on. When\n * a caller does not supply it we keep the old unconditional block, so a\n * forgotten call site degrades to today's behaviour rather than breaking\n * the proxy round-trip.\n */\n const pushToolResult = (part: any): void => {\n const id = part.toolCallId\n const text = getToolResultText(part)\n if (!cliToolCallIds || cliToolCallIds.has(id)) {\n content.push({ type: \"tool_result\", tool_use_id: id, content: text })\n return\n }\n log.info(\"rendering opencode-side tool result as text\", {\n toolCallId: id,\n toolName: part.toolName,\n chars: text.length,\n })\n content.push({\n type: \"text\",\n text: `<opencode_tool_result tool=\"${part.toolName ?? \"unknown\"}\">\\n${text}\\n</opencode_tool_result>`,\n })\n }\n\n if (compactionMode) {\n const transcript = compactConversationHistory(prompt, {\n mode: \"compaction\",\n })\n if (transcript) {\n log.info(\"including compaction transcript\", {\n historyLength: transcript.length,\n })\n content.push({\n type: \"text\",\n text: `<conversation_transcript>\n${transcript}\n</conversation_transcript>\n\nThe complete prior conversation appears above. The synthesis instructions follow below.\n\n`,\n })\n }\n } else if (includeHistoryContext) {\n const historyContext = compactConversationHistory(prompt)\n if (historyContext) {\n log.info(\"including conversation history context\", {\n historyLength: historyContext.length,\n })\n content.push({\n type: \"text\",\n text: `<conversation_history>\nThe following is a summary of our conversation so far (from a previous session that couldn't be resumed):\n\n${historyContext}\n\n</conversation_history>\n\nNow continuing with the current message:\n\n`,\n })\n }\n }\n\n // Find messages since last assistant message\n const messages: typeof prompt = []\n for (let i = prompt.length - 1; i >= 0; i--) {\n if (prompt[i].role === \"assistant\") break\n messages.unshift(prompt[i])\n }\n\n for (const msg of messages) {\n if (msg.role === \"user\") {\n if (parseSideQuestionContent(msg.content) !== null) continue\n if (typeof msg.content === \"string\") {\n const str = msg.content as string\n if (str.trim()) {\n content.push({ type: \"text\", text: str })\n }\n } else if (Array.isArray(msg.content)) {\n for (const part of msg.content as any[]) {\n if (part.type === \"text\") {\n if (part.text && part.text.trim()) {\n content.push({ type: \"text\", text: part.text })\n }\n } else if (part.type === \"file\" || part.type === \"image\") {\n const block = toImageBlock(part)\n if (block) {\n content.push(block)\n } else {\n log.debug(\"skipped non-image file part\", {\n mediaType: part.mediaType,\n })\n }\n } else if (part.type === \"tool-result\") {\n pushToolResult(part)\n }\n }\n }\n } else if (msg.role === \"tool\") {\n // AI SDK V3 delivers tool results in `tool`-role messages, not `user`.\n // Without this branch we'd hit the empty-content sentinel path and\n // send \"(empty)\" to Claude CLI instead of the actual tool result —\n // forcing the user to press \"continue\" between proxy tool calls.\n if (Array.isArray(msg.content)) {\n for (const part of msg.content as any[]) {\n if (part?.type === \"tool-result\") {\n pushToolResult(part)\n }\n }\n }\n }\n }\n\n if (content.length === 0) {\n // CLI rejects a zero-block message with 400, and Anthropic rejects\n // whitespace-only text blocks — so we need a non-whitespace sentinel.\n // \"(empty)\" matches the parenthetical meta-note convention this file\n // already uses for reasoning keywords (\"(think)\", \"(megathink)\", etc.),\n // which the model reads as out-of-band metadata rather than a prompt to\n // continue its previous turn.\n log.warn(\"empty user content; sending sentinel to satisfy CLI\")\n return JSON.stringify({\n type: \"user\",\n message: {\n role: \"user\",\n content: [{ type: \"text\", text: \"(empty)\" }],\n },\n })\n }\n\n return JSON.stringify({\n type: \"user\",\n message: {\n role: \"user\",\n content,\n },\n })\n}\n","/**\n * Per-agent model resolution.\n *\n * opencode's agent config cannot express \"inherit the account, choose the\n * model\". A subagent that omits `model` inherits the invoking agent's WHOLE\n * model string, and one that pins `model` inherits neither half, so pinning\n * Opus also pins the account it was written with. That is the wrong trade on a\n * machine with more than one Claude account: the worker should follow whoever\n * invoked it and still run on the model the job needs.\n *\n * The account is not part of the model id this class sees. It lives in the\n * provider (`claude-code-<account>`), which selects CLAUDE_CONFIG_DIR at spawn\n * time, and in an `@<account>` marker riding on the id for non-default\n * accounts (see `parseModelId` in models.ts). So swapping the model NAME while\n * preserving that marker changes the model and nothing else, which is exactly\n * the gap in the config schema.\n *\n * Declaring it: an agent markdown file says `forceModel: <id>`, or the\n * `defaultSubagentModel` provider option covers every subagent at once.\n * Nothing needs a per-agent entry in opencode.json.\n *\n * The same file can state `reasoningEffort:`, which beats the effort opencode\n * inherited from the caller's picker (see `resolveAgentEffort`). Model and\n * effort together are what a turn costs, so both belong with the agent.\n *\n * Two deliberate silences, because this rewrites what a user's model picker\n * said it would run:\n *\n * - With `defaultSubagentModel` unset there is NO implicit override. An\n * existing setup upgrading the plugin behaves exactly as before, instead\n * of quietly moving somebody's cheap subagent onto an expensive model.\n * - Only agents this plugin discovered are eligible. opencode's built-ins\n * (`explore`, `general`, `compaction`, ...) are never in the registry, so\n * they are never rewritten.\n */\nimport { readFile, readdir } from \"node:fs/promises\"\nimport path from \"node:path\"\nimport { log } from \"./logger.js\"\nimport { defaultModels } from \"./models.js\"\n\n/** Directory names opencode reads agent markdown from, current form first. */\nexport const AGENT_DIR_NAMES = [\"agents\", \"agent\"]\n\n/** Levels the Claude CLI accepts; anything else is refused, not forwarded. */\nconst REASONING_EFFORTS = [\n \"minimal\",\n \"low\",\n \"medium\",\n \"high\",\n \"xhigh\",\n \"max\",\n]\n\nexport type AgentRecord = {\n mode?: string\n /** A fully-qualified `provider/model` the agent pinned for itself. */\n model?: string\n /** Model NAME this agent wants, on whatever account the caller is using. */\n forceModel?: string\n /** Thinking budget this agent wants, whatever the caller's picker says. */\n reasoningEffort?: string\n}\n\nlet registry: Record<string, AgentRecord> = {}\nlet defaultSubagentModel: string | undefined\n\nexport function setAgentRegistry(records: Record<string, AgentRecord>): void {\n registry = records\n}\n\nexport function getAgentRegistry(): Record<string, AgentRecord> {\n return registry\n}\n\n/** `undefined` (the default) means no implicit override for any agent. */\nexport function setDefaultSubagentModel(model: string | undefined): void {\n defaultSubagentModel = model?.trim() || undefined\n}\n\nexport function getDefaultSubagentModel(): string | undefined {\n return defaultSubagentModel\n}\n\nexport function _resetAgentRegistryForTests(): void {\n registry = {}\n defaultSubagentModel = undefined\n}\n\n/** `claude-opus-5-fast@work` -> `@work`; a default-account id has none. */\nfunction accountMarker(modelId: string): string {\n const at = modelId.indexOf(\"@\")\n return at === -1 ? \"\" : modelId.slice(at)\n}\n\nfunction withoutAccountMarker(modelId: string): string {\n const at = modelId.indexOf(\"@\")\n return at === -1 ? modelId : modelId.slice(0, at)\n}\n\n/**\n * The model a request should actually spawn with.\n *\n * Order, first match wins:\n * 1. The agent declared `forceModel`.\n * 2. The agent is a discovered subagent and `defaultSubagentModel` is set.\n * 3. Anything else: the id opencode asked for, untouched.\n *\n * An agent that pinned a full `provider/model` is out of scope entirely:\n * opencode already routed the call to that provider, and second-guessing it\n * here would silently undo a choice the user made explicitly.\n *\n * Fails closed. An id that is not in the model registry is refused and the\n * original kept, because the alternative is spawning the CLI with a `--model`\n * it will reject, on a turn someone is waiting for.\n */\nexport function resolveAgentModel(\n agent: string | undefined,\n modelId: string,\n overrides?: {\n records?: Record<string, AgentRecord>\n defaultSubagentModel?: string\n },\n): string {\n if (!agent) return modelId\n\n const record = (overrides?.records ?? registry)[agent]\n if (!record) return modelId\n if (record.model?.includes(\"/\")) return modelId\n\n const fallback = overrides\n ? overrides.defaultSubagentModel\n : defaultSubagentModel\n const declared = record.forceModel?.trim()\n const wanted =\n declared || (record.mode === \"subagent\" ? fallback : undefined)\n if (!wanted) return modelId\n\n // A `forceModel` carrying its own `@account` would be forcing an account,\n // which is the thing this exists to avoid. Keep the caller's.\n const base = withoutAccountMarker(wanted)\n if (!Object.hasOwn(defaultModels, base)) {\n log.warn(\"agent model override refused: unknown model\", {\n agent,\n wanted: base,\n keeping: modelId,\n })\n return modelId\n }\n\n const resolved = `${base}${accountMarker(modelId)}`\n if (resolved !== modelId) {\n log.debug(\"agent model override\", { agent, from: modelId, to: resolved })\n }\n return resolved\n}\n\n/**\n * The thinking budget a request should actually spawn with.\n *\n * opencode resolves one effort for the whole session (the model picker's\n * selector, or a variant), and a subagent inherits it. That inheritance is\n * wrong in the expensive direction: a caller who picked `max` for their own\n * turn silently hands `max` to every worker it dispatches, so a mechanical\n * lane runs at the most costly setting available and burns a weekly cap that\n * the caller never spent on the work in front of them.\n *\n * An agent that states its own budget wins. Same reasoning as `forceModel`:\n * the declaration lives with the agent, so a file on disk is the whole\n * configuration and the caller's picker stays a choice about the caller.\n *\n * Unknown values are ignored rather than passed on, since the CLI refuses a\n * level it does not recognise and the turn would die at spawn.\n */\nexport function resolveAgentEffort(\n agent: string | undefined,\n inherited: string | undefined,\n overrides?: { records?: Record<string, AgentRecord> },\n): string | undefined {\n if (!agent) return inherited\n\n const record = (overrides?.records ?? registry)[agent]\n const declared = record?.reasoningEffort?.trim()\n if (!declared) return inherited\n\n if (!REASONING_EFFORTS.includes(declared)) {\n log.warn(\"agent effort override refused: unknown level\", {\n agent,\n wanted: declared,\n keeping: inherited,\n })\n return inherited\n }\n\n if (declared !== inherited) {\n log.debug(\"agent effort override\", {\n agent,\n from: inherited,\n to: declared,\n })\n }\n return declared\n}\n\n/**\n * Read the four fields that matter out of an agent markdown file's YAML\n * frontmatter. Hand-parsed rather than pulling a YAML dependency in for four\n * scalars, and deliberately top-level only: `permission:` has nested keys\n * (`bash:`, `edit:`) that must not be mistaken for agent fields.\n */\nexport function parseAgentFrontmatter(text: string): AgentRecord {\n const record: AgentRecord = {}\n if (!text.startsWith(\"---\")) return record\n\n const lines = text.split(/\\r?\\n/)\n for (let i = 1; i < lines.length; i++) {\n const line = lines[i]\n if (line.trim() === \"---\") break\n\n const match = /^([A-Za-z_][A-Za-z0-9_-]*):[ \\t]*(.*)$/.exec(line)\n if (!match) continue\n\n const key = match[1]\n if (\n key !== \"mode\" &&\n key !== \"model\" &&\n key !== \"forceModel\" &&\n key !== \"reasoningEffort\"\n )\n continue\n\n const value = match[2].trim().replace(/^[\"']|[\"']$/g, \"\")\n if (value) record[key] = value\n }\n\n return record\n}\n\n/**\n * Discover agents from markdown on disk. opencode merges these into its own\n * registry, but whether they reach a plugin's config hook is not documented,\n * so they are read directly rather than assumed.\n */\nexport async function readAgentMarkdownRecords(\n directories: string[],\n): Promise<Record<string, AgentRecord>> {\n const records: Record<string, AgentRecord> = {}\n\n for (const directory of directories) {\n let entries: string[]\n try {\n entries = await readdir(directory)\n } catch {\n continue\n }\n\n for (const entry of entries) {\n if (!entry.endsWith(\".md\")) continue\n\n const name = entry.slice(0, -3)\n if (records[name]) continue\n\n try {\n const text = await readFile(path.join(directory, entry), \"utf8\")\n records[name] = parseAgentFrontmatter(text)\n } catch (err) {\n log.debug(\"failed to read agent markdown\", {\n file: path.join(directory, entry),\n error: String(err),\n })\n }\n }\n }\n\n return records\n}\n\n/**\n * Every directory opencode would read agent markdown from, project before\n * global so a project agent of the same name wins, as opencode resolves them.\n */\nexport function agentDirectories(\n home: string | undefined,\n projectDirectory: string | undefined,\n): string[] {\n const directories: string[] = []\n\n if (projectDirectory) {\n for (const name of AGENT_DIR_NAMES) {\n directories.push(path.join(projectDirectory, \".opencode\", name))\n }\n }\n if (home) {\n for (const name of AGENT_DIR_NAMES) {\n directories.push(path.join(home, \".config\", \"opencode\", name))\n }\n }\n\n return directories\n}\n","import type { OpenCodeModel } from \"./opencode-types.js\"\n\nconst PROVIDER_ID = \"claude-code\"\nconst NPM = \"@khalilgharbaoui/opencode-claude-code-plugin\"\n\nconst reasoningVariants: Record<string, Record<string, unknown>> = {\n low: { reasoningEffort: \"low\" },\n medium: { reasoningEffort: \"medium\" },\n high: { reasoningEffort: \"high\" },\n xhigh: { reasoningEffort: \"xhigh\" },\n max: { reasoningEffort: \"max\" },\n}\n\nconst baseCapabilities = {\n temperature: false,\n attachment: true,\n toolcall: true,\n input: { text: true, audio: false, image: true, video: false, pdf: false },\n output: { text: true, audio: false, image: false, video: false, pdf: false },\n interleaved: false as const,\n}\n\nfunction defineModel(opts: {\n id: string\n name: string\n family: string\n reasoning: boolean\n context: number\n output: number\n cost: { input: number; output: number; cacheRead: number; cacheWrite: number }\n releaseDate: string\n // List-price multiplier relative to Haiku (the cheapest model). Derived\n // exactly from published per-token pricing: input AND output ratios both come\n // out to haiku 1, sonnet 3, opus 5, fable/mythos 10. Rendered as an\n // `(N×)` suffix so it surfaces in opencode's model picker, which has no\n // dedicated multiplier field.\n // Display-only: model resolution keys off `id`.\n multiplier: number\n status?: OpenCodeModel[\"status\"]\n}): OpenCodeModel {\n return {\n id: opts.id,\n providerID: PROVIDER_ID,\n api: { id: opts.id, url: \"\", npm: NPM },\n name: `${opts.name} (${opts.multiplier}×)`,\n family: opts.family,\n capabilities: { ...baseCapabilities, reasoning: opts.reasoning },\n cost: {\n input: opts.cost.input,\n output: opts.cost.output,\n cache: { read: opts.cost.cacheRead, write: opts.cost.cacheWrite },\n },\n limit: { context: opts.context, output: opts.output },\n status: opts.status ?? \"active\",\n options: {},\n headers: {},\n release_date: opts.releaseDate,\n variants: opts.reasoning ? reasoningVariants : undefined,\n }\n}\n\n// Costs in US dollars per MILLION tokens, matching Anthropic's published\n// pricing verbatim. This is the unit opencode and models.dev use: opencode\n// divides by 1e6 itself when it multiplies a cost by a token count, so writing\n// per-token values here under-reports session cost by exactly 1,000,000x.\n// Compare models.dev's own entry for the same model:\n// `anthropic/claude-haiku-4-5 -> {\"input\": 1, \"output\": 5, \"cache_read\": 0.1,\n// \"cache_write\": 1.25}`.\n//\n// There is no long-context premium to model. Anthropic's pricing page states\n// that Claude 4.6 and later ship the full 1M-token context window at standard\n// pricing (\"a 900k-token request is billed at the same per-token rate as a\n// 9k-token request\"), and caching/batch discounts apply unchanged across it.\n// opencode 1.18.5 added optional `cost.tiers` / `cost.experimentalOver200K`\n// fields for above-200K pricing; they stay unset here deliberately, because a\n// tier would misreport the real price. Re-check only if Anthropic introduces\n// one. Verified against the pricing docs 2026-07-26.\nconst haikuCost = { input: 1, output: 5, cacheRead: 0.1, cacheWrite: 1.25 }\nconst sonnetCost = { input: 3, output: 15, cacheRead: 0.3, cacheWrite: 3.75 }\n// Opus 4.5+ standard pricing is $5/M in, $25/M out (the price cut at 4.5; held\n// through 4.6/4.7/4.8/5). Cache read 0.1x input, cache write 1.25x input.\nconst opusCost = { input: 5, output: 25, cacheRead: 0.5, cacheWrite: 6.25 }\n// Fable 5 and Mythos 5 are the Mythos-class tier above Opus and share pricing\n// ($10/M in, $50/M out). Cache read/write follow Anthropic's standard 0.1x / 1.25x\n// input ratios (not separately published).\nconst fableCost = { input: 10, output: 50, cacheRead: 1, cacheWrite: 12.5 }\n// Fable 5.1 and Mythos 5.1 keep the same input/output and cache-write rates,\n// but Anthropic cut cache reads to $0.25/M (one quarter of the 5.0 price).\nconst fable51Cost = { input: 10, output: 50, cacheRead: 0.25, cacheWrite: 12.5 }\n// Fast mode bills the same per-token rates as the Mythos-class tier: $10/M in,\n// $50/M out, cache read 1, cache write 12.5. Not an inference; this is the\n// exact table the CLI itself applies for `speed: \"fast\"` on Opus 4.8 / Opus 5\n// (`{inputTokens: 10, outputTokens: 50, promptCacheWriteTokens: 12.5,\n// promptCacheReadTokens: 1}`). Kept as its own binding rather than reusing\n// `fableCost` so a future divergence in either tier stays a one-line change.\n// Verified against Claude Code 2.1.245, 2026-08-30.\nconst opusFastCost = { input: 10, output: 50, cacheRead: 1, cacheWrite: 12.5 }\n\n/**\n * Convert an OpenCodeModel to the flat config schema that OpenCode's\n * provider.ts config parser expects (model.temperature, model.reasoning,\n * model.cost.cache_read, model.modalities, etc.).\n */\nexport function toConfigModel(model: OpenCodeModel): Record<string, unknown> {\n const inputMods: string[] = []\n const outputMods: string[] = []\n for (const [k, v] of Object.entries(model.capabilities.input)) {\n if (v) inputMods.push(k)\n }\n for (const [k, v] of Object.entries(model.capabilities.output)) {\n if (v) outputMods.push(k)\n }\n\n return {\n id: model.api.id,\n name: model.name,\n status: model.status,\n family: model.family ?? \"\",\n release_date: model.release_date,\n\n temperature: model.capabilities.temperature,\n reasoning: model.capabilities.reasoning,\n attachment: model.capabilities.attachment,\n tool_call: model.capabilities.toolcall,\n modalities: { input: inputMods, output: outputMods },\n\n cost: {\n input: model.cost.input,\n output: model.cost.output,\n cache_read: model.cost.cache.read,\n cache_write: model.cost.cache.write,\n },\n\n limit: model.limit,\n options: model.options,\n headers: model.headers,\n variants: model.variants,\n }\n}\n\nexport const defaultModels: Record<string, OpenCodeModel> = {\n \"claude-haiku-4-5\": defineModel({\n id: \"claude-haiku-4-5\",\n name: \"Claude Haiku 4.5\",\n family: \"haiku\",\n reasoning: false,\n context: 200_000,\n output: 64_000,\n cost: haikuCost,\n multiplier: 1,\n releaseDate: \"2025-10-01\",\n }),\n \"claude-sonnet-4-5\": defineModel({\n id: \"claude-sonnet-4-5\",\n name: \"Claude Sonnet 4.5\",\n family: \"sonnet\",\n reasoning: true,\n context: 200_000,\n output: 64_000,\n cost: sonnetCost,\n multiplier: 3,\n releaseDate: \"2025-09-29\",\n }),\n \"claude-sonnet-4-6\": defineModel({\n id: \"claude-sonnet-4-6\",\n name: \"Claude Sonnet 4.6\",\n family: \"sonnet\",\n reasoning: true,\n context: 1_000_000,\n output: 128_000,\n cost: sonnetCost,\n multiplier: 3,\n releaseDate: \"2025-06-19\",\n }),\n \"claude-sonnet-5\": defineModel({\n id: \"claude-sonnet-5\",\n name: \"Claude Sonnet 5\",\n family: \"sonnet\",\n reasoning: true,\n context: 1_000_000,\n output: 128_000,\n cost: sonnetCost,\n multiplier: 3,\n releaseDate: \"2026-06-30\",\n }),\n \"claude-opus-4-5\": defineModel({\n id: \"claude-opus-4-5\",\n name: \"Claude Opus 4.5\",\n family: \"opus\",\n reasoning: true,\n context: 200_000,\n output: 64_000,\n cost: opusCost,\n multiplier: 5,\n releaseDate: \"2025-11-01\",\n }),\n \"claude-opus-4-6\": defineModel({\n id: \"claude-opus-4-6\",\n name: \"Claude Opus 4.6\",\n family: \"opus\",\n reasoning: true,\n context: 1_000_000,\n output: 128_000,\n cost: opusCost,\n multiplier: 5,\n releaseDate: \"2025-06-19\",\n }),\n \"claude-opus-4-7\": defineModel({\n id: \"claude-opus-4-7\",\n name: \"Claude Opus 4.7\",\n family: \"opus\",\n reasoning: true,\n context: 1_000_000,\n output: 128_000,\n cost: opusCost,\n multiplier: 5,\n releaseDate: \"2025-07-16\",\n }),\n \"claude-opus-4-8\": defineModel({\n id: \"claude-opus-4-8\",\n name: \"Claude Opus 4.8\",\n family: \"opus\",\n reasoning: true,\n context: 1_000_000,\n output: 128_000,\n cost: opusCost,\n multiplier: 5,\n releaseDate: \"2026-05-28\",\n }),\n // Fast mode. The `-fast` suffix is OUR marker, not a model name Anthropic\n // serves: `parseModelId` strips it before `--model` and turns it into\n // `--settings {\"fastMode\":true}` on the spawn. Retired `-fast` model strings\n // (`claude-opus-4-6-fast`) are a different thing and are not registered here.\n //\n // Only Opus 4.8 and Opus 5 qualify: the CLI gates fast mode on the resolved\n // model name containing `opus-4-8` or `opus-5`, so registering a fast entry\n // for any other model would produce a picker option that silently runs at\n // standard speed while displaying the 10x price.\n \"claude-opus-4-8-fast\": defineModel({\n id: \"claude-opus-4-8-fast\",\n name: \"Claude Opus 4.8 Fast\",\n family: \"opus\",\n reasoning: true,\n context: 1_000_000,\n output: 128_000,\n cost: opusFastCost,\n multiplier: 10,\n releaseDate: \"2026-05-28\",\n }),\n \"claude-opus-5\": defineModel({\n id: \"claude-opus-5\",\n name: \"Claude Opus 5\",\n family: \"opus\",\n reasoning: true,\n context: 1_000_000,\n output: 128_000,\n cost: opusCost,\n multiplier: 5,\n releaseDate: \"2026-07-24\",\n }),\n \"claude-opus-5-fast\": defineModel({\n id: \"claude-opus-5-fast\",\n name: \"Claude Opus 5 Fast\",\n family: \"opus\",\n reasoning: true,\n context: 1_000_000,\n output: 128_000,\n cost: opusFastCost,\n multiplier: 10,\n releaseDate: \"2026-07-24\",\n }),\n \"claude-fable-5\": defineModel({\n id: \"claude-fable-5\",\n name: \"Claude Fable 5\",\n family: \"fable\",\n reasoning: true,\n context: 1_000_000,\n output: 128_000,\n cost: fableCost,\n multiplier: 10,\n releaseDate: \"2026-06-09\",\n }),\n \"claude-fable-5-1\": defineModel({\n id: \"claude-fable-5-1\",\n name: \"Claude Fable 5.1\",\n family: \"fable\",\n reasoning: true,\n context: 1_000_000,\n output: 128_000,\n cost: fable51Cost,\n multiplier: 10,\n releaseDate: \"2026-09-01\",\n }),\n // Mythos 5 and 5.1 share the corresponding Fable models' capabilities and\n // pricing without the safety classifiers; limited availability via Project\n // Glasswing. `claude --model` simply errors for accounts without access, so\n // they are safe to register unconditionally.\n \"claude-mythos-5\": defineModel({\n id: \"claude-mythos-5\",\n name: \"Claude Mythos 5\",\n family: \"mythos\",\n reasoning: true,\n context: 1_000_000,\n output: 128_000,\n cost: fableCost,\n multiplier: 10,\n releaseDate: \"2026-06-09\",\n }),\n \"claude-mythos-5-1\": defineModel({\n id: \"claude-mythos-5-1\",\n name: \"Claude Mythos 5.1\",\n family: \"mythos\",\n reasoning: true,\n context: 1_000_000,\n output: 128_000,\n cost: fable51Cost,\n multiplier: 10,\n releaseDate: \"2026-09-01\",\n }),\n}\n\n/** Marker this plugin appends to build a fast-mode model id. See below. */\nconst FAST_SUFFIX = \"-fast\"\n\n/**\n * Split an opencode model id into the name the Claude CLI actually accepts\n * and whether fast mode was requested.\n *\n * Two suffixes can ride on one id and they are NOT interchangeable:\n *\n * claude-opus-5-fast@work\n * \\_____________/\\___/\\__/\n * CLI model ours accounts.ts's\n *\n * `@work` must survive: the per-account wrapper script strips it at spawn\n * time to pick a CLAUDE_CONFIG_DIR. `-fast` must not: the CLI has no such\n * model (`claude-opus-4-6-fast` is retired and `claude-opus-4-7-fast` errors\n * outright), so it becomes `--settings {\"fastMode\":true}` instead.\n *\n * The `defaultModels` lookup is the guard against a false positive. Only ids\n * we registered are treated as fast markers, so a user-defined model that\n * happens to end in `-fast` is passed through untouched rather than being\n * silently rewritten into a model name that does not exist.\n */\nexport function parseModelId(modelId: string): { model: string; fast: boolean } {\n const at = modelId.indexOf(\"@\")\n const base = at === -1 ? modelId : modelId.slice(0, at)\n const account = at === -1 ? \"\" : modelId.slice(at)\n\n if (!base.endsWith(FAST_SUFFIX)) return { model: modelId, fast: false }\n if (!Object.hasOwn(defaultModels, base)) return { model: modelId, fast: false }\n\n return { model: base.slice(0, -FAST_SUFFIX.length) + account, fast: true }\n}\n","import * as fs from \"node:fs\"\nimport * as path from \"node:path\"\nimport * as os from \"node:os\"\nimport * as crypto from \"node:crypto\"\nimport {\n parse as parseJsonc,\n printParseErrorCode,\n type ParseError,\n} from \"jsonc-parser\"\nimport { log } from \"./logger.js\"\nimport { pluginTmpDir } from \"./tmp.js\"\n\n/**\n * Bridge opencode's `mcp` config block into a Claude CLI `--mcp-config` file.\n *\n * Opencode core schema (packages/opencode/src/config/mcp.ts):\n * {\n * \"mcp\": {\n * \"name\": {\n * \"type\": \"local\" | \"remote\",\n * \"command\"?: string[], // local\n * \"environment\"?: Record<string,string>,\n * \"url\"?: string, // remote\n * \"headers\"?: Record<string,string>,\n * \"oauth\"?: object | false, // remote — NOT bridged (Claude --mcp-config has no slot)\n * \"timeout\"?: number, // NOT bridged (Claude --mcp-config has no slot)\n * \"enabled\"?: boolean\n * }\n * }\n * }\n *\n * Claude CLI `--mcp-config` schema:\n * {\n * \"mcpServers\": {\n * \"name\": {\n * \"type\": \"stdio\" | \"http\",\n * \"command\"?: string, \"args\"?: string[], \"env\"?: Record<string,string>,\n * \"url\"?: string, \"headers\"?: Record<string,string>\n * }\n * }\n * }\n *\n * Discovery + merge are aligned with opencode core's `loadInstanceState`\n * (packages/opencode/src/config/config.ts). In merge order (last wins),\n * opencode loads:\n *\n * 1. Auth `.well-known` remote configs ← NOT bridged\n * 2. Global: ~/.config/opencode/{config.json,opencode.json,opencode.jsonc}\n * — all three deep-merged, jsonc highest priority\n * 3. OPENCODE_CONFIG env var (single file)\n * 4. Project walk-up: opencode.json[c] in each dir from cwd up to (not past)\n * worktree, both extensions per dir, parent-most first\n * 5. .opencode/ siblings: from cwd up + home dir + OPENCODE_CONFIG_DIR,\n * both extensions per dir, opencode-iteration order (cwd-most first\n * in walk-up — so parent-most `.opencode/` wins, matching upstream)\n * 6. OPENCODE_CONFIG_CONTENT env var (inline JSON) ← NOT bridged\n * 7. Active org remote config ← NOT bridged\n * 8. Managed config dir / macOS MDM ← NOT bridged\n *\n * Sources marked NOT bridged are niche and would require live opencode\n * runtime state (auth tokens, account context, MDM access). Document them\n * here so the gap is explicit; functionality of the common path is intact.\n *\n * Per-server merge is deep-merge (matching opencode's `mergeConfigConcatArrays`\n * → `mergeDeep`), so a project layer can override one field of a global server\n * spec — e.g. `{ \"linear\": { \"enabled\": true } }` lifts global linear's URL.\n */\n\nconst FILE_NAMES = [\"opencode.jsonc\", \"opencode.json\", \"config.json\"] as const\nconst PROJECT_FILE_NAMES = [\"opencode.json\", \"opencode.jsonc\"] as const\n\nfunction fileExists(p: string): boolean {\n try {\n return fs.statSync(p).isFile()\n } catch {\n return false\n }\n}\n\nfunction dirExists(p: string): boolean {\n try {\n return fs.statSync(p).isDirectory()\n } catch {\n return false\n }\n}\n\nfunction readAndParse(file: string): Record<string, unknown> | null {\n try {\n const raw = fs.readFileSync(file, \"utf8\")\n const errors: ParseError[] = []\n const parsed = parseJsonc(raw, errors, { allowTrailingComma: true })\n if (errors.length > 0) {\n const first = errors[0]\n throw new Error(\n `${printParseErrorCode(first.error)} at offset ${first.offset}`,\n )\n }\n return parsed as Record<string, unknown>\n } catch (e) {\n log.warn(\"failed to parse opencode config\", {\n file,\n error: e instanceof Error ? e.message : String(e),\n })\n return null\n }\n}\n\n/**\n * Deep merge two plain-object trees. Arrays and primitives are replaced\n * (not concatenated). Matches the effective behavior of opencode's\n * `mergeDeep` from `remeda` for the MCP block — opencode does not special\n * case array fields inside `mcp.<server>` (its only special case is\n * `instructions`, which is concat-deduped at the config root).\n */\nfunction isPlainObject(x: unknown): x is Record<string, unknown> {\n return typeof x === \"object\" && x !== null && !Array.isArray(x)\n}\n\nfunction deepMerge(\n target: Record<string, unknown>,\n source: Record<string, unknown>,\n): Record<string, unknown> {\n const out: Record<string, unknown> = { ...target }\n for (const [k, v] of Object.entries(source)) {\n if (v === undefined) continue\n const existing = out[k]\n if (isPlainObject(existing) && isPlainObject(v)) {\n out[k] = deepMerge(existing, v)\n } else {\n out[k] = v\n }\n }\n return out\n}\n\n/**\n * Walk up from `start` toward filesystem root (or `stop` if provided),\n * collecting paths where each `target` exists. Mirrors opencode core's\n * `FileSystem.up` (packages/core/src/filesystem.ts): cwd-most first,\n * parent-most last.\n */\nfunction walkUp(opts: {\n start: string\n stop?: string\n targets: readonly string[]\n predicate: (p: string) => boolean\n}): string[] {\n const out: string[] = []\n let current = path.resolve(opts.start)\n while (true) {\n for (const target of opts.targets) {\n const candidate = path.join(current, target)\n if (opts.predicate(candidate)) out.push(candidate)\n }\n if (opts.stop && current === path.resolve(opts.stop)) break\n const parent = path.dirname(current)\n if (parent === current) break\n current = parent\n }\n return out\n}\n\n/**\n * Find the worktree root by walking up from `cwd` looking for a `.git`\n * entry (file or directory — submodules use a file). If no `.git` is\n * found, walk to filesystem root. Honors OPENCODE_WORKTREE override.\n */\nfunction detectWorktree(cwd: string): string | undefined {\n const override = process.env.OPENCODE_WORKTREE\n if (override) return path.resolve(override)\n let current = path.resolve(cwd)\n while (true) {\n const gitPath = path.join(current, \".git\")\n try {\n if (fs.existsSync(gitPath)) return current\n } catch {\n // ignore\n }\n const parent = path.dirname(current)\n if (parent === current) return undefined\n current = parent\n }\n}\n\nfunction globalConfigDir(): string {\n const xdg = process.env.XDG_CONFIG_HOME ?? path.join(os.homedir(), \".config\")\n return path.join(xdg, \"opencode\")\n}\n\n/**\n * Load the merged global config from `~/.config/opencode/`. Mirrors\n * opencode core's `loadGlobal`: deep-merges config.json → opencode.json\n * → opencode.jsonc in that order (jsonc wins).\n */\nfunction loadGlobalConfig(): Record<string, unknown> {\n const dir = globalConfigDir()\n let merged: Record<string, unknown> = {}\n for (const name of FILE_NAMES.slice().reverse()) {\n // FILE_NAMES is jsonc-first; reverse to get config.json-first order.\n const file = path.join(dir, name)\n if (!fileExists(file)) continue\n const parsed = readAndParse(file)\n if (parsed) merged = deepMerge(merged, parsed)\n }\n return merged\n}\n\n/** Load both `opencode.json` and `opencode.jsonc` in `dir`, deep-merged. */\nfunction loadProjectFilesInDir(dir: string): Record<string, unknown> {\n let merged: Record<string, unknown> = {}\n for (const name of PROJECT_FILE_NAMES) {\n const file = path.join(dir, name)\n if (!fileExists(file)) continue\n const parsed = readAndParse(file)\n if (parsed) merged = deepMerge(merged, parsed)\n }\n return merged\n}\n\n/**\n * Build the list of `.opencode/` directories to consider, in opencode core's\n * order (matching `ConfigPaths.directories`):\n * project walk-up (cwd-most first) → home-dir `.opencode/` → OPENCODE_CONFIG_DIR\n */\nfunction dotOpencodeDirs(cwd: string, worktree?: string): string[] {\n const dirs: string[] = []\n const seen = new Set<string>()\n const push = (p: string) => {\n const abs = path.resolve(p)\n if (!seen.has(abs) && dirExists(abs)) {\n seen.add(abs)\n dirs.push(abs)\n }\n }\n\n for (const dir of walkUp({\n start: cwd,\n stop: worktree,\n targets: [\".opencode\"],\n predicate: dirExists,\n })) {\n push(dir)\n }\n\n const home = os.homedir()\n if (home) {\n const homeDot = path.join(home, \".opencode\")\n if (dirExists(homeDot)) push(homeDot)\n }\n\n const envDir = process.env.OPENCODE_CONFIG_DIR\n if (envDir && dirExists(envDir)) push(envDir)\n\n return dirs\n}\n\ninterface OpencodeLocalServer {\n type?: \"local\"\n command?: string[]\n environment?: Record<string, string>\n enabled?: boolean\n}\n\ninterface OpencodeRemoteServer {\n type?: \"remote\"\n url?: string\n headers?: Record<string, string>\n enabled?: boolean\n}\n\ntype OpencodeServer = OpencodeLocalServer | OpencodeRemoteServer | { enabled?: boolean }\n\n/**\n * Substitute opencode's `{env:VAR}` interpolation in a string-keyed record\n * using values from `process.env`. Returns a new object. If the source is\n * not a flat string-valued record, returns it unchanged.\n *\n * Opencode performs this substitution itself when it spawns MCP servers\n * directly, but the spec we read from disk still contains the literal\n * placeholders. Without substituting them here, Claude CLI hands the\n * literal string `{env:FOO}` to the MCP subprocess as the env value, and\n * any server that validates credentials at startup (e.g. slack-mcp-server)\n * crashes before exposing tools. Servers that defer validation to\n * request time (e.g. github-mcp-server) appear to register but every API\n * call 401s.\n */\nfunction substituteEnvPlaceholders(\n source: Record<string, unknown>,\n): Record<string, string> {\n const out: Record<string, string> = {}\n for (const [k, v] of Object.entries(source)) {\n if (typeof v !== \"string\") continue\n out[k] = v.replace(/\\{env:([A-Za-z_][A-Za-z0-9_]*)\\}/g, (_match, name) => {\n const resolved = process.env[name]\n return typeof resolved === \"string\" ? resolved : \"\"\n })\n }\n return out\n}\n\nfunction translateServer(\n name: string,\n spec: Record<string, unknown>,\n): Record<string, unknown> | null {\n if (spec.enabled === false) return null\n\n const type = spec.type\n if (type === \"local\") {\n const cmd = spec.command\n if (!Array.isArray(cmd) || cmd.length === 0) {\n log.warn(\"skipping local MCP server with no command\", { name })\n return null\n }\n const out: Record<string, unknown> = {\n type: \"stdio\",\n command: String(cmd[0]),\n }\n if (cmd.length > 1) out.args = cmd.slice(1).map((s) => String(s))\n if (spec.environment && typeof spec.environment === \"object\") {\n out.env = substituteEnvPlaceholders(\n spec.environment as Record<string, unknown>,\n )\n }\n return out\n }\n\n if (type === \"remote\") {\n if (typeof spec.url !== \"string\" || !spec.url) {\n log.warn(\"skipping remote MCP server with no url\", { name })\n return null\n }\n const out: Record<string, unknown> = {\n type: \"http\",\n url: spec.url,\n }\n if (spec.headers && typeof spec.headers === \"object\") {\n out.headers = substituteEnvPlaceholders(\n spec.headers as Record<string, unknown>,\n )\n }\n return out\n }\n\n log.warn(\"skipping MCP server with unknown type\", {\n name,\n type: type ?? null,\n })\n return null\n}\n\nfunction extractMcpBlock(\n config: Record<string, unknown>,\n): Record<string, OpencodeServer> {\n const mcp = config.mcp\n if (!mcp || typeof mcp !== \"object\" || Array.isArray(mcp)) return {}\n return mcp as Record<string, OpencodeServer>\n}\n\n/**\n * Deep-merge per-server specs from `source` into `target`. Mirrors opencode's\n * `mergeDeep` semantics for the `mcp` record: each server entry is recursively\n * merged so a partial layer (e.g. `{ \"linear\": { \"enabled\": true } }`) can\n * override one field without dropping the rest.\n */\nfunction mergeMcp(\n target: Record<string, OpencodeServer>,\n source: Record<string, OpencodeServer>,\n): Record<string, OpencodeServer> {\n const out: Record<string, OpencodeServer> = { ...target }\n for (const [name, spec] of Object.entries(source)) {\n if (!spec || typeof spec !== \"object\") continue\n const existing = out[name]\n if (existing && typeof existing === \"object\") {\n out[name] = deepMerge(\n existing as Record<string, unknown>,\n spec as Record<string, unknown>,\n ) as OpencodeServer\n } else {\n out[name] = spec\n }\n }\n return out\n}\n\nexport interface BridgedMcp {\n /** Path to the temp file containing the translated `--mcp-config`. */\n path: string\n /** Stable hash of the merged opencode mcp block (pre-translation). */\n hash: string\n /**\n * Names of opencode MCP servers that were bridged into Claude CLI's\n * `--mcp-config`. Excludes any servers passed in `excludeServers`.\n */\n serverNames: string[]\n /**\n * Names of every enabled opencode MCP server after merge + runtime\n * overlay, regardless of whether they ended up bridged or excluded.\n * Callers (e.g. the proxy-tool builder) use this to decide which\n * `<server>_<tool>` IDs in opencode's tool catalog are MCP-origin.\n */\n allEnabledServerNames: string[]\n}\n\n/** Result of merging opencode's MCP config layers + applying runtime overlay. */\nexport interface MergedMcp {\n /** Merged, overlay-applied server specs keyed by opencode server name. */\n servers: Record<string, OpencodeServer>\n /** Server names whose final spec is enabled (or implicitly enabled). */\n enabledServerNames: string[]\n /** Stable hash of the merged (pre-translation) MCP block. */\n hash: string\n}\n\n/**\n * Per-server runtime status from opencode's `client.mcp.status()`. Used as\n * an overlay on top of the on-disk merged config so opencode's UI-toggled\n * state — which lives only in-memory; `connect()`/`disconnect()` never\n * touch disk — propagates to the bridged claude subprocess.\n *\n * Treatment per server:\n * - \"connected\" → force `enabled: true` (mirror opencode)\n * - any other status → force `enabled: false` (don't ship a server\n * opencode can't run; user fixes it in opencode first)\n * - missing entry → leave disk value\n *\n * Omit the overlay and the bridge falls back to disk-only.\n */\nexport type RuntimeMcpStatus = Record<string, string>\n\n/**\n * Read opencode config layers, deep-merge their `mcp` blocks per opencode's\n * own semantics, optionally apply an opencode runtime-status overlay, then\n * translate each server to Claude CLI format, write a scratch file, and\n * return its path + a stable hash. Returns null when no enabled MCP servers\n * remain after the merge + overlay.\n */\nexport function bridgeOpencodeMcp(\n cwd: string,\n runtimeStatus?: RuntimeMcpStatus,\n excludeServers?: ReadonlySet<string>,\n): BridgedMcp | null {\n const {\n servers: merged,\n enabledServerNames: allEnabledServerNames,\n hash,\n } = mergeOpencodeMcp(cwd, runtimeStatus)\n\n // Translate every still-enabled server, skipping any caller has asked us\n // to exclude (because they're being routed through the proxy instead).\n const servers: Record<string, unknown> = {}\n const bridgedServerNames: string[] = []\n for (const [name, spec] of Object.entries(merged)) {\n if (!spec || typeof spec !== \"object\") continue\n if (excludeServers?.has(name)) continue\n const translated = translateServer(name, spec as Record<string, unknown>)\n if (translated) {\n servers[name] = translated\n bridgedServerNames.push(name)\n }\n }\n return finishBridge({\n servers,\n bridgedServerNames,\n allEnabledServerNames,\n hash,\n excludeServers,\n })\n}\n\n/**\n * Merge opencode's MCP config layers (global → `OPENCODE_CONFIG` → project\n * walk-up → `.opencode/` siblings), apply the opencode runtime-status\n * overlay, and hash the result. Split out of `bridgeOpencodeMcp` so\n * read-only callers (startup diagnostics) can inspect what would be bridged\n * without translating servers or writing a scratch config file.\n */\nexport function mergeOpencodeMcp(\n cwd: string,\n runtimeStatus?: RuntimeMcpStatus,\n): MergedMcp {\n const worktree = detectWorktree(cwd)\n\n // Layer 1: global merged\n let merged: Record<string, OpencodeServer> = {}\n merged = mergeMcp(merged, extractMcpBlock(loadGlobalConfig()))\n\n // Layer 2: OPENCODE_CONFIG (single file, applied before project walk-up)\n const explicitConfig = process.env.OPENCODE_CONFIG\n if (explicitConfig && fileExists(explicitConfig)) {\n const parsed = readAndParse(explicitConfig)\n if (parsed) merged = mergeMcp(merged, extractMcpBlock(parsed))\n }\n\n // Layer 3: project walk-up — opencode.json[c] in each dir from cwd to\n // (not past) worktree, both extensions per dir. walkUp returns cwd-most\n // first; collect distinct dirs in that order then reverse for merge so\n // cwd-most wins under last-merge-wins.\n const projectFiles = walkUp({\n start: cwd,\n stop: worktree,\n targets: PROJECT_FILE_NAMES,\n predicate: fileExists,\n })\n const projectDirs: string[] = []\n const seenProjectDirs = new Set<string>()\n for (const f of projectFiles) {\n const d = path.dirname(f)\n if (!seenProjectDirs.has(d)) {\n seenProjectDirs.add(d)\n projectDirs.push(d)\n }\n }\n for (const dir of projectDirs.slice().reverse()) {\n merged = mergeMcp(merged, extractMcpBlock(loadProjectFilesInDir(dir)))\n }\n\n // Layer 4: `.opencode/` siblings — project walk-up then home-dir then\n // OPENCODE_CONFIG_DIR, in that order. Iteration order matches opencode's\n // (cwd-most first within walk-up), so under deep-merge \"later wins\"\n // parent-most `.opencode/` overrides cwd-most. This is upstream's\n // behavior, surprising though it is.\n for (const dir of dotOpencodeDirs(cwd, worktree)) {\n merged = mergeMcp(merged, extractMcpBlock(loadProjectFilesInDir(dir)))\n }\n\n // Layer 5: opencode runtime overlay. opencode's `/mcps` UI toggle calls\n // `mcp.connect()` / `mcp.disconnect()` which only mutate in-memory state,\n // never the on-disk config. Without this overlay the bridge can't see\n // those toggles and claude misses servers the user just enabled.\n if (runtimeStatus) {\n for (const name of Object.keys(merged)) {\n const status = runtimeStatus[name]\n if (status === undefined) continue\n const existing = merged[name]\n const base =\n existing && typeof existing === \"object\"\n ? (existing as Record<string, unknown>)\n : {}\n merged[name] = { ...base, enabled: status === \"connected\" } as OpencodeServer\n }\n }\n\n // Compute the set of enabled server names BEFORE exclusion so callers can\n // tell whether a tool ID like `slack_conversations_add_message` came from\n // an opencode MCP server (vs a built-in tool that happens to contain `_`).\n const enabledServerNames: string[] = []\n for (const [name, spec] of Object.entries(merged)) {\n if (!spec || typeof spec !== \"object\") continue\n const enabled = (spec as { enabled?: unknown }).enabled\n if (enabled === false) continue\n enabledServerNames.push(name)\n }\n\n // Hash the pre-exclusion merged block so the hot-reload detector picks up\n // upstream config changes even when every server is excluded.\n const mergedBody = JSON.stringify({ mcpServers: merged }, null, 2)\n const hash = crypto\n .createHash(\"sha256\")\n .update(mergedBody)\n .digest(\"hex\")\n .slice(0, 12)\n\n return { servers: merged, enabledServerNames, hash }\n}\n\n/** Write the translated config (if any) and shape `bridgeOpencodeMcp`'s result. */\nfunction finishBridge(input: {\n servers: Record<string, unknown>\n bridgedServerNames: string[]\n allEnabledServerNames: string[]\n hash: string\n excludeServers?: ReadonlySet<string>\n}): BridgedMcp | null {\n const { servers, bridgedServerNames, allEnabledServerNames, hash, excludeServers } =\n input\n\n if (Object.keys(servers).length === 0) {\n const allEnabledServersExcluded =\n excludeServers &&\n allEnabledServerNames.length > 0 &&\n allEnabledServerNames.every((name) => excludeServers.has(name))\n\n if (!allEnabledServersExcluded) return null\n\n return {\n path: \"\",\n hash,\n serverNames: [],\n allEnabledServerNames,\n }\n }\n\n const body = JSON.stringify({ mcpServers: servers }, null, 2)\n const outPath = path.join(\n pluginTmpDir(),\n `mcp-${hash}.json`,\n )\n try {\n if (!fileExists(outPath)) {\n fs.writeFileSync(outPath, body, { encoding: \"utf8\", mode: 0o600 })\n }\n } catch (e) {\n log.warn(\"failed to write bridged MCP config\", {\n error: e instanceof Error ? e.message : String(e),\n })\n return null\n }\n\n log.info(\"bridged opencode MCP config\", {\n target: outPath,\n hash,\n servers: bridgedServerNames,\n excluded: excludeServers ? Array.from(excludeServers) : [],\n })\n return {\n path: outPath,\n hash,\n serverNames: bridgedServerNames,\n allEnabledServerNames,\n }\n}\n\n// Internal helpers exported for tests only.\nexport const __test = {\n deepMerge,\n mergeMcp,\n translateServer,\n substituteEnvPlaceholders,\n detectWorktree,\n loadGlobalConfig,\n loadProjectFilesInDir,\n dotOpencodeDirs,\n}\n","import type { RuntimeMcpStatus } from \"./mcp-bridge.js\"\nimport { log } from \"./logger.js\"\n\n/**\n * Captured opencode runtime context (SDK client + project directory) from\n * `PluginInput`. Lives in its own module to break the cycle that would\n * otherwise form between `index.ts` and `claude-code-language-model.ts`.\n * Values are `null`/`undefined` until the plugin's `server` factory runs\n * (e.g. early provider lookups, direct AI-SDK use, tests).\n */\ntype OpencodeClient = {\n mcp?: {\n status?: () => Promise<{ data?: unknown; error?: unknown }>\n }\n tool?: {\n list?: (options: {\n query: { provider: string; model: string; directory?: string }\n }) => Promise<{ data?: unknown; error?: unknown }>\n }\n}\n\nlet opencodeClient: OpencodeClient | null = null\n\nexport function setOpencodeClient(client: unknown): void {\n if (client && typeof client === \"object\") {\n opencodeClient = client as OpencodeClient\n }\n}\n\n/**\n * The captured SDK client, untyped: callers narrow to the surface they use\n * (this module's `OpencodeClient` only mirrors the MCP/tool routes).\n */\nexport function getOpencodeClient(): unknown {\n return opencodeClient\n}\n\n/**\n * Captured opencode project directory from `PluginInput.directory` (with\n * `worktree` as secondary signal). Used as a *fallback* at Claude CLI\n * spawn time only when `process.cwd()` is unusable (macOS GUI launches\n * where launchd hands the process `cwd=/`).\n *\n * IMPORTANT: never bake this into provider config (`mergedOptions.cwd`).\n * Doing so freezes the value at plugin init and breaks workspace\n * switching mid-session, because subsequent workspace changes in\n * opencode's UI never get reflected in `this.config.cwd`. See issue #4.\n */\nlet opencodeProjectDirectory: string | undefined\n\nexport function setOpencodeProjectDirectory(dir: string | undefined): void {\n opencodeProjectDirectory = dir\n}\n\nexport function getOpencodeProjectDirectory(): string | undefined {\n return opencodeProjectDirectory\n}\n\nexport function isUsableDirectory(d: unknown): d is string {\n return typeof d === \"string\" && d.length > 1 && d !== \"/\"\n}\n\n/**\n * Resolve the cwd for a Claude CLI subprocess spawn. Priority:\n *\n * 1. Explicit `configured` value (`options.cwd` from `opencode.json`).\n * Users who pinned a directory keep their override unconditionally.\n * 2. Live `process.cwd()` when it's a real directory. Restores the lazy\n * resolution that lets opencode's project-aware behavior (chdir on\n * workspace switch, project-per-shell on terminal launch) flow\n * through without restarting the plugin.\n * 3. Captured project directory from plugin init. Rescues macOS GUI\n * launches where `process.cwd()` is `/`.\n * 4. Final fallback to `process.cwd()` (returns `/` in the pathological\n * case where neither override nor capture is available).\n */\nexport function resolveSpawnCwd(configured: string | undefined): string {\n return resolveSpawnCwdFrom(\n configured,\n process.cwd(),\n opencodeProjectDirectory,\n )\n}\n\nexport function resolveSpawnCwdFrom(\n configured: string | undefined,\n live: string,\n captured: string | undefined,\n): string {\n if (configured) return configured\n if (isUsableDirectory(live)) return live\n return captured ?? live\n}\n\n/**\n * Snapshot opencode's current MCP runtime status so the bridge can overlay\n * UI-toggled state on top of disk config. Returns `undefined` on any\n * failure (no client captured, status call rejected, malformed response)\n * so the bridge falls back to disk-only.\n */\nexport async function getRuntimeMcpStatus(): Promise<\n RuntimeMcpStatus | undefined\n> {\n const client = opencodeClient\n if (!client?.mcp?.status) return undefined\n try {\n const res = await client.mcp.status()\n const data = (res as { data?: unknown }).data\n if (!data || typeof data !== \"object\") return undefined\n const out: RuntimeMcpStatus = {}\n for (const [name, entry] of Object.entries(data as Record<string, unknown>)) {\n if (entry && typeof entry === \"object\") {\n const status = (entry as { status?: unknown }).status\n if (typeof status === \"string\") out[name] = status\n }\n }\n return out\n } catch (err) {\n log.warn(\"failed to fetch opencode MCP runtime status\", {\n error: err instanceof Error ? err.message : String(err),\n })\n return undefined\n }\n}\n\nexport interface OpencodeToolListItem {\n id: string\n description: string\n parameters: Record<string, unknown>\n}\n\n/**\n * Fetch opencode's full tool catalog (built-ins + MCP-bridged) with JSON\n * Schema parameters via `client.tool.list()`. The provider/model query\n * narrows the schema variants opencode returns; in practice MCP-origin\n * tool schemas are model-agnostic, so any registered (provider, model)\n * works as the query target. Returns `undefined` on any failure so callers\n * can fall back to direct-bridge behavior.\n */\nexport async function fetchOpencodeToolList(\n provider: string,\n model: string,\n directory?: string,\n): Promise<OpencodeToolListItem[] | undefined> {\n const client = opencodeClient\n if (!client?.tool?.list) return undefined\n try {\n const res = await client.tool.list({\n query: { provider, model, ...(directory ? { directory } : {}) },\n })\n const data = (res as { data?: unknown }).data\n if (!Array.isArray(data)) return undefined\n const out: OpencodeToolListItem[] = []\n for (const entry of data as unknown[]) {\n if (!entry || typeof entry !== \"object\") continue\n const e = entry as Record<string, unknown>\n const id = typeof e.id === \"string\" ? e.id : null\n const description =\n typeof e.description === \"string\" ? e.description : \"\"\n const parameters =\n e.parameters && typeof e.parameters === \"object\"\n ? (e.parameters as Record<string, unknown>)\n : {}\n if (!id) continue\n out.push({ id, description, parameters })\n }\n return out\n } catch (err) {\n log.warn(\"failed to fetch opencode tool list\", {\n provider,\n model,\n error: err instanceof Error ? err.message : String(err),\n })\n return undefined\n }\n}\n","import { EventEmitter } from \"node:events\"\nimport { unlink } from \"node:fs/promises\"\nimport { ClaudeSession } from \"./claude-session-bun.js\"\nimport { cliEffortLevel, type ActiveProcess } from \"./session-manager.js\"\nimport type { ReasoningEffort } from \"./types.js\"\nimport { log } from \"./logger.js\"\n\nexport interface InteractiveSpawnOptions {\n cwd: string\n /** Claude CLI executable or account wrapper path. */\n cliPath?: string\n /** Claude config root used for JSONL transcripts. */\n configDir?: string\n model?: string\n /** Request Claude Code's fast mode (Opus 4.8 / Opus 5 only). Folded into\n * the single `--settings` payload alongside `permissions`. */\n fastMode?: boolean\n /** Bridged Claude `--mcp-config` file paths (from effectiveMcpConfig). */\n mcpConfigPaths?: string[]\n /** permissions.allow rules (e.g. mcp__server__*, Bash, Edit). */\n permissionsAllow?: string[]\n /** Optional permission mode. `bypassPermissions` is ignored for interactive\n * sessions because Claude Code shows a safety confirmation screen first. */\n permissionMode?: string\n /** Temp file for --append-system-prompt-file (parity with the headless\n * spawn; unlinked when the session is killed). */\n systemPromptFile?: string\n /** \"\" = skip CLAUDE.md + ambient settings (fast e2e); null/undefined =\n * normal settings (default — parity with the headless transport). */\n settingSources?: string | null\n /** Strip ANTHROPIC_API_KEY/ANTHROPIC_AUTH_TOKEN from the spawn env so the\n * CLI uses subscription auth instead of pay-as-you-go API billing. */\n ignoreAnthropicApiKey?: boolean\n /** Reasoning effort, exported as CLAUDE_CODE_EFFORT_LEVEL for the session. */\n effort?: ReasoningEffort\n}\n\n/**\n * doStream writes stream-json user envelopes to stdin\n * (`{\"type\":\"user\",\"message\":{content:[...]}}`). The interactive TUI expects\n * plain typed text, so decode the envelope: extract the text blocks and drop\n * anything that can't be typed into a terminal (an image block would paste\n * megabytes of base64 into the chat). Tool results are rendered as labeled\n * text so the model still sees the outcome. Non-envelope input (already plain\n * text) passes through verbatim.\n */\nexport function decodeUserEnvelope(chunk: string): string {\n let parsed: any\n try {\n parsed = JSON.parse(chunk)\n } catch {\n return chunk\n }\n if (!parsed || parsed.type !== \"user\" || !parsed.message) return chunk\n const content = parsed.message.content\n if (typeof content === \"string\") return content\n if (!Array.isArray(content)) return chunk\n\n const parts: string[] = []\n let dropped = 0\n for (const block of content) {\n if (block?.type === \"text\" && typeof block.text === \"string\") {\n parts.push(block.text)\n } else if (block?.type === \"tool_result\") {\n const v = block.content\n const text =\n typeof v === \"string\"\n ? v\n : Array.isArray(v)\n ? v\n .map((i: any) => (i?.type === \"text\" ? i.text : \"\"))\n .filter(Boolean)\n .join(\"\\n\")\n : \"\"\n parts.push(\n `[Tool result${block.tool_use_id ? ` ${block.tool_use_id}` : \"\"}]\\n${text}`,\n )\n } else {\n dropped++\n }\n }\n if (dropped > 0) {\n log.warn(\"interactive transport dropped non-text content blocks\", {\n dropped,\n })\n }\n return parts.join(\"\\n\\n\")\n}\n\n/**\n * Adapt a ClaudeSession (interactive Bun ConPTY transport) to the ActiveProcess\n * contract the doStream line handler depends on. The shim's `proc.stdin.write`\n * injects a turn into the live interactive `claude` and re-emits each new JSONL\n * transcript record on `lineEmitter` as a 'line' event, plus a synthetic\n * `{type:'result'}` line on a terminal stop_reason so the existing finish branch\n * (usage + providerMetadata + controller.close) fires unchanged.\n *\n * No node-pty, no node sidecar: runs in-process under opencode's Bun (which\n * bundles a Bun version with native ConPTY). Interactive = subscription billing.\n */\nexport function spawnInteractiveProcess(\n opts: InteractiveSpawnOptions,\n): ActiveProcess {\n const extraArgs: string[] = []\n if (opts.mcpConfigPaths && opts.mcpConfigPaths.length > 0) {\n extraArgs.push(\n \"--mcp-config\",\n ...opts.mcpConfigPaths,\n \"--strict-mcp-config\",\n )\n }\n // One `--settings` for the whole flag-settings layer. The CLI accepts the\n // flag once, so pushing a second occurrence would silently drop the first\n // rather than merge it.\n const flagSettings: Record<string, unknown> = {}\n if (opts.permissionsAllow && opts.permissionsAllow.length > 0) {\n flagSettings.permissions = { allow: opts.permissionsAllow }\n }\n if (opts.fastMode) {\n flagSettings.fastMode = true\n }\n if (Object.keys(flagSettings).length > 0) {\n extraArgs.push(\"--settings\", JSON.stringify(flagSettings))\n }\n if (opts.permissionMode === \"bypassPermissions\") {\n log.warn(\n \"interactive permissionMode bypassPermissions ignored: Claude Code prompts for confirmation in the TUI\",\n )\n } else if (opts.permissionMode) {\n extraArgs.push(\"--permission-mode\", opts.permissionMode)\n }\n if (opts.systemPromptFile) {\n extraArgs.push(\"--append-system-prompt-file\", opts.systemPromptFile)\n }\n\n const session = new ClaudeSession({\n cwd: opts.cwd,\n cliPath: opts.cliPath,\n configDir: opts.configDir,\n model: opts.model,\n // Default null = normal CLAUDE.md + settings load, matching what the\n // headless spawn does. \"\" (skip everything) is for fast e2e runs only.\n settingSources:\n opts.settingSources === undefined ? null : opts.settingSources,\n extraArgs,\n ignoreAnthropicApiKey: opts.ignoreAnthropicApiKey,\n effort: opts.effort ? cliEffortLevel(opts.effort) : undefined,\n })\n log.info(\"prepared interactive claude session\", {\n cwd: opts.cwd,\n cliPath: opts.cliPath ?? \"claude\",\n configDir: session.configDir,\n model: opts.model,\n effort: opts.effort,\n sessionId: session.sessionId,\n jsonlPath: session.jsonlPath,\n })\n\n const lineEmitter = new EventEmitter()\n const errorHandlers = new Set<(err: Error) => void>()\n let startPromise: Promise<void> | null = null\n\n const ensureStarted = (): Promise<void> => {\n if (!startPromise) startPromise = session.start()\n return startPromise\n }\n\n const emitResult = (\n subtype: string,\n isError: boolean,\n result?: string,\n usage?: unknown,\n ): void => {\n lineEmitter.emit(\n \"line\",\n JSON.stringify({\n type: \"result\",\n subtype,\n is_error: isError,\n result,\n session_id: session.sessionId,\n usage: usage ?? {},\n total_cost_usd: null,\n duration_ms: 0,\n }),\n )\n }\n\n const runTurn = (userMsg: string): void => {\n void (async () => {\n try {\n await ensureStarted()\n const { stopReason, usage } = await session.tailTurn(userMsg, (raw) => {\n lineEmitter.emit(\"line\", raw)\n })\n // Synthesize the `result` line the headless transport would have\n // emitted, so doStream's existing finish branch runs verbatim. A turn\n // with no terminal stop_reason (timeout / session exit mid-turn) is\n // reported HONESTLY as an error result — not a clean end_turn — so\n // truncation is visible to the user and to auto-continue.\n const timedOut = !stopReason\n emitResult(\n timedOut ? \"error_during_execution\" : stopReason,\n timedOut,\n timedOut\n ? \"Interactive transport: the turn ended without a terminal stop_reason (turn timeout or claude exit). Output above may be incomplete.\"\n : undefined,\n usage,\n )\n } catch (err) {\n const e = err instanceof Error ? err : new Error(String(err))\n log.error(\"interactive turn failed\", { error: e.message })\n emitResult(\n \"error_during_execution\",\n true,\n `Interactive transport failed: ${e.message}`,\n )\n if (errorHandlers.size > 0) {\n for (const h of errorHandlers) h(e)\n } else {\n lineEmitter.emit(\"close\")\n }\n }\n })()\n }\n\n // Minimal ChildProcess-shaped shim: only the members doStream/session-manager\n // actually touch (stdin.write, on/off 'error', kill).\n const proc: any = {\n stdin: {\n write(chunk: string): boolean {\n const raw =\n typeof chunk === \"string\" && chunk.endsWith(\"\\n\")\n ? chunk.slice(0, -1)\n : chunk\n // doStream writes stream-json envelopes; the TUI needs plain text.\n runTurn(decodeUserEnvelope(raw))\n return true\n },\n end(): void {},\n },\n stdout: null,\n stderr: null,\n pid: -1,\n killed: false,\n on(event: string, fn: (err: Error) => void): unknown {\n if (event === \"error\") errorHandlers.add(fn)\n return proc\n },\n once(): unknown {\n return proc\n },\n off(event: string, fn: (err: Error) => void): unknown {\n if (event === \"error\") errorHandlers.delete(fn)\n return proc\n },\n kill(): boolean {\n try {\n session.dispose()\n } catch {}\n if (opts.systemPromptFile) {\n void unlink(opts.systemPromptFile).catch(() => {})\n }\n proc.killed = true\n return true\n },\n }\n\n return {\n proc: proc as unknown as ActiveProcess[\"proc\"],\n lineEmitter,\n proxyServer: null,\n mcpHash: undefined,\n systemPromptFile: opts.systemPromptFile,\n }\n}\n","import * as os from \"node:os\"\nimport * as fs from \"node:fs\"\nimport * as path from \"node:path\"\nimport { execFileSync } from \"node:child_process\"\nimport { randomUUID } from \"node:crypto\"\n\n/**\n * Persistent interactive Claude Code session driven over Bun's NATIVE PTY\n * (Bun.spawn `terminal` option = openpty on POSIX, ConPTY on Windows). This is\n * the in-process Bun port of claude-tui-bridge/src/claudeSession.ts: same\n * design, node-pty swapped for Bun's own ConPTY so it runs inside opencode's\n * Bun runtime with NO node sidecar and NO node-pty dependency.\n *\n * - ONE long-lived interactive `claude` process per session (multi-turn),\n * - turns injected by writing into the terminal (bracketed paste + Enter),\n * - replies captured by tailing the session JSONL transcript\n * (<CLAUDE_CONFIG_DIR>/projects/<encoded-cwd>/<session-id>.jsonl) and\n * parsing the assistant records; completion detected by a terminal\n * `stop_reason`.\n *\n * Driving the INTERACTIVE TUI (real TTY) keeps model calls on the subscription\n * billing path (not `claude -p` / Agent SDK, which meter after 2026-06-15).\n */\n\nfunction resolveClaude(cmd = \"claude\"): string {\n if (path.isAbsolute(cmd) && fs.existsSync(cmd)) return cmd\n const viaBun = Bun.which(cmd)\n if (viaBun) return viaBun\n const isWin = os.platform() === \"win32\"\n try {\n const out = execFileSync(isWin ? \"where\" : \"which\", [cmd], {\n encoding: \"utf8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n })\n const first = out\n .split(/\\r?\\n/)\n .map((l) => l.trim())\n .filter(Boolean)\n .find((p) => fs.existsSync(p))\n if (first) return first\n } catch {}\n throw new Error(`Could not resolve command on PATH: ${cmd}`)\n}\n\n/** Claude encodes the absolute cwd into the transcript dir name by replacing\n * EVERY non-alphanumeric char with `-` (no collapsing of runs). Verified on\n * Windows against ~/.claude/projects, e.g.:\n * C:\\code\\my-app -> C--code-my-app\n * C:\\dev\\My Project -> C--dev-My-Project (the space also becomes `-`). */\nexport function encodeCwd(cwd: string): string {\n return path.resolve(cwd).replace(/[^a-zA-Z0-9]/g, \"-\")\n}\n\nexport interface TurnResult {\n text: string\n stopReason: string | null\n usage: any | null\n cacheReadTokens: number\n cacheCreationTokens: number\n ephemeral1hTokens: number\n ephemeral5mTokens: number\n inputTokens: number\n outputTokens: number\n elapsedMs: number\n}\n\nexport interface ClaudeSessionOptions {\n cwd?: string\n /** Claude CLI executable or account wrapper path. */\n cliPath?: string\n /** Claude config root used for JSONL transcripts (defaults to ~/.claude). */\n configDir?: string\n model?: string\n /** '' bypasses CLAUDE.md + user/project/local settings load (fast tests).\n * null/undefined omits the flag entirely (normal settings). */\n settingSources?: string | null\n extraArgs?: string[]\n /** Strip ANTHROPIC_API_KEY/ANTHROPIC_AUTH_TOKEN from the spawn env so the\n * CLI uses subscription auth instead of pay-as-you-go API billing. */\n ignoreAnthropicApiKey?: boolean\n /** CLI effort level (low | medium | high | xhigh | max), exported as\n * CLAUDE_CODE_EFFORT_LEVEL so it overrides the account's settings.json. */\n effort?: string\n cols?: number\n rows?: number\n bootMinMs?: number\n bootQuietMs?: number\n bootMaxMs?: number\n pollMs?: number\n turnTimeoutMs?: number\n /** false = plain write(prompt)+Enter; true = wrap in bracketed-paste so\n * multi-line prompts don't submit early. Default true. */\n bracketedPaste?: boolean\n /** Submitting a turn: a large/multi-line bracketed paste collapses into a\n * \"[Pasted text]\" placeholder, and an Enter sent while claude is still\n * ingesting the paste is silently DROPPED — so a single fixed-delay Enter is\n * unreliable and the turn can hang until turnTimeoutMs. Instead: wait\n * submitMinMs, send Enter, then confirm the turn was accepted (a new\n * transcript record appears) within submitConfirmMs; if not, resend Enter,\n * up to submitMaxRetries times. */\n submitMinMs?: number\n submitConfirmMs?: number\n submitMaxRetries?: number\n /** Abort the call (during boot or an in-flight turn): kills the process and\n * rejects with an \"aborted\" error. */\n signal?: AbortSignal\n debug?: boolean\n}\n\nconst TERMINAL_STOP = new Set([\"end_turn\", \"stop_sequence\", \"max_tokens\"])\nconst delay = (ms: number) => new Promise<void>((r) => setTimeout(r, ms))\n\nfunction resolveConfigDir(configDir: string | undefined): string {\n const value = configDir ?? process.env.CLAUDE_CONFIG_DIR\n if (!value) return path.join(os.homedir(), \".claude\")\n if (value === \"~\") return os.homedir()\n if (value.startsWith(\"~/\") || value.startsWith(\"~\\\\\")) {\n return path.join(os.homedir(), value.slice(2))\n }\n return path.resolve(value)\n}\n\nexport class ClaudeSession {\n readonly sessionId: string\n readonly cwd: string\n readonly configDir: string\n readonly jsonlPath: string\n raw = \"\"\n\n private proc: BunSubprocess | null = null\n private cursor = 0 // index into transcript split('\\n')\n private lastDataAt = 0\n private exited = false\n private exitCode: number | null = null\n private aborted = false\n private readonly signal?: AbortSignal\n private readonly o: Required<\n Omit<\n ClaudeSessionOptions,\n | \"cliPath\"\n | \"configDir\"\n | \"model\"\n | \"settingSources\"\n | \"extraArgs\"\n | \"signal\"\n | \"ignoreAnthropicApiKey\"\n | \"effort\"\n >\n > &\n Pick<\n ClaudeSessionOptions,\n | \"cliPath\"\n | \"configDir\"\n | \"model\"\n | \"settingSources\"\n | \"extraArgs\"\n | \"ignoreAnthropicApiKey\"\n | \"effort\"\n >\n\n constructor(opts: ClaudeSessionOptions = {}) {\n this.cwd = path.resolve(opts.cwd ?? process.cwd())\n this.configDir = resolveConfigDir(opts.configDir)\n this.signal = opts.signal\n this.sessionId = randomUUID()\n this.jsonlPath = path.join(\n this.configDir,\n \"projects\",\n encodeCwd(this.cwd),\n `${this.sessionId}.jsonl`,\n )\n this.o = {\n cwd: this.cwd,\n cliPath: opts.cliPath,\n configDir: this.configDir,\n model: opts.model,\n settingSources: opts.settingSources,\n extraArgs: opts.extraArgs ?? [],\n ignoreAnthropicApiKey: opts.ignoreAnthropicApiKey,\n effort: opts.effort,\n cols: opts.cols ?? 200,\n rows: opts.rows ?? 50,\n bootMinMs: opts.bootMinMs ?? 3000,\n bootQuietMs: opts.bootQuietMs ?? 1500,\n bootMaxMs: opts.bootMaxMs ?? 25000,\n pollMs: opts.pollMs ?? 250,\n // Agentic turns (tool loops) routinely run for many minutes; a short\n // cap would surface as a mid-task error result. 30 min mirrors the\n // proxy-tool ceiling rather than a chat-reply expectation.\n turnTimeoutMs: opts.turnTimeoutMs ?? 1_800_000,\n bracketedPaste: opts.bracketedPaste ?? true,\n submitMinMs: opts.submitMinMs ?? 200,\n submitConfirmMs: opts.submitConfirmMs ?? 1500,\n submitMaxRetries: opts.submitMaxRetries ?? 8,\n debug: opts.debug ?? false,\n }\n }\n\n async start(): Promise<void> {\n if (this.signal?.aborted) throw new Error(\"aborted before start\")\n this.signal?.addEventListener(\n \"abort\",\n () => {\n this.aborted = true\n this.dispose()\n },\n { once: true },\n )\n const claude = resolveClaude(this.o.cliPath ?? \"claude\")\n const args: string[] = [\"--session-id\", this.sessionId]\n if (this.o.model) args.push(\"--model\", this.o.model)\n if (this.o.settingSources !== null && this.o.settingSources !== undefined) {\n args.push(\"--setting-sources\", this.o.settingSources)\n }\n if (this.o.extraArgs && this.o.extraArgs.length) args.push(...this.o.extraArgs)\n\n if (this.o.debug)\n process.stderr.write(`[session] spawn: ${claude} ${args.join(\" \")}\\n`)\n\n this.lastDataAt = Date.now()\n this.proc = Bun.spawn([claude, ...args], {\n cwd: this.cwd,\n env: {\n ...process.env,\n CLAUDE_CONFIG_DIR: this.o.configDir,\n TERM: \"xterm-256color\",\n ...(this.o.ignoreAnthropicApiKey\n ? { ANTHROPIC_API_KEY: undefined, ANTHROPIC_AUTH_TOKEN: undefined }\n : {}),\n ...(this.o.effort ? { CLAUDE_CODE_EFFORT_LEVEL: this.o.effort } : {}),\n },\n terminal: {\n cols: this.o.cols,\n rows: this.o.rows,\n data: (_term, d) => {\n this.lastDataAt = Date.now()\n const chunk = Buffer.from(d).toString(\"utf8\")\n this.raw += chunk\n if (this.o.debug) process.stdout.write(chunk)\n },\n },\n })\n this.proc.exited\n .then((code) => {\n this.exitCode = typeof code === \"number\" ? code : null\n this.exited = true\n this.proc = null\n })\n .catch(() => {\n this.exited = true\n this.proc = null\n })\n\n await this.waitForBoot()\n this.cursor = this.lineCount()\n }\n\n /** Wait until the TUI has been quiet for bootQuietMs (Ink ready), bounded by\n * bootMinMs..bootMaxMs. */\n private async waitForBoot(): Promise<void> {\n const start = Date.now()\n while (Date.now() - start < this.o.bootMaxMs) {\n await delay(150)\n if (this.aborted) throw new Error(\"aborted during boot\")\n if (this.exited) {\n throw new Error(this.failureMessage(\"claude exited during boot\", true))\n }\n const elapsed = Date.now() - start\n const sinceData = Date.now() - this.lastDataAt\n if (elapsed >= this.o.bootMinMs && sinceData >= this.o.bootQuietMs) return\n }\n }\n\n /** Submit the freshly-injected prompt and confirm the turn was actually\n * accepted. A large bracketed paste collapses into a \"[Pasted text]\"\n * placeholder; an Enter sent while claude is still ingesting the paste is\n * silently dropped, so a single fixed-delay Enter races the paste and can\n * leave the prompt sitting unsubmitted (→ hang until turnTimeoutMs). Send\n * Enter, then poll for transcript growth past the cursor (the turn's records\n * are written on acceptance); resend Enter until accepted or the retry\n * budget is spent. Polling growth (not a blind delay) also stops us from\n * sending a stray Enter once the turn is in flight. */\n private async submitTurn(): Promise<void> {\n await delay(this.o.submitMinMs)\n for (let attempt = 0; attempt < this.o.submitMaxRetries; attempt++) {\n if (this.aborted || this.exited || !this.proc) return\n this.proc.terminal.write(\"\\r\")\n const until = Date.now() + this.o.submitConfirmMs\n while (Date.now() < until) {\n await delay(80)\n if (this.aborted || this.exited) return\n if (this.lineCount() > this.cursor) return // turn accepted\n }\n }\n }\n\n private readRawLines(): string[] {\n try {\n return fs.readFileSync(this.jsonlPath, \"utf8\").split(\"\\n\")\n } catch {\n return []\n }\n }\n\n /** Count of complete lines (split('\\n') minus the trailing/partial element). */\n private lineCount(): number {\n const lines = this.readRawLines()\n return lines.length > 0 ? lines.length - 1 : 0\n }\n\n private rawTail(max = 600): string {\n const clean = this.raw\n // Strip ANSI escape/control sequences before including terminal output in diagnostics.\n .replace(/\\x1B(?:[@-Z\\\\-_]|\\[[0-?]*[ -/]*[@-~])/g, \"\")\n .replace(/\\s+/g, \" \")\n .trim()\n return clean.length > max ? clean.slice(-max) : clean\n }\n\n private failureMessage(reason: string, includeRaw = false): string {\n const parts = [\n `${reason} (sessionId=${this.sessionId}, jsonlPath=${this.jsonlPath}, exitCode=${this.exitCode ?? \"unknown\"})`,\n ]\n if (includeRaw) {\n const tail = this.rawTail()\n if (tail) parts.push(`terminalTail=${JSON.stringify(tail)}`)\n }\n return parts.join(\"; \")\n }\n\n /**\n * Inject a turn into the live session and return the assistant reply once a\n * terminal stop_reason is observed in the transcript.\n */\n async ask(prompt: string, perTurnTimeoutMs?: number): Promise<TurnResult> {\n if (this.aborted) throw new Error(\"aborted\")\n if (!this.proc || this.exited)\n throw new Error(\"session not started or already exited\")\n const timeout = perTurnTimeoutMs ?? this.o.turnTimeoutMs\n const t0 = Date.now()\n\n // Inject. Bracketed paste keeps multi-line prompts from submitting early;\n // submitTurn() then presses Enter and confirms the turn was accepted,\n // resending Enter if the (collapsed) paste swallowed the first one.\n if (this.o.bracketedPaste) {\n this.proc.terminal.write(\"\\x1b[200~\" + prompt + \"\\x1b[201~\")\n } else {\n this.proc.terminal.write(prompt)\n }\n await this.submitTurn()\n\n const collected: string[] = []\n let lastUsage: any = null\n let stopReason: string | null = null\n const deadline = Date.now() + timeout\n\n while (Date.now() < deadline) {\n await delay(this.o.pollMs)\n if (this.aborted) throw new Error(\"aborted mid-turn\")\n const lines = this.readRawLines()\n const lastComplete = lines.length - 1 // exclusive bound; trailing/partial line skipped\n if (lastComplete <= this.cursor) {\n // Drain the transcript before reacting to exit: a final assistant record\n // can be flushed in the same tick the process exits.\n if (this.exited) throw new Error(this.failureMessage(\"claude exited mid-turn\", true))\n continue\n }\n\n for (let i = this.cursor; i < lastComplete; i++) {\n const s = lines[i]\n if (!s || !s.trim()) continue\n let rec: any\n try {\n rec = JSON.parse(s)\n } catch {\n continue\n }\n if (rec.type === \"assistant\" && rec.message) {\n for (const b of rec.message.content ?? []) {\n if (b?.type === \"text\" && typeof b.text === \"string\")\n collected.push(b.text)\n }\n if (rec.message.usage) lastUsage = rec.message.usage\n if (\n rec.message.stop_reason &&\n TERMINAL_STOP.has(rec.message.stop_reason)\n ) {\n stopReason = rec.message.stop_reason\n }\n }\n }\n this.cursor = lastComplete\n if (stopReason) break\n }\n\n if (!stopReason) {\n throw new Error(\n this.failureMessage(\n `turn timed out after ${timeout}ms (no terminal assistant record; collected ${collected.length} text block(s))`,\n ),\n )\n }\n\n const u = lastUsage ?? {}\n return {\n text: collected.join(\"\\n\").trim(),\n stopReason,\n usage: lastUsage,\n cacheReadTokens: u.cache_read_input_tokens ?? 0,\n cacheCreationTokens: u.cache_creation_input_tokens ?? 0,\n ephemeral1hTokens: u.cache_creation?.ephemeral_1h_input_tokens ?? 0,\n ephemeral5mTokens: u.cache_creation?.ephemeral_5m_input_tokens ?? 0,\n inputTokens: u.input_tokens ?? 0,\n outputTokens: u.output_tokens ?? 0,\n elapsedMs: Date.now() - t0,\n }\n }\n\n /**\n * Like ask(), but instead of collecting the reply text it re-emits each NEW\n * raw JSONL transcript line via onLine (verbatim) until a terminal\n * stop_reason. Returns the terminal stop_reason + the last assistant usage.\n * Used by the opencode plugin transport shim, which feeds these raw lines\n * into the existing stream-json line handler unchanged.\n */\n async tailTurn(\n prompt: string,\n onLine: (rawLine: string) => void,\n perTurnTimeoutMs?: number\n ): Promise<{ stopReason: string | null; usage: any | null }> {\n if (this.aborted) throw new Error(\"aborted\")\n if (!this.proc || this.exited)\n throw new Error(\"session not started or already exited\")\n const timeout = perTurnTimeoutMs ?? this.o.turnTimeoutMs\n\n if (this.o.bracketedPaste) {\n this.proc.terminal.write(\"\\x1b[200~\" + prompt + \"\\x1b[201~\")\n } else {\n this.proc.terminal.write(prompt)\n }\n await this.submitTurn()\n\n let lastUsage: any = null\n let totalOutput = 0\n let stopReason: string | null = null\n const deadline = Date.now() + timeout\n\n while (Date.now() < deadline) {\n await delay(this.o.pollMs)\n if (this.aborted) throw new Error(\"aborted mid-turn\")\n const lines = this.readRawLines()\n const lastComplete = lines.length - 1\n if (lastComplete <= this.cursor) {\n // Drain the transcript before reacting to exit: the terminal assistant\n // record can land in the same tick the process exits.\n if (this.exited) {\n throw new Error(this.failureMessage(\"claude exited mid-turn\", true))\n }\n continue\n }\n for (let i = this.cursor; i < lastComplete; i++) {\n const s = lines[i]\n if (!s || !s.trim()) continue\n onLine(s)\n let rec: any\n try {\n rec = JSON.parse(s)\n } catch {\n continue\n }\n if (rec.type === \"assistant\" && rec.message) {\n if (rec.message.usage) {\n lastUsage = rec.message.usage\n totalOutput += rec.message.usage.output_tokens ?? 0\n }\n if (\n rec.message.stop_reason &&\n TERMINAL_STOP.has(rec.message.stop_reason)\n ) {\n stopReason = rec.message.stop_reason\n }\n }\n }\n this.cursor = lastComplete\n if (stopReason) break\n }\n\n // Context (input/cache) = the LAST record's full conversation state; output\n // = SUM across all assistant records this turn (each generation), else\n // multi-record tool turns undercount output. toUsage() prefers\n // iterations[last], so patch that entry's output too.\n let usage: any = lastUsage\n if (lastUsage) {\n usage = { ...lastUsage, output_tokens: totalOutput }\n if (Array.isArray(lastUsage.iterations) && lastUsage.iterations.length > 0) {\n const iters = lastUsage.iterations.map((it: any) => ({ ...it }))\n iters[iters.length - 1] = {\n ...iters[iters.length - 1],\n output_tokens: totalOutput,\n }\n usage.iterations = iters\n }\n }\n if (!stopReason) {\n throw new Error(\n this.failureMessage(\n `turn timed out after ${timeout}ms (no terminal assistant record)`,\n ),\n )\n }\n\n return { stopReason, usage }\n }\n\n dispose(): void {\n if (this.proc) {\n try {\n this.proc.terminal.write(\"\\x03\")\n } catch {}\n try {\n this.proc.kill()\n } catch {}\n try {\n this.proc.terminal.close()\n } catch {}\n }\n this.proc = null\n }\n}\n\n/** One-shot convenience (drop-in for `claude -p`): start, ask, dispose. */\nexport async function askOnce(\n prompt: string,\n opts: ClaudeSessionOptions = {},\n): Promise<TurnResult> {\n const s = new ClaudeSession(opts)\n await s.start()\n try {\n return await s.ask(prompt)\n } finally {\n s.dispose()\n }\n}\n","import { chmod, lstat, mkdir, readlink, symlink, writeFile } from \"node:fs/promises\"\nimport path from \"node:path\"\nimport { log } from \"./logger.js\"\n\nexport const BASE_PROVIDER_ID = \"claude-code\"\nexport const DEFAULT_ACCOUNT = \"default\"\n\nconst SHARED_CAPABILITY_ITEMS = [\n \"CLAUDE.md\",\n \"settings.json\",\n \"skills\",\n \"agents\",\n \"commands\",\n \"plugins\",\n]\n\nexport function normalizeAccountName(account: string): string {\n return account\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n}\n\nexport function resolveAccounts(value: unknown): string[] | null {\n if (!Array.isArray(value)) return null\n\n const accounts = value\n .map((account) => normalizeAccountName(String(account)))\n .filter(Boolean)\n\n return Array.from(new Set([DEFAULT_ACCOUNT, ...accounts]))\n}\n\nexport function accountProviderId(account: string): string {\n return `${BASE_PROVIDER_ID}-${normalizeAccountName(account)}`\n}\n\nexport function accountDisplayName(account: string): string {\n return `Claude Code (${titleizeAccount(account)})`\n}\n\nexport function accountModelSuffix(account: string): string | undefined {\n const normalized = normalizeAccountName(account)\n return normalized === DEFAULT_ACCOUNT ? undefined : normalized\n}\n\nexport function accountConfigDir(account: string): string | undefined {\n const normalized = normalizeAccountName(account)\n\n if (!normalized || normalized === DEFAULT_ACCOUNT) return undefined\n\n return `~/.claude-${normalized}`\n}\n\nexport function expandHome(value: string): string {\n const home = process.env.HOME ?? process.env.USERPROFILE\n\n if (value === \"~\") return home ?? value\n\n if (value.startsWith(\"~/\") || value.startsWith(\"~\\\\\")) {\n return home ? path.join(home, value.slice(2)) : value\n }\n\n return value\n}\n\nexport async function ensureAccountRuntime(\n account: string,\n baseCliPath: string,\n): Promise<{ cliPath: string; configDir?: string }> {\n const configDir = accountConfigDir(account)\n\n if (!configDir) return { cliPath: baseCliPath }\n\n const expandedConfigDir = expandHome(configDir)\n await mkdir(expandedConfigDir, { recursive: true })\n\n try {\n await ensureSharedCapabilities(expandedConfigDir)\n } catch (err) {\n log.warn(\"failed to symlink shared capabilities; continuing anyway\", {\n account,\n configDir: expandedConfigDir,\n error: String(err),\n })\n }\n\n const cliPath = await writeAccountWrapper(\n normalizeAccountName(account),\n baseCliPath,\n expandedConfigDir,\n )\n\n return { cliPath, configDir: expandedConfigDir }\n}\n\nasync function ensureSharedCapabilities(targetRoot: string): Promise<void> {\n const sourceRoot = expandHome(\"~/.claude\")\n\n for (const item of SHARED_CAPABILITY_ITEMS) {\n await ensureSharedCapabilityItem(sourceRoot, targetRoot, item)\n }\n}\n\nasync function ensureSharedCapabilityItem(\n sourceRoot: string,\n targetRoot: string,\n item: string,\n): Promise<void> {\n const source = path.join(sourceRoot, item)\n const target = path.join(targetRoot, item)\n\n let sourceStat\n try {\n sourceStat = await lstat(source)\n } catch {\n return\n }\n\n try {\n const targetStat = await lstat(target)\n\n if (targetStat.isSymbolicLink()) {\n const current = await readlink(target)\n const resolvedCurrent = path.resolve(path.dirname(target), current)\n const resolvedSource = path.resolve(source)\n\n if (resolvedCurrent === resolvedSource) return\n }\n\n log.warn(\"shared Claude capability already exists; leaving untouched\", {\n item,\n target,\n source,\n })\n\n return\n } catch {\n // Missing target is expected.\n }\n\n const type = sourceStat.isDirectory()\n ? process.platform === \"win32\"\n ? \"junction\"\n : \"dir\"\n : \"file\"\n\n await symlink(source, target, type)\n}\n\nasync function writeAccountWrapper(\n account: string,\n baseCliPath: string,\n configDir: string,\n): Promise<string> {\n const cacheRoot = path.join(\n process.env.XDG_CACHE_HOME ?? expandHome(\"~/.cache\"),\n \"opencode-claude-code-plugin\",\n )\n const wrapperPath = path.join(cacheRoot, `claude-${account}`)\n const suffix = `@${account}`\n\n await mkdir(cacheRoot, { recursive: true })\n\n const script = `#!/usr/bin/env bash\nset -euo pipefail\n\nargs=()\nwhile [[ $# -gt 0 ]]; do\n if [[ \"$1\" == \"--model\" && $# -ge 2 ]]; then\n model=\"$2\"\n if [[ \"$model\" == *${shellDoubleQuote(suffix)} ]]; then\n model=\"\\${model%${shellDoubleQuote(suffix)}}\"\n fi\n args+=(\"$1\" \"$model\")\n shift 2\n else\n args+=(\"$1\")\n shift\n fi\ndone\n\nexport CLAUDE_CONFIG_DIR=${shellSingleQuote(configDir)}\nexec ${shellSingleQuote(baseCliPath)} \"\\${args[@]}\"\n`\n\n await writeFile(wrapperPath, script, \"utf8\")\n await chmod(wrapperPath, 0o755)\n\n return wrapperPath\n}\n\nfunction shellSingleQuote(value: string): string {\n return `'${value.replace(/'/g, `'\"'\"'`)}'`\n}\n\nfunction shellDoubleQuote(value: string): string {\n return value.replace(/[$`\"\\\\]/g, \"\\\\$&\")\n}\n\nfunction titleizeAccount(account: string): string {\n return normalizeAccountName(account)\n .split(\"-\")\n .filter(Boolean)\n .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n .join(\" \")\n}\n","// Removes a stale unscoped `opencode-claude-code-plugin` install left in\n// opencode's plugin cache by older configs. The unscoped name is a different\n// artifact than this scoped plugin and shadows it when both coexist.\n// Disable with OPENCODE_CLAUDE_CODE_PLUGIN_NO_CLEANUP=1.\n\nimport {\n existsSync,\n readFileSync,\n realpathSync,\n rmSync,\n writeFileSync,\n} from \"node:fs\"\nimport { homedir } from \"node:os\"\nimport { join, resolve } from \"node:path\"\nimport { fileURLToPath } from \"node:url\"\nimport { log } from \"./logger.js\"\n\nconst STALE_PACKAGE_NAME = \"opencode-claude-code-plugin\"\nconst SUSPECT_DESCRIPTION_TOKEN = \"Claude Code\"\n\nlet alreadyRan = false\n\nfunction candidateCacheRoots(): string[] {\n const xdg = process.env.XDG_CACHE_HOME\n return [\n xdg ? join(xdg, \"opencode\") : null,\n join(homedir(), \".cache\", \"opencode\"),\n join(homedir(), \"Library\", \"Caches\", \"opencode\"),\n ].filter((p): p is string => Boolean(p))\n}\n\nfunction userOpencodeJsonPath(): string {\n const xdgConfig = process.env.XDG_CONFIG_HOME ?? join(homedir(), \".config\")\n return join(xdgConfig, \"opencode\", \"opencode.json\")\n}\n\nfunction userIntendsToUseUnscoped(): boolean {\n const cfg = userOpencodeJsonPath()\n if (!existsSync(cfg)) return false\n try {\n const json = JSON.parse(readFileSync(cfg, \"utf8\"))\n const plugins: unknown = json.plugin\n if (!Array.isArray(plugins)) return false\n return plugins.some(\n (entry) =>\n typeof entry === \"string\" &&\n /^opencode-claude-code-plugin(@[^/]+)?$/.test(entry),\n )\n } catch {\n return false\n }\n}\n\nfunction ourLoadedDir(): string | null {\n try {\n const filePath = fileURLToPath(import.meta.url)\n return realpathSync(resolve(filePath, \"..\", \"..\"))\n } catch {\n return null\n }\n}\n\nexport function cleanupStaleUnscopedInstall(): void {\n if (alreadyRan) return\n alreadyRan = true\n\n if (process.env.OPENCODE_CLAUDE_CODE_PLUGIN_NO_CLEANUP === \"1\") return\n if (userIntendsToUseUnscoped()) return\n\n const ourDir = ourLoadedDir()\n\n for (const cacheRoot of candidateCacheRoots()) {\n try {\n cleanupOne(cacheRoot, ourDir)\n } catch (err) {\n log.warn(\"cleanup-stale: error processing cache root\", {\n cacheRoot,\n error: String(err),\n })\n }\n }\n}\n\nfunction cleanupOne(cacheRoot: string, ourDir: string | null): void {\n if (!existsSync(cacheRoot)) return\n\n const stalePath = join(cacheRoot, \"node_modules\", STALE_PACKAGE_NAME)\n if (!existsSync(stalePath)) return\n\n // Don't self-delete if we are the unscoped install.\n let realStalePath = stalePath\n try {\n realStalePath = realpathSync(stalePath)\n } catch {\n // ignore\n }\n if (ourDir && realStalePath === ourDir) return\n\n // Verify identity before removing.\n const pkgJsonPath = join(stalePath, \"package.json\")\n if (!existsSync(pkgJsonPath)) return\n let pkg: { name?: string; description?: string } = {}\n try {\n pkg = JSON.parse(readFileSync(pkgJsonPath, \"utf8\"))\n } catch {\n return\n }\n if (pkg.name !== STALE_PACKAGE_NAME) return\n if (!pkg.description?.includes(SUSPECT_DESCRIPTION_TOKEN)) return\n\n log.info(\"cleanup-stale: removing unscoped install\", { stalePath })\n try {\n rmSync(stalePath, { recursive: true, force: true })\n } catch (err) {\n log.warn(\"cleanup-stale: rmSync failed\", {\n stalePath,\n error: String(err),\n })\n return\n }\n\n // Drop the dep from the cache root's package.json so opencode's installer\n // doesn't reinstate it on its next pass. Lockfile is left alone; bun\n // reconciles against package.json on the next install.\n const cachePkgJson = join(cacheRoot, \"package.json\")\n if (!existsSync(cachePkgJson)) return\n try {\n const cfg = JSON.parse(readFileSync(cachePkgJson, \"utf8\"))\n if (cfg?.dependencies?.[STALE_PACKAGE_NAME]) {\n delete cfg.dependencies[STALE_PACKAGE_NAME]\n writeFileSync(cachePkgJson, JSON.stringify(cfg, null, 2) + \"\\n\")\n log.info(\"cleanup-stale: pruned dep from cache package.json\")\n }\n } catch (err) {\n log.warn(\"cleanup-stale: cache package.json update failed\", {\n error: String(err),\n })\n }\n}\n","import { execFile } from \"node:child_process\"\nimport * as fs from \"node:fs\"\nimport * as path from \"node:path\"\nimport { promisify } from \"node:util\"\nimport { fileURLToPath } from \"node:url\"\n\nimport { detectCliVersion } from \"./cli-version.js\"\nimport { log } from \"./logger.js\"\nimport { mergeOpencodeMcp } from \"./mcp-bridge.js\"\nimport { getOpencodeProjectDirectory, isUsableDirectory } from \"./runtime-status.js\"\n\n/**\n * One compact status block logged once per process, right after providers are\n * registered. Every field here answers a question that previously cost a live\n * debugging session: which plugin build is loaded, whether the Claude CLI is\n * even reachable, which cwd the spawn will use and why, what is proxied, and\n * how many MCP servers the bridge sees. Keep it cheap and never let it throw:\n * diagnostics must not be able to break provider registration.\n */\nexport interface StartupDiagnostics {\n plugin: string\n opencode: string\n claudeCli: { path: string; version: string }\n cwd: { resolved: string; source: CwdSource }\n providers: string[]\n accounts: string[]\n proxyTools: string[]\n mcpServers: string[]\n interactiveTransport: boolean\n /** ExitPlanMode approval routed through opencode's `question` tool. */\n planModeQuestion: boolean\n anthropicApiKeyInEnv: boolean\n}\n\n/** Which branch of `resolveSpawnCwd` a Claude CLI spawn would take right now. */\nexport type CwdSource = \"configured\" | \"process\" | \"captured\" | \"unresolved\"\n\nexport interface DiagnosticsProviderEntry {\n name?: string\n options?: Record<string, unknown>\n}\n\nlet cachedPluginVersion: string | undefined\n\n/** Version of this plugin, read from the package manifest one level up. */\nexport function pluginVersion(): string {\n if (cachedPluginVersion) return cachedPluginVersion\n try {\n const here = path.dirname(fileURLToPath(import.meta.url))\n const raw = fs.readFileSync(path.join(here, \"..\", \"package.json\"), \"utf8\")\n const version = (JSON.parse(raw) as { version?: unknown }).version\n cachedPluginVersion = typeof version === \"string\" ? version : \"unknown\"\n } catch {\n cachedPluginVersion = \"unknown\"\n }\n return cachedPluginVersion\n}\n\n/**\n * Best-effort opencode version from the plugin input. Re-verified on opencode\n * 1.18.5: nothing on the plugin surface carries it. `PluginInput` has no\n * version field, the SDK client's `app` namespace exposes only `log`/`agents`,\n * and the server has no `/version` route. So this probes a couple of plausible\n * shapes for future opencode releases and otherwise returns undefined, leaving\n * the binary probe (`detectOpencodeVersion`) as the fallback. Do not replace it\n * with a `client.app.get()` call — that method does not exist.\n */\nexport function pickOpencodeVersion(input: unknown): string | undefined {\n if (!input || typeof input !== \"object\") return undefined\n const app = (input as { app?: unknown }).app\n if (app && typeof app === \"object\") {\n const version = (app as { version?: unknown }).version\n if (typeof version === \"string\" && version.length > 0) return version\n }\n const direct = (input as { version?: unknown }).version\n if (typeof direct === \"string\" && direct.length > 0) return direct\n return undefined\n}\n\nconst execFileAsync = promisify(execFile)\n\nlet opencodeVersionProbe: Promise<string | undefined> | undefined\n\n/**\n * The plugin runs *inside* opencode's process, so `process.execPath` is the\n * opencode binary itself — asking it for `--version` is the only reliable way\n * to name the version, since the plugin API exposes it nowhere (see\n * `pickOpencodeVersion`). Guarded on the basename: when opencode is run from\n * source (`bun run packages/opencode/src/index.ts`) execPath is the Bun binary,\n * and reporting Bun's version as opencode's would be worse than \"unknown\".\n * Cached, 5s timeout, never throws.\n */\nexport function detectOpencodeVersion(\n execPath: string = process.execPath,\n): Promise<string | undefined> {\n if (opencodeVersionProbe) return opencodeVersionProbe\n opencodeVersionProbe = (async (): Promise<string | undefined> => {\n if (!path.basename(execPath).toLowerCase().includes(\"opencode\")) {\n log.debug(\"skipping opencode version probe: execPath is not opencode\", { execPath })\n return undefined\n }\n try {\n const { stdout } = await execFileAsync(execPath, [\"--version\"], { timeout: 5000 })\n const match = /\\d+\\.\\d+\\.\\d+\\S*/.exec(stdout.trim())\n return match ? match[0] : undefined\n } catch (err) {\n log.debug(\"opencode version probe failed\", {\n execPath,\n error: err instanceof Error ? err.message : String(err),\n })\n return undefined\n }\n })()\n return opencodeVersionProbe\n}\n\n/** Test seam: drop the cached probe so a fresh execPath is honored. */\nexport function resetOpencodeVersionProbe(): void {\n opencodeVersionProbe = undefined\n}\n\n/**\n * Mirror of `resolveSpawnCwd`'s priority order, but reporting *which* branch\n * won. `configured` means `options.cwd` pinned it, `process` is the normal\n * lazy path, `captured` means `process.cwd()` was unusable (macOS GUI launch\n * at `/`) and the captured project directory rescued it — that one is the\n * fingerprint of issue #4.\n */\nexport function describeSpawnCwd(\n configured: unknown,\n live: string = process.cwd(),\n captured: string | undefined = getOpencodeProjectDirectory(),\n): { resolved: string; source: CwdSource } {\n if (typeof configured === \"string\" && configured.length > 0) {\n return { resolved: configured, source: \"configured\" }\n }\n if (isUsableDirectory(live)) return { resolved: live, source: \"process\" }\n if (isUsableDirectory(captured)) return { resolved: captured, source: \"captured\" }\n return { resolved: live, source: \"unresolved\" }\n}\n\nfunction stringList(value: unknown): string[] {\n if (!Array.isArray(value)) return []\n return value.filter((entry): entry is string => typeof entry === \"string\")\n}\n\nfunction firstOption(\n providers: Record<string, DiagnosticsProviderEntry>,\n key: string,\n): unknown {\n for (const entry of Object.values(providers)) {\n const value = entry?.options?.[key]\n if (value !== undefined) return value\n }\n return undefined\n}\n\nexport function collectStartupDiagnostics(\n providers: Record<string, DiagnosticsProviderEntry>,\n opencodeVersion?: string,\n): Omit<StartupDiagnostics, \"claudeCli\"> & { claudeCliPath: string } {\n const accounts: string[] = []\n for (const entry of Object.values(providers)) {\n const account = entry?.options?.account\n if (typeof account === \"string\" && account.length > 0) accounts.push(account)\n }\n\n const cwd = describeSpawnCwd(firstOption(providers, \"cwd\"))\n\n let mcpServers: string[] = []\n try {\n // Disk-only view: opencode's runtime MCP status isn't settled at plugin\n // init (servers are still connecting), so the per-turn overlay is not\n // applied here. This is what the bridge would ship on a cold start.\n mcpServers = mergeOpencodeMcp(cwd.resolved).enabledServerNames\n } catch (err) {\n log.debug(\"startup diagnostics could not read MCP config\", {\n error: err instanceof Error ? err.message : String(err),\n })\n }\n\n return {\n plugin: pluginVersion(),\n opencode: opencodeVersion ?? process.env.OPENCODE_VERSION ?? \"unknown\",\n claudeCliPath: String(firstOption(providers, \"cliPath\") ?? \"claude\"),\n cwd,\n providers: Object.keys(providers),\n accounts,\n proxyTools: stringList(firstOption(providers, \"proxyTools\")),\n mcpServers,\n interactiveTransport:\n firstOption(providers, \"interactive\") === true ||\n process.env.CLAUDE_CODE_INTERACTIVE_TRANSPORT === \"1\",\n planModeQuestion: firstOption(providers, \"planModeQuestion\") === true,\n anthropicApiKeyInEnv: Boolean(\n process.env.ANTHROPIC_API_KEY || process.env.ANTHROPIC_AUTH_TOKEN,\n ),\n }\n}\n\nlet logged = false\n\n/**\n * Emit the startup block once per process. Fire-and-forget: the Claude CLI\n * version probe is async (`claude --version`, 5s timeout, cached), and a slow\n * or missing binary must never delay provider registration.\n */\nexport function logStartupDiagnostics(\n providers: Record<string, DiagnosticsProviderEntry>,\n opencodeVersion?: string,\n): void {\n if (logged) return\n logged = true\n void (async () => {\n try {\n // Probe the binary only when the plugin input and env gave us nothing,\n // so a future opencode that reports its version costs no spawn.\n const version =\n opencodeVersion ?? process.env.OPENCODE_VERSION ?? (await detectOpencodeVersion())\n const { claudeCliPath, ...rest } = collectStartupDiagnostics(providers, version)\n const cli = await detectCliVersion(claudeCliPath)\n const diagnostics: StartupDiagnostics = {\n ...rest,\n claudeCli: { path: claudeCliPath, version: cli?.raw ?? \"not detected\" },\n }\n log.notice(\"claude-code plugin ready\", { ...diagnostics })\n } catch (err) {\n log.debug(\"startup diagnostics failed\", {\n error: err instanceof Error ? err.message : String(err),\n })\n }\n })()\n}\n\n/** For tests. */\nexport function _resetStartupDiagnostics(): void {\n logged = false\n}\n","import type { LanguageModelV3 } from \"@ai-sdk/provider\"\nimport { ClaudeCodeLanguageModel } from \"./claude-code-language-model.js\"\nimport { defaultModels, toConfigModel } from \"./models.js\"\nimport type {\n OpenCodeConfig,\n OpenCodeModel,\n OpenCodePlugin,\n OpenCodeProvider,\n} from \"./opencode-types.js\"\nimport type { ClaudeCodeProviderSettings } from \"./types.js\"\nimport {\n BASE_PROVIDER_ID,\n accountDisplayName,\n accountModelSuffix,\n accountProviderId,\n ensureAccountRuntime,\n resolveAccounts,\n} from \"./accounts.js\"\nimport {\n type AgentRecord,\n agentDirectories,\n getDefaultSubagentModel,\n readAgentMarkdownRecords,\n setAgentRegistry,\n setDefaultSubagentModel,\n} from \"./agent-models.js\"\nimport { cleanupStaleUnscopedInstall } from \"./cleanup-stale.js\"\nimport { configureLogger, log } from \"./logger.js\"\nimport { handleBtwCommand, type BtwSdkClient } from \"./btw-command.js\"\nimport { getOpencodeClient } from \"./runtime-status.js\"\nimport {\n getOpencodeProjectDirectory,\n isUsableDirectory,\n setOpencodeClient,\n setOpencodeProjectDirectory,\n} from \"./runtime-status.js\"\nimport {\n logStartupDiagnostics,\n pickOpencodeVersion,\n type DiagnosticsProviderEntry,\n} from \"./startup-diagnostics.js\"\n\nexport interface ClaudeCodeProvider {\n specificationVersion: \"v3\"\n (modelId: string): LanguageModelV3\n languageModel(modelId: string): LanguageModelV3\n}\n\n// Picks the best directory from opencode's plugin context (`directory` /\n// `worktree`). Result is handed to runtime-status so it's available as a\n// *fallback* at spawn time only when `process.cwd()` is unusable (macOS\n// GUI launches at `/`). Never baked into provider config — see #4.\nfunction pickOpencodeDirectory(input: unknown): string | undefined {\n if (!input || typeof input !== \"object\") return undefined\n const ctx = input as { directory?: unknown; worktree?: unknown }\n if (isUsableDirectory(ctx.directory)) return ctx.directory\n if (isUsableDirectory(ctx.worktree)) return ctx.worktree\n return undefined\n}\n\nlet warnedAnthropicApiKey = false\n\n// `Question` is deliberately absent: enabling it disables Claude Code's\n// built-in AskUserQuestion (via --disallowedTools) and replaces the\n// stop-and-wait deny/markdown path with an in-turn blocking form. That is a\n// behavior trade against the issue-#8 guarantee, so it stays opt-in until it\n// has the same live mileage Task had before v0.10.0 flipped it on. Users opt\n// in by listing it in `proxyTools`; see README \"Question proxy tool\".\nexport const DEFAULT_PROXY_TOOL_NAMES = [\n \"Bash\",\n \"Edit\",\n \"Write\",\n \"WebFetch\",\n \"Task\",\n]\n\n/**\n * Registers `/btw` unless the user defined their own. Returns whether the\n * registration is ours: the command hook only intercepts `btw` in that case,\n * so a user-defined command keeps opencode's normal behaviour end to end.\n */\nexport function registerSideQuestionCommand(config: OpenCodeConfig): boolean {\n config.command ??= {}\n if (config.command.btw) return false\n config.command.btw = {\n template: \"/btw $ARGUMENTS\",\n description: \"Ask a side question in the live Claude Code session without changing its context\",\n }\n return true\n}\n\nlet ownsSideQuestionCommand = false\n\n// One-time heads-up: an API key in the environment makes Claude Code bill\n// pay-as-you-go (Console) instead of the logged-in Pro/Max subscription, which\n// silently bypasses the Agent SDK plan credit. Surfaced once per process.\nfunction warnIfAnthropicApiKey(ignore: boolean | undefined): void {\n if (warnedAnthropicApiKey) return\n if (!process.env.ANTHROPIC_API_KEY && !process.env.ANTHROPIC_AUTH_TOKEN) return\n warnedAnthropicApiKey = true\n if (ignore) {\n log.warn(\n \"ANTHROPIC_API_KEY/ANTHROPIC_AUTH_TOKEN detected; stripping it from claude spawns (ignoreAnthropicApiKey) so requests use your subscription auth, not pay-as-you-go API billing.\",\n )\n } else {\n log.warn(\n \"ANTHROPIC_API_KEY/ANTHROPIC_AUTH_TOKEN detected; claude may bill as pay-as-you-go API usage instead of your subscription / Agent SDK credit. Set provider option `ignoreAnthropicApiKey: true` to force subscription auth.\",\n )\n }\n}\n\nexport function createClaudeCode(\n settings: ClaudeCodeProviderSettings = {},\n): ClaudeCodeProvider {\n if (settings.logging) {\n configureLogger({\n file: settings.logging.file ?? false,\n dir: settings.logging.dir ?? null,\n mode: settings.logging.mode ?? \"silent\",\n level: settings.logging.level ?? \"info\",\n })\n }\n warnIfAnthropicApiKey(settings.ignoreAnthropicApiKey)\n const cliPath =\n settings.cliPath ?? process.env.CLAUDE_CLI_PATH ?? \"claude\"\n const providerName = settings.providerID ?? settings.name ?? \"claude-code\"\n const proxyTools = settings.proxyTools ?? [...DEFAULT_PROXY_TOOL_NAMES]\n\n const createModel = (modelId: string): LanguageModelV3 => {\n return new ClaudeCodeLanguageModel(modelId, {\n provider: providerName,\n cliPath,\n cwd: settings.cwd,\n account: settings.account,\n configDir: settings.configDir,\n providerID: settings.providerID,\n skipPermissions: settings.skipPermissions ?? true,\n permissionMode: settings.permissionMode,\n mcpConfig: settings.mcpConfig,\n strictMcpConfig: settings.strictMcpConfig,\n bridgeOpencodeMcp: settings.bridgeOpencodeMcp ?? true,\n controlRequestBehavior: settings.controlRequestBehavior ?? \"allow\",\n controlRequestToolBehaviors: settings.controlRequestToolBehaviors,\n controlRequestDenyMessage: settings.controlRequestDenyMessage,\n proxyTools,\n extraDisallowedTools: settings.extraDisallowedTools,\n proxyToolTimeoutMs: settings.proxyToolTimeoutMs,\n planModeQuestion: settings.planModeQuestion ?? false,\n webSearch: settings.webSearch,\n hotReloadMcp: settings.hotReloadMcp ?? true,\n proxyOpencodeMcpTools: settings.proxyOpencodeMcpTools ?? true,\n multiStepContinuation: settings.multiStepContinuation ?? true,\n autoContinueIncompleteTurns:\n settings.autoContinueIncompleteTurns ?? \"smart\",\n compactionModel: settings.compactionModel,\n ignoreAnthropicApiKey: settings.ignoreAnthropicApiKey,\n interactive: settings.interactive,\n interactiveBypass: settings.interactiveBypass,\n interactiveAllowTools: settings.interactiveAllowTools,\n interactiveSystemPrompt: settings.interactiveSystemPrompt,\n })\n }\n\n const provider = function (modelId: string) {\n return createModel(modelId)\n } as ClaudeCodeProvider\n\n provider.specificationVersion = \"v3\"\n provider.languageModel = createModel\n\n return provider\n}\n\n// ---------------------------------------------------------------------------\n// OpenCode plugin interface\n// ---------------------------------------------------------------------------\n\nconst PROVIDER_ID = BASE_PROVIDER_ID\nconst PACKAGE_NPM = \"@khalilgharbaoui/opencode-claude-code-plugin\"\n\nfunction pluginEntrypoint(): string {\n return import.meta.url.startsWith(\"file:\") ? import.meta.url : PACKAGE_NPM\n}\n\nfunction cleanProviderOptions(\n options: Record<string, unknown> = {},\n): Record<string, unknown> {\n const result = { ...options }\n delete result.accounts\n // Consumed by the config hook (agent registry), not by the language model.\n delete result.defaultSubagentModel\n return result\n}\n\nfunction defaultModelsForProvider(\n providerModels: OpenCodeProvider[\"models\"],\n providerID = PROVIDER_ID,\n modelSuffix?: string,\n) {\n const models = Object.fromEntries(\n Object.entries(defaultModels).map(([id, model]) => {\n const modelId = modelSuffix ? `${id}@${modelSuffix}` : id\n const existing = providerModels[id] ?? providerModels[modelId]\n return [\n modelId,\n {\n ...model,\n id: modelId,\n providerID,\n api: {\n ...model.api,\n id: modelId,\n npm: existing?.api?.npm ?? model.api.npm,\n url: existing?.api?.url ?? model.api.url,\n },\n },\n ]\n }),\n )\n\n for (const [id, model] of Object.entries(providerModels)) {\n if (!(id in models)) {\n models[id] = {\n ...model,\n providerID,\n }\n }\n }\n\n return models\n}\n\n/**\n * Build models in OpenCode's config schema format (flat properties like\n * `temperature`, `reasoning`, `cost.cache_read`, `modalities`, etc.)\n * so the config-path provider loader parses them correctly.\n */\nexport function configModelsForProvider(\n providerModels: OpenCodeProvider[\"models\"],\n providerID: string,\n modelSuffix?: string,\n): Record<string, Record<string, unknown>> {\n const models: Record<string, Record<string, unknown>> = {}\n\n for (const [id, model] of Object.entries(defaultModels)) {\n const modelId = modelSuffix ? `${id}@${modelSuffix}` : id\n const existing = providerModels[id] ?? providerModels[modelId]\n const existingVariants =\n existing && typeof (existing as { variants?: unknown }).variants === \"object\"\n ? ((existing as { variants?: Record<string, Record<string, unknown>> }).variants ?? {})\n : {}\n const full: OpenCodeModel = {\n ...model,\n id: modelId,\n providerID,\n api: {\n ...model.api,\n id: modelId,\n npm: existing?.api?.npm ?? model.api.npm,\n url: existing?.api?.url ?? model.api.url,\n },\n variants: {\n ...(model.variants ?? {}),\n ...existingVariants,\n },\n }\n models[modelId] = toConfigModel(full)\n }\n\n for (const [id, model] of Object.entries(providerModels)) {\n if (!(id in models)) {\n models[id] = toConfigModel({ ...model, providerID } as OpenCodeModel)\n }\n }\n\n return models\n}\n\nasync function providerConfig(\n existing: {\n name?: string\n npm?: string\n options?: Record<string, unknown>\n models?: Record<string, unknown>\n } | undefined,\n providerID = PROVIDER_ID,\n optionDefaults: Record<string, unknown> = {},\n displayName?: string,\n) {\n const mergedOptions: Record<string, unknown> = {\n cliPath: \"claude\",\n proxyTools: [...DEFAULT_PROXY_TOOL_NAMES],\n ...optionDefaults,\n ...cleanProviderOptions(existing?.options),\n providerID,\n }\n\n const cliPath = String(mergedOptions.cliPath ?? \"claude\")\n const account =\n typeof mergedOptions.account === \"string\" ? mergedOptions.account : undefined\n const runtime = account\n ? await ensureAccountRuntime(account, cliPath)\n : { cliPath }\n\n return {\n name: displayName ?? existing?.name,\n npm: existing?.npm ?? pluginEntrypoint(),\n options: {\n ...mergedOptions,\n ...runtime,\n },\n // models is intentionally omitted: both callers overwrite it with\n // configModelsForProvider(), which emits the flat config schema\n // opencode's config-path loader parses (and merges user variants).\n }\n}\n\n/**\n * Narrow opencode's full provider map down to the ones this plugin owns\n * (`claude-code` plus every `claude-code-<account>` expansion) so startup\n * diagnostics never report another provider's options.\n */\nexport function claudeCodeProviders(\n providers: Record<string, DiagnosticsProviderEntry> | undefined,\n): Record<string, DiagnosticsProviderEntry> {\n const out: Record<string, DiagnosticsProviderEntry> = {}\n for (const [id, entry] of Object.entries(providers ?? {})) {\n if (id === PROVIDER_ID || id.startsWith(`${PROVIDER_ID}-`)) out[id] = entry\n }\n return out\n}\n\nasync function expandAccountProviders(config: {\n provider?: Record<\n string,\n {\n name?: string\n npm?: string\n options?: Record<string, unknown>\n models?: Record<string, unknown>\n }\n >\n}): Promise<boolean> {\n const seed = config.provider?.[PROVIDER_ID]\n const accounts = resolveAccounts(seed?.options?.accounts)\n\n if (!accounts) return false\n\n config.provider ??= {}\n\n const seedOptions = cleanProviderOptions(seed?.options)\n let expandedCount = 0\n\n for (const account of accounts) {\n const providerID = accountProviderId(account)\n try {\n const existing = config.provider[providerID]\n const modelSuffix = accountModelSuffix(account)\n\n config.provider[providerID] = {\n ...existing,\n ...(await providerConfig(\n existing,\n providerID,\n {\n ...seedOptions,\n account,\n },\n accountDisplayName(account),\n )),\n models: configModelsForProvider(\n (existing?.models ?? seed?.models ?? {}) as OpenCodeProvider[\"models\"],\n providerID,\n modelSuffix,\n ),\n }\n expandedCount++\n } catch (err) {\n log.error(\"failed to expand account provider\", {\n account,\n providerID,\n error: String(err),\n })\n }\n }\n\n if (expandedCount > 0) {\n delete config.provider[PROVIDER_ID]\n }\n\n return expandedCount > 0\n}\n\n/**\n * Record what every known agent asked for, so `resolveAgentModel` and\n * `resolveAgentEffort` can answer at spawn time without the language model\n * needing to see opencode's config.\n *\n * Runs BEFORE `expandAccountProviders`, which deletes the seed provider entry\n * once it has expanded it: `defaultSubagentModel` has to be read while it is\n * still there.\n *\n * Purely observational. It defines no agents and changes no agent's config;\n * an agent this plugin never heard of is simply absent from the registry,\n * which is what keeps opencode's built-ins out of the override path.\n */\nasync function buildAgentRegistry(config: OpenCodeConfig): Promise<void> {\n const options = config.provider?.[PROVIDER_ID]?.options\n const configured = options?.defaultSubagentModel\n setDefaultSubagentModel(\n typeof configured === \"string\" ? configured : undefined,\n )\n\n // Markdown agents may or may not reach a plugin's config hook (undocumented\n // either way), so they are read from disk and then overlaid with whatever\n // config does carry, which is authoritative when both describe one agent.\n const records: Record<string, AgentRecord> = await readAgentMarkdownRecords(\n agentDirectories(\n process.env.HOME ?? process.env.USERPROFILE,\n getOpencodeProjectDirectory(),\n ),\n )\n\n for (const [name, agent] of Object.entries(config.agent ?? {})) {\n const bag = (agent.options ?? {}) as Record<string, unknown>\n const pick = (key: string): string | undefined => {\n const value = agent[key] ?? bag[key]\n return typeof value === \"string\" ? value : undefined\n }\n\n records[name] = {\n mode: pick(\"mode\") ?? records[name]?.mode,\n model: pick(\"model\") ?? records[name]?.model,\n forceModel: pick(\"forceModel\") ?? records[name]?.forceModel,\n reasoningEffort:\n pick(\"reasoningEffort\") ?? records[name]?.reasoningEffort,\n }\n }\n\n setAgentRegistry(records)\n log.debug(\"agent registry built\", {\n agents: Object.keys(records).length,\n defaultSubagentModel: getDefaultSubagentModel(),\n })\n}\n\nconst server: OpenCodePlugin = async (input) => {\n cleanupStaleUnscopedInstall()\n\n const opencodeVersion = pickOpencodeVersion(input)\n\n // Capture the SDK client so the language model can query opencode's\n // in-memory MCP state per-turn for the runtime overlay. `input` is\n // `unknown` here (kept loose since opencode adds fields over time);\n // narrow defensively.\n if (input && typeof input === \"object\" && \"client\" in input) {\n setOpencodeClient((input as { client?: unknown }).client)\n }\n\n // Capture opencode's project-aware directory as a *fallback* used at\n // Claude CLI spawn time only when `process.cwd()` is unusable. Rescues\n // macOS GUI launches at `/` without freezing the value into provider\n // config, so opencode workspace switches mid-session still take effect.\n // See `resolveSpawnCwd` in runtime-status.ts and issue #4.\n setOpencodeProjectDirectory(pickOpencodeDirectory(input))\n\n return {\n config: async (config) => {\n if (registerSideQuestionCommand(config)) ownsSideQuestionCommand = true\n config.provider ??= {}\n\n await buildAgentRegistry(config)\n\n const expanded = await expandAccountProviders(config)\n if (expanded) {\n logStartupDiagnostics(\n claudeCodeProviders(config.provider),\n opencodeVersion,\n )\n return\n }\n\n const existing = config.provider[PROVIDER_ID]\n config.provider[PROVIDER_ID] = {\n ...existing,\n ...(await providerConfig(existing)),\n models: configModelsForProvider(\n (existing?.models ?? {}) as OpenCodeProvider[\"models\"],\n PROVIDER_ID,\n ),\n }\n logStartupDiagnostics(\n claudeCodeProviders(config.provider),\n opencodeVersion,\n )\n },\n // No `event` hook: MCP config drift is detected at turn start by the\n // hot-reload check in `claude-code-language-model.ts`, which respawns\n // claude safely between turns. Eviction on `global.disposed` would kill\n // an in-flight stream and abort the user's current turn.\n provider: {\n id: PROVIDER_ID,\n models: async (provider) => defaultModelsForProvider(provider.models),\n },\n // Inject opencode's agent name into providerOptions so the language\n // model can distinguish /compact (and title) calls from normal turns.\n // Without this, every no-tools call looks like a title request and\n // gets short-circuited to a synthetic stub.\n // /btw is asked from here, the moment the command is typed, busy or not.\n // The message itself still goes through: opencode queues it behind the\n // running turn and the aside branch in the language model then answers it\n // from the early answer, so the exchange is kept in this conversation.\n \"command.execute.before\": async (input) => {\n if (input.command !== \"btw\" || !ownsSideQuestionCommand) return\n await handleBtwCommand(getOpencodeClient() as BtwSdkClient | null, input)\n },\n \"chat.params\": async (input, output) => {\n const providerID = input.model?.providerID ?? input.provider?.info?.id\n // The hook fires for every provider opencode is configured with, not\n // just ours — keep this at debug to avoid log spam on non-claude-code\n // calls.\n log.debug(\"chat.params hook fired\", {\n agent: input.agent,\n providerID,\n sessionID: input.sessionID,\n })\n if (typeof providerID !== \"string\") return\n if (providerID !== PROVIDER_ID && !providerID.startsWith(`${PROVIDER_ID}-`)) return\n\n // Inject sessionID BEFORE the agent guard so session isolation works\n // even when input.agent is absent (older opencode, provider-switch\n // edge paths). resolveSessionAffinity reads this as a fallback when\n // the x-session-affinity header is missing.\n if (typeof input.sessionID === \"string\" && input.sessionID.length > 0) {\n output.options ??= {}\n ;(output.options as Record<string, unknown>).opencodeSessionID = input.sessionID\n }\n\n if (!input.agent) return\n // opencode wraps the entire `output.options` bag under the providerID\n // via ProviderTransform.providerOptions(model, options) → { [providerID]: options }\n // before handing it to the language model as `providerOptions`. So we\n // write fields at the TOP LEVEL of output.options, not nested under\n // providerID — otherwise the model sees providerOptions[id][id].opencodeAgent.\n output.options ??= {}\n ;(output.options as Record<string, unknown>).opencodeAgent = input.agent\n log.debug(\"chat.params tagged providerOptions\", {\n agent: input.agent,\n sessionID: input.sessionID,\n providerID,\n })\n },\n }\n}\n\nexport default {\n id: \"@khalilgharbaoui/opencode-claude-code-plugin\",\n server,\n}\n\n// ---------------------------------------------------------------------------\n// Re-exports\n// ---------------------------------------------------------------------------\n\nexport { ClaudeCodeLanguageModel } from \"./claude-code-language-model.js\"\nexport { bridgeOpencodeMcp } from \"./mcp-bridge.js\"\nexport {\n type AgentRecord,\n getAgentRegistry,\n getDefaultSubagentModel,\n resolveAgentModel,\n} from \"./agent-models.js\"\nexport { defaultModels } from \"./models.js\"\nexport type {\n ClaudeCodeConfig,\n ClaudeCodeProviderSettings,\n ClaudeStreamMessage,\n} from \"./types.js\"\nexport type { OpenCodeHooks, OpenCodeModel, OpenCodePlugin } from \"./opencode-types.js\"\n"],"mappings":";AASA,SAAS,kBAAkB;;;ACT3B,SAAS,gBAAgB,WAAW,YAAY,gBAAgB;AAChE,SAAS,eAAe;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CAACA,OAAM,MAAO;AAMlB,aAAO,YAAY,CAAC;AACnB,MAAC,OAAO,QAAoC,gBAAgBA,OAAM;AACnE,UAAI,MAAM,sCAAsC;AAAA,QAC9C,OAAOA,OAAM;AAAA,QACb,WAAWA,OAAM;AAAA,QACjB;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF;AACF;AAEA,IAAO,gBAAQ;AAAA,EACb,IAAI;AAAA,EACJ;AACF;","names":["EventEmitter","EventEmitter","fs","path","server","resolve","reject","EventEmitter","sessionKey","sessionKey","sessionKey","randomUUID","randomUUID","resolve","resolve","sessionKey","EventEmitter","resolve","path","path","fs","path","os","crypto","EventEmitter","unlink","os","fs","path","randomUUID","EventEmitter","unlink","readFileSync","writeFileSync","unlink","homedir","tmpdir","randomUUID","dirname","join","content","path","spawn","createInterface","unlink","resolve","stream","completeResult","planId","path","path","existsSync","readFileSync","rmSync","writeFileSync","homedir","join","resolve","join","homedir","existsSync","readFileSync","resolve","rmSync","writeFileSync","execFile","fs","path","promisify","fileURLToPath","fileURLToPath","execFileAsync","promisify","execFile","PROVIDER_ID","input"]}
|
|
1
|
+
{"version":3,"sources":["../src/claude-code-language-model.ts","../src/logger.ts","../src/todo-ledger.ts","../src/tool-mapping.ts","../src/cli-version.ts","../src/session-manager.ts","../src/proxy-broker.ts","../src/proxy-mcp.ts","../src/tmp.ts","../src/plan-mode-question.ts","../src/compression-store.ts","../src/side-question.ts","../src/btw-command.ts","../src/message-builder.ts","../src/agent-models.ts","../src/models.ts","../src/skill-bridge.ts","../src/mcp-bridge.ts","../src/runtime-status.ts","../src/claude-session-wrapper.ts","../src/claude-session-bun.ts","../src/accounts.ts","../src/cleanup-stale.ts","../src/startup-diagnostics.ts","../src/index.ts"],"sourcesContent":["import type {\n LanguageModelV3,\n LanguageModelV3CallOptions,\n LanguageModelV3Content,\n LanguageModelV3FinishReason,\n LanguageModelV3StreamPart,\n LanguageModelV3Usage,\n SharedV3Warning,\n} from \"@ai-sdk/provider\"\nimport { generateId } from \"@ai-sdk/provider-utils\"\nimport type {\n ClaudeCodeConfig,\n ControlRequestBehavior,\n ClaudeStreamMessage,\n ReasoningEffort,\n} from \"./types.js\"\nimport { mapTool, isWebSearchTool, isWebSearchHandledByCli } from \"./tool-mapping.js\"\nimport { applyTaskCreateToolResult } from \"./todo-ledger.js\"\nimport { getClaudeUserMessage } from \"./message-builder.js\"\nimport { resolveAgentEffort, resolveAgentModel } from \"./agent-models.js\"\nimport { parseSideQuestion, requestSideQuestion, collectSideQuestionHistory, SIDE_QUESTION_USAGE, type SideQuestionResult } from \"./side-question.js\"\nimport { BTW_NO_SESSION_MESSAGE, registerAsideSink, takeSideQuestionAnswer } from \"./btw-command.js\"\nimport { resolveSkillPluginDirs } from \"./skill-bridge.js\"\nimport { parseModelId } from \"./models.js\"\nimport {\n QUESTION_TOOL_NAME,\n consumeExitPlanModeQuestionResult,\n createExitPlanModeQuestionCall,\n isPlanModeQuestionActive,\n} from \"./plan-mode-question.js\"\nimport { bridgeOpencodeMcp, type RuntimeMcpStatus } from \"./mcp-bridge.js\"\nimport {\n getRuntimeMcpStatus,\n fetchOpencodeToolList,\n resolveSpawnCwdForSession,\n} from \"./runtime-status.js\"\nimport {\n getActiveProcess,\n setActiveProcess,\n spawnClaudeProcess,\n buildCliArgs,\n setClaudeSessionId,\n getClaudeSessionId,\n deleteClaudeSessionId,\n deleteActiveProcess,\n deleteActiveProcessAndWait,\n respawnActiveProcess,\n scheduleIdleProcessEviction,\n noteTurnStarted,\n isTurnInFlight,\n interruptTurn,\n takeUnattendedLines,\n claudeSpawnEnv,\n isClaudeThinkingDisabled,\n sessionKey,\n effortSessionKey,\n invalidateOtherEffortSessions,\n} from \"./session-manager.js\"\nimport { spawnInteractiveProcess } from \"./claude-session-wrapper.js\"\nimport {\n clearCompression,\n consumeCompressionRestart,\n getCompressionSummary,\n storeCompressionSummary,\n} from \"./compression-store.js\"\nimport { log } from \"./logger.js\"\nimport { detectCliVersion } from \"./cli-version.js\"\nimport {\n createProxyMcpServer,\n resolveDisallowedTools,\n DEFAULT_PROXY_TOOLS,\n overlayTaskProxyDescription,\n overlayQuestionProxyDescription,\n filterQuestionProxyByOpencodeSupport,\n PROXY_TOOL_PREFIX,\n TASK_BATCH_TOOL_NAME,\n taskBatchTasks,\n taskBatchChildToolCallId,\n formatTaskBatchResults,\n type ProxyMcpServer,\n type ProxyToolCall,\n type ProxyToolDef,\n type ProxyToolInterceptor,\n type ProxyToolResult,\n} from \"./proxy-mcp.js\"\nimport {\n getPendingProxyCalls,\n isPendingProxyCallChannelClosed,\n markPendingProxyCallEmitted,\n onPendingProxyCall,\n queuePendingProxyCall,\n rejectAllPendingProxyCallsForSession,\n rejectPendingProxyCallById,\n resolvePendingProxyCallById,\n type PendingProxyCall,\n} from \"./proxy-broker.js\"\nimport { readFileSync, writeFileSync } from \"node:fs\"\nimport { unlink } from \"node:fs/promises\"\nimport { homedir, tmpdir } from \"node:os\"\nimport { randomUUID } from \"node:crypto\"\nimport { dirname, join } from \"node:path\"\n\n/**\n * Default model used for opencode `/compact`. Haiku 4.5 is fast\n * (~150 tok/s), has a hard 8k output cap that bounds latency, and is a\n * strong structured summarizer. Override per-project via the\n * `compactionModel` provider setting in opencode.json / opencode.jsonc,\n * or per-run via the `CLAUDE_CODE_COMPACTION_MODEL` env var (env wins).\n */\nexport const DEFAULT_COMPACTION_MODEL = \"claude-haiku-4-5\"\n\n/**\n * Pick the model used to handle /compact. Precedence:\n * 1. `CLAUDE_CODE_COMPACTION_MODEL` env var (per-process override)\n * 2. `configured` argument (the `compactionModel` provider setting)\n * 3. `DEFAULT_COMPACTION_MODEL`\n *\n * Exported as a free function so it can be unit-tested without\n * instantiating the language model class.\n */\nexport function resolveCompactionModel(configured?: string): string {\n const env = process.env.CLAUDE_CODE_COMPACTION_MODEL?.trim()\n if (env) return env\n const trimmed = configured?.trim()\n if (trimmed) return trimmed\n return DEFAULT_COMPACTION_MODEL\n}\n\n/**\n * Resolve the session affinity token for a given LLM call. The affinity\n * token is part of the session key in session-manager so two different\n * opencode sessions sharing the same cwd+model still get separate Claude\n * CLI processes.\n *\n * Priority:\n * 1. `x-session-affinity` request header (primary — opencode sets it for\n * third-party providers in packages/opencode/src/session/llm.ts).\n * 2. `opencodeSessionID` inside `providerOptions` (injected by the\n * `chat.params` hook in index.ts). Covers cases where the header is\n * absent: provider switch mid-session, title synthesis paths, older\n * opencode versions. opencode wraps `output.options` under the\n * providerID before passing it to the language model, so we look up\n * both the configured provider key and the canonical `\"claude-code\"`.\n * 3. `\"default\"` — safe fallback when neither source is available.\n *\n * Exported as a free function so it can be unit-tested without\n * instantiating the language model class.\n */\nexport function resolveSessionAffinity(\n headers: Record<string, string | undefined> | undefined,\n providerOptions: Record<string, unknown> | undefined,\n providerKey: string,\n): string {\n if (headers) {\n for (const key of Object.keys(headers)) {\n if (key.toLowerCase() === \"x-session-affinity\") {\n const v = headers[key]\n if (typeof v === \"string\" && v.length > 0) return v\n }\n }\n }\n if (providerOptions) {\n const bag =\n (providerOptions as any)[providerKey] ??\n (providerOptions as any)[\"claude-code\"]\n const sid = bag?.opencodeSessionID\n if (typeof sid === \"string\" && sid.length > 0) return sid\n }\n return \"default\"\n}\n\n/**\n * Stream delta types we handle explicitly. `signature_delta` is listed as\n * known-and-silent: it carries encrypted thinking-block signatures that\n * are opaque to clients (the server uses them to reconstitute thinking\n * across turns), so there's nothing for us to do but ignore it.\n */\nconst KNOWN_DELTA_TYPES = new Set([\n \"thinking_delta\",\n \"text_delta\",\n \"input_json_delta\",\n \"signature_delta\",\n])\n\n/**\n * True if the prompt has any user-side content after the last assistant\n * message (text, tool_result, or any user role entry). False when the\n * prompt ends with an assistant message and there is nothing for Claude\n * to respond to — opencode sometimes iterates the agent loop one more\n * time after a turn naturally completed; without short-circuiting we'd\n * spawn Claude CLI on an empty turn and the model would reply with a\n * stub like \"Did you mean to send a message?\".\n */\nexport function hasNewUserContent(\n prompt: LanguageModelV3CallOptions[\"prompt\"],\n): boolean {\n for (let i = prompt.length - 1; i >= 0; i--) {\n const msg = prompt[i]\n if (msg.role === \"assistant\") return false\n // Tool-result turns from opencode's outer loop arrive in `tool`-role\n // messages (AI SDK V3 shape). Treat any tool-result part as new\n // content so the short-circuit doesn't drop turns where opencode is\n // delivering the result for a still-pending proxy MCP call — letting\n // that fire `stop` is what was forcing the user to press \"continue\".\n if (msg.role === \"tool\") {\n const content: any = msg.content\n if (Array.isArray(content)) {\n for (const part of content as any[]) {\n if (part?.type === \"tool-result\") return true\n }\n }\n continue\n }\n if (msg.role !== \"user\") continue\n const content: any = msg.content\n if (typeof content === \"string\") {\n if (content.trim()) return true\n continue\n }\n if (Array.isArray(content)) {\n for (const part of content as any[]) {\n if (part.type === \"text\" && part.text && part.text.trim()) return true\n if (part.type === \"tool-result\") return true\n // Image/file-only user turns count as new input — without this the\n // short-circuit drops them as if the turn were empty.\n if (part.type === \"image\" || part.type === \"file\") return true\n }\n }\n }\n return false\n}\n\nconst AUTO_CONTINUE_MAX_ATTEMPTS = 8\nconst AUTO_CONTINUE_MAX_ELAPSED_MS = 10 * 60 * 1000\nconst AUTO_CONTINUE_NO_PROGRESS_LIMIT = 2\nconst PROXY_RESULT_BOUNDARY_GRACE_MS = 250\n\nconst AUTO_CONTINUE_PROMPT =\n \"Continue the task from where you stopped. Do not summarize; keep working until the requested task is complete, you need clarification, or you hit a real blocker.\"\n\n/** One per-turn snapshot of opencode's live tool registry. */\ninterface LiveToolInfo {\n /** False when nothing answered (no SDK client, fetch failed). */\n resolved: boolean\n taskDescription: string | undefined\n questionDescription: string | undefined\n hasQuestion: boolean\n}\n\ninterface AutoContinueState {\n enabled: boolean | \"smart\" | undefined\n attempts: number\n startedAt: number\n noProgressCount: number\n lastSignature?: string\n aborted?: boolean\n /**\n * Latched true once AskUserQuestion is rendered this turn. Auto-continue\n * must never fire afterwards: the model has handed control to the operator\n * and is waiting for a real reply. Without this, a short trailing text after\n * the question (one that doesn't trip looksLikeQuestion) would let the turn\n * look \"incomplete\", and the auto-continue nudge would make the model\n * proceed on its own — which the operator sees as the question being\n * answered/cancelled without them ever interacting.\n */\n sawAskUserQuestion?: boolean\n}\n\ninterface AutoContinueSnapshot {\n text: string\n /**\n * Text of the most recent assistant text block only. Used for final-answer\n * detection so mid-task narration like \"Implementing now. Updated the\n * search index.\" in an earlier block doesn't trip the keyword regex.\n */\n lastVisibleText: string\n hadReasoning: boolean\n hadToolActivity: boolean\n hadProxyActivity: boolean\n isError?: boolean\n /**\n * Protocol-level stop signal from the Claude API (forwarded by Claude\n * CLI). When present and non-empty, we trust it as authoritative — the\n * model itself signaled why the turn ended (`end_turn`, `max_tokens`,\n * `stop_sequence`, `refusal`, `pause_turn`, `tool_use`, etc.) — and stop\n * without running the keyword regex. The heuristic only runs as a\n * fallback when `stop_reason` is missing (older CLI versions, abrupt\n * termination).\n */\n stopReason?: string | null\n now?: number\n}\n\ninterface AutoContinueDecision {\n continue: boolean\n reason: string\n}\n\nfunction normalizeVisibleText(text: string): string {\n return text.replace(/\\s+/g, \" \").trim()\n}\n\n/** Tool names that mean \"ask the human a question\" (CLI casing variants). */\nexport function isAskUserQuestionTool(name: string | undefined): boolean {\n if (!name) return false\n const n = name.toLowerCase()\n return n === \"askuserquestion\" || n === \"ask_user_question\"\n}\n\n/**\n * Deny message returned to the model when it invokes AskUserQuestion.\n *\n * AskUserQuestion is denied (see controlRequestBehaviorForTool) so the\n * headless CLI cannot self-answer against an empty TTY. The question is\n * already rendered to the operator by formatAskUserQuestion, so this text\n * tells the model to stop and wait — unconditionally. Earlier versions\n * offered an \"if this is non-interactive, proceed with a reasonable guess\"\n * escape hatch, but the model could not reliably tell interactive opencode\n * from a headless run and routinely took it, so questions appeared to be\n * skipped (issue #8). Stopping is the correct default for opencode; a\n * headless run simply ends the turn with the question as its final output.\n */\nconst ASK_USER_QUESTION_DENY_MESSAGE =\n \"Your question and its options have already been presented to the\" +\n \" operator verbatim. This is NOT a cancellation or a refusal — the\" +\n \" operator simply has not answered yet. Stop now: end your turn without\" +\n \" calling any more tools and without answering the question yourself. Do\" +\n \" not say the question was cancelled, skipped, or declined, and do not\" +\n \" guess, assume, or proceed on their behalf. Wait for the operator's\" +\n \" reply, which arrives as the next user message.\"\n\n/** Build the deny message for an auto-denied control request. */\nexport function denyMessageForTool(\n toolName: string | undefined,\n configuredDenyMessage?: string,\n): string {\n if (isAskUserQuestionTool(toolName)) return ASK_USER_QUESTION_DENY_MESSAGE\n return (\n configuredDenyMessage ??\n `Denied by opencode-claude-code policy for tool ${toolName}`\n )\n}\n\n/**\n * Render Claude Code's `AskUserQuestion` tool input as visible markdown.\n *\n * This is the fallback path used when the `Question` proxy is off or the\n * opencode build lacks the `question` registry entry. When the proxy is\n * enabled, `AskUserQuestion` is disabled via `--disallowedTools` and the\n * model calls `mcp__opencode_proxy__question` instead (opencode's native\n * `question` tool renders the TUI form). Here, the question + every\n * option is rendered as readable assistant text and the user answers in\n * the next turn — same approach as the `ExitPlanMode` handling. The\n * previous behavior collapsed the whole payload to a single faint\n * `_Asking: <q>_` line, dropping all options and any question past the\n * first.\n */\nfunction formatAskUserQuestion(input: Record<string, unknown>): string {\n const anyInput = input as any\n const questions: any[] = Array.isArray(anyInput?.questions)\n ? anyInput.questions\n : []\n\n if (questions.length === 0) {\n const single = anyInput?.question ?? anyInput?.text\n const q =\n typeof single === \"string\" && single.trim() ? single.trim() : \"Question?\"\n return `\\n\\n**${q}**\\n\\n_Reply with your answer to continue._\\n\\n`\n }\n\n const out: string[] = [\"\\n\\n\"]\n const multiQ = questions.length > 1\n questions.forEach((q, i) => {\n const text =\n (typeof q?.question === \"string\" && q.question.trim()) ||\n (typeof q?.text === \"string\" && q.text.trim()) ||\n \"Question?\"\n const header =\n typeof q?.header === \"string\" && q.header.trim() ? q.header.trim() : \"\"\n out.push(`**${multiQ ? `${i + 1}. ` : \"\"}${text}**`)\n if (header) out.push(` _(${header})_`)\n out.push(\"\\n\\n\")\n\n const options: any[] = Array.isArray(q?.options) ? q.options : []\n options.forEach((opt, j) => {\n const label =\n (typeof opt?.label === \"string\" && opt.label.trim()) ||\n (typeof opt === \"string\" && opt.trim()) ||\n `Option ${j + 1}`\n const desc =\n typeof opt?.description === \"string\" && opt.description.trim()\n ? ` — ${opt.description.trim()}`\n : \"\"\n out.push(`${j + 1}. **${label}**${desc}\\n`)\n })\n\n out.push(\n q?.multiSelect === true\n ? \"\\n_Select one or more — reply with the numbers or labels._\\n\\n\"\n : \"\\n_Reply with your choice (the number or label)._\\n\\n\",\n )\n })\n return out.join(\"\")\n}\n\nfunction looksLikeQuestion(text: string): boolean {\n const normalized = normalizeVisibleText(text).toLowerCase()\n if (!normalized) return false\n // v0.4.10 tweak 5a: '?' anywhere in the last block, not just trailing.\n // Catches long answers that pose a question mid-text then list options\n // and end with a period. FP risk on inline code (`result?.value`) is\n // accepted — cost is one extra \"continue\" press, in the safe direction.\n if (normalized.includes(\"?\")) return true\n // v0.4.11 additions: ready when you are / standing by / i'll stand by /\n // let me know when. These are awaiting-input idioms with no '?'. The\n // \"standing by\" addition has historical significance — it's the exact\n // stub phrase Claude CLI emits on empty turns that commit 49345e3 was\n // designed to suppress at the message-builder layer. This adds a second\n // line of defense at the model-output layer for cases where the model\n // organically produces the same idiom.\n //\n // v0.4.12 additions: over to you / your turn / all yours / let me know\n // how / i'm here. Defensive coverage of soft-proceed idioms in the\n // model's vocabulary. \"i'm here\" has the highest FP risk (\"I'm here to\n // help with X\" is a conversational opener) but cost of FP is one extra\n // continue press — safe direction.\n return /\\b(please confirm|can you confirm|should i|would you like|do you want|which option|choose|pick one|need your|need you to|what would you like|let me know if|let me know whether|let me know what|let me know when|let me know how|if you'?d like|if you want to|tell me if|tell me which|tell me whether|say (?:go|yes|no)|push back|sign off|sounds? (?:good|right)|your call|your move|your turn|over to you|all yours|up to you|ready to (?:ship|go|proceed|merge)|ready (?:when|whenever|once|if) you|standing by|i'?ll stand ?by|i'?m here|happy to (?:ship|go|proceed|merge))\\b/.test(normalized)\n}\n\nfunction looksLikeBlocker(text: string): boolean {\n const normalized = normalizeVisibleText(text).toLowerCase()\n if (!normalized) return false\n // v0.4.10 tweak 3: 'needs your' / 'needs you to' / 'action required'\n // are intent-equivalent to 'requires your' but use the verb-with-s form.\n return /\\b(blocked|blocker|cannot proceed|can't proceed|unable to proceed|need clarification|need more information|permission denied|failed and needs|requires your|needs your|needs you to|action required|manual step|required from you)\\b/.test(normalized)\n}\n\nfunction looksLikeFinalAnswer(text: string): boolean {\n const normalized = normalizeVisibleText(text).toLowerCase()\n if (looksLikeQuestion(normalized) || looksLikeBlocker(normalized)) return false\n // v0.4.15: strong-completion phrases bypass the 30-char length floor.\n // These are unambiguous end-of-turn signals at any text length — even\n // a short standalone \"We're done.\" should stop.\n if (/\\b(we'?re done|we are done|all done|all set)\\b/.test(normalized)) {\n return true\n }\n // v0.4.10 tweak 4: floor lowered 40 → 30 chars. Catches short clean\n // completions like \"Task is now completely done. Pushed.\" (36 chars)\n // while keeping a buffer against ambiguous short narration.\n if (normalized.length < 30) return false\n // v0.4.15: keyword list extended with deploy/ship verbs the model\n // routinely uses at turn end (shipped, deployed, merged, tagged, live,\n // pinned). FP risk highest on \"live\" — \"live data\" mid-turn could match\n // — but cost of FP is one extra continue press, safe direction.\n return /\\b(done|completed|fixed|implemented|verified|published|released|sent|delivered|updated|shipped|deployed|merged|tagged|live|pinned)\\b/.test(normalized) ||\n // v0.4.15: also accept present-tense \"tests pass\" / \"checks pass\".\n // Real fire 03:31 ended in \"78/78 tests pass\" — past-tense-only regex\n // missed it.\n /\\b(checks?|tests?) (?:pass|passes|passed)\\b/.test(normalized) ||\n /\\b(summary|what changed|verification)\\b/.test(normalized)\n}\n\nfunction continuationSignature(snapshot: AutoContinueSnapshot): string {\n const text = normalizeVisibleText(snapshot.text).slice(-500)\n return JSON.stringify({\n text,\n reasoning: snapshot.hadReasoning,\n tools: snapshot.hadToolActivity,\n proxy: snapshot.hadProxyActivity,\n })\n}\n\nexport function shouldAutoContinueIncompleteTurn(\n state: AutoContinueState,\n snapshot: AutoContinueSnapshot,\n): AutoContinueDecision {\n if (state.enabled === false) return { continue: false, reason: \"disabled\" }\n if (snapshot.isError) return { continue: false, reason: \"error\" }\n if (state.aborted) return { continue: false, reason: \"aborted\" }\n // Once the model asked the operator a question this turn, never nudge it to\n // continue — it is waiting for a reply, not stalled. Latched so it holds\n // even when the trailing text after the question doesn't read as a question.\n if (state.sawAskUserQuestion) return { continue: false, reason: \"question\" }\n // v0.4.17: trust ANY protocol-level stop_reason as authoritative. If\n // Claude CLI emitted a stop_reason value at all, the model has signaled\n // a stop — honor it without consulting the keyword heuristic. The\n // heuristic only runs as a fallback when stop_reason is missing (older\n // CLI versions / edge cases). Maps snake_case → kebab-case for reason\n // label consistency with other reasons.\n if (snapshot.stopReason) {\n return {\n continue: false,\n reason: snapshot.stopReason.replace(/_/g, \"-\"),\n }\n }\n if (state.attempts >= AUTO_CONTINUE_MAX_ATTEMPTS) {\n return { continue: false, reason: \"max-attempts\" }\n }\n const now = snapshot.now ?? Date.now()\n if (now - state.startedAt > AUTO_CONTINUE_MAX_ELAPSED_MS) {\n return { continue: false, reason: \"max-elapsed\" }\n }\n\n const text = normalizeVisibleText(snapshot.text)\n const lastText = normalizeVisibleText(snapshot.lastVisibleText)\n if (looksLikeQuestion(text)) return { continue: false, reason: \"question\" }\n if (looksLikeBlocker(text)) return { continue: false, reason: \"blocker\" }\n // Final-answer detection runs on the most recent text block only. Earlier\n // blocks may contain mid-task narration that would false-positive the\n // keyword regex; the model's actual \"I'm done\" sentence is in the last\n // block before result/end_turn.\n if (looksLikeFinalAnswer(lastText)) {\n return { continue: false, reason: \"final-answer\" }\n }\n\n const hadActivity =\n snapshot.hadReasoning || snapshot.hadToolActivity || snapshot.hadProxyActivity\n if (!hadActivity) return { continue: false, reason: \"no-activity\" }\n\n const signature = continuationSignature(snapshot)\n const noProgress = signature === state.lastSignature\n if (noProgress && state.noProgressCount + 1 >= AUTO_CONTINUE_NO_PROGRESS_LIMIT) {\n return { continue: false, reason: \"no-progress\" }\n }\n\n if (!text) {\n return { continue: true, reason: \"activity-without-visible-answer\" }\n }\n\n return { continue: true, reason: \"non-final-progress\" }\n}\n\nfunction makeAutoContinueMessage(): string {\n return JSON.stringify({\n type: \"user\",\n message: {\n role: \"user\",\n content: [{ type: \"text\", text: AUTO_CONTINUE_PROMPT }],\n },\n })\n}\n\n/**\n * A proxy result whose HTTP reply channel Claude already abandoned cannot\n * go back as a `tool_result` (the CLI closed that tool_use with a timeout\n * error). Hand it over as a user message that names the call instead.\n */\nexport function makeLateProxyResultMessage(\n entries: Array<{ call: PendingProxyCall; result: ProxyToolResult }>,\n): string {\n const sections = entries.map(({ call, result }) => {\n const failed = result.kind === \"error\" || result.isError === true\n const body = result.kind === \"error\" ? result.message : result.text\n return (\n `Your earlier \\`${call.toolName}\\` tool call (id ${call.toolCallId})` +\n ` has ${failed ? \"failed\" : \"completed\"}, but delivery or continuation was interrupted.` +\n ` Treat the following as its ${failed ? \"error\" : \"result\"} and continue from there;` +\n ` do not re-run it.\\n\\n${body}`\n )\n })\n return JSON.stringify({\n type: \"user\",\n message: {\n role: \"user\",\n content: [{ type: \"text\", text: sections.join(\"\\n\\n---\\n\\n\") }],\n },\n })\n}\n\nfunction readPromptFileIfPresent(path: string): string | undefined {\n try {\n const content = readFileSync(path, \"utf8\").trim()\n return content || undefined\n } catch {\n return undefined\n }\n}\n\nfunction nearestWorkspaceAgentsPrompt(cwd: string): string | undefined {\n let dir = cwd\n while (true) {\n const content = readPromptFileIfPresent(join(dir, \"AGENTS.md\"))\n if (content) return content\n const parent = dirname(dir)\n if (parent === dir) return undefined\n dir = parent\n }\n}\n\nconst AGENTS_MAINTENANCE_HINT = `## Keeping AGENTS.md up to date\n\nWhen you complete a task, phase, or to-do item that is listed in AGENTS.md, update the file\nimmediately after the work is done — mark it ✅, check it off, or remove it. Do this inside\nthe same turn so the next session does not repeat work that is already finished.`\n\nconst MULTI_STEP_TASK_HINT = `## Continuing through multi-step tasks\n\nopencode requires the user to press \"continue\" after each turn ends. When a\ntask has multiple steps, do them all in one turn — chain tool calls rather\nthan pausing for user confirmation between subtasks. End the turn only\nwhen the task is done, you need clarification on intent, or you hit a real\nblocker. The user can interrupt or abort at any time; turn endings should\nmark meaningful checkpoints, not every completed substep.`\n\n/**\n * Appended to the system prompt whenever the `task` proxy tool is\n * enabled. Live sessions (2026-07-04) showed models resolving opencode's\n * \"call the task tool with subagent: X\" mention hint to Claude Code's\n * native TaskCreate: haiku created a todo and narrated a dispatch that\n * never happened; sonnet probed TaskCreate's schema before recovering.\n * The proxy tool can also be deferred behind ToolSearch, in which case\n * \"the task tool\" is invisible while TaskCreate is not. Name the exact\n * tool, the recovery path, and the failure mode.\n */\nexport const SUBAGENT_DISPATCH_HINT = `## opencode subagents\n\nSubagent dispatch in this environment goes through exactly two tools: \\`mcp__opencode_proxy__task\\` for one subagent and \\`mcp__opencode_proxy__task_batch\\` for two or more at once.\n\n- Two or more independent subagents in one response: make ONE \\`mcp__opencode_proxy__task_batch\\` call with a \\`tasks\\` array (each item is a normal task input). Claude Code runs MCP calls one at a time, so several \\`mcp__opencode_proxy__task\\` calls in the same response run serially; \\`task_batch\\` runs them concurrently in opencode and returns every result together, labelled in order.\n- When the user mentions \\`@<agent>\\` or an instruction says \"call the task tool with subagent: <name>\", call \\`mcp__opencode_proxy__task\\` with \\`subagent_type: \"<name>\"\\`.\n- If that tool is not in your visible tool list it is deferred — load it with ToolSearch (\\`select:mcp__opencode_proxy__task\\`), then call it.\n- Claude Code's built-in TaskCreate/TaskUpdate/TaskList manage a local todo list. They cannot dispatch subagents; creating a task there runs nothing. Never report a subagent as dispatched unless \\`mcp__opencode_proxy__task\\` returned its result.\n- Do not verify a subagent's existence by searching config files — the tool's description lists the available agent types, and invalid types fail fast with a clear error.`\n\n/**\n * Appended to the system prompt whenever the `question` proxy tool is\n * enabled. Live testing (2026-07-05, haiku) showed the model's reasoning\n * correctly identified `mcp__opencode_proxy__question` as the tool to use,\n * but then emitted a tool call for bare `question` — stripping the MCP\n * prefix. opencode's AI SDK bridge has no bare `question` tool, so the\n * call rendered as `⚙ invalid`. Same near-miss pattern the task proxy\n * hit (TaskCreate vs mcp__opencode_proxy__task); the fix is the same:\n * name the exact tool in the system prompt so the model doesn't\n * abbreviate.\n */\nexport const QUESTION_PROXY_HINT = `## Asking the operator questions\n\nStructured questions in this environment go through exactly one tool: \\`mcp__opencode_proxy__question\\`.\n\n- When you need to ask the operator a question with options, call \\`mcp__opencode_proxy__question\\` with a \\`questions\\` array (each item has \\`question\\`, \\`header\\`, \\`options\\` of \\`{label, description}\\`, and optional \\`multiple\\`).\n- If that tool is not in your visible tool list it is deferred — load it with ToolSearch (\\`select:mcp__opencode_proxy__question\\`), then call it by its FULL name.\n- Do NOT call bare \\`question\\` — that is not a tool. Always use the full \\`mcp__opencode_proxy__question\\` name when invoking it.\n- Claude Code's built-in \\`AskUserQuestion\\` is disabled in this environment; the proxy is the only way to ask structured questions.`\n\n/**\n * Prepended to every appended system prompt so Claude knows which\n * context-management tools exist in the Claude CLI runtime versus a\n * direct API provider. DCP and similar plugins forward compress/distill/\n * prune instructions via system.transform; those reach us through\n * extractSystemMessages, but the tools themselves are not available in\n * the CLI environment. Without this note Claude wastes thinking cycles\n * searching for tools that don't exist.\n */\nconst CLAUDE_CLI_CONTEXT_NOTE = `## Runtime environment: Claude Code CLI\n\nYou are running via the Claude Code CLI (not a direct API call). This affects context management:\n\n- The \\`compress\\` tool is NOT available. Do not attempt to call it.\n- The \\`distill\\`, \\`prune\\`, and \\`extract\\` tools are NOT available.\n- Context window management is handled automatically by Claude CLI's own session history.\n- Ignore any system instructions that tell you to call \\`compress\\` — they are intended for direct API providers, not this environment.\n- DCP context injections (AGENTS.md, dynamic state) arrive via the system prompt and are already applied.`\n\n/**\n * Replaces the note above when `compress` is in the resolved proxy list.\n * The full MCP name is spelled out for the same reason the question proxy\n * hint spells its own out: models strip the prefix and call bare\n * `compress`, which opencode renders as `⚙ invalid`.\n */\nconst CLAUDE_CLI_COMPRESS_NOTE = `## Runtime environment: Claude Code CLI\n\nYou are running via the Claude Code CLI (not a direct API call). This affects context management:\n\n- To compress context, call \\`mcp__opencode_proxy__compress\\` with a \\`summary\\` argument. Use that exact full name.\n- The reset happens at the start of your NEXT turn: this Claude Code session is discarded and a fresh one starts with your summary as its only prior context. Keep working normally after the call.\n- Everything outside the summary is gone after the reset — tool output, files you read, and the earlier conversation are not replayed. Write the summary as the authoritative record.\n- The \\`distill\\`, \\`prune\\`, and \\`extract\\` tools are NOT available.\n- DCP context injections (AGENTS.md, dynamic state) arrive via the system prompt and are already applied.`\n\n/**\n * Extract text content from all `system`-role messages in the prompt.\n * Standard API providers forward these as the `system` parameter; for\n * Claude CLI, the only equivalent path is --append-system-prompt-file.\n * Plugins like opencode-dcp inject AGENTS.md and other context via\n * system-role messages and would otherwise be silently dropped.\n */\nfunction extractSystemMessages(\n prompt: LanguageModelV3CallOptions[\"prompt\"],\n): string[] {\n const out: string[] = []\n for (const msg of prompt) {\n if (msg.role !== \"system\") continue\n if (typeof msg.content === \"string\") {\n if (msg.content.trim()) out.push(msg.content.trim())\n } else if (Array.isArray(msg.content)) {\n for (const part of msg.content as any[]) {\n if (\n part?.type === \"text\" &&\n typeof part.text === \"string\" &&\n part.text.trim()\n ) {\n out.push(part.text.trim())\n }\n }\n }\n }\n return out\n}\n\nexport interface AppendedSystemPromptOptions {\n /** True when `compress` is in the resolved proxy list for this spawn. */\n compressEnabled?: boolean\n /** Summary from a previous `compress` call, if this key has one. */\n compressionSummary?: string\n}\n\nexport function buildAppendedSystemPrompt(\n cwd: string,\n includeMultiStepHint = true,\n extraSystemContent: string[] = [],\n options: AppendedSystemPromptOptions = {},\n): string | undefined {\n const parts: string[] = []\n // First, so it reads as prior context for everything that follows.\n if (options.compressionSummary?.trim()) {\n parts.push(\n `## Summary of earlier work (context was compressed)\\n\\n${options.compressionSummary.trim()}`,\n )\n }\n parts.push(\n options.compressEnabled ? CLAUDE_CLI_COMPRESS_NOTE : CLAUDE_CLI_CONTEXT_NOTE,\n )\n for (const s of extraSystemContent) {\n if (s.trim()) parts.push(s.trim())\n }\n const configRoot =\n process.env.XDG_CONFIG_HOME ?? join(homedir(), \".config\")\n const globalAgents = readPromptFileIfPresent(join(configRoot, \"opencode\", \"AGENTS.md\"))\n const workspaceAgents = nearestWorkspaceAgentsPrompt(cwd)\n\n // opencode already forwards AGENTS.md inside its own system prompt\n // (`extraSystemContent`, under an \"Instructions from:\" header), so a\n // disk-read copy would reach the model twice. Only push ours when the\n // forwarded text does not already contain it. No match (formatting drift,\n // or the interactive path, which forwards nothing) keeps the old behaviour,\n // so AGENTS.md is never lost. (Dedup by @HeikoAtGitHub, 25260a4.)\n const forwarded = extraSystemContent.join(\"\\n\\n\")\n const pushGlobal = !!globalAgents && !forwarded.includes(globalAgents)\n const pushWorkspace =\n !!workspaceAgents && workspaceAgents !== globalAgents &&\n !forwarded.includes(workspaceAgents)\n if (pushGlobal) parts.push(globalAgents)\n if (pushWorkspace) parts.push(workspaceAgents)\n if (pushGlobal || pushWorkspace) parts.push(AGENTS_MAINTENANCE_HINT)\n if (includeMultiStepHint) parts.push(MULTI_STEP_TASK_HINT)\n\n const content = parts.join(\"\\n\\n\")\n if (!content) return undefined\n\n const path = join(tmpdir(), `opencode-cc-sys-${randomUUID()}.md`)\n try {\n writeFileSync(path, content, \"utf8\")\n return path\n } catch (err) {\n log.warn(\"failed to write system prompt file\", { error: String(err) })\n return undefined\n }\n}\n\n/**\n * Human-readable explanations for the CLI's `fast_mode_disabled_reason` codes,\n * so a downgrade tells the user what to do instead of leaking an enum.\n */\nconst FAST_MODE_REASONS: Record<string, string> = {\n sdk_opt_in_required:\n \"the CLI did not receive the headless opt-in (--settings). This is a plugin bug, please report it\",\n extra_usage_disabled:\n \"your account has usage credits turned off. Run /usage-credits in an interactive `claude` session to enable them\",\n free: \"fast mode requires a paid subscription or purchased credits\",\n preference: \"fast mode is turned off for your organization\",\n model_not_allowed:\n \"this model is not in your organization's allowed models\",\n not_first_party:\n \"fast mode only works against the Anthropic API directly, not Bedrock / Vertex / Foundry\",\n network_error: \"the CLI could not reach Anthropic to check availability\",\n disabled_by_env: \"CLAUDE_CODE_DISABLE_FAST_MODE is set in the environment\",\n pending: \"the CLI is still checking availability\",\n}\n\n/** Reasons already surfaced this process, so a persistent block warns once. */\nconst warnedFastModeReasons = new Set<string>()\n\n/** Test-only. */\nexport function _resetFastModeWarnings(): void {\n warnedFastModeReasons.clear()\n}\n\n/**\n * Report what actually happened to a fast-mode request.\n *\n * Fast mode fails soft: an ineligible account or a rate-limit cooldown drops\n * back to standard speed with no error. That silence is the problem worth\n * solving here: the fast model ids advertise 10x pricing in opencode's picker,\n * so a downgrade the user cannot see means the picker is lying about cost for\n * every subsequent turn.\n *\n * A hard block is therefore a WARN, which this codebase routes to the TUI\n * unconditionally (NOTICE only surfaces in debug mode, which would defeat the\n * purpose). It is deduped per reason per process because the blocking\n * conditions are account-level and would otherwise repeat on every respawn.\n * Cooldown stays quieter: it is transient and clears on its own.\n */\nexport function reportFastModeState(\n msg: ClaudeStreamMessage,\n requested: boolean,\n): void {\n const state = msg.fast_mode_state\n if (!state) return\n\n if (!requested) {\n // Nothing was asked for. Only interesting at debug level.\n log.debug(\"fast mode state\", { state })\n return\n }\n\n if (state === \"on\") {\n log.info(\"fast mode active\", { state })\n return\n }\n\n const reason = msg.fast_mode_disabled_reason\n if (state === \"cooldown\") {\n log.notice(\n \"fast mode is in cooldown after a rate limit; this turn runs at standard speed and is billed at standard Opus rates, not the 10x shown in the model picker.\",\n { state, reason: reason ?? null },\n )\n return\n }\n\n const key = reason ?? \"unknown\"\n const explanation = reason ? FAST_MODE_REASONS[reason] : undefined\n const message = `fast mode was requested but is off${\n explanation ? `: ${explanation}` : reason ? ` (${reason})` : \"\"\n }. Turns run at standard speed and are billed at standard Opus rates, not the 10x shown in the model picker. Switch to the non-fast model id to make the picker's price accurate.`\n\n if (warnedFastModeReasons.has(key)) {\n log.debug(message, { state, reason: reason ?? null })\n return\n }\n warnedFastModeReasons.add(key)\n log.warn(message, { state, reason: reason ?? null })\n}\n\nexport class ClaudeCodeLanguageModel implements LanguageModelV3 {\n readonly specificationVersion = \"v3\"\n readonly modelId: string\n private readonly config: ClaudeCodeConfig\n\n constructor(modelId: string, config: ClaudeCodeConfig) {\n this.modelId = modelId\n this.config = config\n }\n\n readonly supportedUrls: Record<string, RegExp[]> = {}\n\n get provider(): string {\n return this.config.provider\n }\n\n private toUsage(rawUsage?: ClaudeStreamMessage[\"usage\"]): LanguageModelV3Usage {\n // Prefer the last iteration's counters over cumulative totals.\n // CLI usage is the sum across all internal tool-use iterations;\n // using it directly inflates context size and triggers premature compaction.\n const iter = rawUsage?.iterations\n const effective = iter?.length ? iter[iter.length - 1] : rawUsage\n // Claude CLI reports input_tokens as non-cached input only.\n // OpenCode expects total = noCache + cacheRead + cacheWrite.\n const noCache = effective?.input_tokens ?? 0\n const cacheRead = effective?.cache_read_input_tokens ?? 0\n const cacheWrite = effective?.cache_creation_input_tokens ?? 0\n return {\n inputTokens: {\n total: noCache + cacheRead + cacheWrite,\n noCache,\n cacheRead: cacheRead || undefined,\n cacheWrite: cacheWrite || undefined,\n },\n outputTokens: {\n total: effective?.output_tokens,\n text: effective?.output_tokens,\n reasoning: undefined,\n },\n raw: rawUsage as any,\n }\n }\n\n private toFinishReason(\n reason: \"stop\" | \"tool-calls\" = \"stop\",\n ): LanguageModelV3FinishReason {\n return {\n unified: reason,\n raw: reason,\n }\n }\n\n private requestScope(options: { tools?: unknown }): \"tools\" | \"no-tools\" {\n const tools = options?.tools\n if (Array.isArray(tools)) return \"tools\"\n if (tools && typeof tools === \"object\") {\n return Object.keys(tools as Record<string, unknown>).length > 0\n ? \"tools\"\n : \"no-tools\"\n }\n return \"no-tools\"\n }\n\n /**\n * Build the combined `--mcp-config` list and return both the list and the\n * hash of the bridged opencode MCP block (or null when bridging is off /\n * yields nothing). The hash is used to detect mid-session config changes\n * and respawn the underlying claude process.\n *\n * `runtimeStatus` is a snapshot of opencode's `client.mcp.status()`. When\n * provided it overlays opencode's UI-toggled state on top of disk config\n * so `/mcps` toggles propagate without a config file write.\n */\n private effectiveMcpConfig(\n cwd: string,\n proxyConfigPath?: string,\n runtimeStatus?: RuntimeMcpStatus,\n excludeServers?: ReadonlySet<string>,\n ): {\n paths: string[]\n bridgedHash: string | null\n allEnabledServerNames: string[]\n } {\n const paths = Array.isArray(this.config.mcpConfig)\n ? this.config.mcpConfig.slice()\n : this.config.mcpConfig\n ? [this.config.mcpConfig]\n : []\n let bridgedHash: string | null = null\n let allEnabledServerNames: string[] = []\n if (this.config.bridgeOpencodeMcp !== false) {\n const bridged = bridgeOpencodeMcp(cwd, runtimeStatus, excludeServers)\n if (bridged) {\n if (bridged.path) paths.push(bridged.path)\n bridgedHash = bridged.hash\n allEnabledServerNames = bridged.allEnabledServerNames\n }\n }\n if (proxyConfigPath) paths.push(proxyConfigPath)\n return { paths, bridgedHash, allEnabledServerNames }\n }\n\n /** Resolve ProxyToolDef[] for the configured proxyTools names. */\n private resolvedProxyTools(): ProxyToolDef[] | null {\n const names = this.config.proxyTools\n if (!names || names.length === 0) return null\n const defsByName = new Map(\n DEFAULT_PROXY_TOOLS.map((t) => [t.name.toLowerCase(), t]),\n )\n const picked: ProxyToolDef[] = []\n const seen = new Set<string>()\n const unknown: string[] = []\n const pick = (def: ProxyToolDef) => {\n if (seen.has(def.name)) return\n seen.add(def.name)\n picked.push(def)\n }\n for (const n of names) {\n const def = defsByName.get(String(n).toLowerCase())\n if (!def) {\n unknown.push(String(n))\n continue\n }\n pick(def)\n // `task_batch` rides along with `task`: it is the same dispatch path for\n // two or more subagents at once (TASK_BATCH_PROXY_NOTE), and a\n // `proxyTools` list that names `Task` should not have to know it exists.\n if (def.name === \"task\") {\n const batch = defsByName.get(TASK_BATCH_TOOL_NAME)\n if (batch) pick(batch)\n }\n }\n // A typo used to vanish here. Silence is the wrong response: unknown\n // names are not proxied, so the matching Claude built-in stays enabled\n // and unmediated, and if *every* name is unknown the whole turn runs\n // with no proxy at all (issue #26).\n if (unknown.length > 0) {\n const known = [...defsByName.keys()].join(\", \")\n if (picked.length === 0) {\n log.warn(\n \"no proxyTools entry was recognised; nothing will be proxied this turn\",\n { unknown, known },\n )\n } else {\n log.warn(\"ignoring unknown proxyTools entries\", { unknown, known })\n }\n }\n return picked.length > 0 ? picked : null\n }\n\n /**\n * Resolve ProxyToolDef[] for opencode's MCP-bridged tools so they go\n * through the in-process proxy instead of being bridged into Claude CLI's\n * `--mcp-config`. Direct bridging causes double execution because both\n * Claude CLI's own MCP child and opencode hold their own connection to\n * the same server; routing through the proxy keeps a single execution\n * site (opencode). Returns null when the feature is disabled, the SDK\n * client is unavailable, or no MCP servers are configured.\n */\n private async resolvedProxyMcpTools(\n allEnabledServerNames: string[],\n ): Promise<ProxyToolDef[] | null> {\n if (this.config.proxyOpencodeMcpTools === false) return null\n if (this.config.bridgeOpencodeMcp === false) return null\n if (allEnabledServerNames.length === 0) return null\n\n const items = await fetchOpencodeToolList(\n this.config.provider,\n this.modelId,\n this.config.cwd,\n )\n if (!items || items.length === 0) return null\n\n // opencode names MCP tools `<server>_<originalToolName>`. Match the\n // longest server name prefix first so e.g. `slack_intl_*` resolves to\n // server `slack_intl` not `slack`.\n const serversByLengthDesc = [...allEnabledServerNames].sort(\n (a, b) => b.length - a.length,\n )\n const out: ProxyToolDef[] = []\n const seen = new Set<string>()\n for (const item of items) {\n const matchedServer = serversByLengthDesc.find(\n (name) => item.id === name || item.id.startsWith(`${name}_`),\n )\n if (!matchedServer) continue\n if (seen.has(item.id)) continue\n seen.add(item.id)\n out.push({\n name: item.id,\n description: item.description ?? \"\",\n inputSchema:\n item.parameters && typeof item.parameters === \"object\"\n ? item.parameters\n : { type: \"object\", properties: {} },\n })\n }\n return out.length > 0 ? out : null\n }\n\n /**\n * Live tool info derived from a single `client.tool.list()` fetch:\n *\n * - `taskDescription`: opencode's `task` tool description exactly as the\n * registry renders it for native models, including the \"Available\n * agent types\" list. Overlaid onto the static `task` proxy def so\n * Claude sees the same subagent catalog native models see, instead\n * of hunting through config files.\n * - `questionDescription` / `hasQuestion`: opencode's `question` tool\n * description and whether the registry has the entry at all. Older\n * builds lack it, in which case a `mcp__opencode_proxy__question`\n * call resolves to `⚙ invalid`; the version gate drops the def.\n *\n * Returns undefined/false when the SDK client is unavailable (direct\n * AI-SDK use, tests) so the static defs stand. `resolved` distinguishes\n * \"the registry answered and has no `question` entry\" from \"nobody\n * answered\": only the former is a real version-gate signal.\n */\n private async fetchLiveToolInfo(): Promise<LiveToolInfo> {\n const items = await fetchOpencodeToolList(\n this.config.provider,\n this.modelId,\n this.config.cwd,\n )\n const question = items?.find((item) => item.id === \"question\")\n return {\n resolved: items !== undefined,\n taskDescription: items?.find((item) => item.id === \"task\")?.description,\n questionDescription: question?.description,\n hasQuestion: !!question,\n }\n }\n\n /** Share one lazy registry request within a turn without making it stale. */\n private createLiveToolInfoLoader(): () => Promise<LiveToolInfo> {\n let pending: Promise<LiveToolInfo> | undefined\n return () => {\n pending ??= this.fetchLiveToolInfo()\n return pending\n }\n }\n\n /**\n * Whether the ExitPlanMode approval bridge is live for this turn: the\n * operator opted in AND opencode's registry actually has the `question`\n * tool. Without the registry entry the emitted tool-call would render as\n * `⚙ invalid` and wedge the turn, so the plugin keeps the text path.\n */\n private async resolvePlanModeQuestion(\n compactionMode: boolean,\n loadLiveToolInfo = () => this.fetchLiveToolInfo(),\n ): Promise<boolean> {\n if (compactionMode || this.config.planModeQuestion !== true) return false\n const info = await loadLiveToolInfo()\n const active = isPlanModeQuestionActive({\n configured: this.config.planModeQuestion,\n opencodeHasQuestion: info.hasQuestion,\n compactionMode,\n })\n if (!active) {\n // Same reasoning as the question proxy's version-gate log: a silent\n // fallback to the text path looks from the outside like the setting\n // was ignored.\n log.info(\"plan-mode question gate\", {\n opencodeHasQuestion: info.hasQuestion,\n registryResolved: info.resolved,\n active,\n })\n }\n return active\n }\n\n /**\n * Create a proxy MCP server for a single active Claude process/session.\n * The process lifecycle owns the server lifecycle via session-manager.\n */\n private async ensureProxyServer(\n tools: ProxyToolDef[],\n sessionKeyForCalls: string,\n ): Promise<ProxyMcpServer> {\n const timeoutOverrides = this.config.proxyToolTimeoutMs\n const interceptors = new Map<string, ProxyToolInterceptor>()\n if (tools.some((t) => t.name === \"compress\")) {\n interceptors.set(\"compress\", (input) => {\n const summary = typeof input.summary === \"string\" ? input.summary.trim() : \"\"\n if (!summary) {\n return {\n kind: \"error\",\n message:\n \"compress needs a non-empty `summary`: it becomes the only\" +\n \" prior context after the reset. Nothing was compressed.\",\n }\n }\n storeCompressionSummary(sessionKeyForCalls, summary)\n log.info(\"compress stored summary; session resets next turn\", {\n sessionKey: sessionKeyForCalls,\n summaryLength: summary.length,\n })\n return {\n kind: \"text\",\n text:\n \"Summary stored. Finish this turn as normal; the next turn starts\" +\n \" a fresh Claude Code session with this summary as its only prior\" +\n \" context.\",\n }\n })\n }\n const srv = await createProxyMcpServer(tools, timeoutOverrides, interceptors)\n srv.calls.on(\"call\", (call: ProxyToolCall) => {\n queuePendingProxyCall(sessionKeyForCalls, call, timeoutOverrides)\n })\n return srv\n }\n\n private extractPendingProxyResult(\n prompt: LanguageModelV3CallOptions[\"prompt\"],\n toolCallId: string,\n ): ProxyToolResult | null {\n for (let i = prompt.length - 1; i >= 0; i--) {\n const msg = prompt[i]\n if (msg.role !== \"tool\" || !Array.isArray(msg.content)) continue\n\n for (const part of msg.content) {\n if (part.type !== \"tool-result\" || part.toolCallId !== toolCallId) continue\n\n const output = part.output as any\n if (!output || typeof output !== \"object\") {\n return {\n kind: \"text\",\n text: String(output ?? \"\"),\n }\n }\n\n if (output.type === \"text\") {\n return {\n kind: \"text\",\n text: String(output.value ?? \"\"),\n }\n }\n\n if (output.type === \"json\") {\n return {\n kind: \"text\",\n text: JSON.stringify(output.value),\n }\n }\n\n if (output.type === \"content\" && Array.isArray(output.value)) {\n const text = output.value\n .filter((v: any) => v?.type === \"text\" && typeof v.text === \"string\")\n .map((v: any) => v.text)\n .join(\"\\n\")\n return {\n kind: \"text\",\n text,\n }\n }\n\n return {\n kind: \"text\",\n text: JSON.stringify(output),\n }\n }\n }\n\n return null\n }\n\n /**\n * The result opencode produced for a pending proxy call, if the prompt\n * carries it. For `task_batch` that means every child's result gathered\n * back onto the parent: opencode runs the children in one step and hands\n * all their results to the next call together, so a partial set is not\n * expected. If it ever happens the batch still resolves, with the gap\n * named in the text, because leaving the parent pending would send this\n * turn down the fresh-envelope path and reject the call as orphaned.\n */\n private extractPendingProxyResultForCall(\n prompt: LanguageModelV3CallOptions[\"prompt\"],\n call: PendingProxyCall,\n ): ProxyToolResult | null {\n if (call.toolName !== TASK_BATCH_TOOL_NAME) {\n return this.extractPendingProxyResult(prompt, call.toolCallId)\n }\n const tasks = taskBatchTasks(call.input)\n if (tasks.length === 0) {\n return { kind: \"error\", message: \"task_batch input is not a list of task objects\" }\n }\n const children = tasks.map((task, index) => ({\n task,\n result: this.extractPendingProxyResult(\n prompt,\n taskBatchChildToolCallId(call.toolCallId, index),\n ),\n }))\n const answered = children.filter((child) => child.result !== null).length\n if (answered === 0) return null\n if (answered < children.length) {\n log.warn(\"task_batch resolving with child results missing\", {\n toolCallId: call.toolCallId,\n answered,\n total: children.length,\n })\n }\n return formatTaskBatchResults(children)\n }\n\n /**\n * Resolve the session affinity token for this LLM call. Delegates to the\n * exported `resolveSessionAffinity` helper so the logic is unit-testable.\n * Priority:\n * 1. `x-session-affinity` request header (primary).\n * 2. `opencodeSessionID` in providerOptions (chat.params hook fallback —\n * covers provider switches mid-session and title synthesis paths\n * where the header is absent).\n * 3. `\"default\"`.\n */\n private sessionAffinity(\n options: LanguageModelV3CallOptions,\n ): string {\n const headers = (options as any)?.headers as\n | Record<string, string | undefined>\n | undefined\n return resolveSessionAffinity(\n headers,\n options.providerOptions as Record<string, unknown> | undefined,\n this.config.provider,\n )\n }\n\n private controlRequestBehaviorForTool(toolName: string): ControlRequestBehavior {\n const configured = this.config.controlRequestToolBehaviors\n if (configured && toolName) {\n const direct = configured[toolName] ?? configured[toolName.toLowerCase()]\n if (direct === \"allow\" || direct === \"deny\") return direct\n\n const lower = toolName.toLowerCase()\n for (const [key, behavior] of Object.entries(configured)) {\n if (key.toLowerCase() === lower && (behavior === \"allow\" || behavior === \"deny\")) {\n return behavior\n }\n }\n }\n\n // AskUserQuestion must never be auto-allowed. Allowing it lets the\n // Claude CLI resolve its own question internally — in headless mode\n // there is no TTY, so the CLI fabricates/empties the answer and the\n // model proceeds on a guess. Deny so the CLI cannot self-answer; the\n // tool_use is still streamed and rendered to the opencode user by\n // formatAskUserQuestion, and the turn stops for a real reply. An\n // explicit controlRequestToolBehaviors entry above can still override.\n if (isAskUserQuestionTool(toolName)) return \"deny\"\n\n return this.config.controlRequestBehavior ?? \"allow\"\n }\n\n private writeControlResponse(\n proc: import(\"child_process\").ChildProcess,\n requestId: string,\n response?: Record<string, unknown>,\n ): void {\n const payload = {\n type: \"control_response\",\n response: {\n subtype: \"success\",\n request_id: requestId,\n response,\n },\n }\n\n try {\n proc.stdin?.write(JSON.stringify(payload) + \"\\n\")\n } catch (error) {\n log.warn(\"failed to write control response\", {\n requestId,\n error: error instanceof Error ? error.message : String(error),\n })\n }\n }\n\n /**\n * Handle Claude stream-json control requests (`can_use_tool`, etc.) and\n * respond via stdin with a matching `control_response`.\n */\n private handleControlRequest(\n msg: ClaudeStreamMessage,\n proc: import(\"child_process\").ChildProcess,\n ): boolean {\n if (msg.type !== \"control_request\") return false\n const requestId = msg.request_id\n const request = msg.request\n if (!requestId || !request?.subtype) return false\n\n if (request.subtype === \"can_use_tool\") {\n const toolName = request.tool_name ?? \"unknown\"\n const behavior = this.controlRequestBehaviorForTool(toolName)\n\n if (behavior === \"allow\") {\n this.writeControlResponse(proc, requestId, {\n behavior: \"allow\",\n updatedInput: request.input ?? {},\n toolUseID: request.tool_use_id,\n })\n log.info(\"control request auto-allowed\", {\n requestId,\n toolName,\n })\n } else {\n const denyMessage = denyMessageForTool(\n toolName,\n this.config.controlRequestDenyMessage,\n )\n this.writeControlResponse(proc, requestId, {\n behavior: \"deny\",\n message: denyMessage,\n toolUseID: request.tool_use_id,\n })\n log.info(\"control request auto-denied\", {\n requestId,\n toolName,\n })\n }\n\n return true\n }\n\n // For control request subtypes we don't actively handle yet, acknowledge\n // with an empty success so the CLI stream does not stall.\n this.writeControlResponse(proc, requestId, {})\n log.debug(\"control request acknowledged\", {\n requestId,\n subtype: request.subtype,\n })\n return true\n }\n\n private getReasoningEffort(\n providerOptions?: LanguageModelV3CallOptions[\"providerOptions\"],\n ): ReasoningEffort | undefined {\n if (!providerOptions) return undefined\n const ownKey = this.config.provider\n const bag =\n (providerOptions as any)[ownKey] ??\n (providerOptions as any)[\"claude-code\"]\n const effort = bag?.reasoningEffort\n const valid: ReasoningEffort[] = [\n \"minimal\",\n \"low\",\n \"medium\",\n \"high\",\n \"xhigh\",\n \"max\",\n ]\n return valid.includes(effort) ? effort : undefined\n }\n\n private getOpencodeAgent(\n providerOptions?: LanguageModelV3CallOptions[\"providerOptions\"],\n ): string | undefined {\n if (!providerOptions) return undefined\n const ownKey = this.config.provider\n const bag =\n (providerOptions as any)[ownKey] ??\n (providerOptions as any)[\"claude-code\"]\n const agent = bag?.opencodeAgent\n return typeof agent === \"string\" ? agent : undefined\n }\n\n private isCompactionCall(\n options: LanguageModelV3CallOptions,\n ): boolean {\n return this.getOpencodeAgent(options.providerOptions) === \"compaction\"\n }\n\n /**\n * Pick the model used to handle /compact. Precedence:\n * 1. `CLAUDE_CODE_COMPACTION_MODEL` env var (per-process override)\n * 2. `compactionModel` provider setting (opencode.json / .jsonc)\n * 3. Built-in default (claude-haiku-4-5)\n */\n private resolveCompactionModel(): string {\n return resolveCompactionModel(this.config.compactionModel)\n }\n\n private thinkingCliOptions(): {\n thinking?: \"enabled\"\n thinkingDisplay?: \"summarized\"\n } {\n if (isClaudeThinkingDisabled()) return {}\n\n return {\n thinking: \"enabled\",\n thinkingDisplay:\n process.env.CLAUDE_CODE_SHOW_THINKING_SUMMARIES === undefined\n ? \"summarized\"\n : undefined,\n }\n }\n\n private latestUserText(\n prompt: LanguageModelV3CallOptions[\"prompt\"],\n ): string {\n for (let i = prompt.length - 1; i >= 0; i--) {\n const msg = prompt[i]\n if (msg.role !== \"user\") continue\n\n if (typeof msg.content === \"string\") {\n return String(msg.content).trim()\n }\n\n if (Array.isArray(msg.content)) {\n const text = (msg.content as any[])\n .filter((part) => part.type === \"text\" && typeof part.text === \"string\")\n .map((part: any) => String(part.text).trim())\n .filter(Boolean)\n .join(\" \")\n if (text) return text\n }\n }\n\n return \"\"\n }\n\n private synthesizeTitle(\n prompt: LanguageModelV3CallOptions[\"prompt\"],\n ): string {\n const source = this.latestUserText(prompt)\n .replace(/\\s+/g, \" \")\n .replace(/[^\\p{L}\\p{N}\\s-]/gu, \" \")\n .trim()\n\n if (!source) return \"New Session\"\n\n const stop = new Set([\n \"a\",\n \"an\",\n \"the\",\n \"and\",\n \"or\",\n \"but\",\n \"to\",\n \"for\",\n \"of\",\n \"in\",\n \"on\",\n \"at\",\n \"with\",\n \"can\",\n \"could\",\n \"would\",\n \"should\",\n \"please\",\n \"hi\",\n \"hello\",\n \"hey\",\n \"there\",\n \"you\",\n \"your\",\n \"this\",\n \"that\",\n \"is\",\n \"are\",\n \"was\",\n \"were\",\n \"be\",\n \"do\",\n \"does\",\n \"did\",\n \"summarize\",\n \"summary\",\n \"project\",\n ])\n\n const words = source\n .split(\" \")\n .map((word) => word.trim())\n .filter(Boolean)\n .filter((word) => !stop.has(word.toLowerCase()))\n\n const picked = (words.length > 0 ? words : source.split(\" \").filter(Boolean))\n .slice(0, 6)\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1))\n .join(\" \")\n\n return picked || \"New Session\"\n }\n\n private async doGenerateViaStream(\n options: LanguageModelV3CallOptions,\n ): Promise<Awaited<ReturnType<LanguageModelV3[\"doGenerate\"]>>> {\n const result = await this.doStream(options)\n const reader = result.stream.getReader()\n\n let text = \"\"\n let reasoning = \"\"\n const toolCalls: LanguageModelV3Content[] = []\n let finishReason = this.toFinishReason(\"stop\")\n let usage: LanguageModelV3Usage = this.toUsage()\n let providerMetadata: any\n\n while (true) {\n const { value, done } = await reader.read()\n if (done) break\n\n switch ((value as any).type) {\n case \"text-delta\":\n text += (value as any).delta ?? \"\"\n break\n case \"reasoning-delta\":\n reasoning += (value as any).delta ?? \"\"\n break\n case \"tool-call\":\n toolCalls.push({\n type: \"tool-call\",\n toolCallId: (value as any).toolCallId,\n toolName: (value as any).toolName,\n input: (value as any).input,\n providerExecuted: (value as any).providerExecuted,\n } as any)\n break\n case \"finish\":\n finishReason = (value as any).finishReason ?? finishReason\n usage = (value as any).usage ?? usage\n providerMetadata = (value as any).providerMetadata ?? providerMetadata\n break\n }\n }\n\n const content: LanguageModelV3Content[] = []\n if (reasoning) {\n content.push({ type: \"reasoning\", text: reasoning } as any)\n }\n if (text) {\n content.push({ type: \"text\", text, providerMetadata } as any)\n }\n content.push(...toolCalls)\n\n return {\n content,\n finishReason,\n usage,\n request: result.request,\n response: {\n id: generateId(),\n timestamp: new Date(),\n modelId: this.modelId,\n },\n providerMetadata,\n warnings: [],\n }\n }\n\n async doGenerate(\n options: LanguageModelV3CallOptions,\n ): Promise<Awaited<ReturnType<LanguageModelV3[\"doGenerate\"]>>> {\n if (!this.isCompactionCall(options) && this.requestScope(options as any) !== \"no-tools\" && parseSideQuestion(options.prompt)) {\n return this.doGenerateViaStream(options)\n }\n const warnings: SharedV3Warning[] = []\n const scope = this.requestScope(options as any)\n const affinity = this.sessionAffinity(options)\n const cwd = await resolveSpawnCwdForSession(this.config.cwd, affinity)\n // An agent may run on a different model than the one opencode routed here\n // (see agent-models.ts). The session key must carry the effective model or\n // an overridden agent shares a claude process with its caller.\n const effectiveModelId = resolveAgentModel(\n this.getOpencodeAgent(options.providerOptions),\n this.modelId,\n )\n const reasoningEffort = resolveAgentEffort(\n this.getOpencodeAgent(options.providerOptions),\n this.getReasoningEffort(options.providerOptions),\n ) as ReasoningEffort | undefined\n // Keep effort invalidation inside one agent/provider, even when callers\n // share a model and opencode session (for example switching agents).\n const baseKey = sessionKey(\n cwd,\n `${effectiveModelId}::${scope}::${affinity}::context=${JSON.stringify([this.config.provider, this.getOpencodeAgent(options.providerOptions) ?? null])}`,\n )\n const sk = effortSessionKey(baseKey, reasoningEffort)\n\n // When selective proxying is enabled, doGenerate must not bypass the\n // proxy path. Reuse doStream and aggregate its events so proxied tools\n // still route through opencode permissions/execution. Same for\n // opencode MCP proxying — doStream is the only path that wires up the\n // proxy server with the dynamically-discovered MCP tool defs.\n const compactionMode = this.isCompactionCall(options)\n\n if (\n scope === \"tools\" &&\n (this.resolvedProxyTools() ||\n (this.config.proxyOpencodeMcpTools !== false &&\n this.config.bridgeOpencodeMcp !== false))\n ) {\n return this.doGenerateViaStream(options)\n }\n\n // Route compaction through doStream so it gets the lean spawn path,\n // model override, and rich transcript handling. Aggregating a stream\n // for doGenerate matches what doGenerateViaStream already does for\n // proxy tools.\n if (compactionMode) {\n return this.doGenerateViaStream(options)\n }\n\n if (scope === \"no-tools\") {\n log.info(\"doGenerate no-tools title stub\", {\n compactionMode,\n opencodeAgent: this.getOpencodeAgent(options.providerOptions),\n providerOptionsKeys: options.providerOptions\n ? Object.keys(options.providerOptions)\n : [],\n })\n const text = this.synthesizeTitle(options.prompt)\n return {\n content: [{ type: \"text\", text }] as any,\n finishReason: this.toFinishReason(\"stop\"),\n usage: this.toUsage({ input_tokens: 0, output_tokens: 0 }),\n request: { body: { text: \"\" } },\n response: {\n id: generateId(),\n timestamp: new Date(),\n modelId: this.modelId,\n },\n providerMetadata: {\n \"claude-code\": {\n synthetic: true,\n path: \"no-tools\",\n },\n },\n warnings,\n }\n }\n\n // Short-circuit when opencode iterates the agent loop one more time\n // after a turn already finished. The prompt ends with an assistant\n // message and has no fresh user input — spawning Claude here would\n // just produce a stub like \"No input received. Standing by\".\n if (!hasNewUserContent(options.prompt)) {\n log.info(\"doGenerate short-circuit: no new user content\")\n return {\n content: [],\n finishReason: this.toFinishReason(\"stop\"),\n usage: this.toUsage({ input_tokens: 0, output_tokens: 0 }),\n request: { body: { text: \"\" } },\n response: {\n id: generateId(),\n timestamp: new Date(),\n modelId: this.modelId,\n },\n providerMetadata: {\n \"claude-code\": { synthetic: true, path: \"no-new-user-content\" },\n },\n warnings,\n }\n }\n\n invalidateOtherEffortSessions(baseKey, reasoningEffort)\n\n const hasPriorConversation =\n options.prompt.filter((m) => m.role === \"user\" || m.role === \"assistant\")\n .length > 1\n\n // New session — clear any stale state from a previous session.\n // A compression summary is scoped to one conversation, so this is the\n // one place it is dropped: the compress restart itself calls\n // deleteClaudeSessionId, and clearing there would wipe the summary\n // just before the fresh spawn reads it.\n if (!hasPriorConversation) {\n deleteClaudeSessionId(sk)\n deleteActiveProcess(sk)\n clearCompression(sk)\n }\n\n const hasExistingSession = !!getClaudeSessionId(sk)\n const includeHistoryContext = !hasExistingSession && hasPriorConversation\n\n const userMsg =\n consumeExitPlanModeQuestionResult(sk, options.prompt as any) ??\n // doGenerate has no proxy wiring, so this process issued no tool calls\n // at all: every tool result reaching it belongs to opencode and must be\n // rendered as text rather than an orphaned `tool_result` (issue #29).\n getClaudeUserMessage(options.prompt, includeHistoryContext, {\n cliToolCallIds: new Set<string>(),\n })\n\n // doGenerate always spawns a fresh process, never reuse session ID.\n // Pre-fetch opencode's MCP runtime status so the bridge overlays\n // UI-toggled state on top of disk config.\n const [runtimeStatus, cliVersion, planModeQuestionActive] = await Promise.all([\n getRuntimeMcpStatus(),\n detectCliVersion(this.config.cliPath),\n this.resolvePlanModeQuestion(compactionMode),\n ])\n const systemPromptFile = buildAppendedSystemPrompt(\n cwd,\n this.config.multiStepContinuation !== false,\n extractSystemMessages(options.prompt),\n // doGenerate has no proxy wiring, so `compress` is not callable here.\n // An existing summary still carries: it is this key's prior context.\n { compressEnabled: false, compressionSummary: getCompressionSummary(sk) },\n )\n const { model: spawnModelId, fast: fastMode } = parseModelId(effectiveModelId)\n const cliArgs = buildCliArgs({\n sessionKey: sk,\n skipPermissions: this.config.skipPermissions !== false,\n includeSessionId: false,\n model: spawnModelId,\n permissionMode: this.config.permissionMode,\n mcpConfig: this.effectiveMcpConfig(cwd, undefined, runtimeStatus).paths,\n strictMcpConfig: this.config.strictMcpConfig,\n disallowedTools:\n this.config.webSearch === \"disabled\" ? [\"WebSearch\"] : undefined,\n appendSystemPromptFile: systemPromptFile,\n ...this.thinkingCliOptions(),\n fastMode,\n cliVersion,\n })\n\n log.info(\"doGenerate starting\", {\n cwd,\n model: effectiveModelId,\n requestedModel: this.modelId,\n textLength: userMsg.length,\n includeHistoryContext,\n })\n\n const { spawn } = await import(\"node:child_process\")\n const { createInterface } = await import(\"node:readline\")\n\n const proc = spawn(this.config.cliPath, cliArgs, {\n cwd,\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n env: claudeSpawnEnv({\n ignoreAnthropicApiKey: this.config.ignoreAnthropicApiKey,\n effort: reasoningEffort,\n }),\n shell: process.platform === \"win32\",\n })\n\n if (systemPromptFile) {\n proc.on(\"exit\", () => {\n void unlink(systemPromptFile).catch(() => {})\n })\n }\n\n const rl = createInterface({ input: proc.stdout! })\n\n let responseText = \"\"\n let thinkingText = \"\"\n let resultMeta: {\n sessionId?: string\n costUsd?: number\n durationMs?: number\n usage?: ClaudeStreamMessage[\"usage\"]\n } = {}\n const toolCalls: Array<{ id: string; name: string; args: unknown }> = []\n // Streaming tool_use entries keyed by content-block index. We accumulate\n // partial_json chunks here instead of trying to JSON.parse each chunk\n // independently, and flush to `toolCalls` at content_block_stop. The\n // previous code indexed `toolCalls` by `msg.index` directly, which is\n // wrong whenever non-tool blocks (text, thinking) precede a tool_use.\n const toolCallStreams = new Map<\n number,\n { id: string; name: string; inputJson: string }\n >()\n\n // Set true once we observe a `stream_event` envelope. When on, the\n // top-level `assistant` message is a duplicate of content already\n // accumulated via the inner content_block_* events — skip it.\n let gotPartialEvents = false\n\n const result = await new Promise<\n typeof resultMeta & {\n text: string\n thinking: string\n toolCalls: typeof toolCalls\n }\n >((resolve, reject) => {\n const cleanup = () => {\n try {\n if (!proc.killed && proc.exitCode === null) proc.kill()\n } catch {}\n }\n\n rl.on(\"line\", (line) => {\n if (!line.trim()) return\n try {\n const outer: ClaudeStreamMessage = JSON.parse(line)\n\n // Unwrap stream_event envelope (--include-partial-messages).\n // Inner event uses the same content_block_* / message_* shape.\n const msg: ClaudeStreamMessage =\n outer.type === \"stream_event\" && outer.event\n ? { ...outer.event, session_id: outer.session_id }\n : outer\n\n if (outer.type === \"stream_event\") {\n gotPartialEvents = true\n }\n\n if (this.handleControlRequest(msg, proc)) {\n return\n }\n\n if (msg.type === \"system\" && msg.subtype === \"init\") {\n if (msg.session_id) {\n setClaudeSessionId(sk, msg.session_id)\n }\n reportFastModeState(msg, fastMode)\n }\n\n if (\n msg.type === \"assistant\" &&\n msg.message?.content &&\n !gotPartialEvents\n ) {\n for (const block of msg.message.content) {\n if (block.type === \"text\" && block.text) {\n responseText += block.text\n }\n if (block.type === \"thinking\" && block.thinking) {\n thinkingText += block.thinking\n }\n if (block.type === \"tool_use\" && block.id && block.name) {\n if (isAskUserQuestionTool(block.name)) {\n // Render the full question + options as visible text so\n // the user can actually see and answer it.\n const parsedInput = (block.input ?? {}) as Record<\n string,\n unknown\n >\n responseText += formatAskUserQuestion(parsedInput)\n continue\n }\n\n if (block.name === \"ExitPlanMode\") {\n const parsedInput = (block.input ?? {}) as Record<\n string,\n unknown\n >\n const plan = (parsedInput?.plan as string) || \"\"\n if (planModeQuestionActive) {\n const questionCall = createExitPlanModeQuestionCall(\n sk,\n block.id,\n plan,\n )\n responseText += questionCall.text\n toolCalls.push({\n id: questionCall.toolCallId,\n name: questionCall.toolName,\n args: questionCall.input,\n })\n continue\n }\n responseText += `\\n\\n${plan}\\n\\n---\\n**Do you want to proceed with this plan?** (yes/no)\\n`\n continue\n }\n\n toolCalls.push({\n id: block.id,\n name: block.name,\n args: block.input ?? {},\n })\n }\n }\n }\n\n if (\n msg.type === \"content_block_start\" &&\n msg.content_block &&\n msg.index !== undefined\n ) {\n if (\n msg.content_block.type === \"tool_use\" &&\n msg.content_block.id &&\n msg.content_block.name\n ) {\n toolCallStreams.set(msg.index, {\n id: msg.content_block.id,\n name: msg.content_block.name,\n inputJson: \"\",\n })\n }\n }\n\n if (\n msg.type === \"content_block_delta\" &&\n msg.delta &&\n msg.index !== undefined\n ) {\n if (msg.delta.type === \"text_delta\" && msg.delta.text) {\n responseText += msg.delta.text\n }\n if (msg.delta.type === \"thinking_delta\" && msg.delta.thinking) {\n thinkingText += msg.delta.thinking\n }\n if (\n msg.delta.type === \"input_json_delta\" &&\n msg.delta.partial_json\n ) {\n const tc = toolCallStreams.get(msg.index)\n if (tc) tc.inputJson += msg.delta.partial_json\n }\n }\n\n if (msg.type === \"content_block_stop\" && msg.index !== undefined) {\n const tc = toolCallStreams.get(msg.index)\n if (tc) {\n let args: unknown = {}\n try {\n args = tc.inputJson ? JSON.parse(tc.inputJson) : {}\n } catch (err) {\n log.warn(\"tool input JSON parse failed\", {\n name: tc.name,\n error: String(err),\n })\n }\n if (tc.name === \"ExitPlanMode\" && planModeQuestionActive) {\n const parsedInput = args as Record<string, unknown>\n const plan = (parsedInput?.plan as string) || \"\"\n const questionCall = createExitPlanModeQuestionCall(sk, tc.id, plan)\n responseText += questionCall.text\n toolCalls.push({\n id: questionCall.toolCallId,\n name: questionCall.toolName,\n args: questionCall.input,\n })\n } else {\n toolCalls.push({ id: tc.id, name: tc.name, args })\n }\n toolCallStreams.delete(msg.index)\n }\n }\n\n if (msg.type === \"result\") {\n if (msg.session_id) {\n setClaudeSessionId(sk, msg.session_id)\n }\n\n // Some CLI failures only surface user-readable text on the final\n // `result` message (without prior assistant text blocks). Preserve\n // that so callers don't receive an empty response.\n if (\n !responseText &&\n msg.is_error &&\n typeof msg.result === \"string\" &&\n msg.result.trim().length > 0\n ) {\n responseText = msg.result\n }\n\n resultMeta = {\n sessionId: msg.session_id,\n costUsd: msg.total_cost_usd,\n durationMs: msg.duration_ms,\n usage: msg.usage,\n }\n cleanup()\n resolve({\n ...resultMeta,\n text: responseText,\n thinking: thinkingText,\n toolCalls,\n })\n }\n } catch {\n // Ignore non-JSON lines\n }\n })\n\n rl.on(\"close\", () => {\n cleanup()\n resolve({\n ...resultMeta,\n text: responseText,\n thinking: thinkingText,\n toolCalls,\n })\n })\n\n proc.on(\"error\", (err) => {\n log.error(\"process error\", { error: err.message })\n cleanup()\n reject(err)\n })\n\n proc.stderr?.on(\"data\", (data: Buffer) => {\n log.debug(\"stderr\", { data: data.toString().slice(0, 200) })\n })\n\n proc.stdin?.write(userMsg + \"\\n\")\n })\n\n const content: LanguageModelV3Content[] = []\n\n if (result.thinking) {\n content.push({\n type: \"reasoning\",\n text: result.thinking,\n } as any)\n }\n\n if (result.text) {\n content.push({\n type: \"text\",\n text: result.text,\n providerMetadata: {\n \"claude-code\": {\n sessionId: result.sessionId ?? null,\n costUsd: result.costUsd ?? null,\n durationMs: result.durationMs ?? null,\n },\n ...(typeof result.usage?.cache_creation_input_tokens === \"number\"\n ? {\n anthropic: {\n cacheCreationInputTokens:\n result.usage.cache_creation_input_tokens,\n },\n }\n : {}),\n },\n })\n }\n\n for (const tc of result.toolCalls) {\n if (tc.name === QUESTION_TOOL_NAME) {\n content.push({\n type: \"tool-call\",\n toolCallId: tc.id,\n toolName: tc.name,\n input: JSON.stringify(tc.args),\n providerExecuted: false,\n } as any)\n continue\n }\n\n const {\n name: mappedName,\n input: mappedInput,\n executed,\n skip,\n } = mapTool(tc.name, tc.args, {\n webSearch: this.config.webSearch,\n sessionId: getClaudeSessionId(sk),\n toolUseId: tc.id,\n })\n if (skip) continue\n content.push({\n type: \"tool-call\",\n toolCallId: tc.id,\n toolName: mappedName,\n input: JSON.stringify(mappedInput),\n providerExecuted: executed,\n } as any)\n }\n\n const usage = this.toUsage(result.usage)\n\n return {\n content,\n // Claude CLI's `result` message normally signals a fully-completed turn:\n // tools have already been executed internally and final assistant text\n // has been produced. ExitPlanMode is the exception: we surface it as\n // opencode's native question tool so the outer loop must run that tool.\n finishReason: this.toFinishReason(\n result.toolCalls.some((tc) => tc.name === QUESTION_TOOL_NAME)\n ? \"tool-calls\"\n : \"stop\",\n ),\n usage,\n request: { body: { text: userMsg } },\n response: {\n id: result.sessionId ?? generateId(),\n timestamp: new Date(),\n modelId: this.modelId,\n },\n providerMetadata: {\n \"claude-code\": {\n sessionId: result.sessionId ?? null,\n costUsd: result.costUsd ?? null,\n durationMs: result.durationMs ?? null,\n },\n ...(typeof result.usage?.cache_creation_input_tokens === \"number\"\n ? {\n anthropic: {\n cacheCreationInputTokens:\n result.usage.cache_creation_input_tokens,\n },\n }\n : {}),\n },\n warnings,\n }\n }\n\n async doStream(\n options: LanguageModelV3CallOptions,\n ): Promise<Awaited<ReturnType<LanguageModelV3[\"doStream\"]>>> {\n const warnings: SharedV3Warning[] = []\n const cliPath = this.config.cliPath\n const skipPermissions = this.config.skipPermissions !== false\n const scope = this.requestScope(options as any)\n const affinity = this.sessionAffinity(options)\n const cwd = await resolveSpawnCwdForSession(this.config.cwd, affinity)\n const compactionMode = this.isCompactionCall(options)\n // Use a separate session key for compaction so its short-lived spawn\n // never collides with the main conversation's claude process.\n const effectiveModelId = compactionMode\n ? this.resolveCompactionModel()\n : resolveAgentModel(\n this.getOpencodeAgent(options.providerOptions),\n this.modelId,\n )\n // `effectiveModelId` stays intact for session keys, logs, and metadata;\n // only the name handed to the CLI gets the `-fast` marker stripped.\n // Session keys keeping it is deliberate: fast and standard must not share\n // a claude process, both because the spawn flags differ and because\n // switching speed invalidates the prompt cache anyway.\n const { model: spawnModelId, fast: fastMode } = parseModelId(effectiveModelId)\n // Compaction skips request/agent effort overrides; other calls key on it.\n const reasoningEffort = compactionMode\n ? undefined\n : (resolveAgentEffort(\n this.getOpencodeAgent(options.providerOptions),\n this.getReasoningEffort(options.providerOptions),\n ) as ReasoningEffort | undefined)\n const baseKey = sessionKey(\n cwd,\n `${effectiveModelId}::${scope}::${affinity}::context=${JSON.stringify([this.config.provider, this.getOpencodeAgent(options.providerOptions) ?? null])}`,\n )\n const sk = compactionMode\n ? sessionKey(cwd, `${effectiveModelId}::compaction::${affinity}`)\n : effortSessionKey(baseKey, reasoningEffort)\n const toUsage = this.toUsage.bind(this)\n const toFinishReason = this.toFinishReason.bind(this)\n const handleControlRequest = this.handleControlRequest.bind(this)\n const flagOn = (v: string | undefined) =>\n v !== undefined &&\n ![\"\", \"0\", \"false\", \"no\", \"off\"].includes(v.trim().toLowerCase())\n // Interactive (subscription) transport: drive the claude TUI over Bun's\n // native ConPTY + JSONL tail instead of headless `--print` stream-json.\n // Prefer the provider option (config-driven, reliable in the GUI app where\n // process env vars are not inherited); fall back to the env var. Self-healing:\n // if Bun.Terminal is unavailable (e.g. not under Bun), use the headless path.\n const interactivePref =\n this.config.interactive ??\n flagOn(process.env.CLAUDE_CODE_INTERACTIVE_TRANSPORT)\n const useInteractive =\n interactivePref && typeof (globalThis as any).Bun?.Terminal === \"function\"\n const interactiveBypassRequested =\n this.config.interactiveBypass ??\n flagOn(process.env.CLAUDE_CODE_INTERACTIVE_BYPASS)\n\n // Tagged onto the process each turn so the /btw command hook, which only\n // knows the opencode session id, can find it and ask it early\n // (btw-command.ts).\n const asideTransportRef = { cliPath, interactive: !!useInteractive }\n\n const aside = !compactionMode && scope !== \"no-tools\" ? parseSideQuestion(options.prompt) : null\n if (aside) {\n // `/btw` is an ordinary user message in this conversation, so opencode\n // keeps the exchange, but it is answered over the CLI's side_question\n // control channel, never as a turn. The command hook normally sent the\n // question ahead, while the previous turn was still streaming, and its\n // answer is taken here; otherwise the process is idle now and is asked\n // directly. Earlier asides in this conversation ride along as history.\n const active = getActiveProcess(sk)\n const early = aside.question ? takeSideQuestionAnswer(affinity, aside.question) : undefined\n const history = collectSideQuestionHistory(options.prompt)\n const answerAside = async (): Promise<SideQuestionResult> => {\n if (!aside.question) return { response: SIDE_QUESTION_USAGE, synthetic: true }\n if (early) {\n try {\n return await early\n } catch (error) {\n log.info(\"btw: early answer failed, asking the idle process\", { error: String(error) })\n }\n }\n if (!active) return { response: BTW_NO_SESSION_MESSAGE, synthetic: true }\n return requestSideQuestion(active, aside.question, {\n cliVersion: await detectCliVersion(cliPath),\n interactive: useInteractive,\n abortSignal: options.abortSignal,\n ...(history.length ? { history } : {}),\n })\n }\n const stream = new ReadableStream<LanguageModelV3StreamPart>({\n async start(controller) {\n controller.enqueue({ type: \"stream-start\", warnings })\n try {\n const answer = await answerAside()\n const id = generateId()\n controller.enqueue({ type: \"text-start\", id })\n controller.enqueue({ type: \"text-delta\", id, delta: answer.response })\n controller.enqueue({ type: \"text-end\", id })\n controller.enqueue({\n type: \"finish\",\n finishReason: toFinishReason(\"stop\"),\n usage: toUsage({}),\n providerMetadata: { \"claude-code\": { path: \"side-question\", synthetic: answer.synthetic, usageUnavailable: true } },\n })\n } catch (error) {\n controller.enqueue({ type: \"error\", error })\n } finally {\n controller.close()\n }\n },\n })\n return { stream, request: { body: { text: aside.question } } }\n }\n\n if (scope === \"no-tools\" && !compactionMode) {\n log.info(\"doStream no-tools title stub\", {\n compactionMode,\n opencodeAgent: this.getOpencodeAgent(options.providerOptions),\n providerOptionsKeys: options.providerOptions\n ? Object.keys(options.providerOptions)\n : [],\n })\n const text = this.synthesizeTitle(options.prompt)\n const textId = generateId()\n const stream = new ReadableStream<LanguageModelV3StreamPart>({\n start(controller) {\n controller.enqueue({ type: \"stream-start\", warnings })\n controller.enqueue({ type: \"text-start\", id: textId } as any)\n controller.enqueue({\n type: \"text-delta\",\n id: textId,\n delta: text,\n })\n controller.enqueue({ type: \"text-end\", id: textId })\n controller.enqueue({\n type: \"finish\",\n finishReason: toFinishReason(\"stop\"),\n usage: toUsage({ input_tokens: 0, output_tokens: 0 }),\n providerMetadata: {\n \"claude-code\": {\n synthetic: true,\n path: \"no-tools\",\n },\n },\n })\n controller.close()\n },\n })\n\n return {\n stream,\n request: { body: { text: \"\" } },\n }\n }\n\n // Short-circuit when opencode iterates the agent loop one more time\n // after a turn already finished. The prompt ends with an assistant\n // message and has no fresh user input — spawning Claude here would\n // just produce a stub like \"No input received. Standing by\".\n if (!hasNewUserContent(options.prompt)) {\n log.info(\"doStream short-circuit: no new user content\")\n const stream = new ReadableStream<LanguageModelV3StreamPart>({\n start(controller) {\n controller.enqueue({ type: \"stream-start\", warnings })\n controller.enqueue({\n type: \"finish\",\n finishReason: toFinishReason(\"stop\"),\n usage: toUsage({ input_tokens: 0, output_tokens: 0 }),\n providerMetadata: {\n \"claude-code\": { synthetic: true, path: \"no-new-user-content\" },\n },\n })\n controller.close()\n },\n })\n return { stream, request: { body: { text: \"\" } } }\n }\n\n if (!compactionMode) invalidateOtherEffortSessions(baseKey, reasoningEffort)\n\n const hasPriorConversation =\n options.prompt.filter((m) => m.role === \"user\" || m.role === \"assistant\")\n .length > 1\n\n // New session — clear any stale state from a previous session.\n // A compression summary is scoped to one conversation, so this is the\n // one place it is dropped: the compress restart itself calls\n // deleteClaudeSessionId, and clearing there would wipe the summary\n // just before the fresh spawn reads it.\n if (!hasPriorConversation) {\n deleteClaudeSessionId(sk)\n deleteActiveProcess(sk)\n clearCompression(sk)\n }\n\n const hasExistingSession = !!getClaudeSessionId(sk)\n const hasActiveProcess = !!getActiveProcess(sk)\n const includeHistoryContext =\n !hasExistingSession && !hasActiveProcess && hasPriorConversation\n\n const exitPlanModeQuestionResult = compactionMode\n ? null\n : consumeExitPlanModeQuestionResult(sk, options.prompt as any)\n if (exitPlanModeQuestionResult) {\n // The whole user message for this turn is the `tool_result` for the\n // pending ExitPlanMode call, so say so: an operator looking at a turn\n // that carries none of their typed text needs the reason in the log.\n log.info(\"sending plan approval decision to claude\", { sk })\n }\n // Read before the envelope is built, and used by it: only these ids were\n // issued by this CLI process, so only these may be sent back as\n // `tool_result` blocks (issue #29).\n const previousPendingProxyCalls = compactionMode\n ? []\n : getPendingProxyCalls(sk)\n const userMsg =\n exitPlanModeQuestionResult ??\n getClaudeUserMessage(options.prompt, includeHistoryContext, {\n compactionMode,\n cliToolCallIds: new Set(previousPendingProxyCalls.map((c) => c.toolCallId)),\n })\n const resolvedProxy = compactionMode ? null : this.resolvedProxyTools()\n const loadLiveToolInfo = this.createLiveToolInfoLoader()\n // Resolved here, not inside the stream body: the ExitPlanMode branches\n // run in a synchronous line handler and a reused process never reaches\n // the spawn block where the registry snapshot is otherwise taken.\n const planModeQuestionActive = await this.resolvePlanModeQuestion(\n compactionMode,\n loadLiveToolInfo,\n )\n const self = this\n\n const previousPendingProxyMatches: Array<{\n call: PendingProxyCall\n result: ProxyToolResult | null\n }> = previousPendingProxyCalls.map((call) => ({\n call,\n result: this.extractPendingProxyResultForCall(options.prompt, call),\n }))\n const hasMatchedPendingResults = previousPendingProxyMatches.some(\n (m) => m.result !== null,\n )\n\n // Pre-fetch opencode's MCP runtime status before constructing the\n // ReadableStream so the sync hot-reload check and async setup() see\n // the same overlay snapshot. One in-process call per turn — cheap;\n // the SDK client routes through `Server.app.fetch` (no socket).\n // Detect the Claude CLI version in parallel so the spawn can decide\n // which optional flags it supports without crashing older binaries.\n const [runtimeStatus, cliVersion] = await Promise.all([\n compactionMode ? Promise.resolve(undefined) : getRuntimeMcpStatus(),\n detectCliVersion(this.config.cliPath),\n ])\n\n log.info(\"doStream starting\", {\n cwd,\n model: effectiveModelId,\n textLength: userMsg.length,\n includeHistoryContext,\n hasActiveProcess,\n reasoningEffort,\n proxyTools: resolvedProxy?.map((t) => t.name) ?? null,\n compactionMode,\n scope,\n opencodeAgent: this.getOpencodeAgent(options.providerOptions),\n providerOptionsKeys: options.providerOptions\n ? Object.keys(options.providerOptions)\n : [],\n })\n\n const stream = new ReadableStream<LanguageModelV3StreamPart>({\n start(controller) {\n // Compaction is a one-shot call. Don't reuse any cached process\n // from a prior compaction — each /compact gets a fresh spawn so\n // the new transcript isn't appended to a stale claude session.\n if (compactionMode) {\n deleteActiveProcess(sk)\n deleteClaudeSessionId(sk)\n }\n\n // A compress call lands mid-turn, when the child is still streaming,\n // so the reset it asks for happens here instead: drop the child and\n // its session id, and the spawn below starts clean. `userMsg` and\n // `includeHistoryContext` were resolved above while the session\n // still existed, so the fresh process is given only this turn's\n // message — the summary in its system prompt is the whole of its\n // prior context, exactly as the tool promised.\n //\n // Not while this turn carries results for the live child: evicting\n // it would send a tool_result to a process that never issued the\n // matching tool_use. The mark survives to the next turn.\n if (!compactionMode && !hasMatchedPendingResults && consumeCompressionRestart(sk)) {\n deleteActiveProcess(sk)\n deleteClaudeSessionId(sk)\n log.info(\"compress reset: dropped claude process and session id\", {\n sessionKey: sk,\n })\n }\n\n let activeProcess = getActiveProcess(sk)\n let proc: import(\"child_process\").ChildProcess\n let lineEmitter: import(\"events\").EventEmitter\n let cliArgs: string[]\n let proxyServer: ProxyMcpServer | null = activeProcess?.proxyServer ?? null\n\n const setup = async () => {\n // Wait for the old owner to exit before resuming its session ID in\n // the replacement, so two processes never append to one transcript.\n if (\n !compactionMode &&\n activeProcess &&\n self.config.hotReloadMcp !== false &&\n self.config.bridgeOpencodeMcp !== false\n ) {\n const probe = self.effectiveMcpConfig(cwd, undefined, runtimeStatus!)\n const previousHash = activeProcess.mcpHash ?? null\n if (previousHash !== probe.bridgedHash) {\n if (previousPendingProxyCalls.length > 0) {\n log.info(\"deferring MCP hot reload until proxy calls resolve\", {\n sk,\n previousHash,\n currentHash: probe.bridgedHash,\n pendingCalls: previousPendingProxyCalls.length,\n })\n } else {\n log.info(\"opencode MCP config changed, respawning claude\", {\n sk,\n previousHash,\n currentHash: probe.bridgedHash,\n })\n await deleteActiveProcessAndWait(sk)\n activeProcess = undefined\n proxyServer = null\n }\n }\n }\n\n if (useInteractive && !compactionMode) {\n // Interactive Bun-ConPTY transport. Reuse the live session if one\n // exists for this key; else spawn a new interactive claude. The\n // wrapper conforms to ActiveProcess, so reuse/eviction/hot-reload\n // and the whole emission body below work unchanged.\n const mcp = self.effectiveMcpConfig(cwd, undefined, runtimeStatus!)\n if (activeProcess) {\n proc = activeProcess.proc\n lineEmitter = activeProcess.lineEmitter\n log.debug(\"reusing active interactive session\", { sk })\n } else {\n // MCP wildcards are always derived from the live bridge config;\n // the built-in tool list is overridable via interactiveAllowTools.\n const allow = [\n ...mcp.allEnabledServerNames.map((n) => `mcp__${n}__*`),\n \"mcp__opencode_proxy__*\",\n ...(self.config.interactiveAllowTools ?? [\n \"Bash\",\n \"Edit\",\n \"Write\",\n \"Read\",\n \"WebFetch\",\n ]),\n ]\n const systemPromptFile =\n self.config.interactiveSystemPrompt === false\n ? undefined\n : buildAppendedSystemPrompt(\n cwd,\n self.config.multiStepContinuation !== false,\n // Do not forward opencode's own system prompt into the\n // interactive TUI. Live subscription-account testing\n // showed that large forwarded payload can trigger Claude\n // Code's third-party-app usage gate, while our static\n // CLI/AGENTS/continuation prompt remains safe.\n )\n if (self.config.interactiveSystemPrompt === false) {\n log.warn(\n \"interactive system prompt disabled; opencode agent prompts will not be appended\",\n )\n }\n if (interactiveBypassRequested) {\n log.warn(\n \"interactiveBypass ignored: Claude Code prompts for bypassPermissions confirmation in the interactive TUI\",\n )\n }\n const ap = spawnInteractiveProcess({\n cwd,\n cliPath,\n configDir: self.config.configDir,\n model: spawnModelId,\n fastMode,\n mcpConfigPaths: mcp.paths,\n permissionsAllow: allow,\n systemPromptFile,\n ignoreAnthropicApiKey: self.config.ignoreAnthropicApiKey,\n effort: reasoningEffort,\n })\n ap.mcpHash = mcp.bridgedHash\n setActiveProcess(sk, ap)\n proc = ap.proc\n lineEmitter = ap.lineEmitter\n activeProcess = ap\n log.info(\"spawned interactive claude session\", {\n sk,\n cliPath,\n configDir: self.config.configDir,\n model: effectiveModelId,\n })\n }\n } else {\n let spawnSystemPromptFile: string | undefined\n let spawnProxyServer: ProxyMcpServer | null = null\n let spawnMcpHash: string | null = null\n\n if (compactionMode) {\n // Compaction takes a lean spawn: no MCP servers, no proxy, no\n // appended system prompt, no disallowed-tools list. The model\n // is asked for text output only on a single turn — all the\n // normal tool wiring is pure overhead and adds latency.\n // Explicitly opt out of `--resume` so a stale id can never\n // resume into the lean spawn.\n cliArgs = buildCliArgs({\n sessionKey: sk,\n skipPermissions,\n includeSessionId: false,\n model: spawnModelId,\n permissionMode: self.config.permissionMode,\n fastMode,\n cliVersion,\n })\n } else {\n // First pass: discover which opencode MCP servers would be\n // bridged. We use this to decide which ones to re-route through\n // the proxy instead. No --mcp-config path is consumed here;\n // it's recomputed below with the exclusion set in place.\n const discovery = self.effectiveMcpConfig(\n cwd,\n undefined,\n runtimeStatus!,\n )\n\n // Fetch the proxy MCP tools (one ProxyToolDef per opencode\n // MCP-bridged tool). If discovery returns nothing or the SDK\n // is unreachable, this is null and we fall back to direct\n // bridging.\n const proxyMcpTools = await self.resolvedProxyMcpTools(\n discovery.allEnabledServerNames,\n )\n const excludeServers: ReadonlySet<string> | undefined = proxyMcpTools\n ? new Set(discovery.allEnabledServerNames)\n : undefined\n\n // Overlay opencode's live tool info onto the static proxy defs.\n // Both the `task` description (with the \"Available agent types\"\n // list, so the model sees which subagents exist instead of\n // grepping configs) and the `question` version gate (older\n // opencode builds lack the `question` registry entry; the def\n // must be dropped or a forwarded call renders `⚙ invalid`)\n // derive from a single tool-list fetch. Spawn-time only, like\n // the rest of this block; a reused process keeps its defs.\n const taskProxyEnabled =\n resolvedProxy?.some((t) => t.name === \"task\") ?? false\n const questionProxyEnabled =\n resolvedProxy?.some((t) => t.name === \"question\") ?? false\n const liveToolInfo =\n taskProxyEnabled || questionProxyEnabled\n ? await loadLiveToolInfo()\n : {\n resolved: false,\n taskDescription: undefined,\n questionDescription: undefined,\n hasQuestion: false,\n }\n let enrichedProxy = resolvedProxy\n if (enrichedProxy && taskProxyEnabled) {\n enrichedProxy = overlayTaskProxyDescription(\n enrichedProxy,\n liveToolInfo.taskDescription,\n )\n // Whether the model will see opencode's agent list is the\n // difference between a dispatch and an \"Unknown agent type\"\n // guess, so say so out loud.\n log.info(\"task proxy description overlay\", {\n applied: Boolean(liveToolInfo.taskDescription),\n liveDescriptionLength: liveToolInfo.taskDescription?.length ?? 0,\n listsAgentTypes: Boolean(\n liveToolInfo.taskDescription?.includes(\n \"Available agent types\",\n ),\n ),\n })\n }\n if (enrichedProxy && questionProxyEnabled) {\n // When the version gate is about to drop the def\n // (`hasQuestion === false`) the live description is moot,\n // so only overlay when the entry actually exists.\n enrichedProxy = overlayQuestionProxyDescription(\n enrichedProxy,\n liveToolInfo.hasQuestion\n ? liveToolInfo.questionDescription\n : undefined,\n )\n enrichedProxy = filterQuestionProxyByOpencodeSupport(\n enrichedProxy,\n liveToolInfo.hasQuestion,\n )\n // Same reasoning as the task overlay log: when the gate drops\n // the def the model silently falls back to the deny/markdown\n // path, which looks from the outside like the feature is off.\n log.info(\"question proxy version gate\", {\n opencodeHasQuestion: liveToolInfo.hasQuestion,\n kept: liveToolInfo.hasQuestion,\n })\n }\n\n // Combine the static proxy defs with any MCP-bridged proxy\n // tools. Guard against the empty case: a version gate can\n // drop every configured def (e.g. `proxyTools: [\"Question\"]`\n // on an opencode build that lacks the `question` registry\n // entry), and spinning up an MCP server with zero tools is\n // wasteful and wrong shape.\n const combinedList = [\n ...(enrichedProxy ?? []),\n ...(proxyMcpTools ?? []),\n ]\n const combinedProxyTools: ProxyToolDef[] | null =\n combinedList.length > 0 ? combinedList : null\n\n if (!proxyServer && combinedProxyTools) {\n proxyServer = await self.ensureProxyServer(combinedProxyTools, sk)\n }\n\n // Whether the question proxy actually survived the version\n // gate (post-filter). Used to decide whether to inject the\n // QUESTION_PROXY_HINT — if the gate dropped the def, the\n // model must fall back to AskUserQuestion (the deny/markdown\n // path) and must NOT be told to call a proxy tool that does\n // not exist.\n const questionProxyActive =\n enrichedProxy?.some((t) => t.name === \"question\") ?? false\n\n // Compute disallowed flags from the POST-FILTER proxy list\n // (enrichedProxy), not the pre-filter one (resolvedProxy).\n // When the version gate drops `question` on an older opencode\n // build, AskUserQuestion must NOT be added to\n // --disallowedTools — otherwise the native tool is disabled\n // while the proxy replacement is absent, leaving the model\n // with no way to ask questions at all (neither proxy nor the\n // deny/markdown fallback path fires).\n const allDisallowed = resolveDisallowedTools({\n proxyTools: enrichedProxy,\n extraDisallowedTools: self.config.extraDisallowedTools,\n disableWebSearch: self.config.webSearch === \"disabled\",\n })\n const mcp = self.effectiveMcpConfig(\n cwd,\n proxyServer?.configPath(),\n runtimeStatus!,\n excludeServers,\n )\n const systemPromptFile = activeProcess\n ? undefined\n : buildAppendedSystemPrompt(\n cwd,\n self.config.multiStepContinuation !== false,\n [\n ...extractSystemMessages(options.prompt),\n ...(taskProxyEnabled ? [SUBAGENT_DISPATCH_HINT] : []),\n ...(questionProxyActive ? [QUESTION_PROXY_HINT] : []),\n ],\n {\n compressEnabled:\n enrichedProxy?.some((t) => t.name === \"compress\") ?? false,\n compressionSummary: getCompressionSummary(sk),\n },\n )\n // Opt-in skill bridge (@broskees): stage opencode skills as a\n // session-scoped --plugin-dir so Claude's Skill tool can run them.\n const skillPluginDirs = await resolveSkillPluginDirs({\n cwd,\n cliPath,\n enabled: self.config.bridgeOpencodeSkills === true,\n })\n cliArgs = buildCliArgs({\n sessionKey: sk,\n skipPermissions,\n model: spawnModelId,\n permissionMode: self.config.permissionMode,\n mcpConfig: mcp.paths,\n strictMcpConfig: self.config.strictMcpConfig,\n disallowedTools: allDisallowed.length > 0 ? allDisallowed : undefined,\n appendSystemPromptFile: systemPromptFile,\n pluginDirs: skillPluginDirs,\n ...self.thinkingCliOptions(),\n fastMode,\n cliVersion,\n })\n spawnSystemPromptFile = systemPromptFile\n spawnProxyServer = proxyServer\n spawnMcpHash = mcp.bridgedHash\n }\n\n if (activeProcess && !compactionMode) {\n proc = activeProcess.proc\n lineEmitter = activeProcess.lineEmitter\n log.debug(\"reusing active process\", { sk })\n } else {\n const ap = spawnClaudeProcess(\n cliPath,\n cliArgs,\n cwd,\n sk,\n spawnProxyServer,\n spawnMcpHash,\n spawnSystemPromptFile,\n self.config.ignoreAnthropicApiKey,\n reasoningEffort,\n )\n proc = ap.proc\n lineEmitter = ap.lineEmitter\n activeProcess = ap\n }\n }\n\n // The CLI serves one turn at a time. If the previous one is still\n // running (the user aborted it, or it ended on our inactivity\n // fallback rather than a real `result`), stop it before this turn\n // attaches any listeners; otherwise its tail streams into us and its\n // `result` closes us before our own answer arrives. Skipped for\n // tool-result turns: there the CLI is deliberately parked inside a\n // proxy MCP call waiting for the result we are about to deliver.\n if (activeProcess && !hasMatchedPendingResults && isTurnInFlight(activeProcess)) {\n log.warn(\"previous turn still in flight; interrupting it\", { sk })\n const idle = await interruptTurn(activeProcess)\n if (!idle) {\n log.warn(\"previous turn did not stop in time; this turn may see stale output\", { sk })\n }\n }\n\n controller.enqueue({ type: \"stream-start\", warnings })\n\n let currentTextId: string | null = null\n const textBlockIndices = new Set<number>()\n\n const startTextBlock = (): string => {\n if (currentTextId) {\n controller.enqueue({ type: \"text-end\", id: currentTextId })\n }\n const id = generateId()\n currentTextId = id\n controller.enqueue({ type: \"text-start\", id } as any)\n return id\n }\n\n const endTextBlock = (): void => {\n if (currentTextId) {\n controller.enqueue({ type: \"text-end\", id: currentTextId })\n currentTextId = null\n }\n }\n\n const reasoningIds = new Map<number, string>()\n const reasoningStarted = new Map<number, boolean>()\n let hadThinkingTextFromStream = false\n\n let turnCompleted = false\n let controllerClosed = false\n // Buffered terminal results belong to the previous CLI turn.\n let unattendedTurnEnded = false\n let watchdogMessage = userMsg\n let pendingProxyUnsubscribe: (() => void) | null = null\n let asideSinkUnregister: (() => void) | null = null\n let resultFallbackTimer: ReturnType<typeof setTimeout> | null = null\n let pendingResultCompletion: (() => void) | null = null\n let hasReceivedContent = false\n let hasReceivedProgress = false\n let visibleTextSinceContinue = \"\"\n let lastVisibleTextSinceContinue = \"\"\n let hadReasoningSinceContinue = false\n let hadToolActivitySinceContinue = false\n let hadProxyActivitySinceContinue = false\n // v0.4.16: protocol-level stop signal captured from Claude CLI's\n // stream. Set by either the `message_delta` partial event or the\n // top-level `assistant` message, whichever arrives first.\n let lastStopReason: string | null = null\n const autoContinueState: AutoContinueState = {\n enabled: self.config.autoContinueIncompleteTurns,\n attempts: 0,\n startedAt: Date.now(),\n noProgressCount: 0,\n }\n\n const clearFallbackTimer = () => {\n if (resultFallbackTimer) {\n clearTimeout(resultFallbackTimer)\n resultFallbackTimer = null\n }\n }\n\n // Wire-inactivity watchdog. Resets on every line received from the\n // CLI; only fires if the CLI has emitted content and then gone\n // silent on stdout for `delayMs` without sending a `result`. The\n // previous design armed this on every text content_block_stop,\n // which killed legitimate mid-turn think pauses (most visibly\n // with sonnet between text-end and the next tool_use_start).\n const startResultFallback = (delayMs = 60_000) => {\n clearFallbackTimer()\n if ((!hasReceivedContent && !hasReceivedProgress) || controllerClosed) return\n resultFallbackTimer = setTimeout(() => {\n if (controllerClosed) return\n log.warn(\"result fallback timer fired — closing stream without result event\", {\n delayMs,\n })\n closeHandler()\n }, delayMs)\n }\n\n // Start watchdog: complementary to the inactivity watchdog above.\n // That one only arms once content has arrived; this one covers the\n // gap the other explicitly skips — a reused process that produces\n // NO stdout at all after a fresh-turn envelope write. Seen after a\n // very long proxy-blocked tool call resumed successfully (the child\n // stays silent on stdout). On first fire we respawn the child with\n // --session-id to resume the conversation transparently; on a\n // second fire (respawn also silent) we end the turn cleanly so the\n // next opencode turn spawns fresh. Tunable via env for reproduces.\n const START_WATCHDOG_MS = (() => {\n const env = process.env.CLAUDE_CODE_START_WATCHDOG_MS\n const parsed = env ? Number.parseInt(env, 10) : NaN\n return Number.isFinite(parsed) && parsed > 0 ? parsed : 90_000\n })()\n let startWatchdog: ReturnType<typeof setTimeout> | null = null\n let respawnAttempted = false\n const clearStartWatchdog = () => {\n if (startWatchdog) {\n clearTimeout(startWatchdog)\n startWatchdog = null\n }\n }\n const onStartWatchdogFire = () => {\n startWatchdog = null\n if (controllerClosed || hasReceivedContent || hasReceivedProgress) return\n if (respawnAttempted) {\n log.error(\n \"claude process still silent after respawn; ending turn\",\n { sessionKey: sk },\n )\n deleteActiveProcess(sk)\n deleteClaudeSessionId(sk)\n controllerClosed = true\n cleanupTurn()\n controller.enqueue({\n type: \"error\",\n error: new Error(\n \"Claude process produced no output after the envelope write (start watchdog timeout).\",\n ),\n })\n try {\n controller.close()\n } catch {}\n return\n }\n respawnAttempted = true\n log.warn(\n \"no stdout after envelope write; respawning claude process to resume conversation\",\n { sessionKey: sk, startWatchdogMs: START_WATCHDOG_MS },\n )\n lineEmitter.off(\"line\", lineHandler)\n lineEmitter.off(\"close\", closeHandler)\n proc.off(\"error\", procErrorHandler)\n const newAp = respawnActiveProcess(\n sk,\n cliPath,\n cliArgs,\n cwd,\n self.config.ignoreAnthropicApiKey,\n )\n if (!newAp) {\n log.error(\n \"no active process to respawn (start watchdog); ending turn\",\n { sessionKey: sk },\n )\n controllerClosed = true\n cleanupTurn()\n controller.enqueue({\n type: \"error\",\n error: new Error(\n \"No active claude process to respawn after start watchdog timeout.\",\n ),\n })\n try {\n controller.close()\n } catch {}\n return\n }\n proc = newAp.proc\n lineEmitter = newAp.lineEmitter\n activeProcess = newAp\n lineEmitter.on(\"line\", lineHandler)\n lineEmitter.on(\"close\", closeHandler)\n proc.on(\"error\", procErrorHandler)\n try {\n if (!deliverPendingCompletions(true)) {\n noteTurnStarted(newAp)\n proc.stdin?.write(watchdogMessage + \"\\n\")\n }\n log.debug(\"re-sent user message after respawn\", {\n textLength: watchdogMessage.length,\n })\n } catch (err) {\n log.error(\"failed to re-send envelope after respawn\", {\n error: err instanceof Error ? err.message : String(err),\n })\n }\n armStartWatchdog()\n }\n const armStartWatchdog = () => {\n clearStartWatchdog()\n if (controllerClosed) return\n startWatchdog = setTimeout(onStartWatchdogFire, START_WATCHDOG_MS)\n }\n\n // Both buffered/live terminal boundaries and respawn consume through\n // this path. Open-channel results remain available for a later close.\n const deliverPendingCompletions = (force = false): boolean => {\n const pending = activeProcess?.pendingProxyCompletions\n const entries = [...(pending?.values() ?? [])].filter(\n (entry) => force || entry.recoveryRequired || isPendingProxyCallChannelClosed(entry.call),\n )\n if (entries.length === 0) return false\n endTextBlock()\n watchdogMessage = makeLateProxyResultMessage(entries)\n proc.stdin!.write(watchdogMessage + \"\\n\")\n for (const { call } of entries) pending!.delete(call.toolCallId)\n log.warn(\"delivering proxy results after interrupted continuation\", {\n sessionKey: sk,\n toolCallIds: entries.map(({ call }) => call.toolCallId),\n respawn: force,\n })\n gotPartialEvents = false\n hasReceivedContent = false\n hasReceivedProgress = false\n turnCompleted = false\n resetAutoContinueWindow()\n clearFallbackTimer()\n armStartWatchdog()\n return true\n }\n\n const toolCallMap = new Map<\n number,\n { id: string; name: string; inputJson: string; started: boolean }\n >()\n // Tool calls the plugin reported as providerExecuted:false — opencode\n // will run these itself and emit its own tool-result, so we must NOT\n // forward Claude CLI's tool_result for them (would short-circuit\n // opencode's execute).\n const skipResultForIds = new Set<string>()\n const toolCallsById = new Map<\n string,\n { id: string; name: string; input: unknown }\n >()\n\n let resultMeta: {\n sessionId?: string\n costUsd?: number\n durationMs?: number\n usage?: ClaudeStreamMessage[\"usage\"]\n } = {}\n\n // Batched drain so claude CLI's parallel tool_use blocks (e.g. two\n // bash calls in one assistant message) end up in a single\n // tool-calls finish event. Without this, the broker would reject\n // every overlapping call and claude would see spurious tool errors.\n const drainBuffer: PendingProxyCall[] = []\n let drainTimer: ReturnType<typeof setTimeout> | null = null\n const DRAIN_QUIET_MS = 100\n\n const finishWithToolCalls = (calls: PendingProxyCall[]) => {\n if (controllerClosed) return\n if (calls.length === 0) return\n const enqueueToolCall = (\n toolCallId: string,\n toolName: string,\n input: Record<string, unknown>,\n ) => {\n controller.enqueue({\n type: \"tool-input-start\",\n id: toolCallId,\n toolName,\n } as any)\n controller.enqueue({\n type: \"tool-call\",\n toolCallId,\n toolName,\n input: JSON.stringify(input),\n providerExecuted: false,\n } as any)\n skipResultForIds.add(toolCallId)\n }\n for (const call of calls) {\n if (call.toolName === TASK_BATCH_TOOL_NAME) {\n // One MCP call from the CLI becomes N opencode `task` calls in\n // this single tool boundary, which is what makes them run at the\n // same time: the CLI serialises MCP calls, opencode runs the\n // tool calls of one step concurrently. Their results are\n // gathered back onto the parent id in\n // extractPendingProxyResultForCall.\n for (const [index, task] of taskBatchTasks(call.input).entries()) {\n enqueueToolCall(\n taskBatchChildToolCallId(call.toolCallId, index),\n \"task\",\n task,\n )\n }\n skipResultForIds.add(call.toolCallId)\n } else {\n enqueueToolCall(call.toolCallId, call.toolName, call.input)\n }\n markPendingProxyCallEmitted(call.toolCallId)\n }\n controller.enqueue({\n type: \"finish\",\n finishReason: toFinishReason(\"tool-calls\"),\n usage: toUsage(resultMeta.usage),\n providerMetadata: {\n \"claude-code\": resultMeta,\n },\n })\n controllerClosed = true\n cleanupTurn()\n try {\n controller.close()\n } catch {}\n }\n\n const finishWithExitPlanQuestion = (\n call: ReturnType<typeof createExitPlanModeQuestionCall>,\n ) => {\n if (controllerClosed) return\n endTextBlock()\n controller.enqueue({\n type: \"tool-input-start\",\n id: call.toolCallId,\n toolName: call.toolName,\n providerExecuted: false,\n } as any)\n controller.enqueue({\n type: \"tool-call\",\n toolCallId: call.toolCallId,\n toolName: call.toolName,\n input: JSON.stringify(call.input),\n providerExecuted: false,\n } as any)\n controller.enqueue({\n type: \"finish\",\n finishReason: toFinishReason(\"tool-calls\"),\n usage: toUsage(resultMeta.usage),\n providerMetadata: {\n \"claude-code\": resultMeta,\n },\n })\n controllerClosed = true\n cleanupTurn()\n try {\n controller.close()\n } catch {}\n }\n\n const drainNow = () => {\n if (drainTimer) {\n clearTimeout(drainTimer)\n drainTimer = null\n }\n if (drainBuffer.length === 0) return\n if (controllerClosed) return\n const batch = drainBuffer.splice(0, drainBuffer.length)\n log.info(\"draining pending proxy calls into stream finish\", {\n sessionKey: sk,\n count: batch.length,\n toolCallIds: batch.map((c) => c.toolCallId),\n })\n finishWithToolCalls(batch)\n }\n\n const settleResultBoundary = () => {\n drainTimer = null\n const completeResult = pendingResultCompletion\n pendingResultCompletion = null\n if (!completeResult || controllerClosed) return\n if (drainBuffer.length > 0) {\n drainNow()\n return\n }\n completeResult()\n }\n\n const scheduleResultBoundary = (\n completeResult: () => void,\n delayMs: number,\n ) => {\n pendingResultCompletion = completeResult\n if (drainTimer) clearTimeout(drainTimer)\n drainTimer = setTimeout(settleResultBoundary, delayMs)\n }\n\n const noteResultBoundaryCall = (): boolean => {\n if (!pendingResultCompletion) return false\n if (drainTimer) clearTimeout(drainTimer)\n drainTimer = setTimeout(settleResultBoundary, DRAIN_QUIET_MS)\n return true\n }\n\n const noteVisibleText = (text: string) => {\n visibleTextSinceContinue += text\n lastVisibleTextSinceContinue += text\n }\n\n const resetLastVisibleTextBlock = () => {\n lastVisibleTextSinceContinue = \"\"\n }\n\n const noteReasoning = () => {\n hadReasoningSinceContinue = true\n }\n\n const noteToolActivity = () => {\n hadToolActivitySinceContinue = true\n }\n\n const noteProxyActivity = () => {\n hadProxyActivitySinceContinue = true\n }\n\n const resetAutoContinueWindow = () => {\n visibleTextSinceContinue = \"\"\n lastVisibleTextSinceContinue = \"\"\n hadReasoningSinceContinue = false\n hadToolActivitySinceContinue = false\n hadProxyActivitySinceContinue = false\n lastStopReason = null\n }\n\n const completeResult = (msg: ClaudeStreamMessage) => {\n if (controllerClosed) return\n // The socket may have closed after the tool-result prompt was matched,\n // or while the result-boundary grace timer was running.\n if (deliverPendingCompletions()) {\n if (drainBuffer.length > 0) drainNow()\n return\n }\n if (drainBuffer.length > 0) {\n drainNow()\n return\n }\n\n const pendingSiblings = getPendingProxyCalls(sk)\n if (pendingSiblings.length > 0) {\n log.info(\"leaving parallel proxy calls pending at result boundary\", {\n sessionKey: sk,\n count: pendingSiblings.length,\n })\n }\n\n activeProcess?.pendingProxyCompletions?.clear()\n\n const autoDecision = shouldAutoContinueIncompleteTurn(\n autoContinueState,\n {\n text: visibleTextSinceContinue,\n lastVisibleText: lastVisibleTextSinceContinue,\n hadReasoning: hadReasoningSinceContinue,\n hadToolActivity: hadToolActivitySinceContinue,\n hadProxyActivity: hadProxyActivitySinceContinue,\n isError: msg.is_error,\n stopReason: lastStopReason,\n },\n )\n if (autoDecision.continue) {\n const signature = continuationSignature({\n text: visibleTextSinceContinue,\n lastVisibleText: lastVisibleTextSinceContinue,\n hadReasoning: hadReasoningSinceContinue,\n hadToolActivity: hadToolActivitySinceContinue,\n hadProxyActivity: hadProxyActivitySinceContinue,\n isError: msg.is_error,\n })\n autoContinueState.noProgressCount =\n signature === autoContinueState.lastSignature\n ? autoContinueState.noProgressCount + 1\n : 0\n autoContinueState.lastSignature = signature\n autoContinueState.attempts++\n log.notice(\"auto-continuing incomplete claude result\", {\n sessionKey: sk,\n reason: autoDecision.reason,\n attempts: autoContinueState.attempts,\n textLength: visibleTextSinceContinue.length,\n lastTextLength: lastVisibleTextSinceContinue.length,\n hadReasoning: hadReasoningSinceContinue,\n hadToolActivity: hadToolActivitySinceContinue,\n hadProxyActivity: hadProxyActivitySinceContinue,\n })\n turnCompleted = false\n resetAutoContinueWindow()\n // The `result` just consumed marked the CLI idle; this puts it back to work.\n if (activeProcess) noteTurnStarted(activeProcess)\n proc.stdin?.write(makeAutoContinueMessage() + \"\\n\")\n return\n }\n log.notice(\"auto-continuation stopped\", {\n sessionKey: sk,\n reason: autoDecision.reason,\n stopReason: lastStopReason,\n attempts: autoContinueState.attempts,\n textLength: visibleTextSinceContinue.length,\n lastTextLength: lastVisibleTextSinceContinue.length,\n hadReasoning: hadReasoningSinceContinue,\n hadToolActivity: hadToolActivitySinceContinue,\n hadProxyActivity: hadProxyActivitySinceContinue,\n })\n\n for (const [idx, reasoningId] of reasoningIds) {\n if (reasoningStarted.get(idx)) {\n controller.enqueue({\n type: \"reasoning-end\",\n id: reasoningId,\n } as any)\n }\n }\n\n controller.enqueue({\n type: \"finish\",\n finishReason: toFinishReason(\"stop\"),\n usage: toUsage(msg.usage),\n providerMetadata: {\n \"claude-code\": {\n ...resultMeta,\n ...(compactionMode\n ? { compactionModel: effectiveModelId }\n : {}),\n },\n ...(typeof msg.usage?.cache_creation_input_tokens === \"number\"\n ? {\n anthropic: {\n cacheCreationInputTokens:\n msg.usage.cache_creation_input_tokens,\n },\n }\n : {}),\n },\n })\n\n controllerClosed = true\n cleanupTurn()\n if (!useInteractive && !compactionMode) {\n scheduleIdleProcessEviction(sk, self.config.idleProcessTimeoutMs)\n }\n\n try {\n controller.close()\n } catch {}\n }\n\n // Set true once we observe a `stream_event` envelope. When on, the\n // top-level `assistant` message is a duplicate of what we already\n // streamed via content_block_* deltas — skip its content.\n let gotPartialEvents = false\n\n const lineHandler = (line: string) => {\n if (!line.trim()) return\n if (controllerClosed) return\n\n // Any line from the CLI counts as activity — reset the inactivity\n // watchdog so mid-turn pauses between blocks don't get killed.\n startResultFallback()\n\n try {\n const outer: ClaudeStreamMessage = JSON.parse(line)\n\n // Unwrap stream_event envelope (--include-partial-messages).\n // Inner event uses the same content_block_* / message_* shape.\n const msg: ClaudeStreamMessage =\n outer.type === \"stream_event\" && outer.event\n ? { ...outer.event, session_id: outer.session_id }\n : outer\n\n const modelProgress =\n (msg.type === \"assistant\" && !!msg.message?.content?.length) ||\n (msg.type === \"content_block_start\" && msg.content_block?.type === \"tool_use\") ||\n (msg.type === \"content_block_delta\" &&\n ((msg.delta?.type === \"text_delta\" && !!msg.delta.text) ||\n (msg.delta?.type === \"thinking_delta\" && !!msg.delta.thinking)))\n if (modelProgress) {\n hasReceivedProgress = true\n clearStartWatchdog()\n startResultFallback()\n }\n\n if (outer.type === \"stream_event\") {\n gotPartialEvents = true\n }\n\n if (handleControlRequest(msg, proc)) {\n return\n }\n\n log.debug(\"stream message\", {\n type: msg.type,\n subtype: msg.subtype,\n })\n\n // Handle system init\n if (msg.type === \"system\" && msg.subtype === \"init\") {\n if (msg.session_id) {\n setClaudeSessionId(sk, msg.session_id)\n log.info(\"session initialized\", {\n claudeSessionId: msg.session_id,\n })\n }\n reportFastModeState(msg, fastMode)\n }\n\n // content_block_start\n if (\n msg.type === \"content_block_start\" &&\n msg.content_block &&\n msg.index !== undefined\n ) {\n const block = msg.content_block\n const idx = msg.index\n\n if (block.type === \"thinking\") {\n noteReasoning()\n const reasoningId = generateId()\n reasoningIds.set(idx, reasoningId)\n }\n\n if (block.type === \"text\") {\n textBlockIndices.add(idx)\n // New text block — clear last-block buffer so final-answer\n // detection only considers this block's contents, not earlier\n // mid-task narration.\n resetLastVisibleTextBlock()\n if (block.text) {\n if (!currentTextId) startTextBlock()\n controller.enqueue({\n type: \"text-delta\",\n id: currentTextId!,\n delta: block.text,\n })\n noteVisibleText(block.text)\n hasReceivedContent = true\n }\n }\n\n if (block.type === \"tool_use\" && block.id && block.name) {\n noteToolActivity()\n const entry = {\n id: block.id,\n name: block.name,\n inputJson: \"\",\n started: false,\n }\n toolCallMap.set(idx, entry)\n\n if (\n block.name !== \"AskUserQuestion\" &&\n block.name !== \"ask_user_question\" &&\n block.name !== \"ExitPlanMode\" &&\n !block.name.startsWith(PROXY_TOOL_PREFIX)\n ) {\n const { name: mappedName, skip, executed } = mapTool(\n block.name,\n undefined,\n {\n webSearch: self.config.webSearch,\n sessionId: getClaudeSessionId(sk),\n toolUseId: block.id,\n },\n )\n if (!skip) {\n entry.started = true\n controller.enqueue({\n type: \"tool-input-start\",\n id: block.id,\n toolName: mappedName,\n providerExecuted: executed,\n } as any)\n log.info(\"tool started\", {\n name: block.name,\n mappedName,\n id: block.id,\n })\n }\n }\n }\n }\n\n // content_block_delta\n if (\n msg.type === \"content_block_delta\" &&\n msg.delta &&\n msg.index !== undefined\n ) {\n const delta = msg.delta\n const idx = msg.index\n\n if (delta.type === \"thinking_delta\" && delta.thinking) {\n noteReasoning()\n hadThinkingTextFromStream = true\n const reasoningId = reasoningIds.get(idx)\n if (reasoningId) {\n if (!reasoningStarted.get(idx)) {\n controller.enqueue({\n type: \"reasoning-start\",\n id: reasoningId,\n } as any)\n reasoningStarted.set(idx, true)\n }\n controller.enqueue({\n type: \"reasoning-delta\",\n id: reasoningId,\n delta: delta.thinking,\n } as any)\n }\n }\n\n if (delta.type === \"text_delta\" && delta.text) {\n if (!currentTextId) startTextBlock()\n controller.enqueue({\n type: \"text-delta\",\n id: currentTextId!,\n delta: delta.text,\n })\n noteVisibleText(delta.text)\n hasReceivedContent = true\n }\n\n if (delta.type === \"input_json_delta\" && delta.partial_json) {\n const tc = toolCallMap.get(idx)\n if (tc) {\n tc.inputJson += delta.partial_json\n // Only forward deltas for tool calls whose tool-input-start\n // was actually emitted. Skipped tools (CLAUDE_INTERNAL_TOOLS,\n // TaskCreate/TaskUpdate, CLI-internal WebSearch, AskUserQuestion,\n // ExitPlanMode, proxy tools) never get a named start part, so\n // forwarding their deltas makes opencode's AI SDK bridge fall\n // back to a nameless pending part rendered as `⚙ unknown`.\n if (tc.started) {\n controller.enqueue({\n type: \"tool-input-delta\",\n id: tc.id,\n delta: delta.partial_json,\n } as any)\n }\n }\n }\n\n if (!KNOWN_DELTA_TYPES.has(delta.type)) {\n log.debug(\"unrecognized content_block_delta type\", {\n type: delta.type,\n idx,\n keys: Object.keys(delta),\n })\n }\n }\n\n // content_block_stop\n if (\n msg.type === \"content_block_stop\" &&\n msg.index !== undefined\n ) {\n const idx = msg.index\n\n const reasoningId = reasoningIds.get(idx)\n if (reasoningId && reasoningStarted.get(idx)) {\n controller.enqueue({\n type: \"reasoning-end\",\n id: reasoningId,\n } as any)\n reasoningStarted.delete(idx)\n }\n\n if (textBlockIndices.has(idx)) {\n endTextBlock()\n textBlockIndices.delete(idx)\n }\n\n const tc = toolCallMap.get(idx)\n if (tc) {\n // Block indices restart at 0 on every assistant message, and a\n // turn can hold several (tool_use -> tool_result -> answer).\n // Without this delete the entry outlives its message, so the\n // next message's block at the same index re-emits a tool-call\n // for an id opencode already completed. That second part never\n // gets a result, opencode aborts it at stream end, and a\n // subagent's `task` call reports \"Tool execution aborted\"\n // even though the child answered correctly.\n toolCallMap.delete(idx)\n let parsedInput: any = {}\n try {\n parsedInput = JSON.parse(tc.inputJson || \"{}\")\n } catch {}\n\n if (isAskUserQuestionTool(tc.name)) {\n // Latch: the model handed control to the operator. Block any\n // auto-continue nudge for the rest of the turn so it can't\n // proceed on its own before the operator replies.\n autoContinueState.sawAskUserQuestion = true\n const askId = startTextBlock()\n controller.enqueue({\n type: \"text-delta\",\n id: askId,\n delta: formatAskUserQuestion(parsedInput),\n })\n endTextBlock()\n } else if (tc.name === \"ExitPlanMode\") {\n const plan = (parsedInput?.plan as string) || \"\"\n\n if (planModeQuestionActive) {\n // Approval bridge: render the plan, then hand the\n // yes/no back to opencode's own `question` tool and end\n // the turn on \"tool-calls\" so the outer loop runs it.\n const questionCall = createExitPlanModeQuestionCall(\n sk,\n tc.id,\n plan,\n )\n const planId = startTextBlock()\n controller.enqueue({\n type: \"text-delta\",\n id: planId,\n delta: questionCall.text,\n })\n finishWithExitPlanQuestion(questionCall)\n return\n }\n\n const planId = startTextBlock()\n controller.enqueue({\n type: \"text-delta\",\n id: planId,\n delta: `\\n\\n${plan}\\n\\n---\\n**Do you want to proceed with this plan?** (yes/no)\\n`,\n })\n endTextBlock()\n } else if (\n isWebSearchTool(tc.name) &&\n isWebSearchHandledByCli(self.config.webSearch)\n ) {\n // Claude CLI runs WebSearch internally. Forwarding the\n // \"WebSearch\" tool-call part would render an invalid tool\n // row in opencode (no registry entry), so show the query\n // as a text line instead. The result stays CLI-internal.\n const query =\n typeof parsedInput?.query === \"string\"\n ? parsedInput.query\n : JSON.stringify(parsedInput)\n const searchId = startTextBlock()\n controller.enqueue({\n type: \"text-delta\",\n id: searchId,\n delta: `\\n> **Web search:** ${query}\\n`,\n })\n endTextBlock()\n } else if (tc.name.startsWith(PROXY_TOOL_PREFIX)) {\n noteProxyActivity()\n log.debug(\"ignoring proxy tool_use block; broker handles it\", {\n name: tc.name,\n id: tc.id,\n })\n } else {\n const {\n name: mappedName,\n input: mappedInput,\n executed,\n skip,\n } = mapTool(tc.name, parsedInput, {\n webSearch: self.config.webSearch,\n sessionId: getClaudeSessionId(sk),\n toolUseId: tc.id,\n })\n\n if (!skip) {\n toolCallsById.set(tc.id, {\n id: tc.id,\n name: tc.name,\n input: parsedInput,\n })\n if (!executed) skipResultForIds.add(tc.id)\n\n controller.enqueue({\n type: \"tool-call\",\n toolCallId: tc.id,\n toolName: mappedName,\n input: JSON.stringify(mappedInput),\n providerExecuted: executed,\n } as any)\n }\n log.info(\"tool call complete\", {\n name: tc.name,\n mappedName,\n id: tc.id,\n executed,\n })\n }\n }\n }\n\n // Capture protocol-level stop_reason from the streaming\n // `message_delta` event (sent right before the final\n // `message_stop`). Any non-empty value is the source-of-truth\n // for why the turn ended — used to bypass the keyword heuristic.\n if (\n gotPartialEvents &&\n msg.type === \"message_delta\" &&\n typeof (msg as any).delta?.stop_reason === \"string\"\n ) {\n lastStopReason = (msg as any).delta.stop_reason\n }\n\n // assistant message (complete, not streaming).\n // When --include-partial-messages is on, this is a duplicate of\n // what we already streamed via content_block_* events. Skip it\n // for content, but still capture stop_reason from it for the\n // non-partial path.\n if (\n msg.type === \"assistant\" &&\n msg.message &&\n typeof (msg.message as any).stop_reason === \"string\"\n ) {\n lastStopReason = (msg.message as any).stop_reason\n }\n // Fallback: extract thinking from the complete assistant\n // message. opus-4-7's CLI strips thinking_delta from stream\n // events but may include thinking in the final message.\n if (\n msg.type === \"assistant\" &&\n msg.message?.content &&\n gotPartialEvents\n ) {\n const thinkingBlocks = (msg.message.content as any[]).filter(\n (b) => b.type === \"thinking\",\n )\n if (thinkingBlocks.length > 0) {\n log.info(\"assistant message thinking blocks\", {\n count: thinkingBlocks.length,\n hasText: thinkingBlocks.some(\n (b) => typeof b.thinking === \"string\" && b.thinking.length > 0,\n ),\n hadStreamThinking: hadThinkingTextFromStream,\n })\n if (!hadThinkingTextFromStream) {\n for (const block of thinkingBlocks) {\n if (block.thinking && block.thinking.length > 0) {\n noteReasoning()\n hadThinkingTextFromStream = true\n const thinkingId = generateId()\n controller.enqueue({\n type: \"reasoning-start\",\n id: thinkingId,\n } as any)\n controller.enqueue({\n type: \"reasoning-delta\",\n id: thinkingId,\n delta: block.thinking,\n } as any)\n controller.enqueue({\n type: \"reasoning-end\",\n id: thinkingId,\n } as any)\n }\n }\n }\n }\n }\n if (\n msg.type === \"assistant\" &&\n msg.message?.content &&\n !gotPartialEvents\n ) {\n const hasText = msg.message.content.some(\n (b: any) => b.type === \"text\" && b.text,\n )\n const hasToolUse = msg.message.content.some(\n (b: any) => b.type === \"tool_use\",\n )\n\n if (hasText) {\n hasReceivedContent = true\n }\n\n if (hasText && !hasToolUse) {\n startResultFallback()\n }\n if (hasToolUse) {\n clearFallbackTimer()\n }\n\n for (const block of msg.message.content) {\n if (block.type === \"text\" && block.text) {\n // New text block — keep only this block's text in the\n // last-block buffer for final-answer detection.\n resetLastVisibleTextBlock()\n const blockId = startTextBlock()\n controller.enqueue({\n type: \"text-delta\",\n id: blockId,\n delta: block.text,\n })\n endTextBlock()\n noteVisibleText(block.text)\n hasReceivedContent = true\n }\n\n if (block.type === \"thinking\" && block.thinking) {\n noteReasoning()\n const thinkingId = generateId()\n controller.enqueue({\n type: \"reasoning-start\",\n id: thinkingId,\n } as any)\n controller.enqueue({\n type: \"reasoning-delta\",\n id: thinkingId,\n delta: block.thinking,\n } as any)\n controller.enqueue({\n type: \"reasoning-end\",\n id: thinkingId,\n } as any)\n }\n\n if (block.type === \"tool_use\" && block.id && block.name) {\n noteToolActivity()\n const parsedInput = (block.input ?? {}) as Record<\n string,\n unknown\n >\n\n if (isAskUserQuestionTool(block.name)) {\n const askId = startTextBlock()\n controller.enqueue({\n type: \"text-delta\",\n id: askId,\n delta: formatAskUserQuestion(parsedInput),\n })\n endTextBlock()\n } else if (block.name === \"ExitPlanMode\") {\n const plan = (parsedInput?.plan as string) || \"\"\n\n if (planModeQuestionActive) {\n const questionCall = createExitPlanModeQuestionCall(\n sk,\n block.id,\n plan,\n )\n const planId = startTextBlock()\n controller.enqueue({\n type: \"text-delta\",\n id: planId,\n delta: questionCall.text,\n })\n finishWithExitPlanQuestion(questionCall)\n return\n }\n\n const planId = startTextBlock()\n controller.enqueue({\n type: \"text-delta\",\n id: planId,\n delta: `\\n\\n${plan}\\n\\n---\\n**Do you want to proceed with this plan?** (yes/no)\\n`,\n })\n endTextBlock()\n } else if (\n isWebSearchTool(block.name) &&\n isWebSearchHandledByCli(self.config.webSearch)\n ) {\n // CLI-internal WebSearch: render the query as text and\n // drop the call/result parts (no opencode registry entry\n // for \"WebSearch\" — would render as an invalid tool row).\n toolCallsById.delete(block.id)\n const query =\n typeof parsedInput?.query === \"string\"\n ? parsedInput.query\n : JSON.stringify(parsedInput)\n const searchId = startTextBlock()\n controller.enqueue({\n type: \"text-delta\",\n id: searchId,\n delta: `\\n> **Web search:** ${query}\\n`,\n })\n endTextBlock()\n } else if (block.name.startsWith(PROXY_TOOL_PREFIX)) {\n noteProxyActivity()\n log.debug(\"ignoring proxy tool_use from assistant message\", {\n name: block.name,\n id: block.id,\n })\n } else {\n const {\n name: mappedName,\n input: mappedInput,\n executed,\n skip,\n } = mapTool(block.name, parsedInput, {\n webSearch: self.config.webSearch,\n sessionId: getClaudeSessionId(sk),\n toolUseId: block.id,\n })\n\n if (!skip) {\n toolCallsById.set(block.id, {\n id: block.id,\n name: block.name,\n input: parsedInput,\n })\n if (!executed) skipResultForIds.add(block.id)\n controller.enqueue({\n type: \"tool-input-start\",\n id: block.id,\n toolName: mappedName,\n providerExecuted: executed,\n } as any)\n controller.enqueue({\n type: \"tool-call\",\n toolCallId: block.id,\n toolName: mappedName,\n input: JSON.stringify(mappedInput),\n providerExecuted: executed,\n } as any)\n }\n log.info(\"tool_use from assistant message\", {\n name: block.name,\n mappedName,\n id: block.id,\n executed,\n })\n }\n }\n\n if (block.type === \"tool_result\") {\n log.debug(\"tool_result\", {\n toolUseId: block.tool_use_id,\n })\n }\n }\n }\n\n // user message (tool results from Claude CLI)\n if (msg.type === \"user\" && msg.message?.content) {\n for (const block of msg.message.content) {\n if (block.type === \"tool_result\" && block.tool_use_id) {\n if (skipResultForIds.has(block.tool_use_id)) {\n log.debug(\"skipping tool-result (opencode runs it)\", {\n toolUseId: block.tool_use_id,\n })\n continue\n }\n\n let resultText = \"\"\n if (typeof block.content === \"string\") {\n resultText = block.content\n } else if (Array.isArray(block.content)) {\n resultText = block.content\n .filter(\n (\n c,\n ): c is { type: string; text: string } =>\n c.type === \"text\" &&\n typeof c.text === \"string\",\n )\n .map((c) => c.text)\n .join(\"\\n\")\n }\n\n // Ledger hook: commit pending TaskCreate to opencode's todo\n // panel via a synthetic todowrite emission. Pass-through —\n // returns null for non-TaskCreate ids, so cheap and silent.\n const claudeSessionId = getClaudeSessionId(sk)\n if (claudeSessionId) {\n const list = applyTaskCreateToolResult(\n claudeSessionId,\n block.tool_use_id,\n resultText,\n )\n if (list) {\n const synthId = `todowrite_${block.tool_use_id}`\n controller.enqueue({\n type: \"tool-input-start\",\n id: synthId,\n toolName: \"todowrite\",\n providerExecuted: false,\n } as any)\n controller.enqueue({\n type: \"tool-call\",\n toolCallId: synthId,\n toolName: \"todowrite\",\n input: JSON.stringify({\n todos: list.map((t) => ({\n id: t.id,\n content: t.content,\n status: t.status,\n priority: \"medium\",\n })),\n }),\n providerExecuted: false,\n } as any)\n noteToolActivity()\n }\n }\n\n const toolCall = toolCallsById.get(block.tool_use_id)\n if (toolCall) {\n controller.enqueue({\n type: \"tool-result\",\n toolCallId: block.tool_use_id,\n toolName: toolCall.name,\n result: {\n output: resultText,\n title: toolCall.name,\n metadata: {},\n },\n providerExecuted: true,\n } as any)\n noteToolActivity()\n log.info(\"tool result emitted\", {\n toolUseId: block.tool_use_id,\n name: toolCall.name,\n })\n toolCallsById.delete(block.tool_use_id)\n }\n }\n }\n }\n\n // result - end of conversation turn\n if (msg.type === \"result\") {\n clearFallbackTimer()\n\n if (msg.session_id) {\n setClaudeSessionId(sk, msg.session_id)\n }\n\n if (deliverPendingCompletions()) {\n // Finish the abandoned turn before submitting its late result.\n // Otherwise this result could close the stream for the new turn.\n return\n }\n\n // Some CLI failures only include user-readable text in\n // `result.result` (no prior assistant text blocks). Emit it so\n // opencode users don't see a blank turn.\n if (\n !currentTextId &&\n msg.is_error &&\n typeof msg.result === \"string\" &&\n msg.result.trim().length > 0\n ) {\n const errId = startTextBlock()\n controller.enqueue({\n type: \"text-delta\",\n id: errId,\n delta: msg.result,\n })\n }\n\n resultMeta = {\n sessionId: msg.session_id,\n costUsd: msg.total_cost_usd,\n durationMs: msg.duration_ms,\n usage: msg.usage,\n }\n\n log.info(\"conversation result\", {\n sessionId: msg.session_id,\n durationMs: msg.duration_ms,\n numTurns: msg.num_turns,\n isError: msg.is_error,\n })\n\n turnCompleted = true\n\n endTextBlock()\n\n const shouldDeferResult =\n !msg.is_error &&\n !autoContinueState.aborted &&\n !autoContinueState.sawAskUserQuestion\n\n if (drainBuffer.length > 0 && shouldDeferResult) {\n log.info(\n \"waiting for parallel proxy calls at turn-result boundary\",\n {\n sessionKey: sk,\n count: drainBuffer.length,\n },\n )\n scheduleResultBoundary(\n () => completeResult(msg),\n DRAIN_QUIET_MS,\n )\n return\n }\n\n if (\n drainBuffer.length === 0 &&\n hadProxyActivitySinceContinue &&\n shouldDeferResult\n ) {\n log.info(\n \"waiting for delayed proxy call at turn-result boundary\",\n {\n sessionKey: sk,\n graceMs: PROXY_RESULT_BOUNDARY_GRACE_MS,\n },\n )\n scheduleResultBoundary(\n () => completeResult(msg),\n PROXY_RESULT_BOUNDARY_GRACE_MS,\n )\n return\n }\n\n completeResult(msg)\n }\n } catch (e) {\n log.debug(\"failed to parse line\", {\n error:\n e instanceof Error ? e.message : String(e),\n })\n }\n }\n\n const closeHandler = () => {\n log.debug(\"readline closed\")\n if (controllerClosed) return\n // Claude CLI's stdio is gone. The proxy-mcp HTTP requests that\n // backed any pending tool calls have no one to answer them now —\n // reject so the handlers return errors rather than hang.\n if (drainBuffer.length > 0 || getPendingProxyCalls(sk).length > 0) {\n rejectAllPendingProxyCallsForSession(\n sk,\n new Error(\n \"Claude CLI subprocess closed before pending tool calls were resolved\",\n ),\n )\n drainBuffer.length = 0\n }\n controllerClosed = true\n cleanupTurn()\n endTextBlock()\n controller.enqueue({\n type: \"finish\",\n finishReason: toFinishReason(\"stop\"),\n usage: toUsage(),\n providerMetadata: {\n \"claude-code\": {\n ...resultMeta,\n ...(compactionMode\n ? { compactionModel: effectiveModelId }\n : {}),\n },\n },\n })\n try {\n controller.close()\n } catch {}\n }\n\n // Centralised per-turn teardown. Every exit path funnels through here\n // so we don't accumulate listeners across turns on a reused process.\n let cleanedUp = false\n const cleanupTurn = () => {\n if (cleanedUp) return\n cleanedUp = true\n clearFallbackTimer()\n pendingResultCompletion = null\n clearStartWatchdog()\n if (drainTimer) {\n clearTimeout(drainTimer)\n drainTimer = null\n }\n lineEmitter.off(\"line\", lineHandler)\n lineEmitter.off(\"close\", closeHandler)\n pendingProxyUnsubscribe?.()\n pendingProxyUnsubscribe = null\n asideSinkUnregister?.()\n asideSinkUnregister = null\n proc.off(\"error\", procErrorHandler)\n }\n\n const procErrorHandler = (err: Error) => {\n log.error(\"process error\", { error: err.message })\n deleteActiveProcess(sk)\n deleteClaudeSessionId(sk)\n if (controllerClosed) return\n // Subprocess failure invalidates every pending HTTP-bound tool\n // call for this session. Reject them so proxy-mcp returns errors\n // to Claude rather than letting the sockets stall.\n if (drainBuffer.length > 0 || getPendingProxyCalls(sk).length > 0) {\n rejectAllPendingProxyCallsForSession(\n sk,\n new Error(\n `Claude CLI subprocess error: ${err.message}`,\n ),\n )\n drainBuffer.length = 0\n }\n controllerClosed = true\n cleanupTurn()\n controller.enqueue({ type: \"error\", error: err })\n try {\n controller.close()\n } catch {}\n }\n\n // Whatever the child said while no turn was listening comes first:\n // the operator gets to see it, and a turn that already ended on the\n // CLI's side is known before this one decides what to send.\n if (activeProcess) {\n const unattended = takeUnattendedLines(activeProcess)\n if (unattended.lines.length > 0 || unattended.dropped > 0) {\n log.notice(\"replaying stdout the child emitted between turns\", {\n sessionKey: sk,\n lines: unattended.lines.length,\n dropped: unattended.dropped,\n })\n // Render narration only. Replaying actionable events could execute\n // old tools or close this new stream on a stale approval/result.\n let partialText = false\n {\n if (unattended.dropped > 0) {\n const id = startTextBlock()\n controller.enqueue({\n type: \"text-delta\",\n id,\n delta: `> _${unattended.dropped} lines of output emitted between turns were dropped._\\n\\n`,\n })\n }\n for (const line of unattended.lines) {\n try {\n const outer: ClaudeStreamMessage = JSON.parse(line)\n const msg = outer.type === \"stream_event\" && outer.event ? outer.event : outer\n let text = \"\"\n if (msg.type === \"content_block_delta\" && msg.delta?.type === \"text_delta\") {\n text = msg.delta.text ?? \"\"\n partialText = true\n } else if (msg.type === \"assistant\") {\n if (!partialText) text = (msg.message?.content ?? []).filter((part) => part.type === \"text\").map((part) => part.text ?? \"\").join(\"\")\n partialText = false\n } else if (msg.type === \"result\") {\n unattendedTurnEnded = true\n for (const entry of activeProcess.pendingProxyCompletions?.values() ?? []) {\n if (isPendingProxyCallChannelClosed(entry.call)) entry.recoveryRequired = true\n }\n if (outer.session_id) setClaudeSessionId(sk, outer.session_id)\n if (msg.is_error && msg.result) text = msg.result\n }\n if (text) controller.enqueue({ type: \"text-delta\", id: startTextBlock(), delta: text })\n } catch { /* Ignore incomplete or malformed buffered lines. */ }\n }\n }\n endTextBlock()\n // Replayed lines are history, not liveness: the watchdogs below\n // must judge the child on what it does from here on.\n clearFallbackTimer()\n hasReceivedContent = false\n }\n }\n\n if (activeProcess && !compactionMode) {\n activeProcess.opencodeSessionID = affinity\n activeProcess.asideTransport = asideTransportRef\n }\n if (!compactionMode) {\n // Lets a `/btw` answered while this turn runs land in the turn's own\n // reply instead of a toast (btw-command.ts). Its own text block, so\n // the marker stays at the start of a part and the block can be\n // stripped exactly when a transcript is rebuilt.\n asideSinkUnregister = registerAsideSink(affinity, (text) => {\n if (controllerClosed) return false\n const asideId = startTextBlock()\n controller.enqueue({ type: \"text-delta\", id: asideId, delta: text })\n endTextBlock()\n return true\n })\n }\n lineEmitter.on(\"line\", lineHandler)\n lineEmitter.on(\"close\", closeHandler)\n\n pendingProxyUnsubscribe = onPendingProxyCall(sk, (call) => {\n if (controllerClosed) {\n // Stream already closed (we already drained). Late arrival —\n // reject immediately so the proxy-mcp HTTP request returns\n // instead of hanging until its 10-min timeout.\n log.warn(\n \"pending proxy call arrived after stream close; rejecting\",\n {\n sessionKey: sk,\n toolCallId: call.toolCallId,\n toolName: call.toolName,\n },\n )\n rejectPendingProxyCallById(\n call.toolCallId,\n new Error(\n `Pending proxy call '${call.toolName}' arrived after the stream was already closed`,\n ),\n )\n return\n }\n log.info(\"received pending proxy call for session\", {\n sessionKey: sk,\n toolCallId: call.toolCallId,\n toolName: call.toolName,\n })\n noteProxyActivity()\n noteToolActivity()\n drainBuffer.push(call)\n if (noteResultBoundaryCall()) return\n if (drainTimer) clearTimeout(drainTimer)\n drainTimer = setTimeout(drainNow, DRAIN_QUIET_MS)\n })\n\n proc.on(\"error\", procErrorHandler)\n\n // On abort, keep process alive for next message\n if (options.abortSignal) {\n options.abortSignal.addEventListener(\"abort\", () => {\n autoContinueState.aborted = true\n if (turnCompleted || controllerClosed) return\n\n // Stop the CLI's turn, not just our end of the stream: it would\n // otherwise run the abandoned turn to completion, billing tokens\n // and executing tools, with its late output landing in the next\n // turn. The process itself stays alive for the next message.\n if (activeProcess) {\n void interruptTurn(activeProcess).then((idle) => {\n log.info(\"interrupt sent for aborted turn\", { sk, idle })\n })\n }\n\n if (!hasReceivedContent) {\n log.info(\n \"abort signal received before content, closing stream immediately\",\n { cwd },\n )\n if (\n drainBuffer.length > 0 ||\n getPendingProxyCalls(sk).length > 0\n ) {\n rejectAllPendingProxyCallsForSession(\n sk,\n new Error(\n \"Provider stream was aborted before pending proxy calls were emitted\",\n ),\n )\n drainBuffer.length = 0\n }\n controllerClosed = true\n cleanupTurn()\n try {\n controller.close()\n } catch {}\n return\n }\n\n log.info(\n \"abort signal received mid-turn, starting grace period\",\n { cwd },\n )\n // Abort grace period — short, since the user already asked to stop.\n startResultFallback(5_000)\n })\n }\n\n if (hasMatchedPendingResults) {\n // Tool-result turn: the prompt carries opencode's results for the\n // proxy tool calls we drained on the previous turn. Resolve each\n // matched call (claude CLI's HTTP handlers wake up and continue).\n // Parallel tools may complete in separate opencode turns. Keep\n // unmatched siblings pending until their own result, an explicit\n // abort/new user turn, or the proxy deadline.\n for (const { call, result } of previousPendingProxyMatches) {\n if (result) {\n const channelClosed = isPendingProxyCallChannelClosed(call)\n log.info(\"resolving pending proxy call from tool result prompt\", {\n sessionKey: sk,\n toolCallId: call.toolCallId,\n toolName: call.toolName,\n channelClosed,\n })\n const completions = (activeProcess!.pendingProxyCompletions ??= new Map())\n if (!completions.has(call.toolCallId)) {\n completions.set(call.toolCallId, {\n call,\n result,\n recoveryRequired: channelClosed || unattendedTurnEnded,\n })\n }\n // With a closed channel this only clears the broker entry;\n // proxy-mcp drops the write and the result travels below.\n resolvePendingProxyCallById(call.toolCallId, result)\n } else {\n log.info(\n \"leaving unmatched parallel proxy call pending\",\n {\n sessionKey: sk,\n toolCallId: call.toolCallId,\n toolName: call.toolName,\n },\n )\n }\n }\n\n if (unattendedTurnEnded) deliverPendingCompletions()\n\n // Calls queued while no turn was attached were never handed to\n // opencode; the child is blocked on them right now.\n const unemitted = getPendingProxyCalls(sk).filter(\n (call) => !call.emitted,\n )\n if (unemitted.length > 0) {\n log.notice(\"draining proxy calls queued between turns\", {\n sessionKey: sk,\n toolCallIds: unemitted.map((call) => call.toolCallId),\n })\n drainBuffer.push(...unemitted)\n drainNow()\n return\n }\n\n if (getPendingProxyCalls(sk).length === 0) {\n armStartWatchdog()\n }\n return\n }\n\n // No pending calls had matching tool-results. If any pending calls\n // are still hanging around from a prior turn, reject them so the\n // HTTP handlers in proxy-mcp don't sit blocked forever while we\n // proceed with a brand new user message.\n if (previousPendingProxyCalls.length > 0) {\n for (const call of previousPendingProxyCalls) {\n rejectPendingProxyCallById(\n call.toolCallId,\n new Error(\n `Pending proxy call '${call.toolName}' (${call.toolCallId}) was orphaned by a new user turn; rejecting`,\n ),\n )\n }\n }\n\n // Send the user message for a fresh turn.\n if (activeProcess) noteTurnStarted(activeProcess)\n proc.stdin?.write(userMsg + \"\\n\")\n log.debug(\"sent user message\", { textLength: userMsg.length })\n // Arm the start watchdog so a reused child that goes silent after\n // the envelope write (seen after a long proxy-blocked tool call)\n // is respawned with --session-id instead of hanging the turn.\n armStartWatchdog()\n }\n\n void setup().catch((err) => {\n log.error(\"failed to set up doStream\", {\n error: err instanceof Error ? err.message : String(err),\n })\n controller.enqueue({\n type: \"error\",\n error: err instanceof Error ? err : new Error(String(err)),\n })\n try {\n controller.close()\n } catch {}\n })\n },\n cancel() {\n // Consumer cancelled the stream\n },\n })\n\n return {\n stream,\n request: { body: { text: userMsg } },\n response: { headers: {} },\n }\n }\n}\n","import { appendFileSync, mkdirSync, renameSync, statSync } from \"node:fs\"\nimport { homedir } from \"node:os\"\nimport { dirname, join } from \"node:path\"\n\nexport type LogLevel = \"debug\" | \"info\" | \"notice\" | \"warn\" | \"error\"\nexport type LogMode = \"silent\" | \"debug\"\n\nexport interface LoggerConfig {\n file: boolean\n dir: string | null\n mode: LogMode\n level: LogLevel\n}\n\nconst LEVEL_RANK: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n notice: 2,\n warn: 3,\n error: 4,\n}\n\nconst MAX_LOG_BYTES = 5 * 1024 * 1024 // 5 MB\nconst DEFAULT_DIR = join(homedir(), \".local\", \"share\", \"opencode-claude-code\")\n\nconst DEFAULT_CONFIG: LoggerConfig = {\n file: false,\n dir: null,\n mode: \"silent\",\n level: \"info\",\n}\n\nfunction parseBoolEnv(v: string | undefined): boolean | undefined {\n if (v == null) return undefined\n const s = v.toLowerCase().trim()\n if (s === \"\") return undefined\n if (s === \"0\" || s === \"false\" || s === \"no\" || s === \"off\") return false\n return true\n}\n\nfunction parseLevelEnv(v: string | undefined): LogLevel | undefined {\n if (v == null) return undefined\n const s = v.toLowerCase().trim()\n if (s === \"\") return undefined\n if (s === \"debug\" || s === \"info\" || s === \"notice\" || s === \"warn\" || s === \"error\") {\n return s\n }\n return undefined\n}\n\nfunction parseModeFromDebugEnv(v: string | undefined): LogMode | undefined {\n if (v == null || v === \"\") return undefined\n return v.includes(\"opencode-claude-code\") ? \"debug\" : undefined\n}\n\nfunction withEnvOverrides(base: LoggerConfig): LoggerConfig {\n const result: LoggerConfig = { ...base }\n const envFile = parseBoolEnv(process.env.OPENCODE_CLAUDE_CODE_LOG_FILE)\n if (envFile !== undefined) result.file = envFile\n const envDir = process.env.OPENCODE_CLAUDE_CODE_LOG_DIR\n if (envDir !== undefined && envDir !== \"\") result.dir = envDir\n const envMode = parseModeFromDebugEnv(process.env.DEBUG)\n if (envMode !== undefined) result.mode = envMode\n const envLevel = parseLevelEnv(process.env.OPENCODE_CLAUDE_CODE_LOG_LEVEL)\n if (envLevel !== undefined) result.level = envLevel\n return result\n}\n\nlet activeConfig: LoggerConfig = withEnvOverrides(DEFAULT_CONFIG)\nlet fileLoggingDisabled = false\n\n/**\n * Configure the logger from plugin settings. Env vars override the supplied\n * config when explicitly set, so a developer can flip behavior for a single\n * process without editing opencode.jsonc.\n *\n * `OPENCODE_CLAUDE_CODE_LOG_FILE` → `file` (1/true/on/yes vs 0/false/no/off)\n * `OPENCODE_CLAUDE_CODE_LOG_DIR` → `dir`\n * `DEBUG=opencode-claude-code` → `mode: \"debug\"`\n * `OPENCODE_CLAUDE_CODE_LOG_LEVEL` → `level` (debug | info | notice | warn | error)\n */\nexport function configureLogger(input: Partial<LoggerConfig>): void {\n const merged: LoggerConfig = { ...DEFAULT_CONFIG, ...input }\n activeConfig = withEnvOverrides(merged)\n fileLoggingDisabled = false\n}\n\nexport function getLoggerConfig(): LoggerConfig {\n return { ...activeConfig }\n}\n\n/** Test-only helper. Resets to defaults+env so tests are deterministic. */\nexport function _resetLoggerForTests(): void {\n activeConfig = withEnvOverrides(DEFAULT_CONFIG)\n fileLoggingDisabled = false\n}\n\nfunction resolvedLogFile(): string {\n return join(activeConfig.dir ?? DEFAULT_DIR, \"plugin.log\")\n}\n\nfunction rotateIfNeeded(logFile: string): void {\n try {\n const stat = statSync(logFile)\n if (stat.size > MAX_LOG_BYTES) {\n renameSync(logFile, `${logFile}.1`)\n }\n } catch {\n // file does not exist yet — nothing to rotate\n }\n}\n\nfunction writeToFile(line: string): void {\n if (!activeConfig.file) return\n if (fileLoggingDisabled) return\n try {\n const logFile = resolvedLogFile()\n mkdirSync(dirname(logFile), { recursive: true })\n rotateIfNeeded(logFile)\n appendFileSync(logFile, line + \"\\n\", \"utf8\")\n } catch {\n // Disable on first failure to avoid spamming errors on a read-only FS.\n fileLoggingDisabled = true\n }\n}\n\nfunction fmt(level: string, msg: string, data?: Record<string, unknown>): string {\n const ts = new Date().toISOString()\n const base = `[${ts}] [opencode-claude-code] ${level}: ${msg}`\n if (data && Object.keys(data).length > 0) {\n return `${base} ${JSON.stringify(data)}`\n }\n return base\n}\n\nfunction shouldEmit(level: LogLevel): boolean {\n return LEVEL_RANK[level] >= LEVEL_RANK[activeConfig.level]\n}\n\nfunction shouldTui(level: LogLevel): boolean {\n // warn/error are alwaysStderr: a developer who passes the level threshold\n // should still see real problems in the TUI regardless of mode. Below-\n // threshold entries are filtered earlier by shouldEmit().\n if (level === \"warn\" || level === \"error\") return true\n return activeConfig.mode === \"debug\"\n}\n\nfunction emit(level: LogLevel, msg: string, data?: Record<string, unknown>): void {\n if (!shouldEmit(level)) return\n const line = fmt(level.toUpperCase(), msg, data)\n if (shouldTui(level)) {\n console.error(line)\n }\n writeToFile(line)\n}\n\nexport const log = {\n debug(msg: string, data?: Record<string, unknown>) {\n emit(\"debug\", msg, data)\n },\n info(msg: string, data?: Record<string, unknown>) {\n emit(\"info\", msg, data)\n },\n notice(msg: string, data?: Record<string, unknown>) {\n emit(\"notice\", msg, data)\n },\n warn(msg: string, data?: Record<string, unknown>) {\n emit(\"warn\", msg, data)\n },\n error(msg: string, data?: Record<string, unknown>) {\n emit(\"error\", msg, data)\n },\n}\n","import { log } from \"./logger.js\"\n\nexport type TodoStatus = \"pending\" | \"in_progress\" | \"completed\"\n\nexport interface TodoEntry {\n id: string\n content: string\n status: TodoStatus\n}\n\ninterface PendingCreate {\n subject: string\n createdAt: number\n}\n\ninterface SessionLedger {\n todos: Map<string, TodoEntry>\n pendingCreates: Map<string, PendingCreate>\n}\n\nconst ledgers = new Map<string, SessionLedger>()\n\nconst PENDING_CREATE_TTL_MS = 60_000\nconst TASK_CREATED_PATTERN = /Task\\s*#?\\s*(\\d+)\\s+created/i\nconst VALID_STATUSES: ReadonlySet<TodoStatus> = new Set([\"pending\", \"in_progress\", \"completed\"])\n\nfunction getOrCreate(sessionId: string): SessionLedger {\n let ledger = ledgers.get(sessionId)\n if (!ledger) {\n ledger = { todos: new Map(), pendingCreates: new Map() }\n ledgers.set(sessionId, ledger)\n }\n return ledger\n}\n\nfunction prunePending(ledger: SessionLedger): void {\n const cutoff = Date.now() - PENDING_CREATE_TTL_MS\n for (const [id, pending] of ledger.pendingCreates) {\n if (pending.createdAt < cutoff) ledger.pendingCreates.delete(id)\n }\n}\n\nfunction materialize(ledger: SessionLedger): TodoEntry[] {\n return Array.from(ledger.todos.values())\n}\n\nfunction resolveSubject(input: { subject?: unknown; description?: unknown } | undefined): string {\n const subject = typeof input?.subject === \"string\" ? input.subject.trim() : \"\"\n if (subject) return subject\n const description = typeof input?.description === \"string\" ? input.description.trim() : \"\"\n if (description) return description\n return \"(no subject)\"\n}\n\nexport function applyTaskCreateToolUse(\n sessionId: string,\n toolUseId: string,\n input: { subject?: unknown; description?: unknown } | undefined,\n): void {\n if (!sessionId || !toolUseId) return\n const ledger = getOrCreate(sessionId)\n prunePending(ledger)\n ledger.pendingCreates.set(toolUseId, {\n subject: resolveSubject(input),\n createdAt: Date.now(),\n })\n}\n\nexport function applyTaskCreateToolResult(\n sessionId: string,\n toolUseId: string,\n resultText: string,\n): TodoEntry[] | null {\n if (!sessionId || !toolUseId) return null\n const ledger = ledgers.get(sessionId)\n if (!ledger) return null\n const pending = ledger.pendingCreates.get(toolUseId)\n if (!pending) return null\n ledger.pendingCreates.delete(toolUseId)\n const match = typeof resultText === \"string\" ? resultText.match(TASK_CREATED_PATTERN) : null\n if (!match) {\n log.debug(\"TaskCreate result did not match expected format\", { sessionId, toolUseId, resultText })\n return null\n }\n const claudeId = match[1]\n if (ledger.todos.has(claudeId)) {\n log.debug(\"TaskCreate result for already-known claude id; overwriting\", { sessionId, claudeId })\n }\n ledger.todos.set(claudeId, { id: claudeId, content: pending.subject, status: \"pending\" })\n return materialize(ledger)\n}\n\nexport function applyTaskUpdate(\n sessionId: string,\n input: { taskId?: unknown; subject?: unknown; status?: unknown } | undefined,\n): TodoEntry[] | null {\n if (!sessionId) return null\n const taskId = typeof input?.taskId === \"string\" ? input.taskId : null\n if (!taskId) return null\n const ledger = ledgers.get(sessionId)\n if (!ledger) return null\n const entry = ledger.todos.get(taskId)\n if (!entry) {\n log.debug(\"TaskUpdate for unknown task id\", { sessionId, taskId })\n return null\n }\n if (input?.status === \"deleted\") {\n ledger.todos.delete(taskId)\n return materialize(ledger)\n }\n if (typeof input?.status === \"string\" && VALID_STATUSES.has(input.status as TodoStatus)) {\n entry.status = input.status as TodoStatus\n }\n if (typeof input?.subject === \"string\" && input.subject.trim().length > 0) {\n entry.content = input.subject.trim()\n }\n return materialize(ledger)\n}\n\nexport function clearLedger(sessionId: string): void {\n if (!sessionId) return\n ledgers.delete(sessionId)\n}\n\nexport function getLedger(sessionId: string): TodoEntry[] {\n const ledger = ledgers.get(sessionId)\n if (!ledger) return []\n return materialize(ledger)\n}\n\nexport function _resetAllLedgersForTests(): void {\n ledgers.clear()\n}\n","import { log } from \"./logger.js\"\nimport { applyTaskCreateToolUse, applyTaskUpdate, type TodoEntry } from \"./todo-ledger.js\"\nimport type { WebSearchRouting } from \"./types.js\"\n\nexport interface MapToolOptions {\n webSearch?: WebSearchRouting\n sessionId?: string\n toolUseId?: string\n}\n\n/** Claude CLI's built-in web search tool (name varies by CLI version). */\nexport function isWebSearchTool(name: string): boolean {\n return name === \"WebSearch\" || name === \"web_search\"\n}\n\n/**\n * True when WebSearch runs inside Claude CLI (default) rather than being\n * forwarded to an opencode tool. In that case the tool-call part must not\n * reach opencode — \"WebSearch\" has no registry entry there and renders as\n * an invalid tool row. Callers show the query as a text line instead.\n */\nexport function isWebSearchHandledByCli(route?: WebSearchRouting): boolean {\n return !route || route === \"claude\" || route === \"disabled\"\n}\n\n/**\n * Map Claude CLI tool input (snake_case) to OpenCode tool input (camelCase)\n */\nfunction mapToolInput(name: string, input: any): any {\n if (!input) return input\n\n switch (name) {\n case \"Write\":\n return {\n filePath: input.file_path ?? input.filePath,\n content: input.content,\n }\n case \"Edit\":\n return {\n filePath: input.file_path ?? input.filePath,\n oldString: input.old_string ?? input.oldString,\n newString: input.new_string ?? input.newString,\n replaceAll: input.replace_all ?? input.replaceAll,\n }\n case \"Read\":\n return {\n filePath: input.file_path ?? input.filePath,\n offset: input.offset,\n limit: input.limit,\n }\n case \"Bash\":\n return {\n command: input.command,\n description:\n input.description ||\n `Execute: ${String(input.command || \"\").slice(0, 50)}${String(input.command || \"\").length > 50 ? \"...\" : \"\"}`,\n timeout: input.timeout,\n }\n case \"NotebookEdit\":\n return {\n notebookPath: input.notebook_path ?? input.notebookPath,\n cellNumber: input.cell_number ?? input.cellNumber,\n newSource: input.new_source ?? input.newSource,\n cellType: input.cell_type ?? input.cellType,\n editMode: input.edit_mode ?? input.editMode,\n }\n case \"Glob\":\n return {\n pattern: input.pattern,\n path: input.path,\n }\n case \"Grep\":\n return {\n pattern: input.pattern,\n path: input.path,\n include: input.include,\n }\n case \"TodoWrite\":\n if (Array.isArray(input.todos)) {\n const mappedTodos = input.todos.map((todo: any, index: number) => ({\n content: todo.content,\n status: todo.status || \"pending\",\n priority: todo.priority || \"medium\",\n id: todo.id || `todo_${Date.now()}_${index}`,\n }))\n return { todos: mappedTodos }\n }\n return input\n default:\n return input\n }\n}\n\n// Tools that Claude CLI executes internally but we report to opencode for UI display\nconst OPENCODE_HANDLED_TOOLS = new Set([\n \"Edit\",\n \"Write\",\n \"Bash\",\n \"NotebookEdit\",\n \"Read\",\n \"Glob\",\n \"Grep\",\n])\n\n// Claude CLI internal tools that should not be forwarded to opencode.\n// These are part of Claude Code's own system and have no opencode equivalent.\n// Tools the Claude CLI emits for its own internal bookkeeping (sub-agents,\n// task tracking, search). opencode has no matching tool registry entry, so\n// forwarding them surfaces as `⚙ invalid` rows in the UI. Skip them.\n// TaskOutput is intentionally NOT here — it has an explicit bash-echo mapping\n// below so the result stays visible.\nconst CLAUDE_INTERNAL_TOOLS = new Set([\n \"ToolSearch\",\n \"Agent\",\n \"AskFollowupQuestion\",\n \"TaskList\",\n \"TaskGet\",\n \"TaskStop\",\n])\n\n/**\n * Wrap model-controlled text as one shell single-quoted word.\n *\n * `TaskOutput` is displayed by running a real `bash` call, so its payload\n * reaches a shell. Double quotes are not enough: inside them `$(…)`,\n * backticks and `${…}` still expand, so `TaskOutput({content: \"X$(id -u)Y\"})`\n * executed `id` while the operator saw a command that read like a print\n * (issue #27). Single quotes suppress every expansion; the only character\n * needing care is `'` itself, closed and reopened around an escaped one.\n */\nexport function singleQuoteForShell(value: string): string {\n return `'${value.replace(/'/g, `'\\\\''`)}'`\n}\n\nfunction emitTodoWrite(todos: TodoEntry[]) {\n return {\n name: \"todowrite\",\n input: {\n todos: todos.map((todo) => ({\n id: todo.id,\n content: todo.content,\n status: todo.status,\n priority: \"medium\",\n })),\n },\n executed: false,\n }\n}\n\nexport function mapTool(\n name: string,\n input?: any,\n opts?: MapToolOptions,\n): { name: string; input?: any; executed: boolean; skip?: boolean } {\n // Claude CLI internal tools — skip entirely\n if (CLAUDE_INTERNAL_TOOLS.has(name)) {\n log.debug(\"skipping Claude CLI internal tool\", { name })\n return { name, input, executed: true, skip: true }\n }\n\n // TaskCreate: stash subject keyed by tool_use_id; emission happens on tool_result.\n // Without sessionId+toolUseId we cannot maintain the ledger, so fall back to skip\n // (preserves old behavior for callers that haven't been threaded yet).\n if (name === \"TaskCreate\") {\n if (opts?.sessionId && opts?.toolUseId) {\n applyTaskCreateToolUse(opts.sessionId, opts.toolUseId, input)\n }\n return { name, input, executed: true, skip: true }\n }\n\n // TaskUpdate: mutate ledger and emit full list as opencode todowrite. Without\n // sessionId, fall back to skip. Unknown task ids return null from the ledger\n // and we drop the event.\n if (name === \"TaskUpdate\") {\n if (opts?.sessionId) {\n const list = applyTaskUpdate(opts.sessionId, input)\n if (list !== null) return emitTodoWrite(list)\n }\n return { name, input, executed: true, skip: true }\n }\n\n // Plan mode tools\n if (name === \"EnterPlanMode\") return { name: \"plan_enter\", input: {}, executed: false }\n if (name === \"ExitPlanMode\") return { name: \"plan_exit\", input, executed: false }\n\n // TodoWrite needs opencode to run it locally so Todo.Service (and the UI\n // widget backed by it) gets populated. Reporting as provider-executed would\n // short-circuit opencode's own execute and leave the todo panel empty.\n if (name === \"TodoWrite\") {\n const mappedInput = mapToolInput(name, input)\n return { name: \"todowrite\", input: mappedInput, executed: false }\n }\n\n // WebSearch — routing controlled by config.webSearch\n if (isWebSearchTool(name)) {\n const mappedInput = input?.query ? { query: input.query } : input\n const route = opts?.webSearch\n if (route && route !== \"claude\" && route !== \"disabled\") {\n log.debug(\"routing WebSearch to opencode tool\", { target: route, mappedInput })\n return { name: route, input: mappedInput, executed: false }\n }\n // Claude CLI runs WebSearch internally; \"WebSearch\" has no opencode\n // registry entry, so forwarding the tool-call part surfaces a\n // \"Model tried to call unavailable tool\" invalid row in opencode.\n // Skip the part — callers render the query as a text line instead.\n log.debug(\"WebSearch executed by Claude CLI\", { mappedInput })\n return { name: \"WebSearch\", input: mappedInput, executed: true, skip: true }\n }\n\n // TaskOutput -> bash printf\n if (name === \"TaskOutput\") {\n if (!input) return { name: \"bash\", executed: false }\n const output = input?.content || input?.output || JSON.stringify(input)\n return {\n name: \"bash\",\n input: {\n command: `printf '%s\\\\n' ${singleQuoteForShell(`TASK OUTPUT: ${String(output)}`)}`,\n description: \"Displaying task output\",\n },\n executed: false,\n }\n }\n\n // Third-party MCP tools: mcp__<server>__<tool> -> <server>_<tool>.\n // Marked provider-executed because Claude CLI runs these internally via\n // its own --mcp-config; the tool-result is already in the stream. If we\n // reported executed:false, opencode would look up the tool in its own\n // registry, fail to find it, and emit an `invalid` tool error that\n // shadows the real result.\n //\n // Our own proxy tools (`mcp__opencode_proxy__*`) are filtered out by\n // callers before reaching here, so this branch only ever sees user MCP\n // servers configured in Claude CLI's settings.\n if (name.startsWith(\"mcp__\")) {\n const parts = name.slice(5).split(\"__\")\n if (parts.length >= 2) {\n const serverName = parts[0]\n const toolName = parts.slice(1).join(\"_\")\n const openCodeName = `${serverName}_${toolName}`\n log.debug(\"mapping MCP tool\", { original: name, mapped: openCodeName })\n return { name: openCodeName, input, executed: true }\n }\n }\n\n // Tools executed by Claude CLI internally - map to lowercase for opencode\n if (OPENCODE_HANDLED_TOOLS.has(name)) {\n const mappedInput = mapToolInput(name, input)\n const openCodeName = name.toLowerCase()\n log.debug(\"mapping CLI-executed tool\", { name, openCodeName })\n return { name: openCodeName, input: mappedInput, executed: true }\n }\n\n // Unknown tools - treated as provider-executed\n return { name, input, executed: true }\n}\n","import { execFile } from \"node:child_process\"\nimport { promisify } from \"node:util\"\nimport { log } from \"./logger.js\"\n\nconst execFileAsync = promisify(execFile)\n\nexport interface CliVersion {\n major: number\n minor: number\n patch: number\n raw: string\n}\n\nconst cache = new Map<string, Promise<CliVersion | null>>()\n\n/**\n * Run `claude --version` once per cliPath and parse the leading semver.\n * Returns null on any failure (binary missing, unparseable output, etc.)\n * so callers can fall back to the most conservative flag set.\n */\nexport function detectCliVersion(cliPath: string): Promise<CliVersion | null> {\n const cached = cache.get(cliPath)\n if (cached) return cached\n const promise = (async (): Promise<CliVersion | null> => {\n try {\n const { stdout } = await execFileAsync(cliPath, [\"--version\"], {\n timeout: 5000,\n })\n const match = /(\\d+)\\.(\\d+)\\.(\\d+)/.exec(stdout.trim())\n if (!match) {\n log.warn(\"claude --version output unparseable\", { stdout: stdout.trim() })\n return null\n }\n const v: CliVersion = {\n major: Number(match[1]),\n minor: Number(match[2]),\n patch: Number(match[3]),\n raw: stdout.trim(),\n }\n log.info(\"detected claude cli version\", { cliPath, version: v.raw })\n if (!cliSupportsThinkingDisplay(v)) {\n log.notice(\n \"claude cli < 2.1.142 detected; Opus 4.7 thinking summaries unavailable. Run `npm i -g @anthropic-ai/claude-code` to upgrade.\",\n { version: v.raw },\n )\n }\n return v\n } catch (err) {\n log.warn(\"failed to detect claude cli version\", {\n cliPath,\n error: err instanceof Error ? err.message : String(err),\n })\n return null\n }\n })()\n cache.set(cliPath, promise)\n return promise\n}\n\nfunction gte(v: CliVersion, target: { major: number; minor: number; patch: number }): boolean {\n if (v.major !== target.major) return v.major > target.major\n if (v.minor !== target.minor) return v.minor > target.minor\n return v.patch >= target.patch\n}\n\n/**\n * `--thinking-display` was introduced in Claude Code 2.1.142 alongside\n * Opus 4.7's \"omitted by default\" thinking behavior. Older CLIs reject\n * the flag with a parse error, so we gate it. Unknown version → return\n * false so we don't risk crashing the spawn.\n */\nexport function cliSupportsThinkingDisplay(v: CliVersion | null): boolean {\n if (!v) return false\n return gte(v, { major: 2, minor: 1, patch: 142 })\n}\n\n/**\n * Fast mode's headless opt-in. In print mode the CLI reports\n * `fast_mode_disabled_reason: \"sdk_opt_in_required\"` unless the *flag* settings\n * layer carries `fastMode: true`, which only `--settings` populates (there is\n * no `--fast` flag, and no fast-mode model name the CLI still accepts).\n *\n * 2.1.220 is the floor because it is the oldest binary the opt-in path was\n * confirmed present in, not because 2.1.219 is known to lack it. An unknown\n * settings key is ignored rather than fatal, so the downside of gating too\n * high is only that fast mode stays off.\n */\nexport function cliSupportsFastMode(v: CliVersion | null): boolean {\n if (!v) return false\n return gte(v, { major: 2, minor: 1, patch: 220 })\n}\n\n/** 2.1.258 is the oldest verified side_question control protocol, not its introduction date. */\nexport function cliSupportsSideQuestion(v: CliVersion | null): boolean {\n if (!v) return false\n return gte(v, { major: 2, minor: 1, patch: 258 })\n}\n\n/**\n * `--thinking` has been part of Claude Code's CLI since the 2.x line.\n * We require a detected 2.0.0+ before passing it; unknown version → skip\n * to avoid crashing a pre-flag binary. Anyone on the 1.x line should\n * upgrade.\n */\nexport function cliSupportsThinking(v: CliVersion | null): boolean {\n if (!v) return false\n return gte(v, { major: 2, minor: 0, patch: 0 })\n}\n\n/** For tests. */\nconst flagSupport = new Map<string, Promise<boolean>>()\n\n/**\n * Probe whether the binary's own `--help` mentions a flag. For flags with no\n * published version marker (`--plugin-dir`), where an invented semver\n * threshold would be a guess. One `--help` spawn per cliPath+flag, cached for\n * the process lifetime. Any failure is false, so the caller skips the flag\n * rather than risking a parse error on spawn. (From @broskees' 68ed142.)\n */\nexport function detectCliSupportsFlag(cliPath: string, flag: string): Promise<boolean> {\n const key = `${cliPath}\\x00${flag}`\n const cached = flagSupport.get(key)\n if (cached) return cached\n const promise = (async (): Promise<boolean> => {\n try {\n const { stdout } = await execFileAsync(cliPath, [\"--help\"], {\n timeout: 5000,\n maxBuffer: 4 * 1024 * 1024,\n })\n return stdout.includes(flag)\n } catch (err) {\n log.warn(\"failed to probe claude cli flag support\", {\n cliPath,\n flag,\n error: err instanceof Error ? err.message : String(err),\n })\n return false\n }\n })()\n flagSupport.set(key, promise)\n return promise\n}\n\nexport function _clearCache(): void {\n flagSupport.clear()\n cache.clear()\n}\n","import { spawn, type ChildProcess } from \"node:child_process\"\nimport { createInterface } from \"node:readline\"\nimport { randomUUID } from \"node:crypto\"\nimport { EventEmitter } from \"node:events\"\nimport { unlink } from \"node:fs/promises\"\nimport { log } from \"./logger.js\"\nimport type { ProxyMcpServer, ProxyToolResult } from \"./proxy-mcp.js\"\nimport { getPendingProxyCalls, type PendingProxyCall } from \"./proxy-broker.js\"\nimport { clearLedger } from \"./todo-ledger.js\"\nimport { clearExitPlanModeQuestions, hasExitPlanModeQuestions } from \"./plan-mode-question.js\"\nimport { clearCompression } from \"./compression-store.js\"\nimport {\n cliSupportsFastMode,\n cliSupportsThinking,\n cliSupportsThinkingDisplay,\n type CliVersion,\n} from \"./cli-version.js\"\nimport type { ReasoningEffort } from \"./types.js\"\nimport { dispatchSideQuestionResponse, isSideQuestionPending } from \"./side-question.js\"\n\nexport interface ActiveProcess {\n proc: ChildProcess\n lineEmitter: EventEmitter\n proxyServer?: ProxyMcpServer | null\n /**\n * Hash of the bridged opencode MCP config the process was spawned with.\n * `null` when the bridge produced nothing (no MCP servers). `undefined`\n * when the bridge was disabled. Used to detect mid-session config drift\n * and force a respawn.\n */\n mcpHash?: string | null\n /** Temp file holding `--append-system-prompt-file` content; unlinked on exit. */\n systemPromptFile?: string\n /** Effort the process was spawned with, so a respawn keeps it. */\n effort?: ReasoningEffort\n cliArgs?: string[]\n // Retain resolved calls until continuation settles, including late channel closure.\n pendingProxyCompletions?: Map<string, {\n call: PendingProxyCall\n result: ProxyToolResult\n recoveryRequired: boolean\n }>\n /**\n * stdout lines the child emitted while no turn had a line listener\n * attached (between opencode turns). Bounded; see `bufferUnattendedLine`.\n * Absent on the interactive shim, which has no unattended window.\n */\n unattendedLines?: string[]\n /** Lines evicted from `unattendedLines` because the cap was hit. */\n unattendedDropped?: number\n /**\n * opencode session this process last served, tagged by doStream each turn.\n * `/btw` runs from a command hook that only knows the session id, so this is\n * how it finds the process to ask (see `findActiveProcessBySessionId`).\n */\n opencodeSessionID?: string\n /** What the /btw command hook needs to send a side question to this process early. */\n asideTransport?: { cliPath: string; interactive: boolean }\n /**\n * True from a stdin write that asks the CLI for work until its terminal\n * `result` line, whether or not a turn is still listening. Set by\n * `noteTurnStarted`, cleared by `noteTurnLine` (see `interruptTurn`).\n */\n turnInFlight?: boolean\n turnIdleWaiters?: Array<() => void>\n}\n\n/** Most recently used process serving an opencode session id, if any. */\nexport function findActiveProcessBySessionId(sessionID: string): ActiveProcess | undefined {\n let found: ActiveProcess | undefined\n // Map order is LRU (see `touch`), so the last match is the freshest.\n for (const ap of activeProcesses.values()) {\n if (ap.opencodeSessionID === sessionID) found = ap\n }\n return found\n}\n\n// A child normally only speaks while a doStream turn is listening. The one\n// exception is a turn that ended on the CLI's side while opencode was still\n// waiting on a proxy call (Claude's MCP client gave up on the request and\n// the model carried on alone). Keep what it said so the next turn can show\n// it instead of losing it; cap it so a runaway child cannot grow the heap.\nconst UNATTENDED_LINE_CAP = 500\nconst UNATTENDED_BYTE_CAP = 2 * 1024 * 1024\n\nexport function bufferUnattendedLine(ap: ActiveProcess, line: string): void {\n const lines = (ap.unattendedLines ??= [])\n lines.push(line)\n let bytes = 0\n for (const kept of lines) bytes += Buffer.byteLength(kept)\n while (\n lines.length > 0 &&\n (lines.length > UNATTENDED_LINE_CAP || bytes > UNATTENDED_BYTE_CAP)\n ) {\n bytes -= Buffer.byteLength(lines.shift()!)\n ap.unattendedDropped = (ap.unattendedDropped ?? 0) + 1\n }\n}\n\n/** Hand over and clear everything the child said while nobody listened. */\nexport function takeUnattendedLines(ap: ActiveProcess): {\n lines: string[]\n dropped: number\n} {\n const lines = ap.unattendedLines ?? []\n const dropped = ap.unattendedDropped ?? 0\n ap.unattendedLines = []\n ap.unattendedDropped = 0\n return { lines, dropped }\n}\n\n// One active CLI process per session key. Keyed by a composite\n// (cwd + model + opencode session-affinity) so two chats don't race.\n// Iteration order is insertion order, which we refresh on access to\n// make this a poor-man's LRU; see `touch()` below.\nconst activeProcesses = new Map<string, ActiveProcess>()\nconst claudeSessions = new Map<string, string>()\n// Idle-eviction timers keyed like `activeProcesses` (idle timeout by\n// @bernardofortes, absorbed from a5f723a).\nconst idleEvictionTimers = new Map<string, ReturnType<typeof setTimeout>>()\nconst MAX_IDLE_TIMEOUT_MS = 2_147_483_647\n\n// Cap on live CLI subprocesses. Session-affinity-keyed entries accumulate\n// one-per-chat, so an unbounded map would leak processes as users open new\n// chats. This caps at a reasonable working-set and evicts the oldest.\nconst MAX_ACTIVE_PROCESSES = 16\nconst PROCESS_EXIT_TIMEOUT_MS = 1_500\nconst PROCESS_FORCE_EXIT_TIMEOUT_MS = 500\n\nfunction envFlagEnabled(value: string | undefined): boolean {\n if (value === undefined) return false\n const normalized = value.trim().toLowerCase()\n if (!normalized) return false\n return ![\"0\", \"false\", \"no\", \"off\"].includes(normalized)\n}\n\nexport function isClaudeThinkingDisabled(): boolean {\n return (\n envFlagEnabled(process.env.CLAUDE_CODE_DISABLE_THINKING) ||\n envFlagEnabled(process.env.CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING)\n )\n}\n\n/**\n * The CLI's effort vocabulary is low | medium | high | xhigh | max. `minimal`\n * is this provider's own lowest step with no CLI counterpart, so it lands on\n * `low`.\n */\nexport function cliEffortLevel(effort: ReasoningEffort): string {\n return effort === \"minimal\" ? \"low\" : effort\n}\n\nexport function claudeSpawnEnv(opts?: {\n ignoreAnthropicApiKey?: boolean\n /** Reasoning effort for this spawn; wins over a shell-level override. */\n effort?: ReasoningEffort\n}): Record<string, string | undefined> {\n const env: Record<string, string | undefined> = {\n ...process.env,\n TERM: \"xterm-256color\",\n }\n\n // Effort travels as CLAUDE_CODE_EFFORT_LEVEL, which the CLI treats as the\n // session-wide override (it beats settings.json and `/effort`). An env var\n // rather than `--effort` because a CLI too old to know it ignores it\n // instead of refusing to start. Unlike the thinking vars below, an explicit\n // effort from the request wins over the shell: the variant picker and an\n // agent's `reasoningEffort` are per-request choices, a shell export is not.\n if (opts?.effort) {\n env.CLAUDE_CODE_EFFORT_LEVEL = cliEffortLevel(opts.effort)\n }\n\n // Force subscription auth: with an API key in the env, Claude Code bills\n // pay-as-you-go (Console) instead of the logged-in plan, bypassing the\n // Agent SDK credit. Opt-in via `ignoreAnthropicApiKey`.\n if (opts?.ignoreAnthropicApiKey) {\n delete env.ANTHROPIC_API_KEY\n delete env.ANTHROPIC_AUTH_TOKEN\n }\n\n // Default-on thinking summaries for opus-4-7 (which omits thinking by\n // default on the CLI side). Any var the user has explicitly set in their\n // shell is passed through untouched; the plugin only fills in the default.\n if (\n !isClaudeThinkingDisabled() &&\n process.env.CLAUDE_CODE_SHOW_THINKING_SUMMARIES === undefined\n ) {\n env.CLAUDE_CODE_SHOW_THINKING_SUMMARIES = \"1\"\n }\n\n return env\n}\n\nfunction touch(key: string): void {\n const existing = activeProcesses.get(key)\n if (existing) {\n activeProcesses.delete(key)\n activeProcesses.set(key, existing)\n }\n}\n\nfunction evictIfNeeded(): void {\n while (activeProcesses.size >= MAX_ACTIVE_PROCESSES) {\n const oldestKey = activeProcesses.keys().next().value\n if (!oldestKey) break\n log.info(\"evicting LRU claude process\", { sessionKey: oldestKey })\n deleteActiveProcess(oldestKey)\n }\n}\n\n// Turn lifecycle and interrupt (from @broskees' 68ed142, adapted).\n//\n// The Claude CLI runs one turn per process. Closing the opencode-side stream\n// tells it nothing: before this, an abort only detached our listeners and the\n// CLI ran the abandoned turn to completion (Joseph Roberts measured ~7,500\n// extra characters generated after abort on a haiku probe), kept billing, kept\n// running tools, and its late output landed in whatever turn came next, whose\n// own stream was then closed early by the stale `result`. The CLI answers a\n// stream-json `control_request` of subtype `interrupt` by aborting the turn\n// and emitting a terminal `result`, normally within milliseconds.\n\nconst TURN_INTERRUPT_TIMEOUT_MS = 5_000\n\n/** Cheap pre-filter before JSON.parse, since every CLI stdout line hits this. */\nfunction isTerminalResultLine(line: string): boolean {\n if (!line.includes('\"result\"')) return false\n try {\n return (JSON.parse(line) as { type?: string }).type === \"result\"\n } catch {\n return false\n }\n}\n\nfunction settleTurn(ap: ActiveProcess): void {\n ap.turnInFlight = false\n const waiters = ap.turnIdleWaiters ?? []\n ap.turnIdleWaiters = []\n for (const wake of waiters) wake()\n}\n\n/** Call immediately before any stdin write that asks the CLI to do work. */\nexport function noteTurnStarted(ap: ActiveProcess): void {\n // The interactive transport never reports through `noteTurnLine`, so a flag\n // set there would never clear.\n if (ap.asideTransport?.interactive) return\n ap.turnInFlight = true\n}\n\n/**\n * Feed every CLI stdout line here, independent of whichever turn currently\n * owns the stream: a `result` that lands after its turn detached (the abort\n * case) must still mark the CLI idle rather than leak into the next turn.\n */\nexport function noteTurnLine(ap: ActiveProcess, line: string): void {\n if (!ap.turnInFlight) return\n if (isTerminalResultLine(line)) settleTurn(ap)\n}\n\nexport function isTurnInFlight(ap: ActiveProcess): boolean {\n return ap.turnInFlight === true\n}\n\n/** Resolves true once the CLI is idle, false if it stayed busy past the timeout. */\nexport function awaitTurnIdle(ap: ActiveProcess, timeoutMs: number): Promise<boolean> {\n if (!ap.turnInFlight) return Promise.resolve(true)\n return new Promise((resolve) => {\n const wake = () => {\n clearTimeout(timer)\n resolve(true)\n }\n const timer = setTimeout(() => {\n const waiters = ap.turnIdleWaiters ?? []\n const at = waiters.indexOf(wake)\n if (at >= 0) waiters.splice(at, 1)\n resolve(false)\n }, timeoutMs)\n ;(ap.turnIdleWaiters ??= []).push(wake)\n })\n}\n\n/** Ask the CLI to abandon the in-flight turn, and wait for it to say it did. */\nexport function interruptTurn(\n ap: ActiveProcess,\n timeoutMs = TURN_INTERRUPT_TIMEOUT_MS,\n): Promise<boolean> {\n if (!ap.turnInFlight) return Promise.resolve(true)\n const stdin = ap.proc.stdin\n if (ap.asideTransport?.interactive || !stdin || !stdin.writable) {\n // A TUI stdin would type the JSON in as text. Wait the turn out instead.\n log.notice(\"cannot interrupt this transport; waiting for the turn to end\")\n return awaitTurnIdle(ap, timeoutMs)\n }\n try {\n stdin.write(\n JSON.stringify({\n type: \"control_request\",\n request_id: randomUUID(),\n request: { subtype: \"interrupt\" },\n }) + \"\\n\",\n )\n } catch (error) {\n log.warn(\"failed to write interrupt control request\", {\n error: error instanceof Error ? error.message : String(error),\n })\n return Promise.resolve(false)\n }\n return awaitTurnIdle(ap, timeoutMs)\n}\n\nfunction cancelIdleProcessEviction(key: string): void {\n const timer = idleEvictionTimers.get(key)\n if (!timer) return\n clearTimeout(timer)\n idleEvictionTimers.delete(key)\n}\n\nexport function getActiveProcess(key: string): ActiveProcess | undefined {\n const ap = activeProcesses.get(key)\n if (ap) {\n cancelIdleProcessEviction(key)\n touch(key)\n }\n return ap\n}\n\nexport function setActiveProcess(key: string, ap: ActiveProcess): void {\n cancelIdleProcessEviction(key)\n activeProcesses.set(key, ap)\n}\n\n/**\n * Evict a headless Claude worker after a completed turn has stayed idle.\n * Reusing the worker through `getActiveProcess` cancels the timer. The\n * Claude session id is intentionally retained so the next turn can continue\n * the same conversation via `--resume`.\n */\nexport function scheduleIdleProcessEviction(\n key: string,\n timeoutMs: number | undefined,\n): void {\n cancelIdleProcessEviction(key)\n if (\n typeof timeoutMs !== \"number\" ||\n !Number.isFinite(timeoutMs) ||\n timeoutMs <= 0 ||\n timeoutMs > MAX_IDLE_TIMEOUT_MS\n ) {\n return\n }\n\n const scheduledProcess = activeProcesses.get(key)\n if (!scheduledProcess) return\n\n const timer = setTimeout(() => {\n idleEvictionTimers.delete(key)\n if (activeProcesses.get(key) !== scheduledProcess) return\n log.info(\"evicting idle claude process\", { sessionKey: key, timeoutMs })\n deleteActiveProcess(key)\n }, timeoutMs)\n timer.unref()\n idleEvictionTimers.set(key, timer)\n}\n\nfunction detachActiveProcess(key: string): ActiveProcess | undefined {\n cancelIdleProcessEviction(key)\n const ap = activeProcesses.get(key)\n if (!ap) return undefined\n activeProcesses.delete(key)\n void ap.proxyServer?.close()\n return ap\n}\n\nexport function deleteActiveProcess(key: string): void {\n const ap = detachActiveProcess(key)\n ap?.proc.kill()\n}\n\nfunction hasProcessExited(proc: ChildProcess): boolean {\n return proc.exitCode !== null || proc.signalCode !== null\n}\n\nfunction waitForProcessExit(\n proc: ChildProcess,\n timeoutMs: number,\n): Promise<boolean> {\n if (hasProcessExited(proc)) return Promise.resolve(true)\n\n return new Promise((resolve) => {\n const onExit = () => {\n clearTimeout(timer)\n resolve(true)\n }\n const timer = setTimeout(() => {\n proc.off(\"exit\", onExit)\n resolve(hasProcessExited(proc))\n }, timeoutMs)\n proc.once(\"exit\", onExit)\n })\n}\n\nexport async function deleteActiveProcessAndWait(\n key: string,\n options: {\n exitTimeoutMs?: number\n forceExitTimeoutMs?: number\n } = {},\n): Promise<boolean> {\n const ap = detachActiveProcess(key)\n if (!ap || hasProcessExited(ap.proc)) return true\n\n const gracefulExit = waitForProcessExit(\n ap.proc,\n options.exitTimeoutMs ?? PROCESS_EXIT_TIMEOUT_MS,\n )\n ap.proc.kill()\n if (await gracefulExit) return true\n\n const forcedExit = waitForProcessExit(\n ap.proc,\n options.forceExitTimeoutMs ?? PROCESS_FORCE_EXIT_TIMEOUT_MS,\n )\n ap.proc.kill(\"SIGKILL\")\n if (await forcedExit) return true\n\n log.warn(\"claude process did not exit; starting a fresh session\", {\n sessionKey: key,\n })\n deleteClaudeSessionId(key)\n return false\n}\n\nexport function getClaudeSessionId(key: string): string | undefined {\n return claudeSessions.get(key)\n}\n\nexport function setClaudeSessionId(key: string, sessionId: string): void {\n claudeSessions.set(key, sessionId)\n}\n\nexport function deleteClaudeSessionId(key: string): void {\n clearExitPlanModeQuestions(key)\n const claudeSessionId = claudeSessions.get(key)\n if (claudeSessionId) clearLedger(claudeSessionId)\n claudeSessions.delete(key)\n}\n\nexport function effortSessionKey(baseKey: string, effort?: ReasoningEffort): string {\n return effort ? `${baseKey}::effort=${effort}` : baseKey\n}\n\n/** Retire sibling effort sessions before deciding whether to replay history. */\nexport function invalidateOtherEffortSessions(\n baseKey: string,\n effort?: ReasoningEffort,\n): void {\n const levels: (ReasoningEffort | undefined)[] = [\n undefined, \"minimal\", \"low\", \"medium\", \"high\", \"xhigh\", \"max\",\n ]\n const staleKeys = levels\n .filter((level) => level !== effort)\n .map((level) => effortSessionKey(baseKey, level))\n\n // Refuse the transition atomically. Tool results and recovery completions\n // still belong to the old process; they must finish at its original effort.\n for (const key of staleKeys) {\n const active = activeProcesses.get(key)\n if (\n getPendingProxyCalls(key).length ||\n hasExitPlanModeQuestions(key) ||\n active?.pendingProxyCompletions?.size ||\n (active && (active.lineEmitter.listenerCount(\"line\") > 0 || isSideQuestionPending(active)))\n ) {\n throw new Error(\n \"Cannot change reasoning effort while the previous effort session has pending work. Finish that work at its original effort first.\",\n )\n }\n }\n for (const key of staleKeys) {\n deleteActiveProcess(key)\n deleteClaudeSessionId(key)\n clearCompression(key)\n }\n}\n\nexport function spawnClaudeProcess(\n cliPath: string,\n cliArgs: string[],\n cwd: string,\n sessionKey: string,\n proxyServer?: ProxyMcpServer | null,\n mcpHash?: string | null,\n systemPromptFile?: string,\n ignoreAnthropicApiKey?: boolean,\n effort?: ReasoningEffort,\n): ActiveProcess {\n evictIfNeeded()\n log.info(\"spawning new claude process\", {\n cliPath,\n cliArgs,\n cwd,\n sessionKey,\n effort,\n })\n\n const proc = spawn(cliPath, cliArgs, {\n cwd,\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n env: claudeSpawnEnv({ ignoreAnthropicApiKey, effort }),\n shell: process.platform === \"win32\",\n })\n\n const lineEmitter = new EventEmitter()\n\n const ap: ActiveProcess = {\n proc,\n lineEmitter,\n proxyServer: proxyServer ?? null,\n mcpHash,\n systemPromptFile,\n effort,\n cliArgs: [...cliArgs],\n unattendedLines: [],\n unattendedDropped: 0,\n }\n\n const rl = createInterface({ input: proc.stdout! })\n rl.on(\"line\", (line: string) => {\n if (dispatchSideQuestionResponse(ap, line)) return\n noteTurnLine(ap, line)\n if (lineEmitter.listenerCount(\"line\") === 0) {\n bufferUnattendedLine(ap, line)\n return\n }\n lineEmitter.emit(\"line\", line)\n })\n rl.on(\"close\", () => {\n settleTurn(ap)\n lineEmitter.emit(\"close\")\n })\n cancelIdleProcessEviction(sessionKey)\n activeProcesses.set(sessionKey, ap)\n\n // Baseline 'error' listener so Node doesn't throw when the process emits\n // an error between stream turns (no per-stream listener attached then).\n proc.on(\"error\", (err) => {\n log.error(\"claude process error\", { sessionKey, error: err.message })\n })\n\n proc.on(\"exit\", (code, signal) => {\n log.info(\"claude process exited\", { code, signal, sessionKey })\n void proxyServer?.close()\n if (systemPromptFile) {\n void unlink(systemPromptFile).catch(() => {})\n }\n const ownsSessionKey = activeProcesses.get(sessionKey) === ap\n if (ownsSessionKey) {\n cancelIdleProcessEviction(sessionKey)\n activeProcesses.delete(sessionKey)\n }\n if (ownsSessionKey && code !== 0 && code !== null) {\n log.info(\"process exited with error, clearing session\", {\n code,\n sessionKey,\n })\n claudeSessions.delete(sessionKey)\n }\n })\n\n proc.stderr?.on(\"data\", (data: Buffer) => {\n const stderr = data.toString()\n log.debug(\"stderr\", { data: stderr.slice(0, 200) })\n\n // \"No conversation found with session ID: <uuid>\" is what `--resume`\n // prints for a purged transcript — note the lowercase \"session ID\",\n // which the capitalized match below does not catch.\n if (\n stderr.includes(\"No conversation found\") ||\n (stderr.includes(\"Session ID\") &&\n (stderr.includes(\"already in use\") ||\n stderr.includes(\"not found\") ||\n stderr.includes(\"invalid\")))\n ) {\n if (activeProcesses.get(sessionKey) === ap) {\n log.warn(\"claude session ID error, clearing session\", {\n sessionKey,\n error: stderr.slice(0, 200),\n })\n claudeSessions.delete(sessionKey)\n } else {\n log.debug(\"ignoring session ID error from stale claude process\", {\n sessionKey,\n })\n }\n }\n })\n\n return ap\n}\n\n/**\n * Append `--resume <id>` to an already-built args vector when a Claude\n * conversation id is known for the session and the args don't already carry\n * a session flag. Used by `respawnActiveProcess` to resume the conversation\n * in a fresh child without rebuilding the whole (version-gated) args vector.\n * `--resume`, not `--session-id`: the latter means \"create a NEW session\n * with this UUID\" and the CLI rejects it with \"Session ID ... is already in\n * use\" whenever a transcript exists on disk — which is exactly the state a\n * mid-conversation respawn is in. If the wedged child died before writing\n * any transcript, `--resume` fails with \"No conversation found with session\n * ID\", which the stderr recovery matcher already catches (fresh-session\n * fallback).\n */\nexport function appendResumeIfNeeded(\n sessionKey: string,\n cliArgs: string[],\n): string[] {\n if (cliArgs.includes(\"--resume\") || cliArgs.includes(\"--session-id\")) {\n return cliArgs\n }\n const sid = claudeSessions.get(sessionKey)\n if (!sid) return cliArgs\n return [...cliArgs, \"--resume\", sid]\n}\n\n/**\n * Replace a wedged reused process with a fresh one, resuming the same\n * Claude conversation. Used by the doStream start-watchdog when a reused\n * process produces no stdout within a grace window after a fresh-turn\n * envelope write — observed after a very long proxy-blocked tool call\n * (e.g. a multi-minute `task` subagent). Before the per-tool proxy timeout\n * fix this was masked because the flat 10-minute ceiling ended the turn\n * first; now that the task proxy blocks and returns successfully, resuming\n * a reused child after such a long wait can leave it silent on stdout.\n *\n * Reuses the existing proxy server, system-prompt file, and MCP hash (their\n * handles are already baked into `cliArgs`' `--mcp-config`/append-prompt\n * paths), so this only swaps the child process. The old child's exit\n * handler is silenced before kill so it doesn't close the proxy server we\n * are reusing; the new child gets its own exit handler from\n * `spawnClaudeProcess`. `claudeSessions` is left intact so the respawn can\n * add `--resume` (see `appendResumeIfNeeded`).\n *\n * Returns the new `ActiveProcess`, or `undefined` if there was no active\n * process for the key (caller should treat that as \"nothing to respawn\").\n */\nexport function respawnActiveProcess(\n sessionKey: string,\n cliPath: string,\n cliArgs: string[],\n cwd: string,\n ignoreAnthropicApiKey?: boolean,\n): ActiveProcess | undefined {\n const old = activeProcesses.get(sessionKey)\n if (!old) return undefined\n activeProcesses.delete(sessionKey)\n // Silence the old exit handler so it doesn't close the proxy server,\n // unlink the system-prompt file, or touch claudeSessions on its way out\n // — those handles are reused by the new child. spawnClaudeProcess wires\n // a fresh exit handler for the respawned child.\n old.proc.removeAllListeners(\"exit\")\n try {\n old.proc.kill()\n } catch {}\n const replacement = spawnClaudeProcess(\n cliPath,\n appendResumeIfNeeded(sessionKey, old.cliArgs ?? cliArgs),\n cwd,\n sessionKey,\n old.proxyServer,\n old.mcpHash,\n old.systemPromptFile,\n ignoreAnthropicApiKey,\n old.effort,\n )\n replacement.pendingProxyCompletions = old.pendingProxyCompletions\n delete old.pendingProxyCompletions\n return replacement\n}\n\nexport function buildCliArgs(opts: {\n sessionKey: string\n skipPermissions: boolean\n includeSessionId?: boolean\n model?: string\n permissionMode?: string\n mcpConfig?: string | string[]\n strictMcpConfig?: boolean\n disallowedTools?: string[]\n appendSystemPromptFile?: string\n /** `--plugin-dir` values (skill bridge), one flag per directory. */\n pluginDirs?: string[]\n thinking?: \"enabled\" | \"disabled\"\n thinkingDisplay?: \"summarized\" | \"omitted\"\n fastMode?: boolean\n cliVersion?: CliVersion | null\n}): string[] {\n const {\n sessionKey,\n skipPermissions,\n includeSessionId = true,\n model,\n permissionMode,\n mcpConfig,\n strictMcpConfig,\n disallowedTools,\n appendSystemPromptFile,\n pluginDirs,\n thinking,\n thinkingDisplay,\n fastMode,\n cliVersion,\n } = opts\n const args = [\n \"--print\",\n \"--output-format\",\n \"stream-json\",\n \"--input-format\",\n \"stream-json\",\n \"--include-partial-messages\",\n \"--verbose\",\n ]\n\n if (model) {\n args.push(\"--model\", model)\n }\n\n if (permissionMode) {\n args.push(\"--permission-mode\", permissionMode)\n }\n\n // `--session-id` means \"create a NEW session with this UUID\" and the CLI\n // exits with \"Session ID ... is already in use\" whenever a transcript for\n // that ID already exists on disk. Continuing an existing session requires\n // `--resume` (which keeps the same session ID in print mode).\n if (includeSessionId) {\n const sessionId = claudeSessions.get(sessionKey)\n if (sessionId && !activeProcesses.has(sessionKey)) {\n args.push(\"--resume\", sessionId)\n }\n }\n\n if (mcpConfig) {\n const configs = Array.isArray(mcpConfig) ? mcpConfig : [mcpConfig]\n const filtered = configs.filter((c) => typeof c === \"string\" && c.length > 0)\n if (filtered.length > 0) {\n args.push(\"--mcp-config\", ...filtered)\n }\n }\n\n if (strictMcpConfig) {\n args.push(\"--strict-mcp-config\")\n }\n\n if (disallowedTools && disallowedTools.length > 0) {\n args.push(\"--disallowedTools\", ...disallowedTools)\n }\n\n // `--thinking` is only present from Claude Code 2.x onward; gate so\n // pre-2.x binaries don't crash with a parse error. Unknown version →\n // skip (the spawn still works, the user just doesn't get extended\n // thinking until they upgrade).\n if (thinking && cliSupportsThinking(cliVersion ?? null)) {\n args.push(\"--thinking\", thinking)\n }\n\n // `--thinking-display` was added in Claude Code 2.1.142. Older CLIs\n // reject it with a parse error, so gate on detected version. When\n // version is unknown (detection failed), be conservative and skip.\n if (thinkingDisplay && cliSupportsThinkingDisplay(cliVersion ?? null)) {\n args.push(\"--thinking-display\", thinkingDisplay)\n }\n\n if (appendSystemPromptFile) {\n args.push(\"--append-system-prompt-file\", appendSystemPromptFile)\n }\n for (const dir of pluginDirs ?? []) {\n args.push(\"--plugin-dir\", dir)\n }\n\n // Fast mode's only headless opt-in. `--settings` feeds the CLI's\n // `flagSettings` layer, which is the one its SDK gate checks; a `fastMode`\n // in the user's own settings.json is NOT enough for a `--print` run.\n // Built as one object so later flag-settings keys merge here instead of\n // adding a second `--settings` (the CLI takes the flag once).\n if (fastMode && cliSupportsFastMode(cliVersion ?? null)) {\n args.push(\"--settings\", JSON.stringify({ fastMode: true }))\n }\n\n if (skipPermissions) {\n args.push(\"--dangerously-skip-permissions\")\n }\n\n return args\n}\n\n/**\n * Build a session key that includes both cwd and model,\n * so different models get separate processes.\n */\nexport function sessionKey(cwd: string, modelId: string): string {\n return `${cwd}::${modelId}`\n}\n","import { EventEmitter } from \"node:events\"\nimport {\n buildProxyTimeoutError,\n resolveProxyCallTimeoutMs,\n type ProxyCallChannel,\n type ProxyToolCall,\n type ProxyToolResult,\n} from \"./proxy-mcp.js\"\nimport { log } from \"./logger.js\"\n\nexport interface PendingProxyCall {\n sessionKey: string\n toolCallId: string\n toolName: string\n input: Record<string, unknown>\n /**\n * Liveness of Claude's HTTP request for this call. Once `closed`, a\n * result written to it is lost; the language model then delivers the\n * result as a user message instead. Absent means open.\n */\n channel?: ProxyCallChannel\n /**\n * True once the language model has handed this call to opencode as a\n * tool-call part. A call that is still pending without it was queued\n * while no turn was attached and has to be drained by the next one.\n */\n emitted?: boolean\n}\n\ntype InternalPending = PendingProxyCall & {\n createdAt: number\n timer: ReturnType<typeof setTimeout>\n resolve(result: ProxyToolResult): void\n reject(error: Error): void\n}\n\n// Primary index: callId -> pending. Tool call IDs are UUIDs produced by\n// proxy-mcp, so they are globally unique across sessions.\nconst pendingByCallId = new Map<string, InternalPending>()\n// Reverse index: sessionKey -> set of callIds, so the language model can\n// drain or reject every pending call for one Claude subprocess at once.\nconst callIdsBySession = new Map<string, Set<string>>()\n\nconst emitter = new EventEmitter()\n\nfunction eventName(sessionKey: string) {\n return `pending:${sessionKey}`\n}\n\nfunction indexAdd(sessionKey: string, callId: string) {\n let s = callIdsBySession.get(sessionKey)\n if (!s) {\n s = new Set()\n callIdsBySession.set(sessionKey, s)\n }\n s.add(callId)\n}\n\nfunction indexRemove(sessionKey: string, callId: string) {\n const s = callIdsBySession.get(sessionKey)\n if (!s) return\n s.delete(callId)\n if (s.size === 0) callIdsBySession.delete(sessionKey)\n}\n\nexport function onPendingProxyCall(\n sessionKey: string,\n handler: (call: PendingProxyCall) => void,\n): () => void {\n const name = eventName(sessionKey)\n emitter.on(name, handler)\n return () => emitter.off(name, handler)\n}\n\nexport function queuePendingProxyCall(\n sessionKey: string,\n call: ProxyToolCall,\n timeoutOverrides?: Record<string, number>,\n): PendingProxyCall {\n // Defensive: if this exact callId is somehow already pending (UUID\n // collision or retry storm), replace it cleanly so we never leak two\n // entries for the same id.\n const previous = pendingByCallId.get(call.id)\n if (previous) {\n clearTimeout(previous.timer)\n previous.reject(\n new Error(`Replaced pending proxy call ${call.id} with a fresh one`),\n )\n pendingByCallId.delete(call.id)\n indexRemove(previous.sessionKey, call.id)\n }\n\n const deadlineMs = resolveProxyCallTimeoutMs(\n call.toolName,\n call.input,\n timeoutOverrides,\n )\n\n const timer = setTimeout(() => {\n const current = pendingByCallId.get(call.id)\n if (!current) return\n pendingByCallId.delete(call.id)\n indexRemove(current.sessionKey, call.id)\n current.reject(buildProxyTimeoutError(call.toolName, deadlineMs))\n // v0.4.13: demoted from warn to notice. AFK-permission-pending\n // sessions can stack many of these; demoting keeps the UI quiet on\n // return while preserving the audit trail in plugin.log.\n log.notice(\"timed out pending proxy call\", {\n sessionKey: current.sessionKey,\n toolCallId: call.id,\n toolName: call.toolName,\n deadlineMs,\n })\n }, deadlineMs)\n\n const pending: InternalPending = {\n sessionKey,\n toolCallId: call.id,\n toolName: call.toolName,\n input: call.input,\n channel: call.channel,\n createdAt: Date.now(),\n timer,\n resolve: call.resolve,\n reject: call.reject,\n }\n pendingByCallId.set(call.id, pending)\n indexAdd(sessionKey, call.id)\n emitter.emit(eventName(sessionKey), pending)\n log.info(\"queued pending proxy call\", {\n sessionKey,\n toolCallId: call.id,\n toolName: call.toolName,\n })\n return pending\n}\n\n/** Record that opencode has been given this call as a tool-call part. */\nexport function markPendingProxyCallEmitted(toolCallId: string): void {\n const pending = pendingByCallId.get(toolCallId)\n if (pending) pending.emitted = true\n}\n\n/** True when Claude's request for this call is gone (see `channel`). */\nexport function isPendingProxyCallChannelClosed(\n call: PendingProxyCall,\n): boolean {\n return call.channel?.closed === true\n}\n\nexport function getPendingProxyCalls(sessionKey: string): PendingProxyCall[] {\n const s = callIdsBySession.get(sessionKey)\n if (!s || s.size === 0) return []\n const out: PendingProxyCall[] = []\n for (const id of s) {\n const p = pendingByCallId.get(id)\n if (p) out.push(p)\n }\n return out\n}\n\nexport function resolvePendingProxyCallById(\n toolCallId: string,\n result: ProxyToolResult,\n): boolean {\n const pending = pendingByCallId.get(toolCallId)\n if (!pending) return false\n pendingByCallId.delete(toolCallId)\n indexRemove(pending.sessionKey, toolCallId)\n clearTimeout(pending.timer)\n pending.resolve(result)\n log.info(\"resolved pending proxy call\", {\n sessionKey: pending.sessionKey,\n toolCallId: pending.toolCallId,\n toolName: pending.toolName,\n })\n return true\n}\n\nexport function rejectPendingProxyCallById(\n toolCallId: string,\n error: Error,\n): boolean {\n const pending = pendingByCallId.get(toolCallId)\n if (!pending) return false\n pendingByCallId.delete(toolCallId)\n indexRemove(pending.sessionKey, toolCallId)\n clearTimeout(pending.timer)\n pending.reject(error)\n // Rejection is the broker's cleanup mechanism — fires on timeouts, orphans,\n // stream closes, etc. None are user-actionable. File-log them at NOTICE so\n // the audit trail is intact; rely on caller sites to decide TUI visibility.\n log.notice(\"rejected pending proxy call\", {\n sessionKey: pending.sessionKey,\n toolCallId: pending.toolCallId,\n toolName: pending.toolName,\n error: error.message,\n })\n return true\n}\n\nexport function rejectAllPendingProxyCallsForSession(\n sessionKey: string,\n error: Error,\n): number {\n const s = callIdsBySession.get(sessionKey)\n if (!s) return 0\n const ids = [...s]\n let count = 0\n for (const id of ids) {\n if (rejectPendingProxyCallById(id, error)) count++\n }\n return count\n}\n","import { createServer, type IncomingMessage, type ServerResponse } from \"node:http\"\nimport type { AddressInfo } from \"node:net\"\nimport * as fs from \"node:fs\"\nimport * as path from \"node:path\"\nimport * as crypto from \"node:crypto\"\nimport { EventEmitter } from \"node:events\"\nimport { log } from \"./logger.js\"\nimport { pluginTmpDir } from \"./tmp.js\"\n\n/**\n * Minimal MCP HTTP server embedded in-process. Exposes a set of \"proxy\"\n * tools (Bash, Edit, Write, etc.) that Claude CLI calls when its built-in\n * equivalents are disabled via --disallowedTools. Our handler blocks until\n * an external broker resolves the call, then responds to Claude.\n *\n * Wire protocol: JSON-RPC 2.0 over plain HTTP POST to `/mcp`. MCP spec\n * also supports SSE streaming, but Claude's HTTP transport accepts single\n * JSON responses for short-lived tool calls, so we keep it simple.\n */\n\nexport interface ProxyMcpServer {\n url: string\n serverName: string\n tools: ProxyToolDef[]\n /** Per-server bearer secret. Minted on start, handed to Claude via the\n * `headers` block of the generated MCP config, and required on every\n * request. Exposed so callers (and tests) can authenticate; MUST NOT be\n * logged or placed in the URL. */\n authToken: string\n /** Fires when Claude invokes one of our proxy tools. The handler resolves\n * the returned pending call once a result is available. */\n calls: EventEmitter\n /** Write `--mcp-config <path>`-compatible scratch file and return its path. */\n configPath(): string\n close(): Promise<void>\n}\n\nexport interface ProxyToolDef {\n /** Raw name as seen by Claude once proxied: the MCP exposed tool name. */\n name: string\n description: string\n inputSchema: Record<string, unknown>\n}\n\n/**\n * Liveness of the HTTP reply channel behind one proxy call. Shared by\n * reference between proxy-mcp (which flips `closed` when Claude's request\n * goes away) and the broker / language model (which read it before\n * answering), so the two never need to import each other.\n */\nexport interface ProxyCallChannel {\n closed: boolean\n}\n\nexport interface ProxyToolCall {\n id: string\n toolName: string\n input: Record<string, unknown>\n resolve: (result: ProxyToolResult) => void\n reject: (err: Error) => void\n /** Absent for calls built by hand in tests; treated as open. */\n channel?: ProxyCallChannel\n}\n\n/**\n * Keep unanswered HTTP calls active independently of the tool deadline.\n * A held call timed out before delivery on CLI 2.1.258; with immediate\n * headers and these comments, the same 390-second hold completed.\n */\nexport const SSE_KEEPALIVE_MS = 15_000\n\n/** True when the client advertised `text/event-stream` in Accept. */\nexport function acceptsEventStream(acceptHeader: unknown): boolean {\n return (\n typeof acceptHeader === \"string\" &&\n acceptHeader.toLowerCase().includes(\"text/event-stream\")\n )\n}\n\nexport type ProxyToolResult =\n | { kind: \"text\"; text: string; isError?: boolean }\n | { kind: \"error\"; message: string }\n\n/**\n * Handler that answers a `tools/call` inside this process instead of\n * queueing it for opencode. Used by tools that act on plugin state rather\n * than on the workspace (currently only `compress`), so they never reach\n * the broker, never block on a human, and have no deadline.\n */\nexport type ProxyToolInterceptor = (\n input: Record<string, unknown>,\n) => Promise<ProxyToolResult> | ProxyToolResult\n\nexport const SERVER_CLOSED_MESSAGE = \"proxy MCP server closed\"\n\n/** Rejections that fire on normal lifecycle transitions: AFK-permission\n * timeouts, orphan rejections at turn boundaries, stream aborts, and server\n * close while its owning Claude process exits or is replaced. None are\n * user-actionable — file-log them at NOTICE. Anything else stays WARN so\n * genuine bugs remain visible in the TUI. */\nexport function isExpectedCleanupError(message: string): boolean {\n return (\n (message.includes(\"timed out after\") &&\n message.includes(\"waiting for opencode to resolve\")) ||\n message.includes(\"rejecting as orphaned\") ||\n message.includes(\"was orphaned by a new user turn\") ||\n message.includes(\"stream was aborted\") ||\n message.includes(SERVER_CLOSED_MESSAGE)\n )\n}\n\nconst PROTOCOL_VERSION = \"2024-11-05\"\nconst SERVER_NAME = \"opencode_proxy\"\nexport const PROXY_TOOL_PREFIX = `mcp__${SERVER_NAME}__`\n\n// Flat fallback cap on how long a proxy tool call may wait for opencode to\n// resolve it. Matches Claude CLI's hard upper bound for Bash (10 min). The\n// effective deadline is resolved per tool — see `resolveProxyCallTimeoutMs`.\nexport const PROXY_DEFAULT_TIMEOUT_MS = 10 * 60 * 1000\n\n// Per-tool default deadlines, keyed by lowercase proxy tool name. `task`\n// dispatches an opencode subagent that routinely runs 20-40 min; the old\n// flat ceiling fired mid-subagent, made Claude believe its dispatch had\n// failed, and (because the proxy had already returned a timeout error) the\n// late subagent result was dropped on the floor -- the operator had to\n// nudge \"please check now, it seems the task succeeded\" (@jknlsn, live\n// session ses_0cfc0da6, 2026-07-05).\n//\n// `question` blocks on a human reading a TUI form, so the flat ceiling is\n// the wrong unit entirely: a question posed just before the operator steps\n// away would be rejected mid-answer. 30 min is jknlsn's original figure and\n// matches the \"prefer fewer, high-signal questions\" guidance in the def.\nexport const PROXY_PER_TOOL_DEFAULT_TIMEOUT_MS: Record<string, number> = {\n task: 60 * 60 * 1000, // 60 min\n task_batch: 60 * 60 * 1000, // 60 min, same reasoning: it IS task calls\n question: 30 * 60 * 1000, // 30 min\n}\n\n// Node's setTimeout delay is a signed 32-bit int; values above 2^31-1 ms\n// (~24.85 days) trigger TimeoutOverflowWarning and fire at ~1ms instead.\n// Clamp absurd overrides / input.timeouts so a misconfigured deadline\n// can't collapse to \"fires immediately\".\nexport const MAX_PROXY_TIMEOUT_MS = 2 ** 31 - 1\n\n/**\n * Resolve the proxy deadline for a tool call. Layers, most-specific last:\n * 1. flat default (`PROXY_DEFAULT_TIMEOUT_MS`, 10 min)\n * 2. per-tool default (`PROXY_PER_TOOL_DEFAULT_TIMEOUT_MS`)\n * 3. user override via `proxyToolTimeoutMs` config (case-insensitive key)\n * 4. for `bash`, the call's own `input.timeout` -- the proxy must never\n * undercut a build the caller explicitly asked to run long. The bash\n * proxy def advertises a `timeout` field; before this fix the proxy\n * ignored it and killed the call at the flat ceiling anyway.\n * Finally clamped to `MAX_PROXY_TIMEOUT_MS` to stay within Node's timer range.\n */\nexport function resolveProxyCallTimeoutMs(\n toolName: string,\n input: Record<string, unknown> | undefined,\n overrides: Record<string, number> | undefined,\n): number {\n const key = toolName.toLowerCase()\n let ms = PROXY_PER_TOOL_DEFAULT_TIMEOUT_MS[key] ?? PROXY_DEFAULT_TIMEOUT_MS\n if (overrides) {\n const ov = lookupCaseInsensitive(overrides, key)\n if (typeof ov === \"number\" && ov > 0) ms = ov\n }\n if (key === \"bash\") {\n const requested = input?.timeout\n if (typeof requested === \"number\" && requested > ms) ms = requested\n }\n return Math.min(ms, MAX_PROXY_TIMEOUT_MS)\n}\n\nfunction lookupCaseInsensitive(\n map: Record<string, number>,\n key: string,\n): number | undefined {\n if (Object.prototype.hasOwnProperty.call(map, key)) return map[key]\n for (const k of Object.keys(map)) {\n if (k.toLowerCase() === key) return map[k]\n }\n return undefined\n}\n\n/**\n * Client-side abort ceiling written into Claude's `--mcp-config` entry for\n * the proxy server. Without a `timeout` there, Claude CLI's remote-HTTP MCP\n * client aborts each call at its 60-second default even while an opencode\n * subagent is still running (@broskees, PR #18). It must be >= the largest\n * server-side deadline or the client gives up before the broker does, so it\n * tracks the max of the flat default, per-tool defaults, and user overrides.\n * (A bash call raising its own `input.timeout` above this ceiling is a known\n * edge; Claude CLI caps bash at 10 min anyway.)\n */\nexport function resolveProxyClientCeilingMs(\n overrides: Record<string, number> | undefined,\n): number {\n let ms = PROXY_DEFAULT_TIMEOUT_MS\n for (const v of Object.values(PROXY_PER_TOOL_DEFAULT_TIMEOUT_MS)) {\n if (v > ms) ms = v\n }\n if (overrides) {\n for (const v of Object.values(overrides)) {\n if (typeof v === \"number\" && v > ms) ms = v\n }\n }\n return Math.min(ms, MAX_PROXY_TIMEOUT_MS)\n}\n\n/**\n * Build the timeout error surfaced to Claude. Keeps the substrings\n * `\"timed out after\"` and `\"waiting for opencode to resolve\"` that the\n * proxy-mcp catch block classifies as expected cleanup (notice, not warn).\n * For `task` we append guidance: a Task timeout means the subagent may\n * still be running but its result is now unreachable, and the model must\n * neither declare the dispatch failed nor \"schedule a wake-up\" -- that is a\n * Claude Code affordance which cannot fire in this headless/proxy context,\n * so deferring silently drops the work.\n */\nexport function buildProxyTimeoutError(toolName: string, ms: number): Error {\n const key = toolName.toLowerCase()\n const base = `Proxy tool '${toolName}' timed out after ${ms}ms waiting for opencode to resolve the call`\n if (key === \"task\" || key === TASK_BATCH_TOOL_NAME) {\n return new Error(\n base +\n (key === \"task\" ? \" (the subagent).\" : \" (the subagents).\") +\n \" The subagent may still be running but its result\" +\n \" is no longer reachable in this session. Do not declare the dispatch\" +\n \" failed, and do not 'schedule a wake-up' or defer -- that mechanism\" +\n \" does not apply here. If the result is required, re-dispatch or\" +\n \" verify it directly now.\",\n )\n }\n return new Error(base)\n}\n\n/**\n * Disambiguation appended to the `task` proxy def (both the static\n * fallback and the live overlay). Models routinely resolve opencode's\n * \"call the task tool with subagent: X\" mention hint to Claude Code's\n * native TaskCreate (a todo tool) — creating a todo, dispatching nothing,\n * and then narrating a successful dispatch. Others burn turns grepping\n * config files to verify a subagent exists before daring to call it.\n * Both failure modes are addressed here, at the tool the model reads.\n */\nexport const TASK_PROXY_NOTE =\n \"This and task_batch are the ONLY tools that dispatch opencode subagents\" +\n \" (including user @-mentions). Claude Code's built-in TaskCreate/TaskUpdate\" +\n \" manage a local todo list and cannot dispatch subagents. Do not search\" +\n \" config files to verify a subagent type exists: invalid types fail fast\" +\n \" with a clear error. Foreground calls block until the subagent finishes;\" +\n \" set `background` to request opencode's background execution mode. For\" +\n \" two or more independent subagents in one response use task_batch, not\" +\n \" several task calls: those run one after another. Task calls get a\" +\n \" 60-minute proxy deadline by default (configurable via proxyToolTimeoutMs).\"\n\n/**\n * `task_batch`: one MCP call that opencode runs as N parallel `task` calls.\n *\n * Design and first implementation by Joseph Roberts (@broskees) on his fork\n * (68ed142), absorbed here with credit. The limitation it works around is\n * measured, not assumed: Claude Code emits several `mcp__opencode_proxy__*`\n * tool_use blocks in one assistant message but sends the MCP requests one at\n * a time, each only after the previous result (2026-09-06, haiku, two\n * 8-second bash calls: second request arrived 7 ms after the first resolved).\n * So \"call task twice\" is serial by construction, and the only way to get two\n * subagents running at once is a single proxy call that the plugin fans out\n * inside one opencode tool boundary, where opencode executes tool calls\n * concurrently. The children are ordinary `task` calls with ids derived from\n * the parent (`taskBatchChildToolCallId`), and their results are gathered\n * back onto the parent id (`formatTaskBatchResults`) before the CLI sees it.\n */\nexport const TASK_BATCH_TOOL_NAME = \"task_batch\"\n\nexport const TASK_BATCH_PROXY_NOTE =\n \"Use this instead of several task calls in one response: Claude Code runs\" +\n \" MCP tool calls one at a time, so separate task calls run serially even\" +\n \" when emitted together, while one task_batch call fans them out as\" +\n \" parallel opencode task calls. Each task takes the same fields as the\" +\n \" task tool. Results come back in task order, each labelled. Same\" +\n \" 60-minute proxy deadline as task (configurable via proxyToolTimeoutMs).\"\n\nexport const TASK_INPUT_REQUIRED = [\"description\", \"prompt\", \"subagent_type\"]\n\n/** Why a `task_batch` input is unusable, or null when it is fine. */\nexport function taskBatchInputError(input: Record<string, unknown> | undefined): string | null {\n const tasks = input?.tasks\n if (!Array.isArray(tasks) || tasks.length < 2) {\n return \"task_batch requires a `tasks` array with at least two items; use `task` for one subagent\"\n }\n for (const [index, task] of tasks.entries()) {\n if (task === null || typeof task !== \"object\" || Array.isArray(task)) {\n return `task_batch tasks[${index}] must be an object`\n }\n const item = task as Record<string, unknown>\n for (const field of TASK_INPUT_REQUIRED) {\n if (typeof item[field] !== \"string\") {\n return `task_batch tasks[${index}].${field} must be a string`\n }\n }\n }\n return null\n}\n\n/** The batch's task inputs, or [] when the input never passed validation. */\nexport function taskBatchTasks(input: Record<string, unknown> | undefined): Record<string, unknown>[] {\n if (taskBatchInputError(input)) return []\n return input!.tasks as Record<string, unknown>[]\n}\n\n/**\n * Child ids stay derivable from the parent so the next turn can find every\n * child's `tool-result` without extra state. Only `[A-Za-z0-9_-]`: AI SDK\n * bridges normalise other characters and the round trip would not match.\n */\nexport function taskBatchChildToolCallId(parentToolCallId: string, index: number): string {\n return `${parentToolCallId}_task_${index}`\n}\n\n/**\n * One readable result for the parent call. Children are labelled in task\n * order; a child opencode did not answer is said so rather than dropped,\n * since a silent gap would read as a subagent that never ran.\n */\nexport function formatTaskBatchResults(\n children: Array<{ task: Record<string, unknown>; result: ProxyToolResult | null }>,\n): ProxyToolResult {\n const total = children.length\n const sections = children.map(({ task, result }, index) => {\n const label = typeof task.description === \"string\" ? task.description : `task ${index + 1}`\n const agent = typeof task.subagent_type === \"string\" ? ` (${task.subagent_type})` : \"\"\n const header = `## task ${index + 1} of ${total}: ${label}${agent}`\n if (!result) return `${header}\\n[missing] opencode returned no result for this task in the batch`\n if (result.kind === \"error\") return `${header}\\n[error] ${result.message}`\n return `${header}\\n${result.isError ? \"[error] \" : \"\"}${result.text}`\n })\n const failed = children.some(({ result }) => !result || result.kind === \"error\" || result.isError)\n return { kind: \"text\", text: sections.join(\"\\n\\n\"), ...(failed ? { isError: true } : {}) }\n}\n\nconst AGENT_TYPES_HEADING = \"Available agent types\"\n\n/** Longest per-agent blurb we keep; enough to choose, short enough to survive. */\nconst AGENT_BLURB_LIMIT = 140\n\n/**\n * Disambiguation appended to the `question` proxy def. Claude Code ships\n * a built-in `AskUserQuestion` that, when proxied, is disabled via\n * `--disallowedTools`; without an explicit hand-off note models keep\n * reaching for the disabled built-in or fall back to plain text. This\n * states that the proxy is the structured-questions path and summarises\n * the answer shape so the model can act on the result without a second\n * round-trip.\n */\nexport const QUESTION_PROXY_NOTE =\n \"This routes structured questions through opencode's native `question`\" +\n \" tool, which renders a TUI form with the options you provide and\" +\n \" blocks until the operator answers. Claude Code's built-in\" +\n \" AskUserQuestion is disabled in this environment; this proxy is the\" +\n \" ONLY way to ask the operator for a decision or clarification.\" +\n \" Answers come back as arrays of selected labels (set `multiple: true`\" +\n \" to allow more than one). If the operator dismisses the form the call\" +\n \" returns an error — treat that as 'no answer' and stop, do not guess.\" +\n \" Question calls get a 30-minute proxy deadline by default (configurable\" +\n \" via proxyToolTimeoutMs); for long-AFK scenarios prefer fewer,\" +\n \" high-signal questions.\"\n\n/**\n * Disambiguation appended to the `compress` proxy def. Two things the\n * model gets wrong without it: when the reset happens (not mid-turn, so\n * it can keep working after the call), and how much survives it (only\n * the summary, because the fresh spawn is not given the prior transcript).\n */\nexport const COMPRESS_PROXY_NOTE =\n \"The current turn continues normally after this call — finish what you\" +\n \" are doing. The reset happens at the START of the next turn: the\" +\n \" Claude Code session is discarded and a fresh one begins with your\" +\n \" summary as its only prior context. Everything else, including tool\" +\n \" output and files you read, is gone, so write the summary as the\" +\n \" authoritative record. Call this once per compression, when older\" +\n \" resolved work no longer needs full detail.\"\n\n/**\n * Pull *only* the agent-type list out of opencode's live `task` description.\n *\n * jknlsn's original overlaid the whole live description (2.8 KB here) in front\n * of the static def. Live check 2026-07-26 showed that backfires: Claude Code\n * truncates long MCP tool descriptions, and opencode puts the agent list at\n * the *end* (char 2306 of 2858), so the one part the model needs is exactly\n * what gets cut — haiku then guessed `general-purpose`, `default`, and\n * `code-reviewer` (Claude Code's own agent names) and every dispatch failed\n * with \"Unknown agent type\". So: keep the list, drop opencode's preamble\n * (generic delegation advice the model already has), trim each blurb, and let\n * the caller put it first.\n *\n * Returns undefined when the description carries no parsable list, so callers\n * leave the static def alone.\n */\nexport function extractAgentTypeList(\n liveDescription: string | undefined,\n): string | undefined {\n const live = liveDescription?.trim()\n if (!live) return undefined\n const start = live.indexOf(AGENT_TYPES_HEADING)\n if (start === -1) return undefined\n const entries: string[] = []\n for (const raw of live.slice(start).split(\"\\n\")) {\n const match = /^-\\s*([^:]+):\\s*(.+)$/.exec(raw.trim())\n if (!match) continue\n const name = match[1].trim()\n const blurb = match[2].trim()\n entries.push(\n `- ${name}: ${\n blurb.length > AGENT_BLURB_LIMIT\n ? `${blurb.slice(0, AGENT_BLURB_LIMIT).trimEnd()}…`\n : blurb\n }`,\n )\n }\n if (entries.length === 0) return undefined\n return `Valid subagent_type values, from opencode's live registry — anything else fails:\\n${entries.join(\"\\n\")}`\n}\n\n/**\n * Front-load opencode's live agent-type list onto the static `task` proxy def\n * so the model picks a real `subagent_type` instead of guessing a Claude Code\n * name. First, not last: see `extractAgentTypeList` for why position matters.\n * No-op when no list can be extracted (SDK client missing, older opencode) or\n * the `task` def is not among the tools.\n */\nexport function overlayTaskProxyDescription(\n tools: ProxyToolDef[],\n liveDescription: string | undefined,\n): ProxyToolDef[] {\n const agentTypes = extractAgentTypeList(liveDescription)\n if (!agentTypes) return tools\n return tools.map((t) =>\n t.name === \"task\" || t.name === TASK_BATCH_TOOL_NAME\n ? { ...t, description: `${agentTypes}\\n\\n${t.description}` }\n : t,\n )\n}\n\n/**\n * Overlay opencode's live `question` tool description onto the static\n * proxy def, then append the disambiguation note. No-op when the live\n * description is unavailable (older opencode, SDK client missing) — the\n * static def + note stands. Mirrors `overlayTaskProxyDescription`.\n */\nexport function overlayQuestionProxyDescription(\n tools: ProxyToolDef[],\n liveDescription: string | undefined,\n): ProxyToolDef[] {\n const live = liveDescription?.trim()\n if (!live) return tools\n return tools.map((t) =>\n t.name === \"question\"\n ? { ...t, description: `${live}\\n\\n${QUESTION_PROXY_NOTE}` }\n : t,\n )\n}\n\n/**\n * Version gate for the `question` proxy. opencode added a built-in\n * `question` tool (registry id `question`) — on older builds that entry\n * is absent and a forwarded `mcp__opencode_proxy__question` call would\n * resolve to `⚙ invalid` in opencode. Drop the def silently when the\n * live registry does not contain it so the model never sees a dead tool.\n */\nexport function filterQuestionProxyByOpencodeSupport(\n tools: ProxyToolDef[],\n opencodeHasQuestion: boolean,\n): ProxyToolDef[] {\n if (opencodeHasQuestion) return tools\n return tools.filter((t) => t.name !== \"question\")\n}\n\n/** Input fields of one `task`, shared with each `task_batch` item. */\nexport const TASK_INPUT_PROPERTIES = {\n description: {\n type: \"string\",\n description: \"A short (3-5 words) description of the task\",\n },\n prompt: {\n type: \"string\",\n description: \"The task for the agent to perform\",\n },\n subagent_type: {\n type: \"string\",\n description: \"The type of specialized agent to use for this task\",\n },\n task_id: {\n type: \"string\",\n description:\n \"Set this only if you mean to resume a previous task: pass the\" +\n \" prior task_id to continue the same subagent session instead of\" +\n \" creating a fresh one.\",\n },\n command: {\n type: \"string\",\n description: \"The command that triggered this task\",\n },\n background: {\n type: \"boolean\",\n description:\n \"Run the task in the background when supported by opencode\",\n },\n}\n\nexport const DEFAULT_PROXY_TOOLS: ProxyToolDef[] = [\n {\n name: \"bash\",\n description:\n \"Execute a shell command. Routed through opencode's bash tool so\" +\n \" permission prompts flow through opencode's UI.\",\n inputSchema: {\n type: \"object\",\n properties: {\n command: {\n type: \"string\",\n description: \"The shell command to execute.\",\n },\n description: {\n type: \"string\",\n description: \"Short human-readable description of what the command does.\",\n },\n timeout: {\n type: \"number\",\n description: \"Optional timeout in milliseconds.\",\n },\n },\n required: [\"command\"],\n },\n },\n {\n name: \"write\",\n description:\n \"Write a file. Routed through opencode's write tool so permission prompts flow through opencode's UI.\",\n inputSchema: {\n type: \"object\",\n properties: {\n filePath: {\n type: \"string\",\n description: \"The file to write. Absolute paths are preferred.\",\n },\n content: {\n type: \"string\",\n description: \"The full content to write to the file.\",\n },\n },\n required: [\"filePath\", \"content\"],\n },\n },\n {\n name: \"edit\",\n description:\n \"Replace text in an existing file. Routed through opencode's edit tool so permission prompts flow through opencode's UI.\",\n inputSchema: {\n type: \"object\",\n properties: {\n filePath: {\n type: \"string\",\n description: \"The file to edit. Absolute paths are preferred.\",\n },\n oldString: {\n type: \"string\",\n description: \"The exact text to replace.\",\n },\n newString: {\n type: \"string\",\n description: \"The replacement text.\",\n },\n replaceAll: {\n type: \"boolean\",\n description: \"Replace all occurrences instead of just the first one.\",\n },\n },\n required: [\"filePath\", \"oldString\", \"newString\"],\n },\n },\n {\n name: \"webfetch\",\n description:\n \"Fetch content from a URL. Routed through opencode's webfetch tool so\" +\n \" permission prompts flow through opencode's UI. Returns the page\" +\n \" content in the requested format.\",\n inputSchema: {\n type: \"object\",\n properties: {\n url: {\n type: \"string\",\n description: \"The URL to fetch content from. Must start with http:// or https://.\",\n },\n format: {\n type: \"string\",\n enum: [\"text\", \"markdown\", \"html\"],\n description:\n \"The format to return the content in. Defaults to markdown.\",\n },\n timeout: {\n type: \"number\",\n description: \"Optional timeout in seconds (max 120).\",\n },\n },\n required: [\"url\"],\n },\n },\n {\n name: \"task\",\n description:\n \"Launch an opencode subagent to handle a complex multi-step task\" +\n \" autonomously. Routed through opencode's task tool so subagent\" +\n \" orchestration, permission, and lifecycle are handled by opencode.\" +\n \" Use `subagent_type` to pick which configured subagent runs (e.g.\" +\n \" `build`, `general`, `explore`, or any custom subagent declared in\" +\n \" opencode.json). \" +\n TASK_PROXY_NOTE,\n inputSchema: {\n type: \"object\",\n properties: TASK_INPUT_PROPERTIES,\n required: TASK_INPUT_REQUIRED,\n },\n },\n {\n name: TASK_BATCH_TOOL_NAME,\n description:\n \"Launch two or more independent opencode subagents at the same time and\" +\n \" get all their results back together. Put one ordinary task input in\" +\n \" `tasks` for each subagent. \" +\n TASK_BATCH_PROXY_NOTE,\n inputSchema: {\n type: \"object\",\n properties: {\n tasks: {\n type: \"array\",\n minItems: 2,\n description: \"Independent subagent tasks to run concurrently\",\n items: {\n type: \"object\",\n properties: TASK_INPUT_PROPERTIES,\n required: TASK_INPUT_REQUIRED,\n },\n },\n },\n required: [\"tasks\"],\n },\n },\n {\n name: \"question\",\n description:\n \"Ask the operator structured questions with options and receive\" +\n \" their answers back. Routed through opencode's native `question`\" +\n \" tool so the prompt renders as a real TUI form (with options and a\" +\n \" custom-answer field) instead of a plain text turn. Use this when\" +\n \" you need a decision, clarification, or preference from the\" +\n \" operator mid-task. \" +\n QUESTION_PROXY_NOTE,\n inputSchema: {\n type: \"object\",\n properties: {\n questions: {\n type: \"array\",\n description: \"Questions to ask.\",\n items: {\n type: \"object\",\n properties: {\n question: {\n type: \"string\",\n description: \"Complete question.\",\n },\n header: {\n type: \"string\",\n description: \"Very short label (max 30 chars).\",\n },\n options: {\n type: \"array\",\n description: \"Available choices.\",\n items: {\n type: \"object\",\n properties: {\n label: {\n type: \"string\",\n description: \"Display text (1-5 words, concise).\",\n },\n description: {\n type: \"string\",\n description: \"Explanation of choice.\",\n },\n },\n required: [\"label\", \"description\"],\n },\n },\n multiple: {\n type: \"boolean\",\n description:\n \"Allow selecting multiple choices. Defaults to false.\",\n },\n },\n required: [\"question\", \"header\", \"options\"],\n },\n },\n },\n required: [\"questions\"],\n },\n },\n {\n name: \"compress\",\n description:\n \"Replace older conversation detail with a summary you write, then\" +\n \" continue in a fresh Claude Code session. Handled inside the plugin,\" +\n \" so it never prompts the operator. \" +\n COMPRESS_PROXY_NOTE,\n inputSchema: {\n type: \"object\",\n properties: {\n summary: {\n type: \"string\",\n description:\n \"Dense technical summary of the work being compressed: decisions\" +\n \" made, files changed, commands run and their outcomes, and what\" +\n \" is still open. This is the ONLY prior context that survives, so\" +\n \" anything omitted is lost.\",\n },\n },\n required: [\"summary\"],\n },\n },\n]\n\nexport async function createProxyMcpServer(\n tools: ProxyToolDef[] = DEFAULT_PROXY_TOOLS,\n timeoutOverrides?: Record<string, number>,\n interceptors?: Map<string, ProxyToolInterceptor>,\n): Promise<ProxyMcpServer> {\n const calls = new EventEmitter()\n const pending = new Map<string, ProxyToolCall>()\n\n // Per-server bearer secret (256 bits). This endpoint executes Bash/Edit/\n // Write through opencode's executor, so an unauthenticated caller on\n // loopback would have arbitrary command execution. The token lives only\n // in this process and in the 0600 MCP config file Claude reads; it is\n // deliberately kept out of the URL, because query strings leak into logs\n // and process listings.\n const authToken = crypto.randomBytes(32).toString(\"hex\")\n const expectedAuth = Buffer.from(`Bearer ${authToken}`)\n // The exact authority we hand to Claude. Set once the ephemeral port is\n // known; compared against the Host header to defeat DNS rebinding.\n let boundAuthority = \"\"\n\n function authOk(req: IncomingMessage): boolean {\n const got = req.headers.authorization\n if (typeof got !== \"string\") return false\n const candidate = Buffer.from(got)\n // timingSafeEqual throws on length mismatch, so length-check first.\n // Length is not secret (the token is fixed-width).\n if (candidate.length !== expectedAuth.length) return false\n return crypto.timingSafeEqual(candidate, expectedAuth)\n }\n\n /**\n * Reject a request without leaving the connection usable.\n *\n * Ending the response alone is not enough. A peer can declare a large\n * Content-Length, send a single byte, take the rejection, and leave the\n * request still arriving — and `server.close()` does not reap connections\n * that are still sending, so a shutdown would hang behind it. Node's\n * default whole-request timeout is five minutes, which is five minutes of\n * a socket held by an unauthenticated caller.\n *\n * `Connection: close` tells Node to close once the response is flushed;\n * destroying the socket on `finish` covers the case where the peer never\n * finishes its body.\n */\n function reject(\n req: IncomingMessage,\n res: ServerResponse,\n statusCode: number,\n reason: string,\n ): void {\n // Every guard below is a measured property of the client we spawn, not a\n // guarantee about future ones. If a later Claude CLI starts sending an\n // Origin header, or a different Content-Type, every proxy call would\n // 403/415 with no other symptom than tools mysteriously not working — so\n // say why, here, once per rejected request. Header VALUES are omitted:\n // this line must never carry the bearer token.\n log.notice(\"proxy-mcp rejected a request\", {\n statusCode,\n reason,\n method: req.method,\n hasAuthorization: typeof req.headers.authorization === \"string\",\n })\n res.statusCode = statusCode\n res.setHeader(\"Connection\", \"close\")\n res.on(\"finish\", () => {\n req.socket?.destroy()\n })\n res.end()\n }\n\n const server = createServer(async (req, res) => {\n if (req.method !== \"POST\" || !req.url?.startsWith(\"/mcp\")) {\n reject(req, res, 404, \"not a POST to /mcp\")\n return\n }\n // Everything below runs BEFORE readBody: an unauthenticated peer must\n // not be able to stream an unbounded body into memory.\n //\n // DNS rebinding: a browser rebound onto this port via an attacker\n // hostname sends that hostname in Host, never the loopback authority we\n // generated. This does NOT block a page posting directly to\n // 127.0.0.1:<port> — such a request carries exactly the expected Host —\n // so it is a rebinding defense specifically, not a browser defense. The\n // Origin and Content-Type guards below, and the token, cover that case.\n if (req.headers.host !== boundAuthority) {\n reject(req, res, 403, \"host header is not the bound authority\")\n return\n }\n // Claude Code 2.1.226 sends no Origin on MCP requests (verified). The MCP\n // transport spec obliges SERVERS to validate Origin; it does not oblige\n // clients to omit it, so this is a measured property of the client we\n // spawn rather than a guarantee about all conforming clients.\n if (req.headers.origin !== undefined) {\n reject(req, res, 403, \"origin header present\")\n return\n }\n // Requiring application/json forces a CORS preflight for cross-origin\n // callers (which then fails), closing the text/plain \"simple request\"\n // bypass that would otherwise allow blind cross-site POSTs.\n const contentType = String(req.headers[\"content-type\"] ?? \"\")\n .split(\";\")[0]\n .trim()\n .toLowerCase()\n if (contentType !== \"application/json\") {\n reject(req, res, 415, \"content-type is not application/json\")\n return\n }\n if (!authOk(req)) {\n reject(req, res, 401, \"missing or invalid bearer token\")\n return\n }\n // Hoist the request id and method so the catch block can echo them\n // in error responses. Without this, a broker rejection (timeout /\n // orphan) on a tools/call lands in the catch with no visible id, and\n // the response goes back with `id: null` which Claude CLI cannot\n // match to the original request. The method is also needed because\n // tools/call errors must be returned as MCP results with isError\n // (not JSON-RPC errors) or Claude CLI rejects them as a \"malformed\n // result that failed schema validation\" (seen live 2026-07-04).\n let requestId: number | string | null = null\n let requestMethod: string | null = null\n // Hoisted for the same reason: once SSE headers are out, an error must\n // travel down the stream instead of through writeJson (which would try\n // to set headers again and throw inside the catch).\n let sse: EventStream | null = null\n try {\n const body = await readBody(req)\n const request = JSON.parse(body) as {\n jsonrpc?: string\n id?: number | string | null\n method?: string\n params?: Record<string, unknown>\n }\n requestId = request?.id ?? null\n requestMethod = typeof request?.method === \"string\" ? request.method : null\n\n if (request?.jsonrpc !== \"2.0\" || typeof request.method !== \"string\") {\n writeJson(res, {\n jsonrpc: \"2.0\",\n id: requestId,\n error: { code: -32600, message: \"Invalid request\" },\n })\n return\n }\n\n log.debug(\"proxy-mcp request\", {\n method: request.method,\n id: request.id,\n })\n\n if (request.method === \"initialize\") {\n writeJson(res, {\n jsonrpc: \"2.0\",\n id: requestId,\n result: {\n protocolVersion: PROTOCOL_VERSION,\n capabilities: { tools: {} },\n serverInfo: {\n name: SERVER_NAME,\n version: \"0.1.0\",\n },\n },\n })\n return\n }\n\n if (request.method === \"notifications/initialized\") {\n res.statusCode = 204\n res.end()\n return\n }\n\n if (request.method === \"tools/list\") {\n writeJson(res, {\n jsonrpc: \"2.0\",\n id: requestId,\n result: {\n tools: tools.map((t) => ({\n name: t.name,\n description: t.description,\n inputSchema: t.inputSchema,\n })),\n },\n })\n return\n }\n\n if (request.method === \"tools/call\") {\n const params = request.params ?? {}\n const toolName = String(params.name ?? \"\")\n const input = (params.arguments ?? {}) as Record<string, unknown>\n\n if (!tools.some((t) => t.name === toolName)) {\n // tools/call failures MUST be MCP results with isError, never\n // JSON-RPC error envelopes: Claude CLI validates every tools/call\n // response against the MCP result schema and rejects JSON-RPC\n // errors as malformed (@jknlsn, seen live 2026-07-04).\n writeJson(res, {\n jsonrpc: \"2.0\",\n id: requestId,\n result: {\n content: [{ type: \"text\", text: `Unknown proxy tool: ${toolName}` }],\n isError: true,\n },\n })\n return\n }\n\n if (toolName === TASK_BATCH_TOOL_NAME) {\n const problem = taskBatchInputError(input)\n if (problem) {\n // Same rule as the unknown-tool path: an MCP result with isError,\n // never a JSON-RPC error envelope.\n writeToolCallResult(res, requestId, { kind: \"error\", message: problem })\n return\n }\n }\n\n // Intercepted tools act on plugin state, not on the workspace, so\n // they are answered here and never queued for opencode. The result\n // still goes through the shared MCP envelope below — a JSON-RPC\n // error here would be rejected by Claude CLI exactly like any other\n // tools/call error envelope.\n const interceptor = interceptors?.get(toolName)\n if (interceptor) {\n let intercepted: ProxyToolResult\n try {\n intercepted = await interceptor(input)\n } catch (interceptorError) {\n const message =\n interceptorError instanceof Error\n ? interceptorError.message\n : String(interceptorError)\n log.warn(\"proxy-mcp interceptor failed\", { toolName, error: message })\n intercepted = { kind: \"error\", message }\n }\n writeToolCallResult(res, requestId, intercepted)\n return\n }\n\n const callId = crypto.randomUUID()\n log.info(\"proxy-mcp tool call received\", {\n callId,\n toolName,\n hasInput: input != null,\n sse: acceptsEventStream(req.headers.accept),\n })\n\n // Broker-backed calls can block for an hour on a subagent. Use SSE when the\n // client accepts one: headers and a comment go out now, keepalive\n // comments follow, and the JSON-RPC result is the final event. A\n // client that only accepts JSON gets the old single-shot reply.\n const channel: ProxyCallChannel = { closed: false }\n if (acceptsEventStream(req.headers.accept)) {\n sse = openEventStream(res)\n }\n res.once(\"close\", () => {\n sse?.stop()\n if (res.writableFinished) return\n channel.closed = true\n log.notice(\"proxy-mcp client closed a tool call before its result\", {\n callId,\n toolName,\n })\n })\n\n let timer: ReturnType<typeof setTimeout> | null = null\n const result = await new Promise<ProxyToolResult>(\n (resolve, reject) => {\n const entry: ProxyToolCall = {\n id: callId,\n toolName,\n input,\n resolve,\n reject,\n channel,\n }\n pending.set(callId, entry)\n const deadlineMs = resolveProxyCallTimeoutMs(\n toolName,\n input,\n timeoutOverrides,\n )\n timer = setTimeout(() => {\n if (!pending.has(callId)) return\n pending.delete(callId)\n // v0.4.13: demoted from warn to notice. Timeouts are usually\n // permission-pending while the user is AFK — surfacing each as\n // a yellow UI bubble produces a wall of noise on return. The\n // file log still captures the event for diagnostics.\n log.notice(\"proxy-mcp tool call timed out\", {\n callId,\n toolName,\n deadlineMs,\n })\n reject(buildProxyTimeoutError(toolName, deadlineMs))\n }, deadlineMs)\n calls.emit(\"call\", entry)\n },\n ).finally(() => {\n if (timer) clearTimeout(timer)\n pending.delete(callId)\n })\n\n if (channel.closed) {\n // Nobody is reading. The language model already saw the closed\n // channel and hands the result to Claude another way.\n log.notice(\"proxy-mcp dropping result for a closed tool call\", {\n callId,\n toolName,\n })\n return\n }\n writeToolCallResult(res, requestId, result, sse)\n return\n }\n\n writeJson(res, {\n jsonrpc: \"2.0\",\n id: requestId,\n error: { code: -32601, message: `Unknown method: ${request.method}` },\n })\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error)\n const logFn = isExpectedCleanupError(errorMessage) ? log.notice : log.warn\n logFn(\"proxy-mcp error handling request\", {\n error: errorMessage,\n })\n // Broker rejections (timeouts, orphans, server close) surface here for\n // tools/call requests. Same rule as above: respond with an MCP result\n // carrying isError, never a JSON-RPC error envelope, or Claude CLI\n // rejects the response as schema-invalid.\n if (requestMethod === \"tools/call\") {\n try {\n writeToolCallResult(\n res,\n requestId,\n { kind: \"error\", message: errorMessage },\n sse,\n )\n } catch {\n try {\n res.statusCode = 500\n res.end()\n } catch {}\n }\n return\n }\n try {\n // tools/call already returned above with an MCP result; anything\n // reaching here is a protocol-level method (initialize, tools/list)\n // where a JSON-RPC error is the correct shape.\n writeJson(res, {\n jsonrpc: \"2.0\",\n id: requestId,\n error: {\n code: -32603,\n message: error instanceof Error ? error.message : \"Internal error\",\n },\n })\n } catch {\n try {\n res.statusCode = 500\n res.end()\n } catch {}\n }\n }\n })\n\n await new Promise<void>((resolve, reject) => {\n server.once(\"error\", reject)\n server.listen(0, \"127.0.0.1\", () => {\n server.off(\"error\", reject)\n resolve()\n })\n })\n\n const addr = server.address() as AddressInfo | null\n if (!addr) {\n server.close()\n throw new Error(\"Failed to bind proxy MCP server\")\n }\n\n boundAuthority = `127.0.0.1:${addr.port}`\n const url = `http://${boundAuthority}/mcp`\n\n // NOTE: authToken is deliberately absent from this line and every other\n // log call. The plugin log is written to disk and echoed to the TUI in\n // debug mode; a leaked token there would defeat the whole mechanism.\n log.info(\"proxy-mcp server started\", {\n url,\n tools: tools.map((t) => t.name),\n })\n\n let configFilePath: string | null = null\n\n const api: ProxyMcpServer = {\n url,\n serverName: SERVER_NAME,\n tools,\n authToken,\n calls,\n configPath() {\n if (configFilePath) return configFilePath\n const body = JSON.stringify(\n {\n mcpServers: {\n [SERVER_NAME]: {\n type: \"http\",\n url,\n // Claude CLI replays these headers on every request to this\n // server, which is what lets the handler above reject anyone\n // who did not read this 0600 file.\n headers: { Authorization: `Bearer ${authToken}` },\n timeout: resolveProxyClientCeilingMs(timeoutOverrides),\n },\n },\n },\n null,\n 2,\n )\n const hash = crypto\n .createHash(\"sha256\")\n .update(body)\n .digest(\"hex\")\n .slice(0, 12)\n const outPath = path.join(\n pluginTmpDir(),\n `proxy-${hash}.json`,\n )\n fs.writeFileSync(outPath, body, { encoding: \"utf8\", mode: 0o600 })\n configFilePath = outPath\n return outPath\n },\n async close() {\n for (const entry of pending.values()) {\n entry.reject(new Error(SERVER_CLOSED_MESSAGE))\n }\n pending.clear()\n await new Promise<void>((resolve) => {\n server.close(() => resolve())\n })\n if (configFilePath) {\n try {\n fs.unlinkSync(configFilePath)\n } catch {}\n configFilePath = null\n }\n },\n }\n\n return api\n}\n\n/** CLI-ready list of Claude tool names to disable, for each proxied tool. */\nexport function disallowedToolFlags(tools: ProxyToolDef[]): string[] {\n // Map our lowercase MCP tool names to the Claude tool name(s) they replace.\n // `edit` covers both `Edit` and `MultiEdit` because opencode has no\n // MultiEdit equivalent; without disabling MultiEdit, Claude can batch\n // file changes through it and bypass opencode's permission UI.\n // `task` disables Claude CLI's `Agent` tool (its built-in subagent\n // dispatcher) so subagent calls flow through opencode's `task` tool\n // instead — which lets opencode's configured subagent set (`build`,\n // `general`, custom subagents in opencode.json) execute the work\n // under opencode's permission/lifecycle, rather than Claude's\n // internal-only general-purpose / Explore / Plan options.\n const nameMap: Record<string, string[]> = {\n bash: [\"Bash\"],\n read: [\"Read\"],\n write: [\"Write\"],\n edit: [\"Edit\", \"MultiEdit\"],\n glob: [\"Glob\"],\n grep: [\"Grep\"],\n webfetch: [\"WebFetch\"],\n task: [\"Agent\"],\n task_batch: [\"Agent\"],\n // `question` disables Claude Code's built-in `AskUserQuestion` so the\n // structured-questions path flows through opencode's native `question`\n // tool instead — same UI/permission/audit benefits as the other\n // proxies. Without this, the model can call both and the two paths\n // diverge (opencode's form vs the headless deny-and-render fallback).\n question: [\"AskUserQuestion\"],\n }\n const out: string[] = []\n const seen = new Set<string>()\n for (const t of tools) {\n const mapped = nameMap[t.name.toLowerCase()]\n if (!mapped) continue\n for (const claudeTool of mapped) {\n if (seen.has(claudeTool)) continue\n seen.add(claudeTool)\n out.push(claudeTool)\n }\n }\n return out\n}\n\n/**\n * Everything that goes to `--disallowedTools` for one spawn: the built-ins\n * the proxied tools replace, plus the ones the operator named directly.\n *\n * `disallowedToolFlags` can only cover tools the plugin has a proxy for, so\n * a built-in with no equivalent (`NotebookEdit`, and anything Claude Code\n * ships next) is unreachable without `extraDisallowedTools` — issue #26.\n */\nexport function resolveDisallowedTools(options: {\n proxyTools?: ProxyToolDef[] | null\n extraDisallowedTools?: string[]\n disableWebSearch?: boolean\n}): string[] {\n const out: string[] = []\n const seen = new Set<string>()\n const push = (name: string) => {\n const trimmed = name.trim()\n if (!trimmed || seen.has(trimmed)) return\n seen.add(trimmed)\n out.push(trimmed)\n }\n\n for (const name of disallowedToolFlags(options.proxyTools ?? [])) push(name)\n for (const name of options.extraDisallowedTools ?? []) push(String(name))\n if (options.disableWebSearch) push(\"WebSearch\")\n return out\n}\n\nfunction readBody(req: IncomingMessage): Promise<string> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = []\n req.on(\"data\", (chunk: Buffer) => chunks.push(chunk))\n req.on(\"end\", () => resolve(Buffer.concat(chunks).toString(\"utf8\")))\n req.on(\"error\", reject)\n })\n}\n\n/**\n * The single exit for every `tools/call`, broker-backed or intercepted.\n * Success and failure share one MCP result envelope: a JSON-RPC error for\n * `kind: \"error\"` was rejected by Claude CLI as a \"malformed result that\n * failed schema validation\", so tool failures must surface as\n * `isError: true` instead.\n */\nfunction writeToolCallResult(\n res: ServerResponse,\n requestId: unknown,\n result: ProxyToolResult,\n sse: EventStream | null = null,\n): void {\n const text = result.kind === \"error\" ? result.message : result.text\n const isError = result.kind === \"error\" || result.isError === true\n const envelope = {\n jsonrpc: \"2.0\",\n id: requestId ?? null,\n result: {\n content: [{ type: \"text\", text }],\n isError,\n },\n }\n if (sse) {\n sse.finish(envelope)\n return\n }\n writeJson(res, envelope)\n}\n\n/**\n * An in-flight SSE reply. `finish` writes the JSON-RPC response as the\n * single `message` event and ends the stream, which is what the MCP\n * Streamable HTTP client expects for a request answered over SSE.\n */\ninterface EventStream {\n finish(envelope: unknown): void\n stop(): void\n}\n\nfunction openEventStream(res: ServerResponse): EventStream {\n res.statusCode = 200\n res.setHeader(\"Content-Type\", \"text/event-stream\")\n res.setHeader(\"Cache-Control\", \"no-cache, no-transform\")\n res.setHeader(\"Connection\", \"keep-alive\")\n res.flushHeaders()\n // Start the response body without waiting for the tool result.\n res.write(\": open\\n\\n\")\n let timer: ReturnType<typeof setInterval> | null = setInterval(() => {\n if (res.writableEnded || res.destroyed) {\n stop()\n return\n }\n res.write(\": keepalive\\n\\n\")\n }, SSE_KEEPALIVE_MS)\n // Never keep the host process alive for a keepalive alone.\n timer.unref?.()\n const stop = () => {\n if (timer) {\n clearInterval(timer)\n timer = null\n }\n }\n return {\n stop,\n finish(envelope) {\n stop()\n if (res.writableEnded || res.destroyed) return\n res.end(`event: message\\ndata: ${JSON.stringify(envelope)}\\n\\n`)\n },\n }\n}\n\nfunction writeJson(res: ServerResponse, body: unknown): void {\n if (res.destroyed || res.writableEnded) return\n const payload = JSON.stringify(body)\n res.statusCode = 200\n res.setHeader(\"Content-Type\", \"application/json\")\n res.setHeader(\"Content-Length\", Buffer.byteLength(payload).toString())\n res.end(payload)\n}\n","import * as fs from \"node:fs\"\nimport * as os from \"node:os\"\nimport * as path from \"node:path\"\n\n/**\n * Per-process scratch directory for plugin tmp files (bridged MCP config,\n * proxy server config, etc.). Created lazily on first use and rm'd on\n * normal process exit so we don't leak across runs. PID-isolated so two\n * concurrent opencode processes don't race on the same files.\n *\n * Caveat: `process.on(\"exit\")` does not fire for SIGKILL or unhandled\n * external signals, so abnormal terminations still leak. OS-level tmpdir\n * cleanup (`systemd-tmpfiles`, macOS periodic) handles those eventually.\n */\nconst PLUGIN_TMP_DIR = path.join(\n os.tmpdir(),\n `opencode-claude-code-${process.pid}`,\n)\n\nlet registered = false\n\nexport function pluginTmpDir(): string {\n if (!fs.existsSync(PLUGIN_TMP_DIR)) {\n fs.mkdirSync(PLUGIN_TMP_DIR, { recursive: true })\n }\n if (!registered) {\n registered = true\n process.on(\"exit\", () => {\n try {\n fs.rmSync(PLUGIN_TMP_DIR, { recursive: true, force: true })\n } catch {}\n })\n }\n return PLUGIN_TMP_DIR\n}\n","export const QUESTION_TOOL_NAME = \"question\"\n\nexport const APPROVED_EXIT_PLAN_MODE_MESSAGE =\n \"User has approved your plan. You can now start coding. Start with updating your todo list if applicable.\"\n\nconst REJECTED_EXIT_PLAN_MODE_PREFIX =\n \"The user doesn't want to proceed with this tool use. The tool use was rejected. To tell you how to proceed, the user said:\"\n\nconst PLAN_MODE_APPROVAL_QUESTION = \"Do you want to proceed with this plan?\"\nconst OPENCODE_QUESTION_RESULT_PREFIX =\n `User has answered your questions: \"${PLAN_MODE_APPROVAL_QUESTION}\"=\"`\nconst OPENCODE_QUESTION_RESULT_SUFFIX =\n `\". You can now continue with the user's answers in mind.`\n\nconst KEY_SEPARATOR = \"\\u0000\"\n\nexport interface ExitPlanModeQuestionCall {\n toolCallId: string\n toolName: typeof QUESTION_TOOL_NAME\n input: {\n questions: Array<{\n header: string\n question: string\n options: Array<{ label: string; description: string }>\n multiple: boolean\n custom: boolean\n }>\n }\n text: string\n}\n\n/**\n * Whether to bridge `ExitPlanMode` into opencode's native `question` tool\n * this turn.\n *\n * Opt-in (`planModeQuestion`) because opencode's question form does not\n * currently render (anomalyco/opencode#36604), so an enabled bridge hangs the\n * turn until the operator interrupts, where the text path still works.\n * Gated on the live registry because emitting a `question` tool-call on a\n * build without that entry renders `⚙ invalid` and wedges the turn just the\n * same. Never bridged during compaction: that turn is text-only and its\n * answer would have nowhere to go.\n */\nexport function isPlanModeQuestionActive(input: {\n configured: boolean | undefined\n opencodeHasQuestion: boolean\n compactionMode: boolean\n}): boolean {\n if (input.compactionMode) return false\n if (input.configured !== true) return false\n return input.opencodeHasQuestion\n}\n\nconst pendingQuestions = new Map<string, string>()\n\nfunction pendingKey(sessionKey: string, questionToolCallId: string): string {\n return `${sessionKey}${KEY_SEPARATOR}${questionToolCallId}`\n}\n\nexport function clearExitPlanModeQuestions(sessionKey: string): void {\n const prefix = `${sessionKey}${KEY_SEPARATOR}`\n for (const key of pendingQuestions.keys()) {\n if (key.startsWith(prefix)) pendingQuestions.delete(key)\n }\n}\n\nexport function hasExitPlanModeQuestions(sessionKey: string): boolean {\n const prefix = `${sessionKey}${KEY_SEPARATOR}`\n return [...pendingQuestions.keys()].some((key) => key.startsWith(prefix))\n}\n\nexport function createExitPlanModeQuestionCall(\n sessionKey: string,\n exitPlanModeToolUseId: string,\n plan: string,\n questionToolCallId = `exit_plan_question_${exitPlanModeToolUseId}`,\n): ExitPlanModeQuestionCall {\n pendingQuestions.set(pendingKey(sessionKey, questionToolCallId), exitPlanModeToolUseId)\n\n return {\n toolCallId: questionToolCallId,\n toolName: QUESTION_TOOL_NAME,\n input: {\n questions: [\n {\n header: \"Plan approval\",\n question: PLAN_MODE_APPROVAL_QUESTION,\n options: [\n { label: \"yes\", description: \"\" },\n { label: \"no\", description: \"\" },\n ],\n multiple: false,\n custom: true,\n },\n ],\n },\n text: plan ? `\\n\\n${plan}\\n` : \"\\n\\n\",\n }\n}\n\nfunction buildToolResultMessage(input: {\n toolUseId: string\n approved: boolean\n feedback: string\n}): string {\n return JSON.stringify({\n type: \"user\",\n message: {\n role: \"user\",\n content: [\n input.approved\n ? {\n type: \"tool_result\",\n tool_use_id: input.toolUseId,\n content: APPROVED_EXIT_PLAN_MODE_MESSAGE,\n }\n : {\n type: \"tool_result\",\n tool_use_id: input.toolUseId,\n content: `${REJECTED_EXIT_PLAN_MODE_PREFIX}\\n${input.feedback || \"no\"}`,\n is_error: true,\n },\n ],\n },\n })\n}\n\nfunction tryParseJson(text: string): unknown {\n try {\n return JSON.parse(text)\n } catch {\n return text\n }\n}\n\nfunction unwrapToolOutput(part: any): unknown {\n const output = part?.output ?? part?.result\n if (typeof output === \"string\") return tryParseJson(output)\n if (!output || typeof output !== \"object\") return output\n\n switch (output.type) {\n case \"json\":\n case \"error-json\":\n return output.value\n case \"text\":\n case \"error-text\":\n return tryParseJson(String(output.value ?? \"\"))\n case \"execution-denied\":\n return {\n denied: true,\n reason: String(output.reason ?? \"question rejected\"),\n }\n case \"content\":\n return Array.isArray(output.value)\n ? output.value\n .map((item: any) => {\n if (item?.type === \"text\") return item.text\n return JSON.stringify(item)\n })\n .join(\"\\n\")\n : output.value\n default:\n return output\n }\n}\n\nfunction unwrapOpencodeQuestionResult(value: string): string {\n if (\n value.startsWith(OPENCODE_QUESTION_RESULT_PREFIX) &&\n value.endsWith(OPENCODE_QUESTION_RESULT_SUFFIX)\n ) {\n return value.slice(\n OPENCODE_QUESTION_RESULT_PREFIX.length,\n -OPENCODE_QUESTION_RESULT_SUFFIX.length,\n )\n }\n return value\n}\n\nfunction collectAnswerStrings(value: unknown): string[] {\n if (typeof value === \"string\") return [unwrapOpencodeQuestionResult(value)]\n if (Array.isArray(value)) return value.flatMap(collectAnswerStrings)\n if (!value || typeof value !== \"object\") return []\n\n const obj = value as Record<string, unknown>\n if (obj.denied === true) return [String(obj.reason ?? \"question rejected\")]\n\n for (const key of [\"answers\", \"answer\", \"selected\", \"selection\", \"value\"]) {\n if (key in obj) return collectAnswerStrings(obj[key])\n }\n\n return []\n}\n\nfunction classifyQuestionResult(part: any): { approved: boolean; feedback: string } {\n const output = unwrapToolOutput(part)\n const answers = collectAnswerStrings(output)\n .map((answer) => answer.trim())\n .filter(Boolean)\n\n if (answers.length === 1 && answers[0].toLowerCase() === \"yes\") {\n return { approved: true, feedback: \"\" }\n }\n\n return {\n approved: false,\n feedback: answers.length > 0 ? answers.join(\"\\n\") : \"no\",\n }\n}\n\nexport function consumeExitPlanModeQuestionResult(\n sessionKey: string,\n prompt: Array<{ role: string; content?: unknown }>,\n): string | null {\n for (let i = prompt.length - 1; i >= 0; i--) {\n const msg = prompt[i]\n if (!Array.isArray(msg.content)) continue\n\n for (const part of msg.content as any[]) {\n if (part?.type !== \"tool-result\" || typeof part.toolCallId !== \"string\") {\n continue\n }\n\n const key = pendingKey(sessionKey, part.toolCallId)\n const exitPlanModeToolUseId = pendingQuestions.get(key)\n if (!exitPlanModeToolUseId) continue\n\n pendingQuestions.delete(key)\n const result = classifyQuestionResult(part)\n return buildToolResultMessage({\n toolUseId: exitPlanModeToolUseId,\n approved: result.approved,\n feedback: result.feedback,\n })\n }\n }\n\n return null\n}\n","/**\n * Per-session state for the opt-in `compress` proxy tool.\n *\n * Keyed by session key (the same `cwd::modelId::scope::affinity` string\n * session-manager uses). When Claude calls the intercepted `compress` tool\n * the summary is stored here and the session is marked for restart. The\n * next `doStream` turn consumes that mark, evicts the running child and its\n * Claude session id, and the fresh spawn gets the summary prepended to its\n * appended system prompt.\n *\n * The summary deliberately survives `deleteClaudeSessionId()`: the restart\n * path calls it, so clearing there would wipe the summary microseconds\n * before the new spawn reads it (the original fork version did exactly\n * that, which made the whole feature a no-op). It is dropped when a new\n * opencode conversation starts on the same key, and by the entry cap below.\n */\n\nimport { log } from \"./logger.js\"\n\ninterface CompressionState {\n summary: string\n restartPending: boolean\n}\n\n/**\n * Session keys are bounded in practice by workspaces × models, and each\n * entry is one summary string, but a long-lived opencode process that\n * hops workspaces should not accumulate them forever.\n */\nconst MAX_COMPRESSION_ENTRIES = 32\n\nconst compressions = new Map<string, CompressionState>()\n\n/**\n * Record a summary and mark the session for restart. Storing and marking\n * are one event on purpose: a stored summary that never resets the session\n * would silently do nothing.\n */\nexport function storeCompressionSummary(sessionKey: string, summary: string): void {\n compressions.set(sessionKey, { summary, restartPending: true })\n while (compressions.size > MAX_COMPRESSION_ENTRIES) {\n const oldest = compressions.keys().next()\n if (oldest.done) break\n compressions.delete(oldest.value)\n log.info(\"compression store evicted oldest entry\", { sessionKey: oldest.value })\n }\n}\n\nexport function getCompressionSummary(sessionKey: string): string | undefined {\n return compressions.get(sessionKey)?.summary\n}\n\n/**\n * True once per compress call, for the turn that performs the reset. The\n * summary is kept: it is the prior context for every spawn that follows,\n * until a new conversation clears it.\n */\nexport function consumeCompressionRestart(sessionKey: string): boolean {\n const state = compressions.get(sessionKey)\n if (!state?.restartPending) return false\n state.restartPending = false\n return true\n}\n\nexport function clearCompression(sessionKey: string): void {\n compressions.delete(sessionKey)\n}\n","import { randomUUID } from \"node:crypto\"\nimport type { ChildProcess } from \"node:child_process\"\nimport { cliSupportsSideQuestion, type CliVersion } from \"./cli-version.js\"\nimport type { ActiveProcess } from \"./session-manager.js\"\n\ntype SideQuestionProcess = Pick<ActiveProcess, \"proc\" | \"lineEmitter\">\n\nexport interface SideQuestionResult {\n response: string\n synthetic: boolean\n}\n\nexport interface SideQuestionOptions {\n cliVersion: CliVersion | null\n interactive?: boolean\n abortSignal?: AbortSignal\n timeoutMs?: number\n history?: readonly { question: string; response: string }[]\n}\n\nexport interface SideQuestionExchange {\n question: string\n response: string\n}\n\nconst MAX_HISTORY_EXCHANGES = 20\n\nexport const SIDE_QUESTION_USAGE =\n \"Usage: /btw <question>. Ask a side question about the current conversation without adding it to the main context.\"\n\nconst pendingProcesses = new WeakSet<ChildProcess>()\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value)\n}\n\n/**\n * opencode appends its own `<system-reminder>` blocks to the user message, as\n * extra text parts on the same message. They instruct a normal turn and are not\n * part of what the operator typed after `/btw`, so they must not travel with the\n * aside: a plan-mode reminder alone is over 1.5 KB, and measured live it both\n * steered the answer and kept a bare `/btw` from ever looking empty.\n *\n * Blocks are removed wherever they sit rather than by matching a whole part,\n * because a harness may append its own trailing metadata after one (opencode-dcp\n * adds a `<dcp-message-id>` marker), which an end-anchored check would miss.\n */\nconst SYSTEM_REMINDER_BLOCK = /<system-reminder>[\\s\\S]*?<\\/system-reminder>/g\n\nexport function parseSideQuestionContent(content: unknown): { question: string } | null {\n let text: string\n if (typeof content === \"string\") {\n text = content\n } else if (Array.isArray(content)) {\n const parts: string[] = []\n for (const part of content) {\n if (!isRecord(part) || part.type !== \"text\" || typeof part.text !== \"string\") return null\n parts.push(part.text)\n }\n text = parts.join(\"\\n\")\n } else {\n return null\n }\n const match = /^\\/btw(?:\\s+([\\s\\S]*))?$/.exec(text.replace(SYSTEM_REMINDER_BLOCK, \"\").trim())\n return match ? { question: (match[1] ?? \"\").trim() } : null\n}\n\n/** Do not replay a historical /btw during an assistant/tool continuation. */\nexport function parseSideQuestion(\n prompt: readonly { role: string; content: unknown }[],\n): { question: string } | null {\n const latest = prompt.at(-1)\n return latest?.role === \"user\" ? parseSideQuestionContent(latest.content) : null\n}\n\nfunction assistantText(content: unknown): string {\n if (typeof content === \"string\") return content.trim()\n if (!Array.isArray(content)) return \"\"\n const parts: string[] = []\n for (const part of content) {\n if (isRecord(part) && part.type === \"text\" && typeof part.text === \"string\") parts.push(part.text)\n }\n return parts.join(\"\\n\").trim()\n}\n\n/**\n * Earlier `/btw` exchanges in this conversation, oldest first, for the\n * control request's `history` so follow-ups can refer to previous asides.\n * The final user message is the current question and is left out.\n */\nexport function collectSideQuestionHistory(\n prompt: readonly { role: string; content: unknown }[],\n): SideQuestionExchange[] {\n const history: SideQuestionExchange[] = []\n for (let index = 0; index < prompt.length - 1; index++) {\n const message = prompt[index]\n if (message.role !== \"user\") continue\n const aside = parseSideQuestionContent(message.content)\n if (!aside?.question) continue\n const reply = prompt[index + 1]\n if (reply.role !== \"assistant\") continue\n const response = assistantText(reply.content)\n if (!response || response === SIDE_QUESTION_USAGE) continue\n history.push({ question: aside.question, response })\n }\n return history.slice(-MAX_HISTORY_EXCHANGES)\n}\n\nexport function isSideQuestionPending(activeProcess: SideQuestionProcess): boolean {\n return pendingProcesses.has(activeProcess.proc)\n}\n\n/**\n * Call before the normal stdout line/buffer dispatch. Only a response with an\n * active request-ID listener is consumed. Progress and unrelated lines retain\n * their existing routing; the helper never subscribes to the shared `line` event.\n */\nexport function dispatchSideQuestionResponse(\n activeProcess: SideQuestionProcess,\n line: string,\n): boolean {\n if (!pendingProcesses.has(activeProcess.proc)) return false\n let message: unknown\n try {\n message = JSON.parse(line)\n } catch {\n return false\n }\n if (!isRecord(message) || message.type !== \"control_response\") return false\n const response = message.response\n if (!isRecord(response) || typeof response.request_id !== \"string\") return false\n return activeProcess.lineEmitter.emit(`side-question:${response.request_id}`, response)\n}\n\n/**\n * Uses an existing headless process, never a user envelope or a new spawn.\n * The process may be mid-turn: Claude Code answers `side_question` on a\n * separate advisor call while the main loop keeps running (measured live on\n * 2.1.258 with the turn blocked on a held MCP tool). Only one aside per\n * process is in flight at a time; responses are matched by request id ahead\n * of the normal stdout routing, so a streaming turn never sees them.\n */\nexport async function requestSideQuestion(\n activeProcess: SideQuestionProcess,\n question: string,\n options: SideQuestionOptions,\n): Promise<SideQuestionResult> {\n question = question.trim()\n if (!question) return { response: SIDE_QUESTION_USAGE, synthetic: true }\n options.abortSignal?.throwIfAborted()\n const { proc, lineEmitter } = activeProcess\n if (options.interactive || !proc.stdout) {\n throw new Error(\"/btw requires the headless Claude Code transport; interactive sessions are not supported.\")\n }\n if (!cliSupportsSideQuestion(options.cliVersion)) {\n throw new Error(\"/btw requires Claude Code CLI 2.1.258 or newer (the oldest verified version).\")\n }\n if (pendingProcesses.has(proc)) {\n throw new Error(\"Wait for the current /btw to finish before asking another.\")\n }\n const stdin = proc.stdin\n if (proc.killed || proc.exitCode != null || proc.signalCode != null ||\n !stdin || stdin.destroyed || stdin.writableEnded || !stdin.writable) {\n throw new Error(\"/btw requires a live Claude Code session with writable stdin.\")\n }\n const timeoutMs = options.timeoutMs ?? 120_000\n if (!Number.isInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2_147_483_647) {\n throw new Error(\"/btw timeoutMs must be a positive 32-bit integer.\")\n }\n const requestId = randomUUID()\n const request = JSON.stringify({\n type: \"control_request\",\n request_id: requestId,\n request: {\n subtype: \"side_question\",\n question,\n ...(options.history === undefined ? {} : { history: options.history }),\n },\n })\n\n pendingProcesses.add(proc)\n return new Promise<SideQuestionResult>((resolve, reject) => {\n const event = `side-question:${requestId}`\n let settled = false\n let sent = false\n let cancelPending = false\n\n const cleanup = (): void => {\n clearTimeout(timer)\n lineEmitter.off(event, onResponse)\n lineEmitter.off(\"close\", onClose)\n lineEmitter.off(\"error\", onError)\n proc.off(\"exit\", onClose)\n proc.off(\"close\", onClose)\n proc.off(\"error\", onError)\n if (!cancelPending) stdin.off(\"error\", onError)\n options.abortSignal?.removeEventListener(\"abort\", onAbort)\n pendingProcesses.delete(proc)\n }\n const fail = (error: unknown, cancel = false): void => {\n if (settled) return\n settled = true\n if (cancel && sent && !stdin.destroyed && !stdin.writableEnded && stdin.writable) {\n try {\n cancelPending = true\n stdin.write(\n JSON.stringify({ type: \"control_cancel_request\", request_id: requestId }) + \"\\n\",\n () => {\n // A failed write emits `error` after its callback. Keep the pipe\n // listener through that event without delaying abort/timeout.\n queueMicrotask(() => stdin.off(\"error\", onError))\n },\n )\n } catch {\n cancelPending = false\n // Preserve the original abort/timeout even if the child has gone away.\n }\n }\n cleanup()\n reject(error)\n }\n const onClose = (): void => fail(new Error(\"Claude Code closed before answering /btw.\"))\n const onError = (error: Error): void => fail(error)\n const onAbort = (): void => fail(\n options.abortSignal?.reason ?? new DOMException(\"/btw was aborted.\", \"AbortError\"),\n true,\n )\n const onResponse = (response: Record<string, unknown>): void => {\n if (settled || response.request_id !== requestId) return\n if (response.subtype === \"error\") {\n fail(new Error(typeof response.error === \"string\" ? response.error : \"Claude Code rejected /btw.\"))\n return\n }\n const result = response.response\n if (response.subtype !== \"success\" || !isRecord(result) ||\n typeof result.response !== \"string\" || typeof result.synthetic !== \"boolean\") {\n fail(new Error(\"Claude Code returned an invalid /btw response.\"))\n return\n }\n settled = true\n cleanup()\n resolve({ response: result.response, synthetic: result.synthetic })\n }\n const timer = setTimeout(() => {\n fail(new Error(`/btw timed out after ${timeoutMs}ms.`), true)\n }, timeoutMs)\n\n lineEmitter.on(event, onResponse)\n lineEmitter.on(\"close\", onClose)\n lineEmitter.on(\"error\", onError)\n proc.on(\"exit\", onClose)\n proc.on(\"close\", onClose)\n proc.on(\"error\", onError)\n stdin.on(\"error\", onError)\n options.abortSignal?.addEventListener(\"abort\", onAbort, { once: true })\n if (options.abortSignal?.aborted) {\n onAbort()\n return\n }\n try {\n sent = true\n stdin.write(request + \"\\n\")\n } catch (error) {\n fail(error)\n }\n })\n}\n","import { detectCliVersion } from \"./cli-version.js\"\nimport { log } from \"./logger.js\"\nimport { getOpencodeClient } from \"./runtime-status.js\"\nimport { findActiveProcessBySessionId, type ActiveProcess } from \"./session-manager.js\"\nimport {\n collectSideQuestionHistory,\n isSideQuestionPending,\n requestSideQuestion,\n SIDE_QUESTION_USAGE,\n type SideQuestionExchange,\n type SideQuestionResult,\n} from \"./side-question.js\"\n\n/**\n * `/btw`: a side question that is answered while the main turn keeps running,\n * and whose exchange is kept in the conversation where it was asked.\n *\n * opencode's TUI sends every slash command to the server the moment it is\n * typed, busy or not (`tui/component/prompt/index.tsx`), so the\n * `command.execute.before` hook fires immediately. The user message the\n * command produces is what gets held back (\"Queued\") until the running turn\n * ends, and opencode's loop then runs it as a step of its own: the loop only\n * exits when the newest assistant message answers the newest user message\n * (`session/prompt.ts`, `lastAssistant.parentID === lastUser.id`).\n *\n * So the hook sends the question to the conversation's live `claude` process\n * as a `side_question` control request right away (Claude Code answers those\n * on a separate advisor call, concurrently with a running turn, from the\n * conversation's context) and remembers the pending answer per session. Where\n * the answer lands then depends on what is open when it arrives:\n * 1. a turn is streaming, so the answer is written into that turn's own\n * reply as its own text block and the `/btw` message is dropped. The\n * operator reads it in place, the moment it is ready, and it stays;\n * 2. nothing is open to write to, so the `/btw` message is held until the\n * turn ends. It then reaches the aside branch in\n * `claude-code-language-model.ts`, which takes the remembered answer and\n * emits it as that message's reply, at no cost;\n * 3. the conversation was idle all along, so the message runs at once and\n * case 2 is all that happens.\n * Every one of those lands in the conversation, so none of them toasts: a\n * toast expires and the operator asked for the answer to stay. The two that\n * remain are the paths where nothing reaches the conversation at all, a bare\n * `/btw` and a turn that never ended, where a toast is the only feedback left.\n * `filterSideQuestionHistory` keeps every `/btw` pair out of Claude's prompt,\n * `INLINE_ASIDE_MARKER` does the same for case 1's block, and the control\n * request never touches Claude's own transcript, so an aside is persisted for\n * the operator only.\n */\n\ntype SdkResult<T = unknown> = Promise<{ data?: T; error?: unknown }>\n\nexport interface BtwToast {\n title?: string\n message: string\n variant: \"info\" | \"success\" | \"warning\" | \"error\"\n duration?: number\n}\n\nexport interface BtwSdkMessage {\n info?: { role?: string }\n parts?: unknown[]\n}\n\nexport interface BtwSdkClient {\n session?: {\n messages?: (options: { path: { id: string } }) => SdkResult<BtwSdkMessage[]>\n /** `GET /session/status`: sessions missing from the map are idle. */\n status?: () => SdkResult<Record<string, { type: string }>>\n }\n tui?: {\n showToast?: (options: { body: BtwToast }) => SdkResult\n }\n}\n\nexport interface BtwCommandInput {\n command: string\n sessionID: string\n arguments: string\n}\n\n/** Every wait the hook can make, so tests do not have to sit through them. */\nexport interface BtwWaitOptions {\n /** How often to re-read opencode's session status. */\n pollMs?: number\n /** Cap on holding the `/btw` message back while a turn runs. */\n timeoutMs?: number\n /** Cap on treating an idle-looking status as not yet registered. */\n settleMs?: number\n /** Cap on waiting for the running turn's `claude` process to be tagged. */\n spawnWaitMs?: number\n /** How often to retry writing the answer into the running turn. */\n inlinePollMs?: number\n /** Cap on waiting for a stream to write the answer into. */\n inlineWaitMs?: number\n}\n\n/** Thrown to make opencode drop the prompt when there is nothing worth keeping. */\nexport class BtwHandledError extends Error {\n override readonly name = \"BtwHandledError\"\n constructor(message = \"/btw was handled by the claude-code plugin; nothing to add to this conversation.\") {\n super(message)\n }\n}\n\nexport const BTW_NO_SESSION_MESSAGE =\n \"/btw needs a live Claude Code session in this conversation. Send a normal message with a Claude Code model first, then ask again.\"\n\nexport const BTW_INLINE_HANDLED_MESSAGE =\n \"/btw was answered inside the running turn; nothing to add to this conversation.\"\n\nexport const BTW_TURN_TOO_LONG_MESSAGE =\n \"/btw gave up waiting for this turn to end. Ask again once it is over.\"\n\nconst IDLE_POLL_MS = 500\nconst IDLE_WAIT_MAX_MS = 30 * 60_000\n/**\n * How long a single status read is allowed to be wrong. opencode registers\n * the turn a moment after the TUI sends the command, and a session missing\n * from `GET /session/status` reads as idle, so a `/btw` typed inside that gap\n * would decide the conversation is free and let its message queue.\n */\nconst BUSY_SETTLE_MS = 1_500\n/**\n * How long to wait for the turn's `claude` process to appear. doStream tags\n * the process only once it attaches its line listener, which is after the\n * whole spawn path, so the first `/btw` of a conversation regularly arrives\n * before there is anything to ask. Bounded, because the running turn may\n * belong to another provider and then no process is ever coming.\n */\nconst SPAWN_WAIT_MAX_MS = 30_000\n\nconst INLINE_POLL_MS = 200\n/**\n * How long to keep trying to write into the turn. A turn is a run of streams,\n * not one: every proxy tool call ends the current stream and opencode opens\n * the next one with the tool's result, so an answer that arrives inside that\n * gap has nothing to write to yet and has to wait for the next stream.\n */\nconst INLINE_WAIT_MAX_MS = 20_000\n\nconst PENDING_ANSWER_TTL_MS = 10 * 60_000\nconst PENDING_ANSWER_CAP = 32\n\ninterface PendingAnswer {\n question: string\n answer: Promise<SideQuestionResult>\n at: number\n}\n\n/** Answers the hook requested ahead of the queued prompt, one per opencode session. */\nconst pendingAnswers = new Map<string, PendingAnswer>()\n\nexport function rememberSideQuestionAnswer(\n sessionID: string,\n question: string,\n answer: Promise<SideQuestionResult>,\n now = Date.now(),\n): void {\n for (const [id, entry] of pendingAnswers) {\n if (now - entry.at > PENDING_ANSWER_TTL_MS) pendingAnswers.delete(id)\n }\n pendingAnswers.delete(sessionID)\n while (pendingAnswers.size >= PENDING_ANSWER_CAP) {\n const oldest = pendingAnswers.keys().next().value\n if (oldest === undefined) break\n pendingAnswers.delete(oldest)\n }\n pendingAnswers.set(sessionID, { question: question.trim(), answer, at: now })\n}\n\n/**\n * The answer the hook already requested for this session, if it was for this\n * question and is still fresh. Taking it consumes it: a later `/btw` with the\n * same text asks again rather than replaying a stale answer.\n *\n * The question the turn parses may be longer than what the hook saw: a\n * harness can append trailing metadata to the message text (opencode-dcp adds\n * a `<dcp-message-id>` marker), so the hook's question only has to be a prefix.\n * Measured live: an exact match missed, the turn asked again, and the\n * single-flight guard refused it as a second concurrent aside.\n */\nexport function takeSideQuestionAnswer(\n sessionID: string,\n question: string,\n now = Date.now(),\n): Promise<SideQuestionResult> | undefined {\n const entry = pendingAnswers.get(sessionID)\n if (!entry) return undefined\n pendingAnswers.delete(sessionID)\n if (!question.trim().startsWith(entry.question) || now - entry.at > PENDING_ANSWER_TTL_MS) return undefined\n return entry.answer\n}\n\n/** Test seam. */\nexport function clearPendingSideQuestionAnswers(): void {\n pendingAnswers.clear()\n}\n\n/**\n * Header of the block an aside writes into the running turn's own reply, and\n * the marker `message-builder` strips by when a transcript has to be rebuilt\n * for a fresh Claude process. Kept as the first characters of its own text\n * part so the strip is exact rather than a guess at where the block ends.\n */\nexport const INLINE_ASIDE_MARKER = \"▌ **btw:**\"\n\n/**\n * Markers of blocks written before the bar replaced the blockquote. Only the\n * strip reads these: a conversation that already holds an old aside still has\n * to keep it out of a rebuilt transcript.\n */\nexport const LEGACY_INLINE_ASIDE_MARKERS = [\"> **btw:**\"]\n\n/**\n * A literal bar on every line, blank ones included, so the aside reads as one\n * block down its whole height.\n *\n * The obvious alternative, a markdown blockquote, was tried first and is why\n * this exists: opencode renders assistant text with OpenTUI's markdown, which\n * draws a blockquote's left border in the `conceal` scope's colour, not the\n * theme's `markdownBlockQuote`. That border is dim by design and there is no\n * per-block way to change it, so the bar has to be text the plugin emits.\n * Line breaks survive because OpenTUI renders a paragraph from `token.raw`,\n * verbatim, rather than reflowing it.\n */\nfunction barEveryLine(text: string): string {\n return text\n .split(\"\\n\")\n .map((line) => (line.trim() === \"\" ? \"▌\" : `▌ ${line}`))\n .join(\"\\n\")\n}\n\nfunction oneLine(question: string): string {\n return question.replace(/\\s+/g, \" \").trim()\n}\n\nfunction asideHeader(question: string): string {\n return `${INLINE_ASIDE_MARKER} ${oneLine(question)}`\n}\n\nexport function formatInlineAside(question: string, answer: string): string {\n return `\\n${asideHeader(question)}\\n▌\\n${barEveryLine(answer.trim())}\\n`\n}\n\n/**\n * The receipt's trailing note. Past tense, because the block stays in the\n * conversation and an \"answering...\" would read as stale the moment the\n * answer lands.\n */\nexport const INLINE_ASIDE_SENT_NOTE = \"*sent to Claude on the side*\"\n\n/**\n * A receipt written into the running turn the moment the question goes out, so\n * a `/btw` typed mid-turn shows as taken instead of looking swallowed until\n * the answer arrives.\n *\n * It quotes the question back **in full**, which is what the operator asked\n * for: the prompt box clears on submit and no `/btw` message is ever created,\n * so this is the only place the question can be read back. It was briefly\n * capped at 240 characters and that was wrong for the same reason, since a\n * long aside would then be unreadable everywhere. The note goes on its own bar\n * line so the question is never crowded by it.\n *\n * The answer block repeats the question rather than dropping it, because the\n * model keeps streaming its own text between the two and a headerless answer\n * arriving after that reads as orphaned.\n */\nexport function formatInlineAsideAsk(question: string): string {\n return `\\n${asideHeader(question)}\\n▌ ${INLINE_ASIDE_SENT_NOTE}\\n`\n}\n\n/**\n * Writes one finished text block into a stream that is open right now.\n * Returns false when there is nothing to write to, which is the whole reason\n * the held-message path is still here.\n */\nexport type AsideSink = (text: string) => boolean\n\n/** At most one open stream per conversation, so a plain map is enough. */\nconst asideSinks = new Map<string, AsideSink>()\n\nexport function registerAsideSink(sessionID: string, sink: AsideSink): () => void {\n asideSinks.set(sessionID, sink)\n return () => {\n // Only the stream that registered may unregister: a later turn's sink\n // must survive the earlier turn's cleanup.\n if (asideSinks.get(sessionID) === sink) asideSinks.delete(sessionID)\n }\n}\n\nexport function emitAsideInline(sessionID: string, text: string): boolean {\n const sink = asideSinks.get(sessionID)\n if (!sink) return false\n try {\n return sink(text)\n } catch (error) {\n log.debug(\"btw: could not write the aside into the running turn\", { sessionID, error: errorText(error) })\n return false\n }\n}\n\n/** Test seam. */\nexport function clearAsideSinks(): void {\n asideSinks.clear()\n}\n\nexport function showToast(client: BtwSdkClient | null, body: BtwToast): void {\n // Keep the receiver: the SDK's namespace methods read `this._client`, so a\n // detached `const show = client.tui.showToast` throws at call time.\n try {\n void client?.tui?.showToast?.({ body })?.catch((error: unknown) => {\n log.debug(\"btw toast failed\", { error: errorText(error) })\n })\n } catch (error) {\n log.debug(\"btw toast failed\", { error: errorText(error) })\n }\n}\n\n/** A turn is streaming from this process, so its transcript cannot show an answer yet. */\nexport function isProcessBusy(active: Pick<ActiveProcess, \"lineEmitter\">): boolean {\n return active.lineEmitter.listenerCount(\"line\") > 0\n}\n\n/**\n * opencode's own view of the session: `busy` for the whole turn, including\n * the gaps where opencode runs a tool and no stream is attached to the\n * process, which `isProcessBusy` cannot see. `unknown` when the SDK has no\n * status route or it fails.\n */\nexport async function sessionStatus(\n client: BtwSdkClient | null,\n sessionID: string,\n): Promise<\"busy\" | \"idle\" | \"unknown\"> {\n const status = client?.session?.status\n if (!status) return \"unknown\"\n try {\n const result = await status.call(client!.session)\n const entry = result.data?.[sessionID]\n return entry && entry.type !== \"idle\" ? \"busy\" : \"idle\"\n } catch (error) {\n log.debug(\"btw: could not read session status\", { sessionID, error: errorText(error) })\n return \"unknown\"\n }\n}\n\n/**\n * Resolves once the session is no longer busy. Returns false on timeout. A\n * client without a status route resolves at once, since there is nothing to\n * wait on.\n */\nexport async function waitForSessionIdle(\n client: BtwSdkClient | null,\n sessionID: string,\n options: { pollMs?: number; timeoutMs?: number; stop?: () => boolean } = {},\n): Promise<boolean> {\n const pollMs = options.pollMs ?? IDLE_POLL_MS\n const timeoutMs = options.timeoutMs ?? IDLE_WAIT_MAX_MS\n const started = Date.now()\n for (;;) {\n if (options.stop?.()) return true\n if ((await sessionStatus(client, sessionID)) !== \"busy\") return true\n if (Date.now() - started >= timeoutMs) return false\n await new Promise((resolve) => setTimeout(resolve, pollMs))\n }\n}\n\n/**\n * Puts the answer in the conversation while the turn that prompted it is\n * still running, by writing it as its own text block into that turn's live\n * stream. It lands in the assistant reply the operator is already watching:\n * full markdown, scrollable, kept by opencode, and readable long after a\n * toast would have gone.\n *\n * Retries while the conversation stays busy, because a turn is a run of\n * streams rather than one and the gap between two of them is short. Gives up\n * once the turn ends, leaving the message to carry the answer instead.\n */\nexport async function deliverAsideInline(\n client: BtwSdkClient | null,\n sessionID: string,\n text: string,\n options: BtwWaitOptions = {},\n): Promise<boolean> {\n const pollMs = options.inlinePollMs ?? INLINE_POLL_MS\n const timeoutMs = options.inlineWaitMs ?? INLINE_WAIT_MAX_MS\n const started = Date.now()\n for (;;) {\n if (emitAsideInline(sessionID, text)) return true\n if (Date.now() - started >= timeoutMs) return false\n if ((await sessionStatus(client, sessionID)) !== \"busy\") return false\n await new Promise((resolve) => setTimeout(resolve, pollMs))\n }\n}\n\n/**\n * The `claude` process serving this conversation, waiting for it when a turn\n * is already running but has not yet reached the point where doStream tags it\n * (`claude-code-language-model.ts`, where the line listener attaches). That\n * gap is the whole spawn path on a conversation's first turn, and a `/btw`\n * typed inside it used to fall straight through, which is exactly what leaves\n * a \"Queued\" bubble in the transcript: measured live on 2026-09-06, a `/btw`\n * logged \"no live claude process for session\" and the same question 22 s\n * later found one and was answered concurrently.\n */\nexport async function waitForAsideProcess(\n client: BtwSdkClient | null,\n sessionID: string,\n options: BtwWaitOptions = {},\n): Promise<ActiveProcess | undefined> {\n const pollMs = options.pollMs ?? IDLE_POLL_MS\n const settleMs = options.settleMs ?? BUSY_SETTLE_MS\n const spawnWaitMs = options.spawnWaitMs ?? SPAWN_WAIT_MAX_MS\n const started = Date.now()\n for (;;) {\n const active = findActiveProcessBySessionId(sessionID)\n if (active) return active\n const busy = (await sessionStatus(client, sessionID)) === \"busy\"\n const waitedMs = Date.now() - started\n if (!busy && waitedMs >= settleMs) {\n // Nothing is running, so no process is on its way either.\n log.info(\"btw: no live claude process for session, leaving it to the turn\", { sessionID, waitedMs })\n return undefined\n }\n if (busy && waitedMs >= spawnWaitMs) {\n // A turn is running but it never produced a process of ours: it belongs\n // to another provider, or the spawn failed. Do not hold the message for\n // the rest of it.\n log.warn(\"btw: a turn is running but no claude process appeared for it\", { sessionID, waitedMs })\n return undefined\n }\n await new Promise((resolve) => setTimeout(resolve, pollMs))\n }\n}\n\n/**\n * Whether a turn is running, tolerant of the same registration lag: a status\n * read taken the instant `/btw` is typed can still say idle while opencode is\n * starting the turn, and skipping the hold on that reading is what queues the\n * message behind the turn instead of releasing it afterwards.\n */\nexport async function settleSessionBusy(\n client: BtwSdkClient | null,\n sessionID: string,\n active: Pick<ActiveProcess, \"lineEmitter\">,\n options: BtwWaitOptions = {},\n): Promise<boolean> {\n const pollMs = options.pollMs ?? IDLE_POLL_MS\n const settleMs = options.settleMs ?? BUSY_SETTLE_MS\n const started = Date.now()\n for (;;) {\n const status = await sessionStatus(client, sessionID)\n if (status === \"busy\") return true\n // No status route to poll: the process's own stream is all there is.\n if (status === \"unknown\") return isProcessBusy(active)\n if (Date.now() - started >= settleMs) return false\n await new Promise((resolve) => setTimeout(resolve, pollMs))\n }\n}\n\nfunction errorText(error: unknown): string {\n if (error instanceof Error) return error.message\n if (error && typeof error === \"object\" && \"message\" in error && typeof (error as { message: unknown }).message === \"string\") {\n return (error as { message: string }).message\n }\n return String(error)\n}\n\nfunction isTextPart(part: unknown): part is { type: \"text\"; text: string } {\n return (\n part !== null &&\n typeof part === \"object\" &&\n (part as { type?: unknown }).type === \"text\" &&\n typeof (part as { text?: unknown }).text === \"string\"\n )\n}\n\n/**\n * Earlier `/btw` exchanges in this conversation, read back from opencode\n * because the hook runs before the current question exists as a message.\n * Best effort: a follow-up without history still gets an answer, just one\n * that cannot refer to previous asides.\n */\nexport async function fetchAsideHistory(\n client: BtwSdkClient | null,\n sessionID: string,\n question: string,\n): Promise<SideQuestionExchange[]> {\n const messages = client?.session?.messages\n if (!messages) return []\n try {\n const result = await messages.call(client!.session, { path: { id: sessionID } })\n const prompt: { role: string; content: unknown }[] = []\n for (const message of result.data ?? []) {\n const role = message.info?.role\n if (role !== \"user\" && role !== \"assistant\") continue\n prompt.push({ role, content: (message.parts ?? []).filter(isTextPart) })\n }\n // collectSideQuestionHistory skips the final message as the question being\n // asked; stand in for the one opencode has not created yet.\n prompt.push({ role: \"user\", content: `/btw ${question}` })\n return collectSideQuestionHistory(prompt)\n } catch (error) {\n log.debug(\"btw: could not read aside history\", { sessionID, error: errorText(error) })\n return []\n }\n}\n\n/**\n * `command.execute.before` handler for `btw`. Returns normally so opencode\n * creates the `/btw` message in this conversation; throws only when there is\n * nothing to keep (a bare `/btw`, or a turn that never ended).\n *\n * While the session is busy the return is delayed until it is idle. opencode\n * would otherwise queue the message behind the running turn and run it as\n * that turn's next step, which is also the step that carries the results of\n * the tools opencode just ran: answering the aside there would swallow the\n * turn's own continuation (measured live: the main answer never appeared).\n * opencode already keeps the command route open for a queued prompt, so\n * holding it here changes nothing on the wire, and the TUI's call is\n * fire-and-forget.\n *\n * Both waits before that hold exist because a `/btw` typed early in a turn\n * used to be seen as belonging to an idle conversation with no process, and\n * was let through to be queued: `waitForAsideProcess` covers the spawn gap,\n * `settleSessionBusy` covers opencode registering the turn.\n */\nexport async function handleBtwCommand(\n client: BtwSdkClient | null,\n input: BtwCommandInput,\n options: BtwWaitOptions = {},\n): Promise<void> {\n const question = input.arguments.trim()\n if (!question) {\n showToast(client, { title: \"btw\", message: SIDE_QUESTION_USAGE, variant: \"warning\", duration: 6_000 })\n throw new BtwHandledError(\"/btw needs a question.\")\n }\n const active = await waitForAsideProcess(client, input.sessionID, options)\n const transport = active?.asideTransport\n if (!active || !transport) {\n // The message still goes through: the aside branch answers it with an\n // explanation that stays readable in the conversation.\n if (active) log.info(\"btw: process has no aside transport, leaving it to the turn\", { sessionID: input.sessionID })\n return\n }\n let busy = false\n let inlineDone = false\n let markInlineDelivered = (): void => {}\n const inlineDelivered = new Promise<\"inline\">((resolve) => {\n markInlineDelivered = () => {\n inlineDone = true\n resolve(\"inline\")\n }\n })\n if (isSideQuestionPending(active)) {\n // One aside per process at a time. Leave the earlier answer in place for\n // its own message; this one asks when its turn comes.\n busy = await settleSessionBusy(client, input.sessionID, active, options)\n log.info(\"btw: an aside is already in flight, leaving this one to the turn\", { sessionID: input.sessionID, busy })\n } else {\n // Settled alongside the request rather than before it: an aside asked\n // while the conversation is idle must not wait out the settle window\n // before it is even sent.\n const settling = settleSessionBusy(client, input.sessionID, active, options)\n const history = await fetchAsideHistory(client, input.sessionID, question)\n const answer = requestSideQuestion(active, question, {\n cliVersion: await detectCliVersion(transport.cliPath),\n interactive: transport.interactive,\n ...(history.length ? { history } : {}),\n })\n // Handled from this tick on. The settle below can span several timer\n // ticks, and an aside that fails immediately (a dead process, an\n // interactive transport) would otherwise raise an unhandled rejection in\n // the host before the real handlers further down are attached.\n answer.catch(() => undefined)\n rememberSideQuestionAnswer(input.sessionID, question, answer)\n busy = await settling\n log.info(\"btw: aside sent ahead of its message\", {\n sessionID: input.sessionID,\n busy,\n questionLength: question.length,\n history: history.length,\n })\n // Written before the answer exists, so a `/btw` typed mid-turn shows up in\n // the turn straight away rather than looking swallowed until the answer\n // arrives. Only while a turn is running: an idle conversation gets the\n // whole pair as its own message a moment later anyway.\n const asked = busy\n ? deliverAsideInline(client, input.sessionID, formatInlineAsideAsk(question), options).catch(() => false)\n : Promise.resolve(false)\n answer.then(\n async (result) => {\n log.info(\"btw: early answer arrived\", { sessionID: input.sessionID, busy, responseLength: result.response.length })\n if (!busy || result.synthetic) return\n // Awaited, not raced: a receipt that landed after the answer it\n // announces would read backwards. In the common case it was written\n // long before this and the await is already settled.\n await asked\n const inline = await deliverAsideInline(\n client,\n input.sessionID,\n formatInlineAside(question, result.response),\n options,\n )\n if (inline) {\n // The answer is in the conversation already, so the `/btw` message\n // has nothing left to carry. The remembered answer is deliberately\n // left in place: if the drop below does not take, the message\n // replays this answer instead of paying for a second one.\n log.info(\"btw: answer written into the running turn\", { sessionID: input.sessionID })\n markInlineDelivered()\n return\n }\n // Nothing was open to write to. The held `/btw` message carries this\n // same answer into the conversation once the turn ends, which is the\n // durable copy, so there is nothing to announce here.\n log.info(\"btw: no open stream for the answer; the held message will carry it\", {\n sessionID: input.sessionID,\n })\n },\n (error: unknown) => {\n // The message asks again once its turn runs.\n log.warn(\"btw: early aside failed; the message will ask again\", {\n sessionID: input.sessionID,\n error: errorText(error),\n })\n },\n )\n }\n if (!busy) return\n const started = Date.now()\n const outcome = await Promise.race([\n inlineDelivered,\n waitForSessionIdle(client, input.sessionID, { ...options, stop: () => inlineDone }).then((idle) =>\n idle ? (\"idle\" as const) : (\"timeout\" as const),\n ),\n ])\n if (outcome === \"inline\") {\n log.info(\"btw: answered inside the running turn, dropping the /btw message\", {\n sessionID: input.sessionID,\n waitedMs: Date.now() - started,\n })\n throw new BtwHandledError(BTW_INLINE_HANDLED_MESSAGE)\n }\n log.info(\"btw: turn over, releasing the /btw message\", {\n sessionID: input.sessionID,\n idle: outcome === \"idle\",\n waitedMs: Date.now() - started,\n })\n if (outcome === \"timeout\") {\n showToast(client, { title: \"btw\", message: BTW_TURN_TOO_LONG_MESSAGE, variant: \"warning\", duration: 8_000 })\n throw new BtwHandledError(BTW_TURN_TOO_LONG_MESSAGE)\n }\n}\n","import type { LanguageModelV3 } from \"@ai-sdk/provider\"\nimport { INLINE_ASIDE_MARKER, LEGACY_INLINE_ASIDE_MARKERS } from \"./btw-command.js\"\nimport { log } from \"./logger.js\"\nimport { parseSideQuestionContent } from \"./side-question.js\"\n\ntype Prompt = Parameters<LanguageModelV3[\"doGenerate\"]>[0][\"prompt\"]\n\nconst ASIDE_MARKERS = [INLINE_ASIDE_MARKER, ...LEGACY_INLINE_ASIDE_MARKERS]\n\nfunction isInlineAside(part: any): boolean {\n if (!part || part.type !== \"text\" || typeof part.text !== \"string\") return false\n const text = part.text.trimStart()\n return ASIDE_MARKERS.some((marker) => text.startsWith(marker))\n}\n\n/**\n * An aside answered while a turn was running was written into that turn's\n * reply as its own text part (btw-command.ts). It was never Claude's own\n * output and was never in Claude's context, so a rebuilt transcript must not\n * hand it back as something Claude said.\n */\nfunction stripInlineAsides(content: unknown): unknown {\n if (!Array.isArray(content)) return content\n const kept = content.filter((part: any) => !isInlineAside(part))\n return kept.length === content.length ? content : kept\n}\n\nexport function filterSideQuestionHistory(prompt: Prompt): Prompt {\n let aside = false\n const kept = prompt.filter((message) => {\n if (message.role === \"user\") {\n aside = parseSideQuestionContent(message.content) !== null\n return !aside\n }\n return message.role !== \"assistant\" || !aside\n })\n return kept.map((message) =>\n message.role === \"assistant\" ? ({ ...message, content: stripInlineAsides(message.content) } as typeof message) : message,\n )\n}\n\nconst SUPPORTED_IMAGE_TYPES = new Set([\n \"image/jpeg\",\n \"image/png\",\n \"image/gif\",\n \"image/webp\",\n])\n\nfunction toImageBlock(part: any): any | null {\n const raw: unknown = part.image ?? part.data ?? part.url ?? part.source?.data\n if (!raw) {\n log.warn(\"file part without data, skipping\")\n return null\n }\n\n let resolvedMediaType: string = part.mediaType || part.mimeType || part.mime || \"\"\n let base64: string | null = null\n\n if (typeof raw === \"string\") {\n if (raw.startsWith(\"data:\")) {\n const match = /^data:([^;,]+)(?:;[^,]*)*(?:;base64)?,(.*)$/s.exec(raw)\n if (!match) {\n log.warn(\"malformed data URI, skipping file part\")\n return null\n }\n resolvedMediaType = resolvedMediaType || match[1]\n base64 = match[2]\n } else if (/^https?:\\/\\//i.test(raw)) {\n log.warn(\"remote URL images are not supported by Claude CLI, skipping\")\n return null\n } else {\n base64 = raw\n }\n } else if (raw instanceof URL) {\n log.warn(\"remote URL images are not supported by Claude CLI, skipping\")\n return null\n } else if (raw instanceof Uint8Array || Buffer.isBuffer(raw)) {\n base64 = Buffer.from(raw as Uint8Array).toString(\"base64\")\n } else {\n log.warn(\"unsupported file part data type\", { dataType: typeof raw })\n return null\n }\n\n if (!resolvedMediaType || !SUPPORTED_IMAGE_TYPES.has(resolvedMediaType)) {\n log.warn(\"unsupported media type for Claude image block, skipping\", {\n mediaType: resolvedMediaType,\n })\n return null\n }\n\n return {\n type: \"image\",\n source: { type: \"base64\", media_type: resolvedMediaType, data: base64 },\n }\n}\n\nfunction getToolResultText(part: any): string {\n const value = part.output ?? part.result\n\n if (typeof value === \"string\") {\n return value\n }\n\n if (!value || typeof value !== \"object\") {\n return JSON.stringify(value)\n }\n\n switch (value.type) {\n case \"text\":\n case \"error-text\":\n return String(value.value)\n case \"json\":\n case \"error-json\":\n return JSON.stringify(value.value)\n case \"execution-denied\":\n return value.reason ? `Execution denied: ${value.reason}` : \"Execution denied\"\n case \"content\":\n return Array.isArray(value.value)\n ? value.value\n .map((item: any) => {\n if (item?.type === \"text\") return item.text\n return JSON.stringify(item)\n })\n .join(\"\\n\")\n : JSON.stringify(value.value)\n default:\n return JSON.stringify(value)\n }\n}\n\n// Compaction-mode caps. These are the only knobs that affect how much\n// transcript content reaches the model when opencode invokes /compact.\n// 180k chars ≈ 60k tokens worst-case — well under Haiku 4.5's 200k window\n// after accounting for system prompt + output budget.\nconst MAX_HISTORY_CHARS = 180_000\nconst MAX_TOOL_RESULT_CHARS = 10_000\nconst MAX_TOOL_INPUT_CHARS = 2_000\n\nfunction clipWithMarker(text: string, max: number): string {\n if (text.length <= max) return text\n return `${text.slice(0, max)}\\n…[truncated ${text.length - max} chars]`\n}\n\nfunction renderToolInput(input: unknown): string {\n let raw: string\n try {\n raw = typeof input === \"string\" ? input : JSON.stringify(input)\n } catch {\n raw = String(input)\n }\n return clipWithMarker(raw, MAX_TOOL_INPUT_CHARS)\n}\n\nfunction renderMessageContentForCompaction(\n msg: any,\n): { text: string; toolResultCount: number } {\n const lines: string[] = []\n let toolResultCount = 0\n\n if (typeof msg.content === \"string\") {\n return { text: msg.content, toolResultCount: 0 }\n }\n\n if (!Array.isArray(msg.content)) {\n return { text: \"\", toolResultCount: 0 }\n }\n\n for (const part of msg.content as any[]) {\n if (!part) continue\n switch (part.type) {\n case \"text\":\n if (part.text) lines.push(part.text)\n break\n case \"tool-call\":\n lines.push(\n `[tool_use:${part.toolName ?? \"unknown\"}(${renderToolInput(part.input)})]`,\n )\n break\n case \"tool-result\":\n toolResultCount++\n lines.push(\n `[tool_result:${part.toolName ?? part.toolCallId ?? \"unknown\"}]\\n${clipWithMarker(\n getToolResultText(part),\n MAX_TOOL_RESULT_CHARS,\n )}`,\n )\n break\n case \"image\":\n lines.push(\n `[image: ${part.mediaType ?? part.mimeType ?? \"unknown\"}]`,\n )\n break\n case \"file\":\n lines.push(\n `[file: ${part.mediaType ?? part.mimeType ?? \"unknown\"}]`,\n )\n break\n case \"reasoning\":\n // Skip reasoning blocks in compaction — they bloat input without\n // helping the summarizer.\n break\n }\n }\n\n return { text: lines.join(\"\\n\"), toolResultCount }\n}\n\n/**\n * Compact conversation history into a context summary.\n *\n * - mode \"fresh-session\" (default): includes user, assistant and tool roles,\n * renders each with the same serializer /compact uses so tool inputs and\n * result bodies survive, then clips each message at 2000 chars. Used when\n * starting a fresh CLI session that lost its prior session id. It used to\n * filter to user/assistant only and reduce tool content to\n * `[Called N tool(s)]` placeholders, which silently dropped subagent\n * output entirely (issue #29).\n * - mode \"compaction\": rich serializer for opencode /compact. Includes\n * tool roles, renders tool_use input and tool_result content (each\n * clipped at MAX_TOOL_RESULT_CHARS), and caps aggregate output at\n * MAX_HISTORY_CHARS by dropping oldest entries first.\n */\nexport function compactConversationHistory(\n prompt: Prompt,\n opts: { mode?: \"fresh-session\" | \"compaction\" } = {},\n): string | null {\n const mode = opts.mode ?? \"fresh-session\"\n prompt = filterSideQuestionHistory(prompt)\n\n if (mode === \"compaction\") {\n return buildCompactionHistory(prompt)\n }\n\n // `tool`-role messages carry the results of everything opencode ran itself,\n // so they belong in the transcript. Filtering them out (issue #29) meant a\n // subagent's whole answer vanished: the assistant message kept a\n // `[Called 1 tool(s): task]` placeholder and the result it referred to was\n // never rendered at all.\n const conversationMessages = prompt.filter(\n (m) => m.role === \"user\" || m.role === \"assistant\" || m.role === \"tool\",\n )\n\n if (conversationMessages.length <= 1) {\n return null\n }\n\n const historyParts: string[] = []\n\n for (let i = 0; i < conversationMessages.length - 1; i++) {\n const msg = conversationMessages[i]\n const role =\n msg.role === \"user\" ? \"User\" : msg.role === \"assistant\" ? \"Assistant\" : \"Tool\"\n\n // Same renderer the /compact transcript uses, so tool inputs and result\n // bodies survive instead of collapsing to counts. This path used to write\n // `[Called N tool(s): ...]` / `[Received N tool result(s)]` and discard\n // every byte of the payload, which is the second half of issue #29.\n const { text } = renderMessageContentForCompaction(msg)\n\n if (text.trim()) {\n const truncated =\n text.length > 2000 ? text.slice(0, 2000) + \"...\" : text\n historyParts.push(`${role}: ${truncated}`)\n }\n }\n\n if (historyParts.length === 0) {\n return null\n }\n\n return historyParts.join(\"\\n\\n\")\n}\n\nfunction buildCompactionHistory(prompt: Prompt): string | null {\n // Iterate newest-first, accumulate up to MAX_HISTORY_CHARS, then reverse\n // to chronological order. Oldest messages get dropped when the budget\n // is exhausted — they are the least relevant for a summary of recent\n // work.\n const entries: string[] = []\n let total = 0\n let totalToolResults = 0\n let droppedOldest = 0\n\n // Skip the trailing user message: opencode's /compact appends the\n // synthesis instruction as the final user turn. The instruction itself\n // is added by getClaudeUserMessage after the transcript block, so we\n // don't want it duplicated inside the transcript.\n const end = prompt.length > 0 && prompt[prompt.length - 1].role === \"user\"\n ? prompt.length - 1\n : prompt.length\n\n for (let i = end - 1; i >= 0; i--) {\n const msg = prompt[i] as any\n const roleLabel =\n msg.role === \"user\"\n ? \"User\"\n : msg.role === \"assistant\"\n ? \"Assistant\"\n : msg.role === \"tool\"\n ? \"Tool\"\n : msg.role\n\n const { text, toolResultCount } = renderMessageContentForCompaction(msg)\n if (!text.trim()) continue\n\n const entry = `${roleLabel}: ${text}`\n if (total + entry.length > MAX_HISTORY_CHARS) {\n droppedOldest = i + 1\n break\n }\n entries.push(entry)\n total += entry.length + 2 // +2 for the \"\\n\\n\" join\n totalToolResults += toolResultCount\n }\n\n if (entries.length === 0) return null\n\n entries.reverse()\n log.info(\"built compaction history\", {\n entries: entries.length,\n chars: total,\n toolResults: totalToolResults,\n droppedOldestBefore: droppedOldest,\n })\n\n return entries.join(\"\\n\\n\")\n}\n\n/**\n * Convert AI SDK prompt into a Claude CLI stream-json user message.\n *\n * `compactionMode` switches behavior for opencode /compact: the prior\n * transcript is rendered with rich tool content (not placeholders) and the\n * wrapper framing tells the model this is the authoritative thread.\n *\n * Reasoning effort is not part of the message. It used to ride here as a\n * thinking keyword (\"(ultrathink)\"), but Claude Code dropped every keyword\n * except that one, so effort now reaches the CLI as CLAUDE_CODE_EFFORT_LEVEL\n * at spawn time (see `claudeSpawnEnv`).\n */\nexport function getClaudeUserMessage(\n prompt: Prompt,\n includeHistoryContext: boolean = false,\n opts: { compactionMode?: boolean; cliToolCallIds?: ReadonlySet<string> } = {},\n): string {\n const compactionMode = opts.compactionMode === true\n const cliToolCallIds = opts.cliToolCallIds\n const content: any[] = []\n\n /**\n * A `tool_result` block is only meaningful to a resumed CLI session when\n * that session issued the matching `tool_use`. Anything opencode ran on its\n * own behalf (a `subtask: true` command's `task` call, issue #29) has an id\n * the CLI never emitted, so the block is orphaned: Claude cannot resolve it\n * and the payload, which is right there in the envelope, is unreachable.\n * Those are rendered as plain text instead, which keeps the content and\n * loses only the pairing the CLI could not have honoured anyway.\n *\n * `cliToolCallIds` is the set of calls this CLI process is waiting on. When\n * a caller does not supply it we keep the old unconditional block, so a\n * forgotten call site degrades to today's behaviour rather than breaking\n * the proxy round-trip.\n */\n const pushToolResult = (part: any): void => {\n const id = part.toolCallId\n const text = getToolResultText(part)\n if (!cliToolCallIds || cliToolCallIds.has(id)) {\n content.push({ type: \"tool_result\", tool_use_id: id, content: text })\n return\n }\n log.info(\"rendering opencode-side tool result as text\", {\n toolCallId: id,\n toolName: part.toolName,\n chars: text.length,\n })\n content.push({\n type: \"text\",\n text: `<opencode_tool_result tool=\"${part.toolName ?? \"unknown\"}\">\\n${text}\\n</opencode_tool_result>`,\n })\n }\n\n if (compactionMode) {\n const transcript = compactConversationHistory(prompt, {\n mode: \"compaction\",\n })\n if (transcript) {\n log.info(\"including compaction transcript\", {\n historyLength: transcript.length,\n })\n content.push({\n type: \"text\",\n text: `<conversation_transcript>\n${transcript}\n</conversation_transcript>\n\nThe complete prior conversation appears above. The synthesis instructions follow below.\n\n`,\n })\n }\n } else if (includeHistoryContext) {\n const historyContext = compactConversationHistory(prompt)\n if (historyContext) {\n log.info(\"including conversation history context\", {\n historyLength: historyContext.length,\n })\n content.push({\n type: \"text\",\n text: `<conversation_history>\nThe following is a summary of our conversation so far (from a previous session that couldn't be resumed):\n\n${historyContext}\n\n</conversation_history>\n\nNow continuing with the current message:\n\n`,\n })\n }\n }\n\n // Find messages since last assistant message\n const messages: typeof prompt = []\n for (let i = prompt.length - 1; i >= 0; i--) {\n if (prompt[i].role === \"assistant\") break\n messages.unshift(prompt[i])\n }\n\n for (const msg of messages) {\n if (msg.role === \"user\") {\n if (parseSideQuestionContent(msg.content) !== null) continue\n if (typeof msg.content === \"string\") {\n const str = msg.content as string\n if (str.trim()) {\n content.push({ type: \"text\", text: str })\n }\n } else if (Array.isArray(msg.content)) {\n for (const part of msg.content as any[]) {\n if (part.type === \"text\") {\n if (part.text && part.text.trim()) {\n content.push({ type: \"text\", text: part.text })\n }\n } else if (part.type === \"file\" || part.type === \"image\") {\n const block = toImageBlock(part)\n if (block) {\n content.push(block)\n } else {\n log.debug(\"skipped non-image file part\", {\n mediaType: part.mediaType,\n })\n }\n } else if (part.type === \"tool-result\") {\n pushToolResult(part)\n }\n }\n }\n } else if (msg.role === \"tool\") {\n // AI SDK V3 delivers tool results in `tool`-role messages, not `user`.\n // Without this branch we'd hit the empty-content sentinel path and\n // send \"(empty)\" to Claude CLI instead of the actual tool result —\n // forcing the user to press \"continue\" between proxy tool calls.\n if (Array.isArray(msg.content)) {\n for (const part of msg.content as any[]) {\n if (part?.type === \"tool-result\") {\n pushToolResult(part)\n }\n }\n }\n }\n }\n\n if (content.length === 0) {\n // CLI rejects a zero-block message with 400, and Anthropic rejects\n // whitespace-only text blocks — so we need a non-whitespace sentinel.\n // \"(empty)\" matches the parenthetical meta-note convention this file\n // already uses for reasoning keywords (\"(think)\", \"(megathink)\", etc.),\n // which the model reads as out-of-band metadata rather than a prompt to\n // continue its previous turn.\n log.warn(\"empty user content; sending sentinel to satisfy CLI\")\n return JSON.stringify({\n type: \"user\",\n message: {\n role: \"user\",\n content: [{ type: \"text\", text: \"(empty)\" }],\n },\n })\n }\n\n return JSON.stringify({\n type: \"user\",\n message: {\n role: \"user\",\n content,\n },\n })\n}\n","/**\n * Per-agent model resolution.\n *\n * opencode's agent config cannot express \"inherit the account, choose the\n * model\". A subagent that omits `model` inherits the invoking agent's WHOLE\n * model string, and one that pins `model` inherits neither half, so pinning\n * Opus also pins the account it was written with. That is the wrong trade on a\n * machine with more than one Claude account: the worker should follow whoever\n * invoked it and still run on the model the job needs.\n *\n * The account is not part of the model id this class sees. It lives in the\n * provider (`claude-code-<account>`), which selects CLAUDE_CONFIG_DIR at spawn\n * time, and in an `@<account>` marker riding on the id for non-default\n * accounts (see `parseModelId` in models.ts). So swapping the model NAME while\n * preserving that marker changes the model and nothing else, which is exactly\n * the gap in the config schema.\n *\n * Declaring it: an agent markdown file says `forceModel: <id>`, or the\n * `defaultSubagentModel` provider option covers every subagent at once.\n * Nothing needs a per-agent entry in opencode.json.\n *\n * The same file can state `reasoningEffort:`, which beats the effort opencode\n * inherited from the caller's picker (see `resolveAgentEffort`). Model and\n * effort together are what a turn costs, so both belong with the agent.\n *\n * Two deliberate silences, because this rewrites what a user's model picker\n * said it would run:\n *\n * - With `defaultSubagentModel` unset there is NO implicit override. An\n * existing setup upgrading the plugin behaves exactly as before, instead\n * of quietly moving somebody's cheap subagent onto an expensive model.\n * - Only agents this plugin discovered are eligible. opencode's built-ins\n * (`explore`, `general`, `compaction`, ...) are never in the registry, so\n * they are never rewritten.\n */\nimport { readFile, readdir } from \"node:fs/promises\"\nimport path from \"node:path\"\nimport { log } from \"./logger.js\"\nimport { defaultModels } from \"./models.js\"\n\n/** Directory names opencode reads agent markdown from, current form first. */\nexport const AGENT_DIR_NAMES = [\"agents\", \"agent\"]\n\n/** Levels the Claude CLI accepts; anything else is refused, not forwarded. */\nconst REASONING_EFFORTS = [\n \"minimal\",\n \"low\",\n \"medium\",\n \"high\",\n \"xhigh\",\n \"max\",\n]\n\nexport type AgentRecord = {\n mode?: string\n /** A fully-qualified `provider/model` the agent pinned for itself. */\n model?: string\n /** Model NAME this agent wants, on whatever account the caller is using. */\n forceModel?: string\n /** Thinking budget this agent wants, whatever the caller's picker says. */\n reasoningEffort?: string\n}\n\nlet registry: Record<string, AgentRecord> = {}\nlet defaultSubagentModel: string | undefined\n\nexport function setAgentRegistry(records: Record<string, AgentRecord>): void {\n registry = records\n}\n\nexport function getAgentRegistry(): Record<string, AgentRecord> {\n return registry\n}\n\n/** `undefined` (the default) means no implicit override for any agent. */\nexport function setDefaultSubagentModel(model: string | undefined): void {\n defaultSubagentModel = model?.trim() || undefined\n}\n\nexport function getDefaultSubagentModel(): string | undefined {\n return defaultSubagentModel\n}\n\nexport function _resetAgentRegistryForTests(): void {\n registry = {}\n defaultSubagentModel = undefined\n}\n\n/** `claude-opus-5-fast@work` -> `@work`; a default-account id has none. */\nfunction accountMarker(modelId: string): string {\n const at = modelId.indexOf(\"@\")\n return at === -1 ? \"\" : modelId.slice(at)\n}\n\nfunction withoutAccountMarker(modelId: string): string {\n const at = modelId.indexOf(\"@\")\n return at === -1 ? modelId : modelId.slice(0, at)\n}\n\n/**\n * The model a request should actually spawn with.\n *\n * Order, first match wins:\n * 1. The agent declared `forceModel`.\n * 2. The agent is a discovered subagent and `defaultSubagentModel` is set.\n * 3. Anything else: the id opencode asked for, untouched.\n *\n * An agent that pinned a full `provider/model` is out of scope entirely:\n * opencode already routed the call to that provider, and second-guessing it\n * here would silently undo a choice the user made explicitly.\n *\n * Fails closed. An id that is not in the model registry is refused and the\n * original kept, because the alternative is spawning the CLI with a `--model`\n * it will reject, on a turn someone is waiting for.\n */\nexport function resolveAgentModel(\n agent: string | undefined,\n modelId: string,\n overrides?: {\n records?: Record<string, AgentRecord>\n defaultSubagentModel?: string\n },\n): string {\n if (!agent) return modelId\n\n const record = (overrides?.records ?? registry)[agent]\n if (!record) return modelId\n if (record.model?.includes(\"/\")) return modelId\n\n const fallback = overrides\n ? overrides.defaultSubagentModel\n : defaultSubagentModel\n const declared = record.forceModel?.trim()\n const wanted =\n declared || (record.mode === \"subagent\" ? fallback : undefined)\n if (!wanted) return modelId\n\n // A `forceModel` carrying its own `@account` would be forcing an account,\n // which is the thing this exists to avoid. Keep the caller's.\n const base = withoutAccountMarker(wanted)\n if (!Object.hasOwn(defaultModels, base)) {\n log.warn(\"agent model override refused: unknown model\", {\n agent,\n wanted: base,\n keeping: modelId,\n })\n return modelId\n }\n\n const resolved = `${base}${accountMarker(modelId)}`\n if (resolved !== modelId) {\n log.debug(\"agent model override\", { agent, from: modelId, to: resolved })\n }\n return resolved\n}\n\n/**\n * The thinking budget a request should actually spawn with.\n *\n * opencode resolves one effort for the whole session (the model picker's\n * selector, or a variant), and a subagent inherits it. That inheritance is\n * wrong in the expensive direction: a caller who picked `max` for their own\n * turn silently hands `max` to every worker it dispatches, so a mechanical\n * lane runs at the most costly setting available and burns a weekly cap that\n * the caller never spent on the work in front of them.\n *\n * An agent that states its own budget wins. Same reasoning as `forceModel`:\n * the declaration lives with the agent, so a file on disk is the whole\n * configuration and the caller's picker stays a choice about the caller.\n *\n * Unknown values are ignored rather than passed on, since the CLI refuses a\n * level it does not recognise and the turn would die at spawn.\n */\nexport function resolveAgentEffort(\n agent: string | undefined,\n inherited: string | undefined,\n overrides?: { records?: Record<string, AgentRecord> },\n): string | undefined {\n if (!agent) return inherited\n\n const record = (overrides?.records ?? registry)[agent]\n const declared = record?.reasoningEffort?.trim()\n if (!declared) return inherited\n\n if (!REASONING_EFFORTS.includes(declared)) {\n log.warn(\"agent effort override refused: unknown level\", {\n agent,\n wanted: declared,\n keeping: inherited,\n })\n return inherited\n }\n\n if (declared !== inherited) {\n log.debug(\"agent effort override\", {\n agent,\n from: inherited,\n to: declared,\n })\n }\n return declared\n}\n\n/**\n * Read the four fields that matter out of an agent markdown file's YAML\n * frontmatter. Hand-parsed rather than pulling a YAML dependency in for four\n * scalars, and deliberately top-level only: `permission:` has nested keys\n * (`bash:`, `edit:`) that must not be mistaken for agent fields.\n */\nexport function parseAgentFrontmatter(text: string): AgentRecord {\n const record: AgentRecord = {}\n if (!text.startsWith(\"---\")) return record\n\n const lines = text.split(/\\r?\\n/)\n for (let i = 1; i < lines.length; i++) {\n const line = lines[i]\n if (line.trim() === \"---\") break\n\n const match = /^([A-Za-z_][A-Za-z0-9_-]*):[ \\t]*(.*)$/.exec(line)\n if (!match) continue\n\n const key = match[1]\n if (\n key !== \"mode\" &&\n key !== \"model\" &&\n key !== \"forceModel\" &&\n key !== \"reasoningEffort\"\n )\n continue\n\n const value = match[2].trim().replace(/^[\"']|[\"']$/g, \"\")\n if (value) record[key] = value\n }\n\n return record\n}\n\n/**\n * Discover agents from markdown on disk. opencode merges these into its own\n * registry, but whether they reach a plugin's config hook is not documented,\n * so they are read directly rather than assumed.\n */\nexport async function readAgentMarkdownRecords(\n directories: string[],\n): Promise<Record<string, AgentRecord>> {\n const records: Record<string, AgentRecord> = {}\n\n for (const directory of directories) {\n let entries: string[]\n try {\n entries = await readdir(directory)\n } catch {\n continue\n }\n\n for (const entry of entries) {\n if (!entry.endsWith(\".md\")) continue\n\n const name = entry.slice(0, -3)\n if (records[name]) continue\n\n try {\n const text = await readFile(path.join(directory, entry), \"utf8\")\n records[name] = parseAgentFrontmatter(text)\n } catch (err) {\n log.debug(\"failed to read agent markdown\", {\n file: path.join(directory, entry),\n error: String(err),\n })\n }\n }\n }\n\n return records\n}\n\n/**\n * Every directory opencode would read agent markdown from, project before\n * global so a project agent of the same name wins, as opencode resolves them.\n */\nexport function agentDirectories(\n home: string | undefined,\n projectDirectory: string | undefined,\n): string[] {\n const directories: string[] = []\n\n if (projectDirectory) {\n for (const name of AGENT_DIR_NAMES) {\n directories.push(path.join(projectDirectory, \".opencode\", name))\n }\n }\n if (home) {\n for (const name of AGENT_DIR_NAMES) {\n directories.push(path.join(home, \".config\", \"opencode\", name))\n }\n }\n\n return directories\n}\n","import type { OpenCodeModel } from \"./opencode-types.js\"\n\nconst PROVIDER_ID = \"claude-code\"\nconst NPM = \"@khalilgharbaoui/opencode-claude-code-plugin\"\n\nconst reasoningVariants: Record<string, Record<string, unknown>> = {\n low: { reasoningEffort: \"low\" },\n medium: { reasoningEffort: \"medium\" },\n high: { reasoningEffort: \"high\" },\n xhigh: { reasoningEffort: \"xhigh\" },\n max: { reasoningEffort: \"max\" },\n}\n\nconst baseCapabilities = {\n temperature: false,\n attachment: true,\n toolcall: true,\n input: { text: true, audio: false, image: true, video: false, pdf: false },\n output: { text: true, audio: false, image: false, video: false, pdf: false },\n interleaved: false as const,\n}\n\nfunction defineModel(opts: {\n id: string\n name: string\n family: string\n reasoning: boolean\n context: number\n output: number\n cost: { input: number; output: number; cacheRead: number; cacheWrite: number }\n releaseDate: string\n // List-price multiplier relative to Haiku (the cheapest model). Derived\n // exactly from published per-token pricing: input AND output ratios both come\n // out to haiku 1, sonnet 3, opus 5, fable/mythos 10. Rendered as an\n // `(N×)` suffix so it surfaces in opencode's model picker, which has no\n // dedicated multiplier field.\n // Display-only: model resolution keys off `id`.\n multiplier: number\n status?: OpenCodeModel[\"status\"]\n}): OpenCodeModel {\n return {\n id: opts.id,\n providerID: PROVIDER_ID,\n api: { id: opts.id, url: \"\", npm: NPM },\n name: `${opts.name} (${opts.multiplier}×)`,\n family: opts.family,\n capabilities: { ...baseCapabilities, reasoning: opts.reasoning },\n cost: {\n input: opts.cost.input,\n output: opts.cost.output,\n cache: { read: opts.cost.cacheRead, write: opts.cost.cacheWrite },\n },\n limit: { context: opts.context, output: opts.output },\n status: opts.status ?? \"active\",\n options: {},\n headers: {},\n release_date: opts.releaseDate,\n variants: opts.reasoning ? reasoningVariants : undefined,\n }\n}\n\n// Costs in US dollars per MILLION tokens, matching Anthropic's published\n// pricing verbatim. This is the unit opencode and models.dev use: opencode\n// divides by 1e6 itself when it multiplies a cost by a token count, so writing\n// per-token values here under-reports session cost by exactly 1,000,000x.\n// Compare models.dev's own entry for the same model:\n// `anthropic/claude-haiku-4-5 -> {\"input\": 1, \"output\": 5, \"cache_read\": 0.1,\n// \"cache_write\": 1.25}`.\n//\n// There is no long-context premium to model. Anthropic's pricing page states\n// that Claude 4.6 and later ship the full 1M-token context window at standard\n// pricing (\"a 900k-token request is billed at the same per-token rate as a\n// 9k-token request\"), and caching/batch discounts apply unchanged across it.\n// opencode 1.18.5 added optional `cost.tiers` / `cost.experimentalOver200K`\n// fields for above-200K pricing; they stay unset here deliberately, because a\n// tier would misreport the real price. Re-check only if Anthropic introduces\n// one. Verified against the pricing docs 2026-07-26.\nconst haikuCost = { input: 1, output: 5, cacheRead: 0.1, cacheWrite: 1.25 }\nconst sonnetCost = { input: 3, output: 15, cacheRead: 0.3, cacheWrite: 3.75 }\n// Opus 4.5+ standard pricing is $5/M in, $25/M out (the price cut at 4.5; held\n// through 4.6/4.7/4.8/5). Cache read 0.1x input, cache write 1.25x input.\nconst opusCost = { input: 5, output: 25, cacheRead: 0.5, cacheWrite: 6.25 }\n// Fable 5 and Mythos 5 are the Mythos-class tier above Opus and share pricing\n// ($10/M in, $50/M out). Cache read/write follow Anthropic's standard 0.1x / 1.25x\n// input ratios (not separately published).\nconst fableCost = { input: 10, output: 50, cacheRead: 1, cacheWrite: 12.5 }\n// Fable 5.1 and Mythos 5.1 keep the same input/output and cache-write rates,\n// but Anthropic cut cache reads to $0.25/M (one quarter of the 5.0 price).\nconst fable51Cost = { input: 10, output: 50, cacheRead: 0.25, cacheWrite: 12.5 }\n// Fast mode bills the same per-token rates as the Mythos-class tier: $10/M in,\n// $50/M out, cache read 1, cache write 12.5. Not an inference; this is the\n// exact table the CLI itself applies for `speed: \"fast\"` on Opus 4.8 / Opus 5\n// (`{inputTokens: 10, outputTokens: 50, promptCacheWriteTokens: 12.5,\n// promptCacheReadTokens: 1}`). Kept as its own binding rather than reusing\n// `fableCost` so a future divergence in either tier stays a one-line change.\n// Verified against Claude Code 2.1.245, 2026-08-30.\nconst opusFastCost = { input: 10, output: 50, cacheRead: 1, cacheWrite: 12.5 }\n\n/**\n * Convert an OpenCodeModel to the flat config schema that OpenCode's\n * provider.ts config parser expects (model.temperature, model.reasoning,\n * model.cost.cache_read, model.modalities, etc.).\n */\nexport function toConfigModel(model: OpenCodeModel): Record<string, unknown> {\n const inputMods: string[] = []\n const outputMods: string[] = []\n for (const [k, v] of Object.entries(model.capabilities.input)) {\n if (v) inputMods.push(k)\n }\n for (const [k, v] of Object.entries(model.capabilities.output)) {\n if (v) outputMods.push(k)\n }\n\n return {\n id: model.api.id,\n name: model.name,\n status: model.status,\n family: model.family ?? \"\",\n release_date: model.release_date,\n\n temperature: model.capabilities.temperature,\n reasoning: model.capabilities.reasoning,\n attachment: model.capabilities.attachment,\n tool_call: model.capabilities.toolcall,\n modalities: { input: inputMods, output: outputMods },\n\n cost: {\n input: model.cost.input,\n output: model.cost.output,\n cache_read: model.cost.cache.read,\n cache_write: model.cost.cache.write,\n },\n\n limit: model.limit,\n options: model.options,\n headers: model.headers,\n variants: model.variants,\n }\n}\n\nexport const defaultModels: Record<string, OpenCodeModel> = {\n \"claude-haiku-4-5\": defineModel({\n id: \"claude-haiku-4-5\",\n name: \"Claude Haiku 4.5\",\n family: \"haiku\",\n reasoning: false,\n context: 200_000,\n output: 64_000,\n cost: haikuCost,\n multiplier: 1,\n releaseDate: \"2025-10-01\",\n }),\n \"claude-sonnet-4-5\": defineModel({\n id: \"claude-sonnet-4-5\",\n name: \"Claude Sonnet 4.5\",\n family: \"sonnet\",\n reasoning: true,\n context: 200_000,\n output: 64_000,\n cost: sonnetCost,\n multiplier: 3,\n releaseDate: \"2025-09-29\",\n }),\n \"claude-sonnet-4-6\": defineModel({\n id: \"claude-sonnet-4-6\",\n name: \"Claude Sonnet 4.6\",\n family: \"sonnet\",\n reasoning: true,\n context: 1_000_000,\n output: 128_000,\n cost: sonnetCost,\n multiplier: 3,\n releaseDate: \"2025-06-19\",\n }),\n \"claude-sonnet-5\": defineModel({\n id: \"claude-sonnet-5\",\n name: \"Claude Sonnet 5\",\n family: \"sonnet\",\n reasoning: true,\n context: 1_000_000,\n output: 128_000,\n cost: sonnetCost,\n multiplier: 3,\n releaseDate: \"2026-06-30\",\n }),\n \"claude-opus-4-5\": defineModel({\n id: \"claude-opus-4-5\",\n name: \"Claude Opus 4.5\",\n family: \"opus\",\n reasoning: true,\n context: 200_000,\n output: 64_000,\n cost: opusCost,\n multiplier: 5,\n releaseDate: \"2025-11-01\",\n }),\n \"claude-opus-4-6\": defineModel({\n id: \"claude-opus-4-6\",\n name: \"Claude Opus 4.6\",\n family: \"opus\",\n reasoning: true,\n context: 1_000_000,\n output: 128_000,\n cost: opusCost,\n multiplier: 5,\n releaseDate: \"2025-06-19\",\n }),\n \"claude-opus-4-7\": defineModel({\n id: \"claude-opus-4-7\",\n name: \"Claude Opus 4.7\",\n family: \"opus\",\n reasoning: true,\n context: 1_000_000,\n output: 128_000,\n cost: opusCost,\n multiplier: 5,\n releaseDate: \"2025-07-16\",\n }),\n \"claude-opus-4-8\": defineModel({\n id: \"claude-opus-4-8\",\n name: \"Claude Opus 4.8\",\n family: \"opus\",\n reasoning: true,\n context: 1_000_000,\n output: 128_000,\n cost: opusCost,\n multiplier: 5,\n releaseDate: \"2026-05-28\",\n }),\n // Fast mode. The `-fast` suffix is OUR marker, not a model name Anthropic\n // serves: `parseModelId` strips it before `--model` and turns it into\n // `--settings {\"fastMode\":true}` on the spawn. Retired `-fast` model strings\n // (`claude-opus-4-6-fast`) are a different thing and are not registered here.\n //\n // Only Opus 4.8 and Opus 5 qualify: the CLI gates fast mode on the resolved\n // model name containing `opus-4-8` or `opus-5`, so registering a fast entry\n // for any other model would produce a picker option that silently runs at\n // standard speed while displaying the 10x price.\n \"claude-opus-4-8-fast\": defineModel({\n id: \"claude-opus-4-8-fast\",\n name: \"Claude Opus 4.8 Fast\",\n family: \"opus\",\n reasoning: true,\n context: 1_000_000,\n output: 128_000,\n cost: opusFastCost,\n multiplier: 10,\n releaseDate: \"2026-05-28\",\n }),\n \"claude-opus-5\": defineModel({\n id: \"claude-opus-5\",\n name: \"Claude Opus 5\",\n family: \"opus\",\n reasoning: true,\n context: 1_000_000,\n output: 128_000,\n cost: opusCost,\n multiplier: 5,\n releaseDate: \"2026-07-24\",\n }),\n \"claude-opus-5-fast\": defineModel({\n id: \"claude-opus-5-fast\",\n name: \"Claude Opus 5 Fast\",\n family: \"opus\",\n reasoning: true,\n context: 1_000_000,\n output: 128_000,\n cost: opusFastCost,\n multiplier: 10,\n releaseDate: \"2026-07-24\",\n }),\n \"claude-fable-5\": defineModel({\n id: \"claude-fable-5\",\n name: \"Claude Fable 5\",\n family: \"fable\",\n reasoning: true,\n context: 1_000_000,\n output: 128_000,\n cost: fableCost,\n multiplier: 10,\n releaseDate: \"2026-06-09\",\n }),\n \"claude-fable-5-1\": defineModel({\n id: \"claude-fable-5-1\",\n name: \"Claude Fable 5.1\",\n family: \"fable\",\n reasoning: true,\n context: 1_000_000,\n output: 128_000,\n cost: fable51Cost,\n multiplier: 10,\n releaseDate: \"2026-09-01\",\n }),\n // Mythos 5 and 5.1 share the corresponding Fable models' capabilities and\n // pricing without the safety classifiers; limited availability via Project\n // Glasswing. `claude --model` simply errors for accounts without access, so\n // they are safe to register unconditionally.\n \"claude-mythos-5\": defineModel({\n id: \"claude-mythos-5\",\n name: \"Claude Mythos 5\",\n family: \"mythos\",\n reasoning: true,\n context: 1_000_000,\n output: 128_000,\n cost: fableCost,\n multiplier: 10,\n releaseDate: \"2026-06-09\",\n }),\n \"claude-mythos-5-1\": defineModel({\n id: \"claude-mythos-5-1\",\n name: \"Claude Mythos 5.1\",\n family: \"mythos\",\n reasoning: true,\n context: 1_000_000,\n output: 128_000,\n cost: fable51Cost,\n multiplier: 10,\n releaseDate: \"2026-09-01\",\n }),\n}\n\n/** Marker this plugin appends to build a fast-mode model id. See below. */\nconst FAST_SUFFIX = \"-fast\"\n\n/**\n * Split an opencode model id into the name the Claude CLI actually accepts\n * and whether fast mode was requested.\n *\n * Two suffixes can ride on one id and they are NOT interchangeable:\n *\n * claude-opus-5-fast@work\n * \\_____________/\\___/\\__/\n * CLI model ours accounts.ts's\n *\n * `@work` must survive: the per-account wrapper script strips it at spawn\n * time to pick a CLAUDE_CONFIG_DIR. `-fast` must not: the CLI has no such\n * model (`claude-opus-4-6-fast` is retired and `claude-opus-4-7-fast` errors\n * outright), so it becomes `--settings {\"fastMode\":true}` instead.\n *\n * The `defaultModels` lookup is the guard against a false positive. Only ids\n * we registered are treated as fast markers, so a user-defined model that\n * happens to end in `-fast` is passed through untouched rather than being\n * silently rewritten into a model name that does not exist.\n */\nexport function parseModelId(modelId: string): { model: string; fast: boolean } {\n const at = modelId.indexOf(\"@\")\n const base = at === -1 ? modelId : modelId.slice(0, at)\n const account = at === -1 ? \"\" : modelId.slice(at)\n\n if (!base.endsWith(FAST_SUFFIX)) return { model: modelId, fast: false }\n if (!Object.hasOwn(defaultModels, base)) return { model: modelId, fast: false }\n\n return { model: base.slice(0, -FAST_SUFFIX.length) + account, fast: true }\n}\n","import * as crypto from \"node:crypto\"\nimport * as fs from \"node:fs\"\nimport * as os from \"node:os\"\nimport * as path from \"node:path\"\nimport { detectCliSupportsFlag } from \"./cli-version.js\"\nimport { log } from \"./logger.js\"\nimport { pluginTmpDir } from \"./tmp.js\"\n\n/**\n * Bridge opencode skills into Claude Code's native Skill tool.\n *\n * Written by Joseph Roberts (@broskees) on his fork, commit 68ed142, and\n * absorbed here with light edits. Opt-in via `bridgeOpencodeSkills`; see\n * README for why it is off by default upstream.\n *\n * opencode and Claude Code use the same on-disk skill format, a\n * `<name>/SKILL.md` file whose YAML frontmatter carries `name` and\n * `description`, but they read from different roots. opencode looks in\n * `~/.config/opencode/skills/` and `.opencode/skills/`; the Claude CLI we\n * wrap looks in `~/.claude/skills/` and its own plugins. So opencode's\n * skills are invisible to the CLI, while opencode still advertises them in\n * the system prompt it forwards. The model reads that list, calls\n * `Skill(\"browser-automation\")`, and gets `Unknown skill`.\n *\n * Fix: assemble a throwaway Claude Code *plugin* directory whose `skills/`\n * folder links each discovered opencode skill, and hand it to the CLI with\n * `--plugin-dir`. Claude registers them natively as\n * `opencode-skills:<name>`, listed by the Skill tool, invocable, and\n * usable as `/opencode-skills:<name>`.\n *\n * `--plugin-dir` is documented as \"for this session only\", so this never\n * writes into the user's `~/.claude`. The staging dir lives under the\n * per-process tmp dir and is removed on exit with everything else.\n */\n\n/** Plugin name, and therefore the `<plugin>:<skill>` prefix Claude assigns. */\nexport const SKILL_PLUGIN_NAME = \"opencode-skills\"\n\nexport interface DiscoveredSkill {\n name: string\n /** Absolute path to the skill directory containing SKILL.md. */\n dir: string\n}\n\nfunction dirExists(p: string): boolean {\n try {\n return fs.statSync(p).isDirectory()\n } catch {\n return false\n }\n}\n\nfunction fileExists(p: string): boolean {\n try {\n return fs.statSync(p).isFile()\n } catch {\n return false\n }\n}\n\n/**\n * Skill roots in opencode's own precedence order: nearest project\n * `.opencode/skills` first, then outward, then the home-dir `.opencode`,\n * then `OPENCODE_CONFIG_DIR`, then the global `~/.config/opencode`. First\n * occurrence of a given skill name wins, so a project can shadow a global\n * skill, matching how opencode resolves its own config.\n */\nexport function skillRoots(cwd: string): string[] {\n const roots: string[] = []\n const seen = new Set<string>()\n const push = (p: string) => {\n const abs = path.resolve(p)\n if (seen.has(abs)) return\n seen.add(abs)\n if (dirExists(abs)) roots.push(abs)\n }\n\n let current = path.resolve(cwd)\n while (true) {\n push(path.join(current, \".opencode\", \"skills\"))\n const parent = path.dirname(current)\n if (parent === current) break\n current = parent\n }\n\n const home = os.homedir()\n if (home) push(path.join(home, \".opencode\", \"skills\"))\n\n const envDir = process.env.OPENCODE_CONFIG_DIR\n if (envDir) push(path.join(envDir, \"skills\"))\n\n const xdg = process.env.XDG_CONFIG_HOME ?? (home ? path.join(home, \".config\") : null)\n if (xdg) push(path.join(xdg, \"opencode\", \"skills\"))\n\n return roots\n}\n\n/**\n * Walk the skill roots and collect every `<name>/SKILL.md`. Directories\n * without a SKILL.md are skipped silently, opencode ignores them too.\n */\nexport function discoverOpencodeSkills(cwd: string): DiscoveredSkill[] {\n const found: DiscoveredSkill[] = []\n const claimed = new Set<string>()\n\n for (const root of skillRoots(cwd)) {\n let entries: fs.Dirent[]\n try {\n entries = fs.readdirSync(root, { withFileTypes: true })\n } catch {\n continue\n }\n for (const entry of entries) {\n // `withFileTypes` reports a symlinked dir as a link, not a dir.\n if (!entry.isDirectory() && !entry.isSymbolicLink()) continue\n const name = entry.name\n if (name.startsWith(\".\")) continue\n if (claimed.has(name)) continue\n const dir = path.join(root, name)\n if (!fileExists(path.join(dir, \"SKILL.md\"))) continue\n claimed.add(name)\n found.push({ name, dir })\n }\n }\n\n return found.sort((a, b) => a.name.localeCompare(b.name))\n}\n\n/** Link a skill dir into the staging tree, falling back to a copy. */\nfunction linkSkill(source: string, target: string): void {\n try {\n // Windows needs an explicit junction for directory links, and even then\n // only with the right privileges, hence the copy fallback below.\n fs.symlinkSync(source, target, process.platform === \"win32\" ? \"junction\" : \"dir\")\n return\n } catch {\n fs.cpSync(source, target, { recursive: true, dereference: true })\n }\n}\n\n/**\n * Materialise the synthetic plugin directory. Returns its path, or null if\n * there are no skills to bridge. The path is keyed by a hash of the\n * resolved skill set, so an unchanged set reuses the existing tree instead\n * of rebuilding it on every spawn.\n */\nexport function buildSkillPluginDir(skills: DiscoveredSkill[]): string | null {\n if (skills.length === 0) return null\n\n const fingerprint = skills.map((s) => `${s.name}\\0${s.dir}`).join(\"\\n\")\n const hash = crypto.createHash(\"sha256\").update(fingerprint).digest(\"hex\").slice(0, 12)\n const root = path.join(pluginTmpDir(), `skills-${hash}`)\n const manifest = path.join(root, \".claude-plugin\", \"plugin.json\")\n\n // Same skill set as a previous spawn in this process, reuse the tree.\n if (fileExists(manifest)) return root\n\n try {\n fs.rmSync(root, { recursive: true, force: true })\n fs.mkdirSync(path.join(root, \".claude-plugin\"), { recursive: true })\n fs.mkdirSync(path.join(root, \"skills\"), { recursive: true })\n fs.writeFileSync(\n manifest,\n JSON.stringify(\n {\n name: SKILL_PLUGIN_NAME,\n description:\n \"Skills discovered from this opencode installation, bridged into Claude Code.\",\n },\n null,\n 2,\n ),\n { encoding: \"utf8\", mode: 0o600 },\n )\n for (const skill of skills) {\n linkSkill(skill.dir, path.join(root, \"skills\", skill.name))\n }\n } catch (err) {\n log.warn(\"failed to stage opencode skill plugin dir\", {\n root,\n error: err instanceof Error ? err.message : String(err),\n })\n return null\n }\n\n return root\n}\n\n/**\n * One-call entry point for the spawn sites: discover, stage, and return the\n * `--plugin-dir` values. Returns an empty array whenever the feature is off,\n * the CLI is too old to accept the flag, or the user has no skills, so\n * callers can spread the result unconditionally.\n */\nexport async function resolveSkillPluginDirs(opts: {\n cwd: string\n cliPath: string\n enabled: boolean\n}): Promise<string[]> {\n if (!opts.enabled) return []\n\n const skills = discoverOpencodeSkills(opts.cwd)\n if (skills.length === 0) return []\n\n // No published version marks `--plugin-dir`'s arrival, so probe the\n // binary's own help text rather than inventing a semver threshold.\n const supported = await detectCliSupportsFlag(opts.cliPath, \"--plugin-dir\")\n if (!supported) {\n log.notice(\n \"claude cli does not support --plugin-dir; opencode skills will not be bridged. Run `npm i -g @anthropic-ai/claude-code` to upgrade.\",\n { skills: skills.length },\n )\n return []\n }\n\n const dir = buildSkillPluginDir(skills)\n if (!dir) return []\n\n log.info(\"bridged opencode skills into claude\", {\n count: skills.length,\n names: skills.map((s) => s.name),\n pluginDir: dir,\n })\n return [dir]\n}\n","import * as fs from \"node:fs\"\nimport * as path from \"node:path\"\nimport * as os from \"node:os\"\nimport * as crypto from \"node:crypto\"\nimport {\n parse as parseJsonc,\n printParseErrorCode,\n type ParseError,\n} from \"jsonc-parser\"\nimport { log } from \"./logger.js\"\nimport { pluginTmpDir } from \"./tmp.js\"\n\n/**\n * Bridge opencode's `mcp` config block into a Claude CLI `--mcp-config` file.\n *\n * Opencode core schema (packages/opencode/src/config/mcp.ts):\n * {\n * \"mcp\": {\n * \"name\": {\n * \"type\": \"local\" | \"remote\",\n * \"command\"?: string[], // local\n * \"environment\"?: Record<string,string>,\n * \"url\"?: string, // remote\n * \"headers\"?: Record<string,string>,\n * \"oauth\"?: object | false, // remote — NOT bridged (Claude --mcp-config has no slot)\n * \"timeout\"?: number, // NOT bridged (Claude --mcp-config has no slot)\n * \"enabled\"?: boolean\n * }\n * }\n * }\n *\n * Claude CLI `--mcp-config` schema:\n * {\n * \"mcpServers\": {\n * \"name\": {\n * \"type\": \"stdio\" | \"http\",\n * \"command\"?: string, \"args\"?: string[], \"env\"?: Record<string,string>,\n * \"url\"?: string, \"headers\"?: Record<string,string>\n * }\n * }\n * }\n *\n * Discovery + merge are aligned with opencode core's `loadInstanceState`\n * (packages/opencode/src/config/config.ts). In merge order (last wins),\n * opencode loads:\n *\n * 1. Auth `.well-known` remote configs ← NOT bridged\n * 2. Global: ~/.config/opencode/{config.json,opencode.json,opencode.jsonc}\n * — all three deep-merged, jsonc highest priority\n * 3. OPENCODE_CONFIG env var (single file)\n * 4. Project walk-up: opencode.json[c] in each dir from cwd up to (not past)\n * worktree, both extensions per dir, parent-most first\n * 5. .opencode/ siblings: from cwd up + home dir + OPENCODE_CONFIG_DIR,\n * both extensions per dir, opencode-iteration order (cwd-most first\n * in walk-up — so parent-most `.opencode/` wins, matching upstream)\n * 6. OPENCODE_CONFIG_CONTENT env var (inline JSON) ← NOT bridged\n * 7. Active org remote config ← NOT bridged\n * 8. Managed config dir / macOS MDM ← NOT bridged\n *\n * Sources marked NOT bridged are niche and would require live opencode\n * runtime state (auth tokens, account context, MDM access). Document them\n * here so the gap is explicit; functionality of the common path is intact.\n *\n * Per-server merge is deep-merge (matching opencode's `mergeConfigConcatArrays`\n * → `mergeDeep`), so a project layer can override one field of a global server\n * spec — e.g. `{ \"linear\": { \"enabled\": true } }` lifts global linear's URL.\n */\n\nconst FILE_NAMES = [\"opencode.jsonc\", \"opencode.json\", \"config.json\"] as const\nconst PROJECT_FILE_NAMES = [\"opencode.json\", \"opencode.jsonc\"] as const\n\nfunction fileExists(p: string): boolean {\n try {\n return fs.statSync(p).isFile()\n } catch {\n return false\n }\n}\n\nfunction dirExists(p: string): boolean {\n try {\n return fs.statSync(p).isDirectory()\n } catch {\n return false\n }\n}\n\nfunction readAndParse(file: string): Record<string, unknown> | null {\n try {\n const raw = fs.readFileSync(file, \"utf8\")\n const errors: ParseError[] = []\n const parsed = parseJsonc(raw, errors, { allowTrailingComma: true })\n if (errors.length > 0) {\n const first = errors[0]\n throw new Error(\n `${printParseErrorCode(first.error)} at offset ${first.offset}`,\n )\n }\n return parsed as Record<string, unknown>\n } catch (e) {\n log.warn(\"failed to parse opencode config\", {\n file,\n error: e instanceof Error ? e.message : String(e),\n })\n return null\n }\n}\n\n/**\n * Deep merge two plain-object trees. Arrays and primitives are replaced\n * (not concatenated). Matches the effective behavior of opencode's\n * `mergeDeep` from `remeda` for the MCP block — opencode does not special\n * case array fields inside `mcp.<server>` (its only special case is\n * `instructions`, which is concat-deduped at the config root).\n */\nfunction isPlainObject(x: unknown): x is Record<string, unknown> {\n return typeof x === \"object\" && x !== null && !Array.isArray(x)\n}\n\nfunction deepMerge(\n target: Record<string, unknown>,\n source: Record<string, unknown>,\n): Record<string, unknown> {\n const out: Record<string, unknown> = { ...target }\n for (const [k, v] of Object.entries(source)) {\n if (v === undefined) continue\n const existing = out[k]\n if (isPlainObject(existing) && isPlainObject(v)) {\n out[k] = deepMerge(existing, v)\n } else {\n out[k] = v\n }\n }\n return out\n}\n\n/**\n * Walk up from `start` toward filesystem root (or `stop` if provided),\n * collecting paths where each `target` exists. Mirrors opencode core's\n * `FileSystem.up` (packages/core/src/filesystem.ts): cwd-most first,\n * parent-most last.\n */\nfunction walkUp(opts: {\n start: string\n stop?: string\n targets: readonly string[]\n predicate: (p: string) => boolean\n}): string[] {\n const out: string[] = []\n let current = path.resolve(opts.start)\n while (true) {\n for (const target of opts.targets) {\n const candidate = path.join(current, target)\n if (opts.predicate(candidate)) out.push(candidate)\n }\n if (opts.stop && current === path.resolve(opts.stop)) break\n const parent = path.dirname(current)\n if (parent === current) break\n current = parent\n }\n return out\n}\n\n/**\n * Find the worktree root by walking up from `cwd` looking for a `.git`\n * entry (file or directory — submodules use a file). If no `.git` is\n * found, walk to filesystem root. Honors OPENCODE_WORKTREE override.\n */\nfunction detectWorktree(cwd: string): string | undefined {\n const override = process.env.OPENCODE_WORKTREE\n if (override) return path.resolve(override)\n let current = path.resolve(cwd)\n while (true) {\n const gitPath = path.join(current, \".git\")\n try {\n if (fs.existsSync(gitPath)) return current\n } catch {\n // ignore\n }\n const parent = path.dirname(current)\n if (parent === current) return undefined\n current = parent\n }\n}\n\nfunction globalConfigDir(): string {\n const xdg = process.env.XDG_CONFIG_HOME ?? path.join(os.homedir(), \".config\")\n return path.join(xdg, \"opencode\")\n}\n\n/**\n * Load the merged global config from `~/.config/opencode/`. Mirrors\n * opencode core's `loadGlobal`: deep-merges config.json → opencode.json\n * → opencode.jsonc in that order (jsonc wins).\n */\nfunction loadGlobalConfig(): Record<string, unknown> {\n const dir = globalConfigDir()\n let merged: Record<string, unknown> = {}\n for (const name of FILE_NAMES.slice().reverse()) {\n // FILE_NAMES is jsonc-first; reverse to get config.json-first order.\n const file = path.join(dir, name)\n if (!fileExists(file)) continue\n const parsed = readAndParse(file)\n if (parsed) merged = deepMerge(merged, parsed)\n }\n return merged\n}\n\n/** Load both `opencode.json` and `opencode.jsonc` in `dir`, deep-merged. */\nfunction loadProjectFilesInDir(dir: string): Record<string, unknown> {\n let merged: Record<string, unknown> = {}\n for (const name of PROJECT_FILE_NAMES) {\n const file = path.join(dir, name)\n if (!fileExists(file)) continue\n const parsed = readAndParse(file)\n if (parsed) merged = deepMerge(merged, parsed)\n }\n return merged\n}\n\n/**\n * Build the list of `.opencode/` directories to consider, in opencode core's\n * order (matching `ConfigPaths.directories`):\n * project walk-up (cwd-most first) → home-dir `.opencode/` → OPENCODE_CONFIG_DIR\n */\nfunction dotOpencodeDirs(cwd: string, worktree?: string): string[] {\n const dirs: string[] = []\n const seen = new Set<string>()\n const push = (p: string) => {\n const abs = path.resolve(p)\n if (!seen.has(abs) && dirExists(abs)) {\n seen.add(abs)\n dirs.push(abs)\n }\n }\n\n for (const dir of walkUp({\n start: cwd,\n stop: worktree,\n targets: [\".opencode\"],\n predicate: dirExists,\n })) {\n push(dir)\n }\n\n const home = os.homedir()\n if (home) {\n const homeDot = path.join(home, \".opencode\")\n if (dirExists(homeDot)) push(homeDot)\n }\n\n const envDir = process.env.OPENCODE_CONFIG_DIR\n if (envDir && dirExists(envDir)) push(envDir)\n\n return dirs\n}\n\ninterface OpencodeLocalServer {\n type?: \"local\"\n command?: string[]\n environment?: Record<string, string>\n enabled?: boolean\n}\n\ninterface OpencodeRemoteServer {\n type?: \"remote\"\n url?: string\n headers?: Record<string, string>\n enabled?: boolean\n}\n\ntype OpencodeServer = OpencodeLocalServer | OpencodeRemoteServer | { enabled?: boolean }\n\n/**\n * Substitute opencode's `{env:VAR}` interpolation in a string-keyed record\n * using values from `process.env`. Returns a new object. If the source is\n * not a flat string-valued record, returns it unchanged.\n *\n * Opencode performs this substitution itself when it spawns MCP servers\n * directly, but the spec we read from disk still contains the literal\n * placeholders. Without substituting them here, Claude CLI hands the\n * literal string `{env:FOO}` to the MCP subprocess as the env value, and\n * any server that validates credentials at startup (e.g. slack-mcp-server)\n * crashes before exposing tools. Servers that defer validation to\n * request time (e.g. github-mcp-server) appear to register but every API\n * call 401s.\n */\nfunction substituteEnvPlaceholders(\n source: Record<string, unknown>,\n): Record<string, string> {\n const out: Record<string, string> = {}\n for (const [k, v] of Object.entries(source)) {\n if (typeof v !== \"string\") continue\n out[k] = v.replace(/\\{env:([A-Za-z_][A-Za-z0-9_]*)\\}/g, (_match, name) => {\n const resolved = process.env[name]\n return typeof resolved === \"string\" ? resolved : \"\"\n })\n }\n return out\n}\n\nfunction translateServer(\n name: string,\n spec: Record<string, unknown>,\n): Record<string, unknown> | null {\n if (spec.enabled === false) return null\n\n const type = spec.type\n if (type === \"local\") {\n const cmd = spec.command\n if (!Array.isArray(cmd) || cmd.length === 0) {\n log.warn(\"skipping local MCP server with no command\", { name })\n return null\n }\n const out: Record<string, unknown> = {\n type: \"stdio\",\n command: String(cmd[0]),\n }\n if (cmd.length > 1) out.args = cmd.slice(1).map((s) => String(s))\n if (spec.environment && typeof spec.environment === \"object\") {\n out.env = substituteEnvPlaceholders(\n spec.environment as Record<string, unknown>,\n )\n }\n return out\n }\n\n if (type === \"remote\") {\n if (typeof spec.url !== \"string\" || !spec.url) {\n log.warn(\"skipping remote MCP server with no url\", { name })\n return null\n }\n const out: Record<string, unknown> = {\n type: \"http\",\n url: spec.url,\n }\n if (spec.headers && typeof spec.headers === \"object\") {\n out.headers = substituteEnvPlaceholders(\n spec.headers as Record<string, unknown>,\n )\n }\n return out\n }\n\n log.warn(\"skipping MCP server with unknown type\", {\n name,\n type: type ?? null,\n })\n return null\n}\n\nfunction extractMcpBlock(\n config: Record<string, unknown>,\n): Record<string, OpencodeServer> {\n const mcp = config.mcp\n if (!mcp || typeof mcp !== \"object\" || Array.isArray(mcp)) return {}\n return mcp as Record<string, OpencodeServer>\n}\n\n/**\n * Deep-merge per-server specs from `source` into `target`. Mirrors opencode's\n * `mergeDeep` semantics for the `mcp` record: each server entry is recursively\n * merged so a partial layer (e.g. `{ \"linear\": { \"enabled\": true } }`) can\n * override one field without dropping the rest.\n */\nfunction mergeMcp(\n target: Record<string, OpencodeServer>,\n source: Record<string, OpencodeServer>,\n): Record<string, OpencodeServer> {\n const out: Record<string, OpencodeServer> = { ...target }\n for (const [name, spec] of Object.entries(source)) {\n if (!spec || typeof spec !== \"object\") continue\n const existing = out[name]\n if (existing && typeof existing === \"object\") {\n out[name] = deepMerge(\n existing as Record<string, unknown>,\n spec as Record<string, unknown>,\n ) as OpencodeServer\n } else {\n out[name] = spec\n }\n }\n return out\n}\n\nexport interface BridgedMcp {\n /** Path to the temp file containing the translated `--mcp-config`. */\n path: string\n /** Stable hash of the merged opencode mcp block (pre-translation). */\n hash: string\n /**\n * Names of opencode MCP servers that were bridged into Claude CLI's\n * `--mcp-config`. Excludes any servers passed in `excludeServers`.\n */\n serverNames: string[]\n /**\n * Names of every enabled opencode MCP server after merge + runtime\n * overlay, regardless of whether they ended up bridged or excluded.\n * Callers (e.g. the proxy-tool builder) use this to decide which\n * `<server>_<tool>` IDs in opencode's tool catalog are MCP-origin.\n */\n allEnabledServerNames: string[]\n}\n\n/** Result of merging opencode's MCP config layers + applying runtime overlay. */\nexport interface MergedMcp {\n /** Merged, overlay-applied server specs keyed by opencode server name. */\n servers: Record<string, OpencodeServer>\n /** Server names whose final spec is enabled (or implicitly enabled). */\n enabledServerNames: string[]\n /** Stable hash of the merged (pre-translation) MCP block. */\n hash: string\n}\n\n/**\n * Per-server runtime status from opencode's `client.mcp.status()`. Used as\n * an overlay on top of the on-disk merged config so opencode's UI-toggled\n * state — which lives only in-memory; `connect()`/`disconnect()` never\n * touch disk — propagates to the bridged claude subprocess.\n *\n * Treatment per server:\n * - \"connected\" → force `enabled: true` (mirror opencode)\n * - any other status → force `enabled: false` (don't ship a server\n * opencode can't run; user fixes it in opencode first)\n * - missing entry → leave disk value\n *\n * Omit the overlay and the bridge falls back to disk-only.\n */\nexport type RuntimeMcpStatus = Record<string, string>\n\n/**\n * Read opencode config layers, deep-merge their `mcp` blocks per opencode's\n * own semantics, optionally apply an opencode runtime-status overlay, then\n * translate each server to Claude CLI format, write a scratch file, and\n * return its path + a stable hash. Returns null when no enabled MCP servers\n * remain after the merge + overlay.\n */\nexport function bridgeOpencodeMcp(\n cwd: string,\n runtimeStatus?: RuntimeMcpStatus,\n excludeServers?: ReadonlySet<string>,\n): BridgedMcp | null {\n const {\n servers: merged,\n enabledServerNames: allEnabledServerNames,\n hash,\n } = mergeOpencodeMcp(cwd, runtimeStatus)\n\n // Translate every still-enabled server, skipping any caller has asked us\n // to exclude (because they're being routed through the proxy instead).\n const servers: Record<string, unknown> = {}\n const bridgedServerNames: string[] = []\n for (const [name, spec] of Object.entries(merged)) {\n if (!spec || typeof spec !== \"object\") continue\n if (excludeServers?.has(name)) continue\n const translated = translateServer(name, spec as Record<string, unknown>)\n if (translated) {\n servers[name] = translated\n bridgedServerNames.push(name)\n }\n }\n return finishBridge({\n servers,\n bridgedServerNames,\n allEnabledServerNames,\n hash,\n excludeServers,\n })\n}\n\n/**\n * Merge opencode's MCP config layers (global → `OPENCODE_CONFIG` → project\n * walk-up → `.opencode/` siblings), apply the opencode runtime-status\n * overlay, and hash the result. Split out of `bridgeOpencodeMcp` so\n * read-only callers (startup diagnostics) can inspect what would be bridged\n * without translating servers or writing a scratch config file.\n */\nexport function mergeOpencodeMcp(\n cwd: string,\n runtimeStatus?: RuntimeMcpStatus,\n): MergedMcp {\n const worktree = detectWorktree(cwd)\n\n // Layer 1: global merged\n let merged: Record<string, OpencodeServer> = {}\n merged = mergeMcp(merged, extractMcpBlock(loadGlobalConfig()))\n\n // Layer 2: OPENCODE_CONFIG (single file, applied before project walk-up)\n const explicitConfig = process.env.OPENCODE_CONFIG\n if (explicitConfig && fileExists(explicitConfig)) {\n const parsed = readAndParse(explicitConfig)\n if (parsed) merged = mergeMcp(merged, extractMcpBlock(parsed))\n }\n\n // Layer 3: project walk-up — opencode.json[c] in each dir from cwd to\n // (not past) worktree, both extensions per dir. walkUp returns cwd-most\n // first; collect distinct dirs in that order then reverse for merge so\n // cwd-most wins under last-merge-wins.\n const projectFiles = walkUp({\n start: cwd,\n stop: worktree,\n targets: PROJECT_FILE_NAMES,\n predicate: fileExists,\n })\n const projectDirs: string[] = []\n const seenProjectDirs = new Set<string>()\n for (const f of projectFiles) {\n const d = path.dirname(f)\n if (!seenProjectDirs.has(d)) {\n seenProjectDirs.add(d)\n projectDirs.push(d)\n }\n }\n for (const dir of projectDirs.slice().reverse()) {\n merged = mergeMcp(merged, extractMcpBlock(loadProjectFilesInDir(dir)))\n }\n\n // Layer 4: `.opencode/` siblings — project walk-up then home-dir then\n // OPENCODE_CONFIG_DIR, in that order. Iteration order matches opencode's\n // (cwd-most first within walk-up), so under deep-merge \"later wins\"\n // parent-most `.opencode/` overrides cwd-most. This is upstream's\n // behavior, surprising though it is.\n for (const dir of dotOpencodeDirs(cwd, worktree)) {\n merged = mergeMcp(merged, extractMcpBlock(loadProjectFilesInDir(dir)))\n }\n\n // Layer 5: opencode runtime overlay. opencode's `/mcps` UI toggle calls\n // `mcp.connect()` / `mcp.disconnect()` which only mutate in-memory state,\n // never the on-disk config. Without this overlay the bridge can't see\n // those toggles and claude misses servers the user just enabled.\n if (runtimeStatus) {\n for (const name of Object.keys(merged)) {\n const status = runtimeStatus[name]\n if (status === undefined) continue\n const existing = merged[name]\n const base =\n existing && typeof existing === \"object\"\n ? (existing as Record<string, unknown>)\n : {}\n merged[name] = { ...base, enabled: status === \"connected\" } as OpencodeServer\n }\n }\n\n // Compute the set of enabled server names BEFORE exclusion so callers can\n // tell whether a tool ID like `slack_conversations_add_message` came from\n // an opencode MCP server (vs a built-in tool that happens to contain `_`).\n const enabledServerNames: string[] = []\n for (const [name, spec] of Object.entries(merged)) {\n if (!spec || typeof spec !== \"object\") continue\n const enabled = (spec as { enabled?: unknown }).enabled\n if (enabled === false) continue\n enabledServerNames.push(name)\n }\n\n // Hash the pre-exclusion merged block so the hot-reload detector picks up\n // upstream config changes even when every server is excluded.\n const mergedBody = JSON.stringify({ mcpServers: merged }, null, 2)\n const hash = crypto\n .createHash(\"sha256\")\n .update(mergedBody)\n .digest(\"hex\")\n .slice(0, 12)\n\n return { servers: merged, enabledServerNames, hash }\n}\n\n/** Write the translated config (if any) and shape `bridgeOpencodeMcp`'s result. */\nfunction finishBridge(input: {\n servers: Record<string, unknown>\n bridgedServerNames: string[]\n allEnabledServerNames: string[]\n hash: string\n excludeServers?: ReadonlySet<string>\n}): BridgedMcp | null {\n const { servers, bridgedServerNames, allEnabledServerNames, hash, excludeServers } =\n input\n\n if (Object.keys(servers).length === 0) {\n const allEnabledServersExcluded =\n excludeServers &&\n allEnabledServerNames.length > 0 &&\n allEnabledServerNames.every((name) => excludeServers.has(name))\n\n if (!allEnabledServersExcluded) return null\n\n return {\n path: \"\",\n hash,\n serverNames: [],\n allEnabledServerNames,\n }\n }\n\n const body = JSON.stringify({ mcpServers: servers }, null, 2)\n const outPath = path.join(\n pluginTmpDir(),\n `mcp-${hash}.json`,\n )\n try {\n if (!fileExists(outPath)) {\n fs.writeFileSync(outPath, body, { encoding: \"utf8\", mode: 0o600 })\n }\n } catch (e) {\n log.warn(\"failed to write bridged MCP config\", {\n error: e instanceof Error ? e.message : String(e),\n })\n return null\n }\n\n log.info(\"bridged opencode MCP config\", {\n target: outPath,\n hash,\n servers: bridgedServerNames,\n excluded: excludeServers ? Array.from(excludeServers) : [],\n })\n return {\n path: outPath,\n hash,\n serverNames: bridgedServerNames,\n allEnabledServerNames,\n }\n}\n\n// Internal helpers exported for tests only.\nexport const __test = {\n deepMerge,\n mergeMcp,\n translateServer,\n substituteEnvPlaceholders,\n detectWorktree,\n loadGlobalConfig,\n loadProjectFilesInDir,\n dotOpencodeDirs,\n}\n","import type { RuntimeMcpStatus } from \"./mcp-bridge.js\"\nimport { log } from \"./logger.js\"\n\n/**\n * Captured opencode runtime context (SDK client + project directory) from\n * `PluginInput`. Lives in its own module to break the cycle that would\n * otherwise form between `index.ts` and `claude-code-language-model.ts`.\n * Values are `null`/`undefined` until the plugin's `server` factory runs\n * (e.g. early provider lookups, direct AI-SDK use, tests).\n */\ntype OpencodeClient = {\n mcp?: {\n status?: () => Promise<{ data?: unknown; error?: unknown }>\n }\n tool?: {\n list?: (options: {\n query: { provider: string; model: string; directory?: string }\n }) => Promise<{ data?: unknown; error?: unknown }>\n }\n session?: {\n /** `GET /session/{id}` — the returned Session carries `directory`. */\n get?: (options: {\n path: { id: string }\n query?: { directory?: string }\n }) => Promise<{ data?: unknown; error?: unknown }>\n }\n}\n\nlet opencodeClient: OpencodeClient | null = null\n\nexport function setOpencodeClient(client: unknown): void {\n if (client && typeof client === \"object\") {\n opencodeClient = client as OpencodeClient\n }\n}\n\n/**\n * The captured SDK client, untyped: callers narrow to the surface they use\n * (this module's `OpencodeClient` only mirrors the MCP/tool routes).\n */\nexport function getOpencodeClient(): unknown {\n return opencodeClient\n}\n\n/**\n * Captured opencode project directory from `PluginInput.directory` (with\n * `worktree` as secondary signal). Used as a *fallback* at Claude CLI\n * spawn time only when `process.cwd()` is unusable (macOS GUI launches\n * where launchd hands the process `cwd=/`).\n *\n * IMPORTANT: never bake this into provider config (`mergedOptions.cwd`).\n * Doing so freezes the value at plugin init and breaks workspace\n * switching mid-session, because subsequent workspace changes in\n * opencode's UI never get reflected in `this.config.cwd`. See issue #4.\n */\nlet opencodeProjectDirectory: string | undefined\n\nexport function setOpencodeProjectDirectory(dir: string | undefined): void {\n opencodeProjectDirectory = dir\n}\n\nexport function getOpencodeProjectDirectory(): string | undefined {\n return opencodeProjectDirectory\n}\n\nexport function isUsableDirectory(d: unknown): d is string {\n return typeof d === \"string\" && d.length > 1 && d !== \"/\"\n}\n\n/**\n * Resolve the cwd for a Claude CLI subprocess spawn. Priority:\n *\n * 1. Explicit `configured` value (`options.cwd` from `opencode.json`).\n * Users who pinned a directory keep their override unconditionally.\n * 2. The opencode session's own `directory` (resolved per-call from the\n * `x-session-affinity` id via the SDK). Authoritative for\n * `opencode serve` / web-UI mode, where one long-lived server process\n * handles many projects and `process.cwd()` is the server's launch\n * dir — not the session's project. Equals `process.cwd()` in the TUI,\n * so it does not regress that path.\n * 3. Live `process.cwd()` when it's a real directory. Lazy resolution\n * that lets opencode's project-aware behavior (chdir on workspace\n * switch, project-per-shell on terminal launch) flow through.\n * 4. Captured project directory from plugin init. Rescues macOS GUI\n * launches where `process.cwd()` is `/`.\n * 5. Final fallback to `process.cwd()` (returns `/` in the pathological\n * case where neither override nor capture is available).\n */\nexport function resolveSpawnCwd(configured: string | undefined): string {\n return resolveSpawnCwdFrom(\n configured,\n process.cwd(),\n opencodeProjectDirectory,\n )\n}\n\nexport function resolveSpawnCwdFrom(\n configured: string | undefined,\n live: string,\n captured: string | undefined,\n sessionDir?: string,\n): string {\n if (configured) return configured\n if (isUsableDirectory(sessionDir)) return sessionDir\n if (isUsableDirectory(live)) return live\n return captured ?? live\n}\n\n/**\n * Resolve the spawn cwd for a specific opencode session. Looks up the\n * session's `directory` via the SDK (keyed by the `x-session-affinity`\n * id opencode sets on LLM calls) and feeds it into `resolveSpawnCwdFrom`\n * as tier 2. Falls back cleanly to the non-session resolution when the\n * id is absent (\"default\"), no SDK client is captured, or the lookup\n * fails — so the TUI / direct-AI-SDK / test paths are unaffected.\n */\nexport async function resolveSpawnCwdForSession(\n configured: string | undefined,\n sessionID: string | undefined,\n): Promise<string> {\n // An explicit pin wins unconditionally — skip the lookup entirely.\n if (configured) return configured\n const sessionDir = sessionID\n ? await fetchSessionDirectory(sessionID)\n : undefined\n return resolveSpawnCwdFrom(\n configured,\n process.cwd(),\n opencodeProjectDirectory,\n sessionDir,\n )\n}\n\n/**\n * Fetch an opencode session's project directory via `GET /session/{id}`.\n * Returns `undefined` on any failure (no client, \"default\"/empty id,\n * rejected call, malformed response, unusable directory) so callers fall\n * back to `process.cwd()`-based resolution. No caching: a session's\n * directory can change (workspace switch) and the call is a cheap\n * localhost round-trip relative to spawning Claude.\n */\nexport async function fetchSessionDirectory(\n sessionID: string,\n): Promise<string | undefined> {\n if (!sessionID || sessionID === \"default\") return undefined\n const client = opencodeClient\n if (!client?.session?.get) return undefined\n try {\n const res = await client.session.get({ path: { id: sessionID } })\n const data = (res as { data?: unknown }).data\n if (!data || typeof data !== \"object\") return undefined\n const dir = (data as { directory?: unknown }).directory\n return isUsableDirectory(dir) ? dir : undefined\n } catch (err) {\n log.warn(\"failed to fetch opencode session directory\", {\n sessionID,\n error: err instanceof Error ? err.message : String(err),\n })\n return undefined\n }\n}\n\n/**\n * Snapshot opencode's current MCP runtime status so the bridge can overlay\n * UI-toggled state on top of disk config. Returns `undefined` on any\n * failure (no client captured, status call rejected, malformed response)\n * so the bridge falls back to disk-only.\n */\nexport async function getRuntimeMcpStatus(): Promise<\n RuntimeMcpStatus | undefined\n> {\n const client = opencodeClient\n if (!client?.mcp?.status) return undefined\n try {\n const res = await client.mcp.status()\n const data = (res as { data?: unknown }).data\n if (!data || typeof data !== \"object\") return undefined\n const out: RuntimeMcpStatus = {}\n for (const [name, entry] of Object.entries(data as Record<string, unknown>)) {\n if (entry && typeof entry === \"object\") {\n const status = (entry as { status?: unknown }).status\n if (typeof status === \"string\") out[name] = status\n }\n }\n return out\n } catch (err) {\n log.warn(\"failed to fetch opencode MCP runtime status\", {\n error: err instanceof Error ? err.message : String(err),\n })\n return undefined\n }\n}\n\nexport interface OpencodeToolListItem {\n id: string\n description: string\n parameters: Record<string, unknown>\n}\n\n/**\n * Fetch opencode's full tool catalog (built-ins + MCP-bridged) with JSON\n * Schema parameters via `client.tool.list()`. The provider/model query\n * narrows the schema variants opencode returns; in practice MCP-origin\n * tool schemas are model-agnostic, so any registered (provider, model)\n * works as the query target. Returns `undefined` on any failure so callers\n * can fall back to direct-bridge behavior.\n */\nexport async function fetchOpencodeToolList(\n provider: string,\n model: string,\n directory?: string,\n): Promise<OpencodeToolListItem[] | undefined> {\n const client = opencodeClient\n if (!client?.tool?.list) return undefined\n try {\n const res = await client.tool.list({\n query: { provider, model, ...(directory ? { directory } : {}) },\n })\n const data = (res as { data?: unknown }).data\n if (!Array.isArray(data)) return undefined\n const out: OpencodeToolListItem[] = []\n for (const entry of data as unknown[]) {\n if (!entry || typeof entry !== \"object\") continue\n const e = entry as Record<string, unknown>\n const id = typeof e.id === \"string\" ? e.id : null\n const description =\n typeof e.description === \"string\" ? e.description : \"\"\n const parameters =\n e.parameters && typeof e.parameters === \"object\"\n ? (e.parameters as Record<string, unknown>)\n : {}\n if (!id) continue\n out.push({ id, description, parameters })\n }\n return out\n } catch (err) {\n log.warn(\"failed to fetch opencode tool list\", {\n provider,\n model,\n error: err instanceof Error ? err.message : String(err),\n })\n return undefined\n }\n}\n","import { EventEmitter } from \"node:events\"\nimport { unlink } from \"node:fs/promises\"\nimport { ClaudeSession } from \"./claude-session-bun.js\"\nimport { cliEffortLevel, type ActiveProcess } from \"./session-manager.js\"\nimport type { ReasoningEffort } from \"./types.js\"\nimport { log } from \"./logger.js\"\n\nexport interface InteractiveSpawnOptions {\n cwd: string\n /** Claude CLI executable or account wrapper path. */\n cliPath?: string\n /** Claude config root used for JSONL transcripts. */\n configDir?: string\n model?: string\n /** Request Claude Code's fast mode (Opus 4.8 / Opus 5 only). Folded into\n * the single `--settings` payload alongside `permissions`. */\n fastMode?: boolean\n /** Bridged Claude `--mcp-config` file paths (from effectiveMcpConfig). */\n mcpConfigPaths?: string[]\n /** permissions.allow rules (e.g. mcp__server__*, Bash, Edit). */\n permissionsAllow?: string[]\n /** Optional permission mode. `bypassPermissions` is ignored for interactive\n * sessions because Claude Code shows a safety confirmation screen first. */\n permissionMode?: string\n /** Temp file for --append-system-prompt-file (parity with the headless\n * spawn; unlinked when the session is killed). */\n systemPromptFile?: string\n /** \"\" = skip CLAUDE.md + ambient settings (fast e2e); null/undefined =\n * normal settings (default — parity with the headless transport). */\n settingSources?: string | null\n /** Strip ANTHROPIC_API_KEY/ANTHROPIC_AUTH_TOKEN from the spawn env so the\n * CLI uses subscription auth instead of pay-as-you-go API billing. */\n ignoreAnthropicApiKey?: boolean\n /** Reasoning effort, exported as CLAUDE_CODE_EFFORT_LEVEL for the session. */\n effort?: ReasoningEffort\n}\n\n/**\n * doStream writes stream-json user envelopes to stdin\n * (`{\"type\":\"user\",\"message\":{content:[...]}}`). The interactive TUI expects\n * plain typed text, so decode the envelope: extract the text blocks and drop\n * anything that can't be typed into a terminal (an image block would paste\n * megabytes of base64 into the chat). Tool results are rendered as labeled\n * text so the model still sees the outcome. Non-envelope input (already plain\n * text) passes through verbatim.\n */\nexport function decodeUserEnvelope(chunk: string): string {\n let parsed: any\n try {\n parsed = JSON.parse(chunk)\n } catch {\n return chunk\n }\n if (!parsed || parsed.type !== \"user\" || !parsed.message) return chunk\n const content = parsed.message.content\n if (typeof content === \"string\") return content\n if (!Array.isArray(content)) return chunk\n\n const parts: string[] = []\n let dropped = 0\n for (const block of content) {\n if (block?.type === \"text\" && typeof block.text === \"string\") {\n parts.push(block.text)\n } else if (block?.type === \"tool_result\") {\n const v = block.content\n const text =\n typeof v === \"string\"\n ? v\n : Array.isArray(v)\n ? v\n .map((i: any) => (i?.type === \"text\" ? i.text : \"\"))\n .filter(Boolean)\n .join(\"\\n\")\n : \"\"\n parts.push(\n `[Tool result${block.tool_use_id ? ` ${block.tool_use_id}` : \"\"}]\\n${text}`,\n )\n } else {\n dropped++\n }\n }\n if (dropped > 0) {\n log.warn(\"interactive transport dropped non-text content blocks\", {\n dropped,\n })\n }\n return parts.join(\"\\n\\n\")\n}\n\n/**\n * Adapt a ClaudeSession (interactive Bun ConPTY transport) to the ActiveProcess\n * contract the doStream line handler depends on. The shim's `proc.stdin.write`\n * injects a turn into the live interactive `claude` and re-emits each new JSONL\n * transcript record on `lineEmitter` as a 'line' event, plus a synthetic\n * `{type:'result'}` line on a terminal stop_reason so the existing finish branch\n * (usage + providerMetadata + controller.close) fires unchanged.\n *\n * No node-pty, no node sidecar: runs in-process under opencode's Bun (which\n * bundles a Bun version with native ConPTY). Interactive = subscription billing.\n */\nexport function spawnInteractiveProcess(\n opts: InteractiveSpawnOptions,\n): ActiveProcess {\n const extraArgs: string[] = []\n if (opts.mcpConfigPaths && opts.mcpConfigPaths.length > 0) {\n extraArgs.push(\n \"--mcp-config\",\n ...opts.mcpConfigPaths,\n \"--strict-mcp-config\",\n )\n }\n // One `--settings` for the whole flag-settings layer. The CLI accepts the\n // flag once, so pushing a second occurrence would silently drop the first\n // rather than merge it.\n const flagSettings: Record<string, unknown> = {}\n if (opts.permissionsAllow && opts.permissionsAllow.length > 0) {\n flagSettings.permissions = { allow: opts.permissionsAllow }\n }\n if (opts.fastMode) {\n flagSettings.fastMode = true\n }\n if (Object.keys(flagSettings).length > 0) {\n extraArgs.push(\"--settings\", JSON.stringify(flagSettings))\n }\n if (opts.permissionMode === \"bypassPermissions\") {\n log.warn(\n \"interactive permissionMode bypassPermissions ignored: Claude Code prompts for confirmation in the TUI\",\n )\n } else if (opts.permissionMode) {\n extraArgs.push(\"--permission-mode\", opts.permissionMode)\n }\n if (opts.systemPromptFile) {\n extraArgs.push(\"--append-system-prompt-file\", opts.systemPromptFile)\n }\n\n const session = new ClaudeSession({\n cwd: opts.cwd,\n cliPath: opts.cliPath,\n configDir: opts.configDir,\n model: opts.model,\n // Default null = normal CLAUDE.md + settings load, matching what the\n // headless spawn does. \"\" (skip everything) is for fast e2e runs only.\n settingSources:\n opts.settingSources === undefined ? null : opts.settingSources,\n extraArgs,\n ignoreAnthropicApiKey: opts.ignoreAnthropicApiKey,\n effort: opts.effort ? cliEffortLevel(opts.effort) : undefined,\n })\n log.info(\"prepared interactive claude session\", {\n cwd: opts.cwd,\n cliPath: opts.cliPath ?? \"claude\",\n configDir: session.configDir,\n model: opts.model,\n effort: opts.effort,\n sessionId: session.sessionId,\n jsonlPath: session.jsonlPath,\n })\n\n const lineEmitter = new EventEmitter()\n const errorHandlers = new Set<(err: Error) => void>()\n let startPromise: Promise<void> | null = null\n\n const ensureStarted = (): Promise<void> => {\n if (!startPromise) startPromise = session.start()\n return startPromise\n }\n\n const emitResult = (\n subtype: string,\n isError: boolean,\n result?: string,\n usage?: unknown,\n ): void => {\n lineEmitter.emit(\n \"line\",\n JSON.stringify({\n type: \"result\",\n subtype,\n is_error: isError,\n result,\n session_id: session.sessionId,\n usage: usage ?? {},\n total_cost_usd: null,\n duration_ms: 0,\n }),\n )\n }\n\n const runTurn = (userMsg: string): void => {\n void (async () => {\n try {\n await ensureStarted()\n const { stopReason, usage } = await session.tailTurn(userMsg, (raw) => {\n lineEmitter.emit(\"line\", raw)\n })\n // Synthesize the `result` line the headless transport would have\n // emitted, so doStream's existing finish branch runs verbatim. A turn\n // with no terminal stop_reason (timeout / session exit mid-turn) is\n // reported HONESTLY as an error result — not a clean end_turn — so\n // truncation is visible to the user and to auto-continue.\n const timedOut = !stopReason\n emitResult(\n timedOut ? \"error_during_execution\" : stopReason,\n timedOut,\n timedOut\n ? \"Interactive transport: the turn ended without a terminal stop_reason (turn timeout or claude exit). Output above may be incomplete.\"\n : undefined,\n usage,\n )\n } catch (err) {\n const e = err instanceof Error ? err : new Error(String(err))\n log.error(\"interactive turn failed\", { error: e.message })\n emitResult(\n \"error_during_execution\",\n true,\n `Interactive transport failed: ${e.message}`,\n )\n if (errorHandlers.size > 0) {\n for (const h of errorHandlers) h(e)\n } else {\n lineEmitter.emit(\"close\")\n }\n }\n })()\n }\n\n // Minimal ChildProcess-shaped shim: only the members doStream/session-manager\n // actually touch (stdin.write, on/off 'error', kill).\n const proc: any = {\n stdin: {\n write(chunk: string): boolean {\n const raw =\n typeof chunk === \"string\" && chunk.endsWith(\"\\n\")\n ? chunk.slice(0, -1)\n : chunk\n // doStream writes stream-json envelopes; the TUI needs plain text.\n runTurn(decodeUserEnvelope(raw))\n return true\n },\n end(): void {},\n },\n stdout: null,\n stderr: null,\n pid: -1,\n killed: false,\n on(event: string, fn: (err: Error) => void): unknown {\n if (event === \"error\") errorHandlers.add(fn)\n return proc\n },\n once(): unknown {\n return proc\n },\n off(event: string, fn: (err: Error) => void): unknown {\n if (event === \"error\") errorHandlers.delete(fn)\n return proc\n },\n kill(): boolean {\n try {\n session.dispose()\n } catch {}\n if (opts.systemPromptFile) {\n void unlink(opts.systemPromptFile).catch(() => {})\n }\n proc.killed = true\n return true\n },\n }\n\n return {\n proc: proc as unknown as ActiveProcess[\"proc\"],\n lineEmitter,\n proxyServer: null,\n mcpHash: undefined,\n systemPromptFile: opts.systemPromptFile,\n }\n}\n","import * as os from \"node:os\"\nimport * as fs from \"node:fs\"\nimport * as path from \"node:path\"\nimport { execFileSync } from \"node:child_process\"\nimport { randomUUID } from \"node:crypto\"\n\n/**\n * Persistent interactive Claude Code session driven over Bun's NATIVE PTY\n * (Bun.spawn `terminal` option = openpty on POSIX, ConPTY on Windows). This is\n * the in-process Bun port of claude-tui-bridge/src/claudeSession.ts: same\n * design, node-pty swapped for Bun's own ConPTY so it runs inside opencode's\n * Bun runtime with NO node sidecar and NO node-pty dependency.\n *\n * - ONE long-lived interactive `claude` process per session (multi-turn),\n * - turns injected by writing into the terminal (bracketed paste + Enter),\n * - replies captured by tailing the session JSONL transcript\n * (<CLAUDE_CONFIG_DIR>/projects/<encoded-cwd>/<session-id>.jsonl) and\n * parsing the assistant records; completion detected by a terminal\n * `stop_reason`.\n *\n * Driving the INTERACTIVE TUI (real TTY) keeps model calls on the subscription\n * billing path (not `claude -p` / Agent SDK, which meter after 2026-06-15).\n */\n\nfunction resolveClaude(cmd = \"claude\"): string {\n if (path.isAbsolute(cmd) && fs.existsSync(cmd)) return cmd\n const viaBun = Bun.which(cmd)\n if (viaBun) return viaBun\n const isWin = os.platform() === \"win32\"\n try {\n const out = execFileSync(isWin ? \"where\" : \"which\", [cmd], {\n encoding: \"utf8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n })\n const first = out\n .split(/\\r?\\n/)\n .map((l) => l.trim())\n .filter(Boolean)\n .find((p) => fs.existsSync(p))\n if (first) return first\n } catch {}\n throw new Error(`Could not resolve command on PATH: ${cmd}`)\n}\n\n/** Claude encodes the absolute cwd into the transcript dir name by replacing\n * EVERY non-alphanumeric char with `-` (no collapsing of runs). Verified on\n * Windows against ~/.claude/projects, e.g.:\n * C:\\code\\my-app -> C--code-my-app\n * C:\\dev\\My Project -> C--dev-My-Project (the space also becomes `-`). */\nexport function encodeCwd(cwd: string): string {\n return path.resolve(cwd).replace(/[^a-zA-Z0-9]/g, \"-\")\n}\n\nexport interface TurnResult {\n text: string\n stopReason: string | null\n usage: any | null\n cacheReadTokens: number\n cacheCreationTokens: number\n ephemeral1hTokens: number\n ephemeral5mTokens: number\n inputTokens: number\n outputTokens: number\n elapsedMs: number\n}\n\nexport interface ClaudeSessionOptions {\n cwd?: string\n /** Claude CLI executable or account wrapper path. */\n cliPath?: string\n /** Claude config root used for JSONL transcripts (defaults to ~/.claude). */\n configDir?: string\n model?: string\n /** '' bypasses CLAUDE.md + user/project/local settings load (fast tests).\n * null/undefined omits the flag entirely (normal settings). */\n settingSources?: string | null\n extraArgs?: string[]\n /** Strip ANTHROPIC_API_KEY/ANTHROPIC_AUTH_TOKEN from the spawn env so the\n * CLI uses subscription auth instead of pay-as-you-go API billing. */\n ignoreAnthropicApiKey?: boolean\n /** CLI effort level (low | medium | high | xhigh | max), exported as\n * CLAUDE_CODE_EFFORT_LEVEL so it overrides the account's settings.json. */\n effort?: string\n cols?: number\n rows?: number\n bootMinMs?: number\n bootQuietMs?: number\n bootMaxMs?: number\n pollMs?: number\n turnTimeoutMs?: number\n /** false = plain write(prompt)+Enter; true = wrap in bracketed-paste so\n * multi-line prompts don't submit early. Default true. */\n bracketedPaste?: boolean\n /** Submitting a turn: a large/multi-line bracketed paste collapses into a\n * \"[Pasted text]\" placeholder, and an Enter sent while claude is still\n * ingesting the paste is silently DROPPED — so a single fixed-delay Enter is\n * unreliable and the turn can hang until turnTimeoutMs. Instead: wait\n * submitMinMs, send Enter, then confirm the turn was accepted (a new\n * transcript record appears) within submitConfirmMs; if not, resend Enter,\n * up to submitMaxRetries times. */\n submitMinMs?: number\n submitConfirmMs?: number\n submitMaxRetries?: number\n /** Abort the call (during boot or an in-flight turn): kills the process and\n * rejects with an \"aborted\" error. */\n signal?: AbortSignal\n debug?: boolean\n}\n\nconst TERMINAL_STOP = new Set([\"end_turn\", \"stop_sequence\", \"max_tokens\"])\nconst delay = (ms: number) => new Promise<void>((r) => setTimeout(r, ms))\n\nfunction resolveConfigDir(configDir: string | undefined): string {\n const value = configDir ?? process.env.CLAUDE_CONFIG_DIR\n if (!value) return path.join(os.homedir(), \".claude\")\n if (value === \"~\") return os.homedir()\n if (value.startsWith(\"~/\") || value.startsWith(\"~\\\\\")) {\n return path.join(os.homedir(), value.slice(2))\n }\n return path.resolve(value)\n}\n\nexport class ClaudeSession {\n readonly sessionId: string\n readonly cwd: string\n readonly configDir: string\n readonly jsonlPath: string\n raw = \"\"\n\n private proc: BunSubprocess | null = null\n private cursor = 0 // index into transcript split('\\n')\n private lastDataAt = 0\n private exited = false\n private exitCode: number | null = null\n private aborted = false\n private readonly signal?: AbortSignal\n private readonly o: Required<\n Omit<\n ClaudeSessionOptions,\n | \"cliPath\"\n | \"configDir\"\n | \"model\"\n | \"settingSources\"\n | \"extraArgs\"\n | \"signal\"\n | \"ignoreAnthropicApiKey\"\n | \"effort\"\n >\n > &\n Pick<\n ClaudeSessionOptions,\n | \"cliPath\"\n | \"configDir\"\n | \"model\"\n | \"settingSources\"\n | \"extraArgs\"\n | \"ignoreAnthropicApiKey\"\n | \"effort\"\n >\n\n constructor(opts: ClaudeSessionOptions = {}) {\n this.cwd = path.resolve(opts.cwd ?? process.cwd())\n this.configDir = resolveConfigDir(opts.configDir)\n this.signal = opts.signal\n this.sessionId = randomUUID()\n this.jsonlPath = path.join(\n this.configDir,\n \"projects\",\n encodeCwd(this.cwd),\n `${this.sessionId}.jsonl`,\n )\n this.o = {\n cwd: this.cwd,\n cliPath: opts.cliPath,\n configDir: this.configDir,\n model: opts.model,\n settingSources: opts.settingSources,\n extraArgs: opts.extraArgs ?? [],\n ignoreAnthropicApiKey: opts.ignoreAnthropicApiKey,\n effort: opts.effort,\n cols: opts.cols ?? 200,\n rows: opts.rows ?? 50,\n bootMinMs: opts.bootMinMs ?? 3000,\n bootQuietMs: opts.bootQuietMs ?? 1500,\n bootMaxMs: opts.bootMaxMs ?? 25000,\n pollMs: opts.pollMs ?? 250,\n // Agentic turns (tool loops) routinely run for many minutes; a short\n // cap would surface as a mid-task error result. 30 min mirrors the\n // proxy-tool ceiling rather than a chat-reply expectation.\n turnTimeoutMs: opts.turnTimeoutMs ?? 1_800_000,\n bracketedPaste: opts.bracketedPaste ?? true,\n submitMinMs: opts.submitMinMs ?? 200,\n submitConfirmMs: opts.submitConfirmMs ?? 1500,\n submitMaxRetries: opts.submitMaxRetries ?? 8,\n debug: opts.debug ?? false,\n }\n }\n\n async start(): Promise<void> {\n if (this.signal?.aborted) throw new Error(\"aborted before start\")\n this.signal?.addEventListener(\n \"abort\",\n () => {\n this.aborted = true\n this.dispose()\n },\n { once: true },\n )\n const claude = resolveClaude(this.o.cliPath ?? \"claude\")\n const args: string[] = [\"--session-id\", this.sessionId]\n if (this.o.model) args.push(\"--model\", this.o.model)\n if (this.o.settingSources !== null && this.o.settingSources !== undefined) {\n args.push(\"--setting-sources\", this.o.settingSources)\n }\n if (this.o.extraArgs && this.o.extraArgs.length) args.push(...this.o.extraArgs)\n\n if (this.o.debug)\n process.stderr.write(`[session] spawn: ${claude} ${args.join(\" \")}\\n`)\n\n this.lastDataAt = Date.now()\n this.proc = Bun.spawn([claude, ...args], {\n cwd: this.cwd,\n env: {\n ...process.env,\n CLAUDE_CONFIG_DIR: this.o.configDir,\n TERM: \"xterm-256color\",\n ...(this.o.ignoreAnthropicApiKey\n ? { ANTHROPIC_API_KEY: undefined, ANTHROPIC_AUTH_TOKEN: undefined }\n : {}),\n ...(this.o.effort ? { CLAUDE_CODE_EFFORT_LEVEL: this.o.effort } : {}),\n },\n terminal: {\n cols: this.o.cols,\n rows: this.o.rows,\n data: (_term, d) => {\n this.lastDataAt = Date.now()\n const chunk = Buffer.from(d).toString(\"utf8\")\n this.raw += chunk\n if (this.o.debug) process.stdout.write(chunk)\n },\n },\n })\n this.proc.exited\n .then((code) => {\n this.exitCode = typeof code === \"number\" ? code : null\n this.exited = true\n this.proc = null\n })\n .catch(() => {\n this.exited = true\n this.proc = null\n })\n\n await this.waitForBoot()\n this.cursor = this.lineCount()\n }\n\n /** Wait until the TUI has been quiet for bootQuietMs (Ink ready), bounded by\n * bootMinMs..bootMaxMs. */\n private async waitForBoot(): Promise<void> {\n const start = Date.now()\n while (Date.now() - start < this.o.bootMaxMs) {\n await delay(150)\n if (this.aborted) throw new Error(\"aborted during boot\")\n if (this.exited) {\n throw new Error(this.failureMessage(\"claude exited during boot\", true))\n }\n const elapsed = Date.now() - start\n const sinceData = Date.now() - this.lastDataAt\n if (elapsed >= this.o.bootMinMs && sinceData >= this.o.bootQuietMs) return\n }\n }\n\n /** Submit the freshly-injected prompt and confirm the turn was actually\n * accepted. A large bracketed paste collapses into a \"[Pasted text]\"\n * placeholder; an Enter sent while claude is still ingesting the paste is\n * silently dropped, so a single fixed-delay Enter races the paste and can\n * leave the prompt sitting unsubmitted (→ hang until turnTimeoutMs). Send\n * Enter, then poll for transcript growth past the cursor (the turn's records\n * are written on acceptance); resend Enter until accepted or the retry\n * budget is spent. Polling growth (not a blind delay) also stops us from\n * sending a stray Enter once the turn is in flight. */\n private async submitTurn(): Promise<void> {\n await delay(this.o.submitMinMs)\n for (let attempt = 0; attempt < this.o.submitMaxRetries; attempt++) {\n if (this.aborted || this.exited || !this.proc) return\n this.proc.terminal.write(\"\\r\")\n const until = Date.now() + this.o.submitConfirmMs\n while (Date.now() < until) {\n await delay(80)\n if (this.aborted || this.exited) return\n if (this.lineCount() > this.cursor) return // turn accepted\n }\n }\n }\n\n private readRawLines(): string[] {\n try {\n return fs.readFileSync(this.jsonlPath, \"utf8\").split(\"\\n\")\n } catch {\n return []\n }\n }\n\n /** Count of complete lines (split('\\n') minus the trailing/partial element). */\n private lineCount(): number {\n const lines = this.readRawLines()\n return lines.length > 0 ? lines.length - 1 : 0\n }\n\n private rawTail(max = 600): string {\n const clean = this.raw\n // Strip ANSI escape/control sequences before including terminal output in diagnostics.\n .replace(/\\x1B(?:[@-Z\\\\-_]|\\[[0-?]*[ -/]*[@-~])/g, \"\")\n .replace(/\\s+/g, \" \")\n .trim()\n return clean.length > max ? clean.slice(-max) : clean\n }\n\n private failureMessage(reason: string, includeRaw = false): string {\n const parts = [\n `${reason} (sessionId=${this.sessionId}, jsonlPath=${this.jsonlPath}, exitCode=${this.exitCode ?? \"unknown\"})`,\n ]\n if (includeRaw) {\n const tail = this.rawTail()\n if (tail) parts.push(`terminalTail=${JSON.stringify(tail)}`)\n }\n return parts.join(\"; \")\n }\n\n /**\n * Inject a turn into the live session and return the assistant reply once a\n * terminal stop_reason is observed in the transcript.\n */\n async ask(prompt: string, perTurnTimeoutMs?: number): Promise<TurnResult> {\n if (this.aborted) throw new Error(\"aborted\")\n if (!this.proc || this.exited)\n throw new Error(\"session not started or already exited\")\n const timeout = perTurnTimeoutMs ?? this.o.turnTimeoutMs\n const t0 = Date.now()\n\n // Inject. Bracketed paste keeps multi-line prompts from submitting early;\n // submitTurn() then presses Enter and confirms the turn was accepted,\n // resending Enter if the (collapsed) paste swallowed the first one.\n if (this.o.bracketedPaste) {\n this.proc.terminal.write(\"\\x1b[200~\" + prompt + \"\\x1b[201~\")\n } else {\n this.proc.terminal.write(prompt)\n }\n await this.submitTurn()\n\n const collected: string[] = []\n let lastUsage: any = null\n let stopReason: string | null = null\n const deadline = Date.now() + timeout\n\n while (Date.now() < deadline) {\n await delay(this.o.pollMs)\n if (this.aborted) throw new Error(\"aborted mid-turn\")\n const lines = this.readRawLines()\n const lastComplete = lines.length - 1 // exclusive bound; trailing/partial line skipped\n if (lastComplete <= this.cursor) {\n // Drain the transcript before reacting to exit: a final assistant record\n // can be flushed in the same tick the process exits.\n if (this.exited) throw new Error(this.failureMessage(\"claude exited mid-turn\", true))\n continue\n }\n\n for (let i = this.cursor; i < lastComplete; i++) {\n const s = lines[i]\n if (!s || !s.trim()) continue\n let rec: any\n try {\n rec = JSON.parse(s)\n } catch {\n continue\n }\n if (rec.type === \"assistant\" && rec.message) {\n for (const b of rec.message.content ?? []) {\n if (b?.type === \"text\" && typeof b.text === \"string\")\n collected.push(b.text)\n }\n if (rec.message.usage) lastUsage = rec.message.usage\n if (\n rec.message.stop_reason &&\n TERMINAL_STOP.has(rec.message.stop_reason)\n ) {\n stopReason = rec.message.stop_reason\n }\n }\n }\n this.cursor = lastComplete\n if (stopReason) break\n }\n\n if (!stopReason) {\n throw new Error(\n this.failureMessage(\n `turn timed out after ${timeout}ms (no terminal assistant record; collected ${collected.length} text block(s))`,\n ),\n )\n }\n\n const u = lastUsage ?? {}\n return {\n text: collected.join(\"\\n\").trim(),\n stopReason,\n usage: lastUsage,\n cacheReadTokens: u.cache_read_input_tokens ?? 0,\n cacheCreationTokens: u.cache_creation_input_tokens ?? 0,\n ephemeral1hTokens: u.cache_creation?.ephemeral_1h_input_tokens ?? 0,\n ephemeral5mTokens: u.cache_creation?.ephemeral_5m_input_tokens ?? 0,\n inputTokens: u.input_tokens ?? 0,\n outputTokens: u.output_tokens ?? 0,\n elapsedMs: Date.now() - t0,\n }\n }\n\n /**\n * Like ask(), but instead of collecting the reply text it re-emits each NEW\n * raw JSONL transcript line via onLine (verbatim) until a terminal\n * stop_reason. Returns the terminal stop_reason + the last assistant usage.\n * Used by the opencode plugin transport shim, which feeds these raw lines\n * into the existing stream-json line handler unchanged.\n */\n async tailTurn(\n prompt: string,\n onLine: (rawLine: string) => void,\n perTurnTimeoutMs?: number\n ): Promise<{ stopReason: string | null; usage: any | null }> {\n if (this.aborted) throw new Error(\"aborted\")\n if (!this.proc || this.exited)\n throw new Error(\"session not started or already exited\")\n const timeout = perTurnTimeoutMs ?? this.o.turnTimeoutMs\n\n if (this.o.bracketedPaste) {\n this.proc.terminal.write(\"\\x1b[200~\" + prompt + \"\\x1b[201~\")\n } else {\n this.proc.terminal.write(prompt)\n }\n await this.submitTurn()\n\n let lastUsage: any = null\n let totalOutput = 0\n let stopReason: string | null = null\n const deadline = Date.now() + timeout\n\n while (Date.now() < deadline) {\n await delay(this.o.pollMs)\n if (this.aborted) throw new Error(\"aborted mid-turn\")\n const lines = this.readRawLines()\n const lastComplete = lines.length - 1\n if (lastComplete <= this.cursor) {\n // Drain the transcript before reacting to exit: the terminal assistant\n // record can land in the same tick the process exits.\n if (this.exited) {\n throw new Error(this.failureMessage(\"claude exited mid-turn\", true))\n }\n continue\n }\n for (let i = this.cursor; i < lastComplete; i++) {\n const s = lines[i]\n if (!s || !s.trim()) continue\n onLine(s)\n let rec: any\n try {\n rec = JSON.parse(s)\n } catch {\n continue\n }\n if (rec.type === \"assistant\" && rec.message) {\n if (rec.message.usage) {\n lastUsage = rec.message.usage\n totalOutput += rec.message.usage.output_tokens ?? 0\n }\n if (\n rec.message.stop_reason &&\n TERMINAL_STOP.has(rec.message.stop_reason)\n ) {\n stopReason = rec.message.stop_reason\n }\n }\n }\n this.cursor = lastComplete\n if (stopReason) break\n }\n\n // Context (input/cache) = the LAST record's full conversation state; output\n // = SUM across all assistant records this turn (each generation), else\n // multi-record tool turns undercount output. toUsage() prefers\n // iterations[last], so patch that entry's output too.\n let usage: any = lastUsage\n if (lastUsage) {\n usage = { ...lastUsage, output_tokens: totalOutput }\n if (Array.isArray(lastUsage.iterations) && lastUsage.iterations.length > 0) {\n const iters = lastUsage.iterations.map((it: any) => ({ ...it }))\n iters[iters.length - 1] = {\n ...iters[iters.length - 1],\n output_tokens: totalOutput,\n }\n usage.iterations = iters\n }\n }\n if (!stopReason) {\n throw new Error(\n this.failureMessage(\n `turn timed out after ${timeout}ms (no terminal assistant record)`,\n ),\n )\n }\n\n return { stopReason, usage }\n }\n\n dispose(): void {\n if (this.proc) {\n try {\n this.proc.terminal.write(\"\\x03\")\n } catch {}\n try {\n this.proc.kill()\n } catch {}\n try {\n this.proc.terminal.close()\n } catch {}\n }\n this.proc = null\n }\n}\n\n/** One-shot convenience (drop-in for `claude -p`): start, ask, dispose. */\nexport async function askOnce(\n prompt: string,\n opts: ClaudeSessionOptions = {},\n): Promise<TurnResult> {\n const s = new ClaudeSession(opts)\n await s.start()\n try {\n return await s.ask(prompt)\n } finally {\n s.dispose()\n }\n}\n","import { chmod, lstat, mkdir, readlink, symlink, writeFile } from \"node:fs/promises\"\nimport path from \"node:path\"\nimport { log } from \"./logger.js\"\n\nexport const BASE_PROVIDER_ID = \"claude-code\"\nexport const DEFAULT_ACCOUNT = \"default\"\n\nconst SHARED_CAPABILITY_ITEMS = [\n \"CLAUDE.md\",\n \"settings.json\",\n \"skills\",\n \"agents\",\n \"commands\",\n \"plugins\",\n]\n\nexport function normalizeAccountName(account: string): string {\n return account\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n}\n\nexport function resolveAccounts(value: unknown): string[] | null {\n if (!Array.isArray(value)) return null\n\n const accounts = value\n .map((account) => normalizeAccountName(String(account)))\n .filter(Boolean)\n\n return Array.from(new Set([DEFAULT_ACCOUNT, ...accounts]))\n}\n\nexport function accountProviderId(account: string): string {\n return `${BASE_PROVIDER_ID}-${normalizeAccountName(account)}`\n}\n\nexport function accountDisplayName(account: string): string {\n return `Claude Code (${titleizeAccount(account)})`\n}\n\nexport function accountModelSuffix(account: string): string | undefined {\n const normalized = normalizeAccountName(account)\n return normalized === DEFAULT_ACCOUNT ? undefined : normalized\n}\n\nexport function accountConfigDir(account: string): string | undefined {\n const normalized = normalizeAccountName(account)\n\n if (!normalized || normalized === DEFAULT_ACCOUNT) return undefined\n\n return `~/.claude-${normalized}`\n}\n\nexport function expandHome(value: string): string {\n const home = process.env.HOME ?? process.env.USERPROFILE\n\n if (value === \"~\") return home ?? value\n\n if (value.startsWith(\"~/\") || value.startsWith(\"~\\\\\")) {\n return home ? path.join(home, value.slice(2)) : value\n }\n\n return value\n}\n\nexport async function ensureAccountRuntime(\n account: string,\n baseCliPath: string,\n): Promise<{ cliPath: string; configDir?: string }> {\n const configDir = accountConfigDir(account)\n\n if (!configDir) return { cliPath: baseCliPath }\n\n const expandedConfigDir = expandHome(configDir)\n await mkdir(expandedConfigDir, { recursive: true })\n\n try {\n await ensureSharedCapabilities(expandedConfigDir)\n } catch (err) {\n log.warn(\"failed to symlink shared capabilities; continuing anyway\", {\n account,\n configDir: expandedConfigDir,\n error: String(err),\n })\n }\n\n const cliPath = await writeAccountWrapper(\n normalizeAccountName(account),\n baseCliPath,\n expandedConfigDir,\n )\n\n return { cliPath, configDir: expandedConfigDir }\n}\n\nasync function ensureSharedCapabilities(targetRoot: string): Promise<void> {\n const sourceRoot = expandHome(\"~/.claude\")\n\n for (const item of SHARED_CAPABILITY_ITEMS) {\n await ensureSharedCapabilityItem(sourceRoot, targetRoot, item)\n }\n}\n\nasync function ensureSharedCapabilityItem(\n sourceRoot: string,\n targetRoot: string,\n item: string,\n): Promise<void> {\n const source = path.join(sourceRoot, item)\n const target = path.join(targetRoot, item)\n\n let sourceStat\n try {\n sourceStat = await lstat(source)\n } catch {\n return\n }\n\n try {\n const targetStat = await lstat(target)\n\n if (targetStat.isSymbolicLink()) {\n const current = await readlink(target)\n const resolvedCurrent = path.resolve(path.dirname(target), current)\n const resolvedSource = path.resolve(source)\n\n if (resolvedCurrent === resolvedSource) return\n }\n\n log.warn(\"shared Claude capability already exists; leaving untouched\", {\n item,\n target,\n source,\n })\n\n return\n } catch {\n // Missing target is expected.\n }\n\n const type = sourceStat.isDirectory()\n ? process.platform === \"win32\"\n ? \"junction\"\n : \"dir\"\n : \"file\"\n\n await symlink(source, target, type)\n}\n\nasync function writeAccountWrapper(\n account: string,\n baseCliPath: string,\n configDir: string,\n): Promise<string> {\n const cacheRoot = path.join(\n process.env.XDG_CACHE_HOME ?? expandHome(\"~/.cache\"),\n \"opencode-claude-code-plugin\",\n )\n const wrapperPath = path.join(cacheRoot, `claude-${account}`)\n const suffix = `@${account}`\n\n await mkdir(cacheRoot, { recursive: true })\n\n const script = `#!/usr/bin/env bash\nset -euo pipefail\n\nargs=()\nwhile [[ $# -gt 0 ]]; do\n if [[ \"$1\" == \"--model\" && $# -ge 2 ]]; then\n model=\"$2\"\n if [[ \"$model\" == *${shellDoubleQuote(suffix)} ]]; then\n model=\"\\${model%${shellDoubleQuote(suffix)}}\"\n fi\n args+=(\"$1\" \"$model\")\n shift 2\n else\n args+=(\"$1\")\n shift\n fi\ndone\n\nexport CLAUDE_CONFIG_DIR=${shellSingleQuote(configDir)}\nexec ${shellSingleQuote(baseCliPath)} \"\\${args[@]}\"\n`\n\n await writeFile(wrapperPath, script, \"utf8\")\n await chmod(wrapperPath, 0o755)\n\n return wrapperPath\n}\n\nfunction shellSingleQuote(value: string): string {\n return `'${value.replace(/'/g, `'\"'\"'`)}'`\n}\n\nfunction shellDoubleQuote(value: string): string {\n return value.replace(/[$`\"\\\\]/g, \"\\\\$&\")\n}\n\nfunction titleizeAccount(account: string): string {\n return normalizeAccountName(account)\n .split(\"-\")\n .filter(Boolean)\n .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n .join(\" \")\n}\n","// Removes a stale unscoped `opencode-claude-code-plugin` install left in\n// opencode's plugin cache by older configs. The unscoped name is a different\n// artifact than this scoped plugin and shadows it when both coexist.\n// Disable with OPENCODE_CLAUDE_CODE_PLUGIN_NO_CLEANUP=1.\n\nimport {\n existsSync,\n readFileSync,\n realpathSync,\n rmSync,\n writeFileSync,\n} from \"node:fs\"\nimport { homedir } from \"node:os\"\nimport { join, resolve } from \"node:path\"\nimport { fileURLToPath } from \"node:url\"\nimport { log } from \"./logger.js\"\n\nconst STALE_PACKAGE_NAME = \"opencode-claude-code-plugin\"\nconst SUSPECT_DESCRIPTION_TOKEN = \"Claude Code\"\n\nlet alreadyRan = false\n\nfunction candidateCacheRoots(): string[] {\n const xdg = process.env.XDG_CACHE_HOME\n return [\n xdg ? join(xdg, \"opencode\") : null,\n join(homedir(), \".cache\", \"opencode\"),\n join(homedir(), \"Library\", \"Caches\", \"opencode\"),\n ].filter((p): p is string => Boolean(p))\n}\n\nfunction userOpencodeJsonPath(): string {\n const xdgConfig = process.env.XDG_CONFIG_HOME ?? join(homedir(), \".config\")\n return join(xdgConfig, \"opencode\", \"opencode.json\")\n}\n\nfunction userIntendsToUseUnscoped(): boolean {\n const cfg = userOpencodeJsonPath()\n if (!existsSync(cfg)) return false\n try {\n const json = JSON.parse(readFileSync(cfg, \"utf8\"))\n const plugins: unknown = json.plugin\n if (!Array.isArray(plugins)) return false\n return plugins.some(\n (entry) =>\n typeof entry === \"string\" &&\n /^opencode-claude-code-plugin(@[^/]+)?$/.test(entry),\n )\n } catch {\n return false\n }\n}\n\nfunction ourLoadedDir(): string | null {\n try {\n const filePath = fileURLToPath(import.meta.url)\n return realpathSync(resolve(filePath, \"..\", \"..\"))\n } catch {\n return null\n }\n}\n\nexport function cleanupStaleUnscopedInstall(): void {\n if (alreadyRan) return\n alreadyRan = true\n\n if (process.env.OPENCODE_CLAUDE_CODE_PLUGIN_NO_CLEANUP === \"1\") return\n if (userIntendsToUseUnscoped()) return\n\n const ourDir = ourLoadedDir()\n\n for (const cacheRoot of candidateCacheRoots()) {\n try {\n cleanupOne(cacheRoot, ourDir)\n } catch (err) {\n log.warn(\"cleanup-stale: error processing cache root\", {\n cacheRoot,\n error: String(err),\n })\n }\n }\n}\n\nfunction cleanupOne(cacheRoot: string, ourDir: string | null): void {\n if (!existsSync(cacheRoot)) return\n\n const stalePath = join(cacheRoot, \"node_modules\", STALE_PACKAGE_NAME)\n if (!existsSync(stalePath)) return\n\n // Don't self-delete if we are the unscoped install.\n let realStalePath = stalePath\n try {\n realStalePath = realpathSync(stalePath)\n } catch {\n // ignore\n }\n if (ourDir && realStalePath === ourDir) return\n\n // Verify identity before removing.\n const pkgJsonPath = join(stalePath, \"package.json\")\n if (!existsSync(pkgJsonPath)) return\n let pkg: { name?: string; description?: string } = {}\n try {\n pkg = JSON.parse(readFileSync(pkgJsonPath, \"utf8\"))\n } catch {\n return\n }\n if (pkg.name !== STALE_PACKAGE_NAME) return\n if (!pkg.description?.includes(SUSPECT_DESCRIPTION_TOKEN)) return\n\n log.info(\"cleanup-stale: removing unscoped install\", { stalePath })\n try {\n rmSync(stalePath, { recursive: true, force: true })\n } catch (err) {\n log.warn(\"cleanup-stale: rmSync failed\", {\n stalePath,\n error: String(err),\n })\n return\n }\n\n // Drop the dep from the cache root's package.json so opencode's installer\n // doesn't reinstate it on its next pass. Lockfile is left alone; bun\n // reconciles against package.json on the next install.\n const cachePkgJson = join(cacheRoot, \"package.json\")\n if (!existsSync(cachePkgJson)) return\n try {\n const cfg = JSON.parse(readFileSync(cachePkgJson, \"utf8\"))\n if (cfg?.dependencies?.[STALE_PACKAGE_NAME]) {\n delete cfg.dependencies[STALE_PACKAGE_NAME]\n writeFileSync(cachePkgJson, JSON.stringify(cfg, null, 2) + \"\\n\")\n log.info(\"cleanup-stale: pruned dep from cache package.json\")\n }\n } catch (err) {\n log.warn(\"cleanup-stale: cache package.json update failed\", {\n error: String(err),\n })\n }\n}\n","import { execFile } from \"node:child_process\"\nimport * as fs from \"node:fs\"\nimport * as path from \"node:path\"\nimport { promisify } from \"node:util\"\nimport { fileURLToPath } from \"node:url\"\n\nimport { detectCliVersion } from \"./cli-version.js\"\nimport { log } from \"./logger.js\"\nimport { mergeOpencodeMcp } from \"./mcp-bridge.js\"\nimport { getOpencodeProjectDirectory, isUsableDirectory } from \"./runtime-status.js\"\n\n/**\n * One compact status block logged once per process, right after providers are\n * registered. Every field here answers a question that previously cost a live\n * debugging session: which plugin build is loaded, whether the Claude CLI is\n * even reachable, which cwd the spawn will use and why, what is proxied, and\n * how many MCP servers the bridge sees. Keep it cheap and never let it throw:\n * diagnostics must not be able to break provider registration.\n */\nexport interface StartupDiagnostics {\n plugin: string\n opencode: string\n claudeCli: { path: string; version: string }\n cwd: { resolved: string; source: CwdSource }\n providers: string[]\n accounts: string[]\n proxyTools: string[]\n mcpServers: string[]\n interactiveTransport: boolean\n /** ExitPlanMode approval routed through opencode's `question` tool. */\n planModeQuestion: boolean\n anthropicApiKeyInEnv: boolean\n}\n\n/** Which branch of `resolveSpawnCwd` a Claude CLI spawn would take right now. */\nexport type CwdSource = \"configured\" | \"process\" | \"captured\" | \"unresolved\"\n\nexport interface DiagnosticsProviderEntry {\n name?: string\n options?: Record<string, unknown>\n}\n\nlet cachedPluginVersion: string | undefined\n\n/** Version of this plugin, read from the package manifest one level up. */\nexport function pluginVersion(): string {\n if (cachedPluginVersion) return cachedPluginVersion\n try {\n const here = path.dirname(fileURLToPath(import.meta.url))\n const raw = fs.readFileSync(path.join(here, \"..\", \"package.json\"), \"utf8\")\n const version = (JSON.parse(raw) as { version?: unknown }).version\n cachedPluginVersion = typeof version === \"string\" ? version : \"unknown\"\n } catch {\n cachedPluginVersion = \"unknown\"\n }\n return cachedPluginVersion\n}\n\n/**\n * Best-effort opencode version from the plugin input. Re-verified on opencode\n * 1.18.5: nothing on the plugin surface carries it. `PluginInput` has no\n * version field, the SDK client's `app` namespace exposes only `log`/`agents`,\n * and the server has no `/version` route. So this probes a couple of plausible\n * shapes for future opencode releases and otherwise returns undefined, leaving\n * the binary probe (`detectOpencodeVersion`) as the fallback. Do not replace it\n * with a `client.app.get()` call — that method does not exist.\n */\nexport function pickOpencodeVersion(input: unknown): string | undefined {\n if (!input || typeof input !== \"object\") return undefined\n const app = (input as { app?: unknown }).app\n if (app && typeof app === \"object\") {\n const version = (app as { version?: unknown }).version\n if (typeof version === \"string\" && version.length > 0) return version\n }\n const direct = (input as { version?: unknown }).version\n if (typeof direct === \"string\" && direct.length > 0) return direct\n return undefined\n}\n\nconst execFileAsync = promisify(execFile)\n\nlet opencodeVersionProbe: Promise<string | undefined> | undefined\n\n/**\n * The plugin runs *inside* opencode's process, so `process.execPath` is the\n * opencode binary itself — asking it for `--version` is the only reliable way\n * to name the version, since the plugin API exposes it nowhere (see\n * `pickOpencodeVersion`). Guarded on the basename: when opencode is run from\n * source (`bun run packages/opencode/src/index.ts`) execPath is the Bun binary,\n * and reporting Bun's version as opencode's would be worse than \"unknown\".\n * Cached, 5s timeout, never throws.\n */\nexport function detectOpencodeVersion(\n execPath: string = process.execPath,\n): Promise<string | undefined> {\n if (opencodeVersionProbe) return opencodeVersionProbe\n opencodeVersionProbe = (async (): Promise<string | undefined> => {\n if (!path.basename(execPath).toLowerCase().includes(\"opencode\")) {\n log.debug(\"skipping opencode version probe: execPath is not opencode\", { execPath })\n return undefined\n }\n try {\n const { stdout } = await execFileAsync(execPath, [\"--version\"], { timeout: 5000 })\n const match = /\\d+\\.\\d+\\.\\d+\\S*/.exec(stdout.trim())\n return match ? match[0] : undefined\n } catch (err) {\n log.debug(\"opencode version probe failed\", {\n execPath,\n error: err instanceof Error ? err.message : String(err),\n })\n return undefined\n }\n })()\n return opencodeVersionProbe\n}\n\n/** Test seam: drop the cached probe so a fresh execPath is honored. */\nexport function resetOpencodeVersionProbe(): void {\n opencodeVersionProbe = undefined\n}\n\n/**\n * Mirror of `resolveSpawnCwd`'s priority order, but reporting *which* branch\n * won. `configured` means `options.cwd` pinned it, `process` is the normal\n * lazy path, `captured` means `process.cwd()` was unusable (macOS GUI launch\n * at `/`) and the captured project directory rescued it — that one is the\n * fingerprint of issue #4.\n */\nexport function describeSpawnCwd(\n configured: unknown,\n live: string = process.cwd(),\n captured: string | undefined = getOpencodeProjectDirectory(),\n): { resolved: string; source: CwdSource } {\n if (typeof configured === \"string\" && configured.length > 0) {\n return { resolved: configured, source: \"configured\" }\n }\n if (isUsableDirectory(live)) return { resolved: live, source: \"process\" }\n if (isUsableDirectory(captured)) return { resolved: captured, source: \"captured\" }\n return { resolved: live, source: \"unresolved\" }\n}\n\nfunction stringList(value: unknown): string[] {\n if (!Array.isArray(value)) return []\n return value.filter((entry): entry is string => typeof entry === \"string\")\n}\n\nfunction firstOption(\n providers: Record<string, DiagnosticsProviderEntry>,\n key: string,\n): unknown {\n for (const entry of Object.values(providers)) {\n const value = entry?.options?.[key]\n if (value !== undefined) return value\n }\n return undefined\n}\n\nexport function collectStartupDiagnostics(\n providers: Record<string, DiagnosticsProviderEntry>,\n opencodeVersion?: string,\n): Omit<StartupDiagnostics, \"claudeCli\"> & { claudeCliPath: string } {\n const accounts: string[] = []\n for (const entry of Object.values(providers)) {\n const account = entry?.options?.account\n if (typeof account === \"string\" && account.length > 0) accounts.push(account)\n }\n\n const cwd = describeSpawnCwd(firstOption(providers, \"cwd\"))\n\n let mcpServers: string[] = []\n try {\n // Disk-only view: opencode's runtime MCP status isn't settled at plugin\n // init (servers are still connecting), so the per-turn overlay is not\n // applied here. This is what the bridge would ship on a cold start.\n mcpServers = mergeOpencodeMcp(cwd.resolved).enabledServerNames\n } catch (err) {\n log.debug(\"startup diagnostics could not read MCP config\", {\n error: err instanceof Error ? err.message : String(err),\n })\n }\n\n return {\n plugin: pluginVersion(),\n opencode: opencodeVersion ?? process.env.OPENCODE_VERSION ?? \"unknown\",\n claudeCliPath: String(firstOption(providers, \"cliPath\") ?? \"claude\"),\n cwd,\n providers: Object.keys(providers),\n accounts,\n proxyTools: stringList(firstOption(providers, \"proxyTools\")),\n mcpServers,\n interactiveTransport:\n firstOption(providers, \"interactive\") === true ||\n process.env.CLAUDE_CODE_INTERACTIVE_TRANSPORT === \"1\",\n planModeQuestion: firstOption(providers, \"planModeQuestion\") === true,\n anthropicApiKeyInEnv: Boolean(\n process.env.ANTHROPIC_API_KEY || process.env.ANTHROPIC_AUTH_TOKEN,\n ),\n }\n}\n\nlet logged = false\n\n/**\n * Emit the startup block once per process. Fire-and-forget: the Claude CLI\n * version probe is async (`claude --version`, 5s timeout, cached), and a slow\n * or missing binary must never delay provider registration.\n */\nexport function logStartupDiagnostics(\n providers: Record<string, DiagnosticsProviderEntry>,\n opencodeVersion?: string,\n): void {\n if (logged) return\n logged = true\n void (async () => {\n try {\n // Probe the binary only when the plugin input and env gave us nothing,\n // so a future opencode that reports its version costs no spawn.\n const version =\n opencodeVersion ?? process.env.OPENCODE_VERSION ?? (await detectOpencodeVersion())\n const { claudeCliPath, ...rest } = collectStartupDiagnostics(providers, version)\n const cli = await detectCliVersion(claudeCliPath)\n const diagnostics: StartupDiagnostics = {\n ...rest,\n claudeCli: { path: claudeCliPath, version: cli?.raw ?? \"not detected\" },\n }\n log.notice(\"claude-code plugin ready\", { ...diagnostics })\n } catch (err) {\n log.debug(\"startup diagnostics failed\", {\n error: err instanceof Error ? err.message : String(err),\n })\n }\n })()\n}\n\n/** For tests. */\nexport function _resetStartupDiagnostics(): void {\n logged = false\n}\n","import type { LanguageModelV3 } from \"@ai-sdk/provider\"\nimport { ClaudeCodeLanguageModel } from \"./claude-code-language-model.js\"\nimport { defaultModels, toConfigModel } from \"./models.js\"\nimport type {\n OpenCodeConfig,\n OpenCodeModel,\n OpenCodePlugin,\n OpenCodeProvider,\n} from \"./opencode-types.js\"\nimport type { ClaudeCodeProviderSettings } from \"./types.js\"\nimport {\n BASE_PROVIDER_ID,\n accountDisplayName,\n accountModelSuffix,\n accountProviderId,\n ensureAccountRuntime,\n resolveAccounts,\n} from \"./accounts.js\"\nimport {\n type AgentRecord,\n agentDirectories,\n getDefaultSubagentModel,\n readAgentMarkdownRecords,\n setAgentRegistry,\n setDefaultSubagentModel,\n} from \"./agent-models.js\"\nimport { cleanupStaleUnscopedInstall } from \"./cleanup-stale.js\"\nimport { configureLogger, log } from \"./logger.js\"\nimport { handleBtwCommand, type BtwSdkClient } from \"./btw-command.js\"\nimport { getOpencodeClient } from \"./runtime-status.js\"\nimport {\n getOpencodeProjectDirectory,\n isUsableDirectory,\n setOpencodeClient,\n setOpencodeProjectDirectory,\n} from \"./runtime-status.js\"\nimport {\n logStartupDiagnostics,\n pickOpencodeVersion,\n type DiagnosticsProviderEntry,\n} from \"./startup-diagnostics.js\"\n\nexport interface ClaudeCodeProvider {\n specificationVersion: \"v3\"\n (modelId: string): LanguageModelV3\n languageModel(modelId: string): LanguageModelV3\n}\n\n// Picks the best directory from opencode's plugin context (`directory` /\n// `worktree`). Result is handed to runtime-status so it's available as a\n// *fallback* at spawn time only when `process.cwd()` is unusable (macOS\n// GUI launches at `/`). Never baked into provider config — see #4.\nfunction pickOpencodeDirectory(input: unknown): string | undefined {\n if (!input || typeof input !== \"object\") return undefined\n const ctx = input as { directory?: unknown; worktree?: unknown }\n if (isUsableDirectory(ctx.directory)) return ctx.directory\n if (isUsableDirectory(ctx.worktree)) return ctx.worktree\n return undefined\n}\n\nlet warnedAnthropicApiKey = false\n\n// `Question` is deliberately absent: enabling it disables Claude Code's\n// built-in AskUserQuestion (via --disallowedTools) and replaces the\n// stop-and-wait deny/markdown path with an in-turn blocking form. That is a\n// behavior trade against the issue-#8 guarantee, so it stays opt-in until it\n// has the same live mileage Task had before v0.10.0 flipped it on. Users opt\n// in by listing it in `proxyTools`; see README \"Question proxy tool\".\nexport const DEFAULT_PROXY_TOOL_NAMES = [\n \"Bash\",\n \"Edit\",\n \"Write\",\n \"WebFetch\",\n \"Task\",\n]\n\n/**\n * Registers `/btw` unless the user defined their own. Returns whether the\n * registration is ours: the command hook only intercepts `btw` in that case,\n * so a user-defined command keeps opencode's normal behaviour end to end.\n */\nexport function registerSideQuestionCommand(config: OpenCodeConfig): boolean {\n config.command ??= {}\n if (config.command.btw) return false\n config.command.btw = {\n template: \"/btw $ARGUMENTS\",\n description: \"Ask a side question in the live Claude Code session without changing its context\",\n }\n return true\n}\n\nlet ownsSideQuestionCommand = false\n\n// One-time heads-up: an API key in the environment makes Claude Code bill\n// pay-as-you-go (Console) instead of the logged-in Pro/Max subscription, which\n// silently bypasses the Agent SDK plan credit. Surfaced once per process.\nfunction warnIfAnthropicApiKey(ignore: boolean | undefined): void {\n if (warnedAnthropicApiKey) return\n if (!process.env.ANTHROPIC_API_KEY && !process.env.ANTHROPIC_AUTH_TOKEN) return\n warnedAnthropicApiKey = true\n if (ignore) {\n log.warn(\n \"ANTHROPIC_API_KEY/ANTHROPIC_AUTH_TOKEN detected; stripping it from claude spawns (ignoreAnthropicApiKey) so requests use your subscription auth, not pay-as-you-go API billing.\",\n )\n } else {\n log.warn(\n \"ANTHROPIC_API_KEY/ANTHROPIC_AUTH_TOKEN detected; claude may bill as pay-as-you-go API usage instead of your subscription / Agent SDK credit. Set provider option `ignoreAnthropicApiKey: true` to force subscription auth.\",\n )\n }\n}\n\nexport function createClaudeCode(\n settings: ClaudeCodeProviderSettings = {},\n): ClaudeCodeProvider {\n if (settings.logging) {\n configureLogger({\n file: settings.logging.file ?? false,\n dir: settings.logging.dir ?? null,\n mode: settings.logging.mode ?? \"silent\",\n level: settings.logging.level ?? \"info\",\n })\n }\n warnIfAnthropicApiKey(settings.ignoreAnthropicApiKey)\n const cliPath =\n settings.cliPath ?? process.env.CLAUDE_CLI_PATH ?? \"claude\"\n const providerName = settings.providerID ?? settings.name ?? \"claude-code\"\n const proxyTools = settings.proxyTools ?? [...DEFAULT_PROXY_TOOL_NAMES]\n\n const createModel = (modelId: string): LanguageModelV3 => {\n return new ClaudeCodeLanguageModel(modelId, {\n provider: providerName,\n cliPath,\n cwd: settings.cwd,\n account: settings.account,\n configDir: settings.configDir,\n providerID: settings.providerID,\n skipPermissions: settings.skipPermissions ?? true,\n permissionMode: settings.permissionMode,\n mcpConfig: settings.mcpConfig,\n strictMcpConfig: settings.strictMcpConfig,\n bridgeOpencodeMcp: settings.bridgeOpencodeMcp ?? true,\n controlRequestBehavior: settings.controlRequestBehavior ?? \"allow\",\n controlRequestToolBehaviors: settings.controlRequestToolBehaviors,\n controlRequestDenyMessage: settings.controlRequestDenyMessage,\n proxyTools,\n extraDisallowedTools: settings.extraDisallowedTools,\n proxyToolTimeoutMs: settings.proxyToolTimeoutMs,\n planModeQuestion: settings.planModeQuestion ?? false,\n webSearch: settings.webSearch,\n hotReloadMcp: settings.hotReloadMcp ?? true,\n proxyOpencodeMcpTools: settings.proxyOpencodeMcpTools ?? true,\n multiStepContinuation: settings.multiStepContinuation ?? true,\n autoContinueIncompleteTurns:\n settings.autoContinueIncompleteTurns ?? \"smart\",\n compactionModel: settings.compactionModel,\n ignoreAnthropicApiKey: settings.ignoreAnthropicApiKey,\n idleProcessTimeoutMs: settings.idleProcessTimeoutMs,\n bridgeOpencodeSkills: settings.bridgeOpencodeSkills === true,\n interactive: settings.interactive,\n interactiveBypass: settings.interactiveBypass,\n interactiveAllowTools: settings.interactiveAllowTools,\n interactiveSystemPrompt: settings.interactiveSystemPrompt,\n })\n }\n\n const provider = function (modelId: string) {\n return createModel(modelId)\n } as ClaudeCodeProvider\n\n provider.specificationVersion = \"v3\"\n provider.languageModel = createModel\n\n return provider\n}\n\n// ---------------------------------------------------------------------------\n// OpenCode plugin interface\n// ---------------------------------------------------------------------------\n\nconst PROVIDER_ID = BASE_PROVIDER_ID\nconst PACKAGE_NPM = \"@khalilgharbaoui/opencode-claude-code-plugin\"\n\nfunction pluginEntrypoint(): string {\n return import.meta.url.startsWith(\"file:\") ? import.meta.url : PACKAGE_NPM\n}\n\nfunction cleanProviderOptions(\n options: Record<string, unknown> = {},\n): Record<string, unknown> {\n const result = { ...options }\n delete result.accounts\n // Consumed by the config hook (agent registry), not by the language model.\n delete result.defaultSubagentModel\n return result\n}\n\nfunction defaultModelsForProvider(\n providerModels: OpenCodeProvider[\"models\"],\n providerID = PROVIDER_ID,\n modelSuffix?: string,\n) {\n const models = Object.fromEntries(\n Object.entries(defaultModels).map(([id, model]) => {\n const modelId = modelSuffix ? `${id}@${modelSuffix}` : id\n const existing = providerModels[id] ?? providerModels[modelId]\n return [\n modelId,\n {\n ...model,\n id: modelId,\n providerID,\n api: {\n ...model.api,\n id: modelId,\n npm: existing?.api?.npm ?? model.api.npm,\n url: existing?.api?.url ?? model.api.url,\n },\n },\n ]\n }),\n )\n\n for (const [id, model] of Object.entries(providerModels)) {\n if (!(id in models)) {\n models[id] = {\n ...model,\n providerID,\n }\n }\n }\n\n return models\n}\n\n/**\n * Build models in OpenCode's config schema format (flat properties like\n * `temperature`, `reasoning`, `cost.cache_read`, `modalities`, etc.)\n * so the config-path provider loader parses them correctly.\n */\nexport function configModelsForProvider(\n providerModels: OpenCodeProvider[\"models\"],\n providerID: string,\n modelSuffix?: string,\n): Record<string, Record<string, unknown>> {\n const models: Record<string, Record<string, unknown>> = {}\n\n for (const [id, model] of Object.entries(defaultModels)) {\n const modelId = modelSuffix ? `${id}@${modelSuffix}` : id\n const existing = providerModels[id] ?? providerModels[modelId]\n const existingVariants =\n existing && typeof (existing as { variants?: unknown }).variants === \"object\"\n ? ((existing as { variants?: Record<string, Record<string, unknown>> }).variants ?? {})\n : {}\n const full: OpenCodeModel = {\n ...model,\n id: modelId,\n providerID,\n api: {\n ...model.api,\n id: modelId,\n npm: existing?.api?.npm ?? model.api.npm,\n url: existing?.api?.url ?? model.api.url,\n },\n variants: {\n ...(model.variants ?? {}),\n ...existingVariants,\n },\n }\n models[modelId] = toConfigModel(full)\n }\n\n for (const [id, model] of Object.entries(providerModels)) {\n if (!(id in models)) {\n models[id] = toConfigModel({ ...model, providerID } as OpenCodeModel)\n }\n }\n\n return models\n}\n\nasync function providerConfig(\n existing: {\n name?: string\n npm?: string\n options?: Record<string, unknown>\n models?: Record<string, unknown>\n } | undefined,\n providerID = PROVIDER_ID,\n optionDefaults: Record<string, unknown> = {},\n displayName?: string,\n) {\n const mergedOptions: Record<string, unknown> = {\n cliPath: \"claude\",\n proxyTools: [...DEFAULT_PROXY_TOOL_NAMES],\n ...optionDefaults,\n ...cleanProviderOptions(existing?.options),\n providerID,\n }\n\n const cliPath = String(mergedOptions.cliPath ?? \"claude\")\n const account =\n typeof mergedOptions.account === \"string\" ? mergedOptions.account : undefined\n const runtime = account\n ? await ensureAccountRuntime(account, cliPath)\n : { cliPath }\n\n return {\n name: displayName ?? existing?.name,\n npm: existing?.npm ?? pluginEntrypoint(),\n options: {\n ...mergedOptions,\n ...runtime,\n },\n // models is intentionally omitted: both callers overwrite it with\n // configModelsForProvider(), which emits the flat config schema\n // opencode's config-path loader parses (and merges user variants).\n }\n}\n\n/**\n * Narrow opencode's full provider map down to the ones this plugin owns\n * (`claude-code` plus every `claude-code-<account>` expansion) so startup\n * diagnostics never report another provider's options.\n */\nexport function claudeCodeProviders(\n providers: Record<string, DiagnosticsProviderEntry> | undefined,\n): Record<string, DiagnosticsProviderEntry> {\n const out: Record<string, DiagnosticsProviderEntry> = {}\n for (const [id, entry] of Object.entries(providers ?? {})) {\n if (id === PROVIDER_ID || id.startsWith(`${PROVIDER_ID}-`)) out[id] = entry\n }\n return out\n}\n\nasync function expandAccountProviders(config: {\n provider?: Record<\n string,\n {\n name?: string\n npm?: string\n options?: Record<string, unknown>\n models?: Record<string, unknown>\n }\n >\n}): Promise<boolean> {\n const seed = config.provider?.[PROVIDER_ID]\n const accounts = resolveAccounts(seed?.options?.accounts)\n\n if (!accounts) return false\n\n config.provider ??= {}\n\n const seedOptions = cleanProviderOptions(seed?.options)\n let expandedCount = 0\n\n for (const account of accounts) {\n const providerID = accountProviderId(account)\n try {\n const existing = config.provider[providerID]\n const modelSuffix = accountModelSuffix(account)\n\n config.provider[providerID] = {\n ...existing,\n ...(await providerConfig(\n existing,\n providerID,\n {\n ...seedOptions,\n account,\n },\n accountDisplayName(account),\n )),\n models: configModelsForProvider(\n (existing?.models ?? seed?.models ?? {}) as OpenCodeProvider[\"models\"],\n providerID,\n modelSuffix,\n ),\n }\n expandedCount++\n } catch (err) {\n log.error(\"failed to expand account provider\", {\n account,\n providerID,\n error: String(err),\n })\n }\n }\n\n if (expandedCount > 0) {\n delete config.provider[PROVIDER_ID]\n }\n\n return expandedCount > 0\n}\n\n/**\n * Record what every known agent asked for, so `resolveAgentModel` and\n * `resolveAgentEffort` can answer at spawn time without the language model\n * needing to see opencode's config.\n *\n * Runs BEFORE `expandAccountProviders`, which deletes the seed provider entry\n * once it has expanded it: `defaultSubagentModel` has to be read while it is\n * still there.\n *\n * Purely observational. It defines no agents and changes no agent's config;\n * an agent this plugin never heard of is simply absent from the registry,\n * which is what keeps opencode's built-ins out of the override path.\n */\nasync function buildAgentRegistry(config: OpenCodeConfig): Promise<void> {\n const options = config.provider?.[PROVIDER_ID]?.options\n const configured = options?.defaultSubagentModel\n setDefaultSubagentModel(\n typeof configured === \"string\" ? configured : undefined,\n )\n\n // Markdown agents may or may not reach a plugin's config hook (undocumented\n // either way), so they are read from disk and then overlaid with whatever\n // config does carry, which is authoritative when both describe one agent.\n const records: Record<string, AgentRecord> = await readAgentMarkdownRecords(\n agentDirectories(\n process.env.HOME ?? process.env.USERPROFILE,\n getOpencodeProjectDirectory(),\n ),\n )\n\n for (const [name, agent] of Object.entries(config.agent ?? {})) {\n const bag = (agent.options ?? {}) as Record<string, unknown>\n const pick = (key: string): string | undefined => {\n const value = agent[key] ?? bag[key]\n return typeof value === \"string\" ? value : undefined\n }\n\n records[name] = {\n mode: pick(\"mode\") ?? records[name]?.mode,\n model: pick(\"model\") ?? records[name]?.model,\n forceModel: pick(\"forceModel\") ?? records[name]?.forceModel,\n reasoningEffort:\n pick(\"reasoningEffort\") ?? records[name]?.reasoningEffort,\n }\n }\n\n setAgentRegistry(records)\n log.debug(\"agent registry built\", {\n agents: Object.keys(records).length,\n defaultSubagentModel: getDefaultSubagentModel(),\n })\n}\n\nconst server: OpenCodePlugin = async (input) => {\n cleanupStaleUnscopedInstall()\n\n const opencodeVersion = pickOpencodeVersion(input)\n\n // Capture the SDK client so the language model can query opencode's\n // in-memory MCP state per-turn for the runtime overlay. `input` is\n // `unknown` here (kept loose since opencode adds fields over time);\n // narrow defensively.\n if (input && typeof input === \"object\" && \"client\" in input) {\n setOpencodeClient((input as { client?: unknown }).client)\n }\n\n // Capture opencode's project-aware directory as a *fallback* used at\n // Claude CLI spawn time only when `process.cwd()` is unusable. Rescues\n // macOS GUI launches at `/` without freezing the value into provider\n // config, so opencode workspace switches mid-session still take effect.\n // See `resolveSpawnCwd` in runtime-status.ts and issue #4.\n setOpencodeProjectDirectory(pickOpencodeDirectory(input))\n\n return {\n config: async (config) => {\n if (registerSideQuestionCommand(config)) ownsSideQuestionCommand = true\n config.provider ??= {}\n\n await buildAgentRegistry(config)\n\n const expanded = await expandAccountProviders(config)\n if (expanded) {\n logStartupDiagnostics(\n claudeCodeProviders(config.provider),\n opencodeVersion,\n )\n return\n }\n\n const existing = config.provider[PROVIDER_ID]\n config.provider[PROVIDER_ID] = {\n ...existing,\n ...(await providerConfig(existing)),\n models: configModelsForProvider(\n (existing?.models ?? {}) as OpenCodeProvider[\"models\"],\n PROVIDER_ID,\n ),\n }\n logStartupDiagnostics(\n claudeCodeProviders(config.provider),\n opencodeVersion,\n )\n },\n // No `event` hook: MCP config drift is detected at turn start by the\n // hot-reload check in `claude-code-language-model.ts`, which respawns\n // claude safely between turns. Eviction on `global.disposed` would kill\n // an in-flight stream and abort the user's current turn.\n provider: {\n id: PROVIDER_ID,\n models: async (provider) => defaultModelsForProvider(provider.models),\n },\n // Inject opencode's agent name into providerOptions so the language\n // model can distinguish /compact (and title) calls from normal turns.\n // Without this, every no-tools call looks like a title request and\n // gets short-circuited to a synthetic stub.\n // /btw is asked from here, the moment the command is typed, busy or not.\n // The message itself still goes through: opencode queues it behind the\n // running turn and the aside branch in the language model then answers it\n // from the early answer, so the exchange is kept in this conversation.\n \"command.execute.before\": async (input) => {\n if (input.command !== \"btw\" || !ownsSideQuestionCommand) return\n await handleBtwCommand(getOpencodeClient() as BtwSdkClient | null, input)\n },\n \"chat.params\": async (input, output) => {\n const providerID = input.model?.providerID ?? input.provider?.info?.id\n // The hook fires for every provider opencode is configured with, not\n // just ours — keep this at debug to avoid log spam on non-claude-code\n // calls.\n log.debug(\"chat.params hook fired\", {\n agent: input.agent,\n providerID,\n sessionID: input.sessionID,\n })\n if (typeof providerID !== \"string\") return\n if (providerID !== PROVIDER_ID && !providerID.startsWith(`${PROVIDER_ID}-`)) return\n\n // Inject sessionID BEFORE the agent guard so session isolation works\n // even when input.agent is absent (older opencode, provider-switch\n // edge paths). resolveSessionAffinity reads this as a fallback when\n // the x-session-affinity header is missing.\n if (typeof input.sessionID === \"string\" && input.sessionID.length > 0) {\n output.options ??= {}\n ;(output.options as Record<string, unknown>).opencodeSessionID = input.sessionID\n }\n\n if (!input.agent) return\n // opencode wraps the entire `output.options` bag under the providerID\n // via ProviderTransform.providerOptions(model, options) → { [providerID]: options }\n // before handing it to the language model as `providerOptions`. So we\n // write fields at the TOP LEVEL of output.options, not nested under\n // providerID — otherwise the model sees providerOptions[id][id].opencodeAgent.\n output.options ??= {}\n ;(output.options as Record<string, unknown>).opencodeAgent = input.agent\n log.debug(\"chat.params tagged providerOptions\", {\n agent: input.agent,\n sessionID: input.sessionID,\n providerID,\n })\n },\n }\n}\n\nexport default {\n id: \"@khalilgharbaoui/opencode-claude-code-plugin\",\n server,\n}\n\n// ---------------------------------------------------------------------------\n// Re-exports\n// ---------------------------------------------------------------------------\n\nexport { ClaudeCodeLanguageModel } from \"./claude-code-language-model.js\"\nexport { bridgeOpencodeMcp } from \"./mcp-bridge.js\"\nexport {\n type AgentRecord,\n getAgentRegistry,\n getDefaultSubagentModel,\n resolveAgentModel,\n} from \"./agent-models.js\"\nexport { defaultModels } from \"./models.js\"\nexport type {\n ClaudeCodeConfig,\n ClaudeCodeProviderSettings,\n ClaudeStreamMessage,\n} from \"./types.js\"\nexport type { OpenCodeHooks, OpenCodeModel, OpenCodePlugin } from \"./opencode-types.js\"\n"],"mappings":";AASA,SAAS,kBAAkB;;;ACT3B,SAAS,gBAAgB,WAAW,YAAY,gBAAgB;AAChE,SAAS,eAAe;AACxB,SAAS,SAAS,YAAY;AAY9B,IAAM,aAAuC;AAAA,EAC3C,OAAO;AAAA,EACP,MAAM;AAAA,EACN,QAAQ;AAAA,EACR,MAAM;AAAA,EACN,OAAO;AACT;AAEA,IAAM,gBAAgB,IAAI,OAAO;AACjC,IAAM,cAAc,KAAK,QAAQ,GAAG,UAAU,SAAS,sBAAsB;AAE7E,IAAM,iBAA+B;AAAA,EACnC,MAAM;AAAA,EACN,KAAK;AAAA,EACL,MAAM;AAAA,EACN,OAAO;AACT;AAEA,SAAS,aAAa,GAA4C;AAChE,MAAI,KAAK,KAAM,QAAO;AACtB,QAAM,IAAI,EAAE,YAAY,EAAE,KAAK;AAC/B,MAAI,MAAM,GAAI,QAAO;AACrB,MAAI,MAAM,OAAO,MAAM,WAAW,MAAM,QAAQ,MAAM,MAAO,QAAO;AACpE,SAAO;AACT;AAEA,SAAS,cAAc,GAA6C;AAClE,MAAI,KAAK,KAAM,QAAO;AACtB,QAAM,IAAI,EAAE,YAAY,EAAE,KAAK;AAC/B,MAAI,MAAM,GAAI,QAAO;AACrB,MAAI,MAAM,WAAW,MAAM,UAAU,MAAM,YAAY,MAAM,UAAU,MA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ACpC,UAAI,eAAeD,gBAAe,CAAC,WAAW,WAAW,GAAGA,YAAW,GAAG,EAAG;AAM7E,UAAI,OAAOC,OAAM,cAAc,YAAYA,OAAM,UAAU,SAAS,GAAG;AACrE,eAAO,YAAY,CAAC;AACnB,QAAC,OAAO,QAAoC,oBAAoBA,OAAM;AAAA,MACzE;AAEA,UAAI,CAACA,OAAM,MAAO;AAMlB,aAAO,YAAY,CAAC;AACnB,MAAC,OAAO,QAAoC,gBAAgBA,OAAM;AACnE,UAAI,MAAM,sCAAsC;AAAA,QAC9C,OAAOA,OAAM;AAAA,QACb,WAAWA,OAAM;AAAA,QACjB;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF;AACF;AAEA,IAAO,gBAAQ;AAAA,EACb,IAAI;AAAA,EACJ;AACF;","names":["randomUUID","EventEmitter","EventEmitter","fs","path","server","resolve","reject","EventEmitter","sessionKey","sessionKey","sessionKey","randomUUID","randomUUID","resolve","resolve","randomUUID","sessionKey","EventEmitter","resolve","path","path","crypto","fs","os","path","fs","path","os","crypto","fileExists","dirExists","EventEmitter","unlink","os","fs","path","randomUUID","EventEmitter","unlink","readFileSync","writeFileSync","unlink","homedir","tmpdir","randomUUID","dirname","join","content","path","spawn","createInterface","unlink","resolve","stream","completeResult","planId","path","path","existsSync","readFileSync","rmSync","writeFileSync","homedir","join","resolve","join","homedir","existsSync","readFileSync","resolve","rmSync","writeFileSync","execFile","fs","path","promisify","fileURLToPath","fileURLToPath","execFileAsync","promisify","execFile","PROVIDER_ID","input"]}
|