reasonix 0.5.4 → 0.5.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/client.ts","../src/retry.ts","../src/harvest.ts","../src/consistency.ts","../src/hooks.ts","../src/tokenizer.ts","../src/repair/flatten.ts","../src/tools.ts","../src/mcp/registry.ts","../src/memory.ts","../src/repair/scavenge.ts","../src/repair/storm.ts","../src/repair/truncation.ts","../src/repair/index.ts","../src/session.ts","../src/telemetry.ts","../src/loop.ts","../src/project-memory.ts","../src/user-memory.ts","../src/skills.ts","../src/tools/filesystem.ts","../src/tools/memory.ts","../src/tools/plan.ts","../src/tools/subagent.ts","../src/tools/shell.ts","../src/tools/web.ts","../src/env.ts","../src/transcript.ts","../src/replay.ts","../src/diff.ts","../src/mcp/types.ts","../src/mcp/client.ts","../src/mcp/stdio.ts","../src/mcp/sse.ts","../src/mcp/shell-split.ts","../src/mcp/spec.ts","../src/mcp/inspect.ts","../src/code/edit-blocks.ts","../src/code/prompt.ts","../src/config.ts","../src/version.ts","../src/usage.ts"],"sourcesContent":["import { type EventSourceMessage, createParser } from \"eventsource-parser\";\nimport { type RetryOptions, fetchWithRetry } from \"./retry.js\";\nimport type { ChatMessage, ChatRequestOptions, RawUsage, ToolCall, ToolSpec } from \"./types.js\";\n\nexport class Usage {\n constructor(\n public promptTokens = 0,\n public completionTokens = 0,\n public totalTokens = 0,\n public promptCacheHitTokens = 0,\n public promptCacheMissTokens = 0,\n ) {}\n\n get cacheHitRatio(): number {\n const denom = this.promptCacheHitTokens + this.promptCacheMissTokens;\n return denom > 0 ? this.promptCacheHitTokens / denom : 0;\n }\n\n static fromApi(raw: RawUsage | undefined | null): Usage {\n const u = raw ?? {};\n return new Usage(\n u.prompt_tokens ?? 0,\n u.completion_tokens ?? 0,\n u.total_tokens ?? 0,\n u.prompt_cache_hit_tokens ?? 0,\n u.prompt_cache_miss_tokens ?? 0,\n );\n }\n}\n\nexport interface ChatResponse {\n content: string;\n reasoningContent: string | null;\n toolCalls: ToolCall[];\n usage: Usage;\n raw: unknown;\n}\n\nexport interface StreamChunk {\n contentDelta?: string;\n reasoningDelta?: string;\n toolCallDelta?: { index: number; id?: string; name?: string; argumentsDelta?: string };\n usage?: Usage;\n finishReason?: string;\n raw: any;\n}\n\n/**\n * Response shape for DeepSeek's `/user/balance` endpoint. One entry\n * per currency the account is funded in (typically CNY, sometimes\n * USD). `total_balance` is the spendable figure; `granted_balance`\n * counts promotional credits that expire, `topped_up_balance` is\n * what the user paid for and keeps.\n */\nexport interface BalanceInfo {\n currency: string;\n total_balance: string;\n granted_balance?: string;\n topped_up_balance?: string;\n}\n\nexport interface UserBalance {\n is_available: boolean;\n balance_infos: BalanceInfo[];\n}\n\n/**\n * Response shape for DeepSeek's `/models` endpoint. Mirrors the OpenAI\n * models list shape DeepSeek copied — `id` is the model name to pass to\n * `/chat/completions`, `owned_by` is the provider string (always\n * `\"deepseek\"` today).\n */\nexport interface ModelInfo {\n id: string;\n object: \"model\";\n owned_by: string;\n}\n\nexport interface ModelList {\n object: \"list\";\n data: ModelInfo[];\n}\n\nexport interface DeepSeekClientOptions {\n apiKey?: string;\n baseUrl?: string;\n timeoutMs?: number;\n fetch?: typeof fetch;\n /** Retry configuration. Pass `{ maxAttempts: 1 }` to disable retries. */\n retry?: RetryOptions;\n}\n\nexport class DeepSeekClient {\n readonly apiKey: string;\n readonly baseUrl: string;\n readonly timeoutMs: number;\n readonly retry: RetryOptions;\n private readonly _fetch: typeof fetch;\n\n constructor(opts: DeepSeekClientOptions = {}) {\n const apiKey = opts.apiKey ?? process.env.DEEPSEEK_API_KEY;\n if (!apiKey) {\n throw new Error(\n \"DEEPSEEK_API_KEY is not set. Put it in .env or pass apiKey to DeepSeekClient.\",\n );\n }\n this.apiKey = apiKey;\n this.baseUrl = (\n opts.baseUrl ??\n process.env.DEEPSEEK_BASE_URL ??\n \"https://api.deepseek.com\"\n ).replace(/\\/+$/, \"\");\n this.timeoutMs = opts.timeoutMs ?? 120_000;\n this._fetch = opts.fetch ?? globalThis.fetch.bind(globalThis);\n this.retry = opts.retry ?? {};\n }\n\n private buildPayload(opts: ChatRequestOptions, stream: boolean) {\n const payload: Record<string, unknown> = {\n model: opts.model,\n messages: opts.messages,\n stream,\n };\n if (opts.tools?.length) payload.tools = opts.tools;\n if (opts.temperature !== undefined) payload.temperature = opts.temperature;\n if (opts.maxTokens !== undefined) payload.max_tokens = opts.maxTokens;\n if (opts.responseFormat) payload.response_format = opts.responseFormat;\n return payload;\n }\n\n /**\n * Fetch the current DeepSeek account balance. Separate endpoint\n * from chat completions, no billing impact. Returns null on any\n * network/auth failure so callers can gate the balance display\n * without a hard error — the rest of the session works regardless.\n */\n async getBalance(opts: { signal?: AbortSignal } = {}): Promise<UserBalance | null> {\n try {\n const resp = await this._fetch(`${this.baseUrl}/user/balance`, {\n method: \"GET\",\n headers: { Authorization: `Bearer ${this.apiKey}` },\n signal: opts.signal,\n });\n if (!resp.ok) return null;\n const data = (await resp.json()) as UserBalance;\n if (!data || !Array.isArray(data.balance_infos)) return null;\n return data;\n } catch {\n return null;\n }\n }\n\n /**\n * Fetch the model catalog DeepSeek currently exposes. Today this is\n * `deepseek-chat` (V3) and `deepseek-reasoner` (R1), but querying is\n * the only way to learn about new ones without a Reasonix release.\n * Returns null on any network/auth failure so callers can degrade\n * gracefully — e.g. `/models` falls back to the hardcoded hint.\n */\n async listModels(opts: { signal?: AbortSignal } = {}): Promise<ModelList | null> {\n try {\n const resp = await this._fetch(`${this.baseUrl}/models`, {\n method: \"GET\",\n headers: { Authorization: `Bearer ${this.apiKey}` },\n signal: opts.signal,\n });\n if (!resp.ok) return null;\n const data = (await resp.json()) as ModelList;\n if (!data || !Array.isArray(data.data)) return null;\n return data;\n } catch {\n return null;\n }\n }\n\n async chat(opts: ChatRequestOptions): Promise<ChatResponse> {\n const ctrl = new AbortController();\n const timer = setTimeout(() => ctrl.abort(), this.timeoutMs);\n const signal = opts.signal ?? ctrl.signal;\n\n try {\n const resp = await fetchWithRetry(\n this._fetch,\n `${this.baseUrl}/chat/completions`,\n {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(this.buildPayload(opts, false)),\n signal,\n },\n { ...this.retry, signal },\n );\n if (!resp.ok) {\n throw new Error(`DeepSeek ${resp.status}: ${await resp.text()}`);\n }\n const data: any = await resp.json();\n const choice = data.choices?.[0]?.message ?? {};\n return {\n content: choice.content ?? \"\",\n reasoningContent: choice.reasoning_content ?? null,\n toolCalls: choice.tool_calls ?? [],\n usage: Usage.fromApi(data.usage),\n raw: data,\n };\n } finally {\n clearTimeout(timer);\n }\n }\n\n async *stream(opts: ChatRequestOptions): AsyncGenerator<StreamChunk> {\n const ctrl = new AbortController();\n const timer = setTimeout(() => ctrl.abort(), this.timeoutMs);\n const signal = opts.signal ?? ctrl.signal;\n\n let resp: Response;\n try {\n // Only the initial fetch is retried. Once the server has started sending\n // the stream body we do NOT retry — a mid-stream retry would re-bill and\n // desync the session context.\n resp = await fetchWithRetry(\n this._fetch,\n `${this.baseUrl}/chat/completions`,\n {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n \"Content-Type\": \"application/json\",\n Accept: \"text/event-stream\",\n },\n body: JSON.stringify(this.buildPayload(opts, true)),\n signal,\n },\n { ...this.retry, signal },\n );\n } catch (err) {\n clearTimeout(timer);\n throw err;\n }\n if (!resp.ok || !resp.body) {\n clearTimeout(timer);\n throw new Error(`DeepSeek ${resp.status}: ${await resp.text().catch(() => \"\")}`);\n }\n\n const queue: StreamChunk[] = [];\n let done = false;\n const parser = createParser({\n onEvent: (ev: EventSourceMessage) => {\n if (!ev.data || ev.data === \"[DONE]\") {\n done = true;\n return;\n }\n try {\n const json = JSON.parse(ev.data);\n const delta = json.choices?.[0]?.delta ?? {};\n const finishReason = json.choices?.[0]?.finish_reason ?? undefined;\n const chunk: StreamChunk = { raw: json, finishReason };\n if (typeof delta.content === \"string\" && delta.content.length > 0) {\n chunk.contentDelta = delta.content;\n }\n if (typeof delta.reasoning_content === \"string\" && delta.reasoning_content.length > 0) {\n chunk.reasoningDelta = delta.reasoning_content;\n }\n if (Array.isArray(delta.tool_calls) && delta.tool_calls.length > 0) {\n const tc = delta.tool_calls[0];\n chunk.toolCallDelta = {\n index: tc.index ?? 0,\n id: tc.id,\n name: tc.function?.name,\n argumentsDelta: tc.function?.arguments,\n };\n }\n if (json.usage) {\n chunk.usage = Usage.fromApi(json.usage);\n }\n queue.push(chunk);\n } catch {\n /* skip malformed sse frame */\n }\n },\n });\n\n const reader = resp.body.getReader();\n const decoder = new TextDecoder();\n try {\n while (true) {\n if (queue.length > 0) {\n yield queue.shift()!;\n continue;\n }\n if (done) break;\n const { value, done: streamDone } = await reader.read();\n if (streamDone) break;\n parser.feed(decoder.decode(value, { stream: true }));\n }\n while (queue.length > 0) yield queue.shift()!;\n } finally {\n clearTimeout(timer);\n reader.releaseLock();\n }\n }\n}\n\nexport type { ChatMessage, ToolCall, ToolSpec };\n","/**\n * Retry layer for DeepSeek API calls.\n *\n * Wraps a `fetch` function so that transient failures (rate limiting, server\n * overload, network blips) don't kill an agent session. We explicitly DO NOT\n * retry:\n * - 4xx client errors other than 408 / 429 (bad key, bad request, ...)\n * - aborted requests (user cancelled)\n * - mid-stream body read errors (retrying costs money AND would desync)\n *\n * Retrying is controlled by attempt count + exponential backoff with jitter.\n * If the server sends a `Retry-After` header we honor it (capped by\n * `maxBackoffMs` so a misconfigured upstream can't park us forever).\n */\n\nexport interface RetryOptions {\n /** Maximum total attempts (including the first). Default 4. */\n maxAttempts?: number;\n /** Initial backoff in ms. Doubles each retry, with jitter. Default 500. */\n initialBackoffMs?: number;\n /** Upper bound on any single backoff delay. Default 10000 (10s). */\n maxBackoffMs?: number;\n /** HTTP statuses to treat as retryable. Default [408, 429, 500, 502, 503, 504]. */\n retryableStatuses?: readonly number[];\n /** Abort signal; we do NOT retry once aborted. */\n signal?: AbortSignal;\n /** Telemetry hook — called before each wait. */\n onRetry?: (info: RetryInfo) => void;\n}\n\nexport interface RetryInfo {\n attempt: number;\n reason: string;\n waitMs: number;\n}\n\nconst DEFAULT_RETRYABLE_STATUSES = [408, 429, 500, 502, 503, 504] as const;\n\nexport async function fetchWithRetry(\n fetchFn: typeof fetch,\n url: string,\n init: RequestInit,\n opts: RetryOptions = {},\n): Promise<Response> {\n const maxAttempts = opts.maxAttempts ?? 4;\n const initial = opts.initialBackoffMs ?? 500;\n const cap = opts.maxBackoffMs ?? 10_000;\n const retryable = new Set(opts.retryableStatuses ?? DEFAULT_RETRYABLE_STATUSES);\n\n let lastError: unknown;\n\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n if (opts.signal?.aborted) throw new Error(\"aborted\");\n\n try {\n const resp = await fetchFn(url, init);\n\n // Success or non-retryable failure: return as-is.\n if (resp.ok || !retryable.has(resp.status)) return resp;\n\n // Retryable but out of attempts: return the last response so the caller\n // can surface the status to the user.\n if (attempt === maxAttempts - 1) return resp;\n\n // Drain the body so the connection can be reused on the next attempt.\n await resp.text().catch(() => undefined);\n\n const waitMs = computeWait(attempt, initial, cap, resp.headers.get(\"Retry-After\"));\n opts.onRetry?.({ attempt: attempt + 1, reason: `http ${resp.status}`, waitMs });\n await sleep(waitMs, opts.signal);\n } catch (err) {\n lastError = err;\n // Respect explicit aborts — do not retry.\n if (isAbortError(err) || opts.signal?.aborted) throw err;\n if (attempt === maxAttempts - 1) throw err;\n\n const waitMs = computeWait(attempt, initial, cap, null);\n opts.onRetry?.({\n attempt: attempt + 1,\n reason: `network: ${messageOf(err)}`,\n waitMs,\n });\n await sleep(waitMs, opts.signal);\n }\n }\n\n throw lastError ?? new Error(\"fetchWithRetry: loop exited unexpectedly\");\n}\n\nfunction computeWait(\n attempt: number,\n initial: number,\n cap: number,\n retryAfter: string | null,\n): number {\n if (retryAfter) {\n const seconds = Number.parseFloat(retryAfter);\n if (Number.isFinite(seconds) && seconds > 0) {\n return Math.min(seconds * 1000, cap);\n }\n }\n const exp = initial * 2 ** attempt;\n // Jitter range [75%, 125%] to spread retries out when many clients hit 429 together.\n const jitter = exp * (0.75 + Math.random() * 0.5);\n return Math.min(Math.max(jitter, 0), cap);\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n if (ms <= 0) return Promise.resolve();\n return new Promise((resolve, reject) => {\n const timer = setTimeout(resolve, ms);\n if (signal) {\n const onAbort = () => {\n clearTimeout(timer);\n reject(new Error(\"aborted\"));\n };\n if (signal.aborted) onAbort();\n else signal.addEventListener(\"abort\", onAbort, { once: true });\n }\n });\n}\n\nfunction isAbortError(err: unknown): boolean {\n if (!err || typeof err !== \"object\") return false;\n const name = (err as { name?: unknown }).name;\n return name === \"AbortError\";\n}\n\nfunction messageOf(err: unknown): string {\n if (err instanceof Error) return err.message;\n try {\n return String(err);\n } catch {\n return \"unknown error\";\n }\n}\n","/**\n * Pillar 2 — R1 Thought Harvesting.\n *\n * Takes the `reasoning_content` emitted by a thinking model (deepseek-reasoner\n * / R1) and extracts a structured plan state by making a cheap secondary call\n * to V3 in JSON mode. The typed state is intended for the orchestrator to\n * branch on — e.g. trigger self-consistency sampling when `uncertainties.length\n * > 2`, or surface the subgoals to the user.\n *\n * Opt-in: loops disable harvesting by default. Failures (bad JSON, API error,\n * empty reasoning) return an empty TypedPlanState — the main turn is never\n * aborted because of a harvest hiccup.\n */\n\nimport type { DeepSeekClient } from \"./client.js\";\n\nexport interface TypedPlanState {\n subgoals: string[];\n hypotheses: string[];\n uncertainties: string[];\n rejectedPaths: string[];\n}\n\nexport interface HarvestOptions {\n /** Model used for the extraction call. Defaults to the cheap chat model. */\n model?: string;\n /** Cap on how many items land in each array. Default 5. */\n maxItems?: number;\n /** Per-item character cap. Default 80. */\n maxItemLen?: number;\n /** Abort the extraction if R1 reasoning is shorter than this. Default 40. */\n minReasoningLen?: number;\n}\n\nexport function emptyPlanState(): TypedPlanState {\n return { subgoals: [], hypotheses: [], uncertainties: [], rejectedPaths: [] };\n}\n\nexport function isPlanStateEmpty(s: TypedPlanState | null | undefined): boolean {\n if (!s) return true;\n return (\n s.subgoals.length === 0 &&\n s.hypotheses.length === 0 &&\n s.uncertainties.length === 0 &&\n s.rejectedPaths.length === 0\n );\n}\n\nconst SYSTEM_PROMPT = `You extract a typed plan state from a reasoning trace produced by another LLM.\nOutput ONLY a JSON object. No markdown, no prose, no backticks.\n\nSchema:\n{\n \"subgoals\": string[], // concrete intermediate objectives the trace identifies\n \"hypotheses\": string[], // candidate approaches or assumptions being weighed\n \"uncertainties\": string[], // facts the trace flags as unclear / to verify\n \"rejectedPaths\": string[] // approaches the trace considered and then abandoned\n}\n\nConstraints:\n- Every field must be present. Use [] if not applicable.\n- Each array has at most {maxItems} items.\n- Each item is plain text, at most {maxItemLen} characters, no markdown.\n- Write in the same language as the trace (Chinese in → Chinese out, etc.).\n- Do not quote back the trace; write short, specific phrases.`;\n\nexport async function harvest(\n reasoningContent: string | null | undefined,\n client?: DeepSeekClient,\n options: HarvestOptions = {},\n signal?: AbortSignal,\n): Promise<TypedPlanState> {\n if (!client || !reasoningContent) return emptyPlanState();\n // Fast-path the already-aborted case so we don't burn a network\n // round-trip for a result the caller no longer wants.\n if (signal?.aborted) return emptyPlanState();\n const minLen = options.minReasoningLen ?? 40;\n const trimmed = reasoningContent.trim();\n if (trimmed.length < minLen) return emptyPlanState();\n\n const model = options.model ?? \"deepseek-chat\";\n const maxItems = options.maxItems ?? 5;\n const maxItemLen = options.maxItemLen ?? 80;\n const system = SYSTEM_PROMPT.replace(\"{maxItems}\", String(maxItems)).replace(\n \"{maxItemLen}\",\n String(maxItemLen),\n );\n\n try {\n const resp = await client.chat({\n model,\n messages: [\n { role: \"system\", content: system },\n { role: \"user\", content: trimmed },\n ],\n responseFormat: { type: \"json_object\" },\n temperature: 0,\n maxTokens: 600,\n signal,\n });\n return parsePlanState(resp.content, maxItems, maxItemLen);\n } catch {\n return emptyPlanState();\n }\n}\n\nfunction parsePlanState(raw: string, maxItems: number, maxItemLen: number): TypedPlanState {\n const text = (raw ?? \"\").trim();\n if (!text) return emptyPlanState();\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n // Occasionally a model wraps JSON in fences despite instructions.\n const match = text.match(/\\{[\\s\\S]*\\}/);\n if (!match) return emptyPlanState();\n try {\n parsed = JSON.parse(match[0]);\n } catch {\n return emptyPlanState();\n }\n }\n if (!parsed || typeof parsed !== \"object\") return emptyPlanState();\n const obj = parsed as Record<string, unknown>;\n return {\n subgoals: sanitizeArray(obj.subgoals, maxItems, maxItemLen),\n hypotheses: sanitizeArray(obj.hypotheses, maxItems, maxItemLen),\n uncertainties: sanitizeArray(obj.uncertainties, maxItems, maxItemLen),\n rejectedPaths: sanitizeArray(obj.rejectedPaths ?? obj.rejected_paths, maxItems, maxItemLen),\n };\n}\n\nfunction sanitizeArray(raw: unknown, maxItems: number, maxItemLen: number): string[] {\n if (!Array.isArray(raw)) return [];\n const out: string[] = [];\n for (const item of raw) {\n if (out.length >= maxItems) break;\n if (typeof item !== \"string\") continue;\n const cleaned = item.trim().replace(/\\s+/g, \" \");\n if (!cleaned) continue;\n out.push(cleaned.length <= maxItemLen ? cleaned : `${cleaned.slice(0, maxItemLen - 1)}…`);\n }\n return out;\n}\n","/**\n * Self-consistency branching.\n *\n * When enabled, the loop fans out into N parallel samples per turn (varied\n * temperatures), runs Pillar 2 harvest on each, and selects the sample with\n * the fewest flagged uncertainties (ties broken by answer length — a crude\n * Occam prior).\n *\n * The unique opportunity here: because DeepSeek is ~20× cheaper than Claude,\n * running N=3–5 samples per turn is still cheaper than a single Claude call,\n * while the majority-confidence selection tends to dominate single-sample\n * answers on fuzzy multi-step reasoning tasks.\n */\n\nimport type { ChatResponse, DeepSeekClient } from \"./client.js\";\nimport { type HarvestOptions, type TypedPlanState, harvest } from \"./harvest.js\";\nimport type { ChatRequestOptions } from \"./types.js\";\n\nexport interface BranchSample {\n index: number;\n temperature: number;\n response: ChatResponse;\n planState: TypedPlanState;\n}\n\nexport type BranchSelector = (samples: BranchSample[]) => BranchSample;\n\nexport interface BranchOptions {\n /** Number of parallel samples. 1 disables branching. Default 1. */\n budget?: number;\n /** Temperatures for each branch. Default spreads across [0, 1]. */\n temperatures?: readonly number[];\n /** Harvest options; the selector needs harvest to score samples. */\n harvestOptions?: HarvestOptions;\n /** Custom selector. Default: min uncertainties, tie-break shortest answer. */\n selector?: BranchSelector;\n /**\n * Fires as each sample finishes (main call + harvest both complete).\n * Useful for progress UI. Not awaited; exceptions are swallowed.\n */\n onSampleDone?: (sample: BranchSample) => void;\n}\n\nexport interface BranchResult {\n chosen: BranchSample;\n samples: BranchSample[];\n}\n\n/** Default: fewest uncertainties wins, ties broken by shorter answer content. */\nexport const defaultSelector: BranchSelector = (samples) => {\n if (samples.length === 0) throw new Error(\"defaultSelector: samples is empty\");\n return samples.slice().sort((a, b) => {\n const uDiff = a.planState.uncertainties.length - b.planState.uncertainties.length;\n if (uDiff !== 0) return uDiff;\n const aLen = a.response.content?.length ?? 0;\n const bLen = b.response.content?.length ?? 0;\n return aLen - bLen;\n })[0]!;\n};\n\nexport async function runBranches(\n client: DeepSeekClient,\n request: ChatRequestOptions,\n opts: BranchOptions = {},\n): Promise<BranchResult> {\n const budget = Math.max(1, opts.budget ?? 1);\n const temperatures = resolveTemperatures(budget, opts.temperatures);\n const selector = opts.selector ?? defaultSelector;\n\n const samples = await Promise.all(\n temperatures.map(async (temperature, index): Promise<BranchSample> => {\n const response = await client.chat({ ...request, temperature });\n const planState = await harvest(response.reasoningContent, client, opts.harvestOptions);\n const sample: BranchSample = { index, temperature, response, planState };\n try {\n opts.onSampleDone?.(sample);\n } catch {\n /* callback errors must not poison the await */\n }\n return sample;\n }),\n );\n\n return { chosen: selector(samples), samples };\n}\n\n/** Sum usage across branch samples for telemetry purposes. */\nexport function aggregateBranchUsage(samples: readonly BranchSample[]) {\n let promptTokens = 0;\n let completionTokens = 0;\n let totalTokens = 0;\n let promptCacheHitTokens = 0;\n let promptCacheMissTokens = 0;\n for (const s of samples) {\n promptTokens += s.response.usage.promptTokens;\n completionTokens += s.response.usage.completionTokens;\n totalTokens += s.response.usage.totalTokens;\n promptCacheHitTokens += s.response.usage.promptCacheHitTokens;\n promptCacheMissTokens += s.response.usage.promptCacheMissTokens;\n }\n return {\n promptTokens,\n completionTokens,\n totalTokens,\n promptCacheHitTokens,\n promptCacheMissTokens,\n };\n}\n\nfunction resolveTemperatures(budget: number, custom?: readonly number[]): number[] {\n if (custom && custom.length >= budget) return [...custom.slice(0, budget)];\n // Spread evenly across [0, 1] to encourage reasoning-path diversity.\n if (budget === 1) return [0];\n const out: number[] = [];\n for (let i = 0; i < budget; i++) {\n out.push(Number((i / (budget - 1)).toFixed(2)));\n }\n return out;\n}\n","/**\n * Hooks — user-defined automation that fires at well-known points in\n * the agent loop. Mirrors the two-scope layout we use for memory and\n * skills:\n *\n * - `<project>/.reasonix/settings.json` — committable per-project\n * - `~/.reasonix/settings.json` — every session\n *\n * A hook is a shell command. We invoke it with stdin = a JSON\n * payload describing the event, and interpret the exit code:\n *\n * - `0` — pass; loop continues normally\n * - `2` — block; for `PreToolUse` / `UserPromptSubmit` the\n * loop refuses to continue with that step and surfaces the\n * hook's stderr as the reason. For `PostToolUse` / `Stop` block\n * is meaningless (the action already happened) — treat as warn.\n * - anything else — warn; loop continues but stderr is rendered\n * to the user as an inline notice.\n *\n * stdin JSON shape (one envelope per event):\n *\n * {\n * \"event\": \"PreToolUse\" | \"PostToolUse\" | \"UserPromptSubmit\" | \"Stop\",\n * \"cwd\": \"<absolute project root or process.cwd()>\",\n * \"toolName\": \"<string>\", // tool events only\n * \"toolArgs\": <unknown>, // tool events only — already JSON-decoded\n * \"toolResult\": \"<string>\", // PostToolUse only — same body the model sees\n * \"prompt\": \"<string>\", // UserPromptSubmit only\n * \"lastAssistantText\": \"<string>\", // Stop only\n * \"turn\": <number>, // Stop only\n * }\n *\n * Hooks are executed in order: project scope first, then global.\n * `Pre*` events stop dispatching at the first block; non-block\n * outcomes accumulate into a single report so the UI can render\n * each warning inline.\n */\n\nimport { spawn } from \"node:child_process\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nexport type HookEvent = \"PreToolUse\" | \"PostToolUse\" | \"UserPromptSubmit\" | \"Stop\";\n\n/** All four events as a const array — drives slash listing + validation. */\nexport const HOOK_EVENTS: readonly HookEvent[] = [\n \"PreToolUse\",\n \"PostToolUse\",\n \"UserPromptSubmit\",\n \"Stop\",\n] as const;\n\n/** Only the gating events can block the loop. */\nconst BLOCKING_EVENTS: ReadonlySet<HookEvent> = new Set([\"PreToolUse\", \"UserPromptSubmit\"]);\n\n/** Per-event default timeout. Tool/prompt hooks gate progress, so they're tight. */\nconst DEFAULT_TIMEOUTS_MS: Record<HookEvent, number> = {\n PreToolUse: 5_000,\n UserPromptSubmit: 5_000,\n PostToolUse: 30_000,\n Stop: 30_000,\n};\n\nexport type HookScope = \"project\" | \"global\";\n\nexport interface HookConfig {\n /**\n * Tool-name pattern (PreToolUse / PostToolUse only). Anchored regex.\n * Omitted or `\"*\"` matches every tool. Ignored for prompt / Stop\n * events (they have no tool name to match against).\n */\n match?: string;\n /** Shell command to run. Spawned through the platform shell. */\n command: string;\n /** Optional human description — surfaced in `/hooks`. */\n description?: string;\n /** Per-hook timeout override in ms. */\n timeout?: number;\n /**\n * Working directory for the spawned process. Defaults to:\n * - project scope → the project root\n * - global scope → process.cwd()\n */\n cwd?: string;\n}\n\n/** Shape of `<scope>/.reasonix/settings.json` — only `hooks` for now. */\nexport interface HookSettings {\n hooks?: Partial<Record<HookEvent, HookConfig[]>>;\n}\n\n/** A loaded hook with its origin scope baked in (used for ordering and `/hooks`). */\nexport interface ResolvedHook extends HookConfig {\n event: HookEvent;\n scope: HookScope;\n /** Absolute path to the settings.json the hook came from. */\n source: string;\n}\n\n/** Outcome of a single hook invocation. */\nexport interface HookOutcome {\n /** Which hook fired. */\n hook: ResolvedHook;\n /**\n * Decision:\n * - `pass` — exit 0\n * - `block` — exit 2 on a blocking event (otherwise downgraded to `warn`)\n * - `warn` — non-zero exit that is not a successful block\n * - `timeout` — the spawn was killed past `timeout`\n * - `error` — could not spawn at all (missing command, etc.)\n */\n decision: \"pass\" | \"block\" | \"warn\" | \"timeout\" | \"error\";\n exitCode: number | null;\n /** Captured stdout (trimmed). May be empty. */\n stdout: string;\n /** Captured stderr (trimmed). The block / warn message comes from here. */\n stderr: string;\n durationMs: number;\n}\n\n/** Aggregate report for `runHooks`. */\nexport interface HookReport {\n event: HookEvent;\n outcomes: HookOutcome[];\n /** True iff at least one outcome was a `block` — only meaningful for blocking events. */\n blocked: boolean;\n}\n\nexport const HOOK_SETTINGS_FILENAME = \"settings.json\";\nexport const HOOK_SETTINGS_DIRNAME = \".reasonix\";\n\n/** Where the global settings.json lives. Equivalent to `~/.reasonix/settings.json`. */\nexport function globalSettingsPath(homeDirOverride?: string): string {\n return join(homeDirOverride ?? homedir(), HOOK_SETTINGS_DIRNAME, HOOK_SETTINGS_FILENAME);\n}\n\n/** Where the project settings.json lives for a given root. */\nexport function projectSettingsPath(projectRoot: string): string {\n return join(projectRoot, HOOK_SETTINGS_DIRNAME, HOOK_SETTINGS_FILENAME);\n}\n\nfunction readSettingsFile(path: string): HookSettings | null {\n if (!existsSync(path)) return null;\n try {\n const raw = readFileSync(path, \"utf8\");\n const parsed = JSON.parse(raw);\n if (parsed && typeof parsed === \"object\") return parsed as HookSettings;\n } catch {\n /* malformed JSON → treat as no hooks; do NOT throw, the user\n * shouldn't lose the whole CLI to a typo in their settings */\n }\n return null;\n}\n\n/**\n * Pull every configured hook out of the project + global settings\n * files, in the order they should fire (project first, global second,\n * within each scope: array order from the file).\n *\n * Returns a flat list — the dispatcher filters by event + match\n * pattern at run time. Loading is cheap (one or two JSON files), so\n * we don't memoize across processes; re-load is allowed via\n * `/hooks reload` and on every fresh App mount.\n */\nexport interface LoadHookSettingsOptions {\n /** Absolute project root, if any. Without it, only global hooks load. */\n projectRoot?: string;\n /** Override `~` for tests. */\n homeDir?: string;\n}\n\nexport function loadHooks(opts: LoadHookSettingsOptions = {}): ResolvedHook[] {\n const out: ResolvedHook[] = [];\n if (opts.projectRoot) {\n const projPath = projectSettingsPath(opts.projectRoot);\n const settings = readSettingsFile(projPath);\n if (settings) appendResolved(out, settings, \"project\", projPath);\n }\n const globalPath = globalSettingsPath(opts.homeDir);\n const settings = readSettingsFile(globalPath);\n if (settings) appendResolved(out, settings, \"global\", globalPath);\n return out;\n}\n\nfunction appendResolved(\n out: ResolvedHook[],\n settings: HookSettings,\n scope: HookScope,\n source: string,\n): void {\n if (!settings.hooks) return;\n for (const event of HOOK_EVENTS) {\n const list = settings.hooks[event];\n if (!Array.isArray(list)) continue;\n for (const cfg of list) {\n if (!cfg || typeof cfg.command !== \"string\" || cfg.command.trim() === \"\") continue;\n out.push({ ...cfg, event, scope, source });\n }\n }\n}\n\n/**\n * True if `toolName` matches the hook's `match` field. `\"*\"` and\n * undefined match everything. Otherwise we anchor the field as a\n * regex — partial-name matches don't fire, so `\"file\"` would not\n * trigger on `read_file` (use `\".*file\"` for that).\n */\nexport function matchesTool(hook: ResolvedHook, toolName: string): boolean {\n if (hook.event !== \"PreToolUse\" && hook.event !== \"PostToolUse\") return true;\n const m = hook.match;\n if (!m || m === \"*\") return true;\n try {\n const re = new RegExp(`^(?:${m})$`);\n return re.test(toolName);\n } catch {\n /* malformed regex → don't fire (safer than firing on every tool) */\n return false;\n }\n}\n\n/** Payload envelope passed to hook stdin. */\nexport interface HookPayload {\n event: HookEvent;\n cwd: string;\n toolName?: string;\n toolArgs?: unknown;\n toolResult?: string;\n prompt?: string;\n lastAssistantText?: string;\n turn?: number;\n}\n\n/** Test seam — same shape as Node's spawn but returns a Promise of the raw outcome bits. */\nexport interface HookSpawnInput {\n command: string;\n cwd: string;\n stdin: string;\n timeoutMs: number;\n}\n\nexport interface HookSpawnResult {\n exitCode: number | null;\n stdout: string;\n stderr: string;\n timedOut: boolean;\n /** True iff spawn() itself failed (ENOENT, EACCES, …). */\n spawnError?: Error;\n}\n\nexport type HookSpawner = (input: HookSpawnInput) => Promise<HookSpawnResult>;\n\n/**\n * Default spawner — runs `command` through the platform shell so\n * `&&`, pipes, env-var expansion all work without a tokenizer.\n * Stdin is the JSON payload, stdout / stderr are buffered.\n *\n * Why `shell: true`? A hook is intentionally a shell command — that's\n * the contract. Treating it like an argv array would surprise users\n * who write `bun run check && eslint .` and expect it to behave the\n * way it does in their terminal.\n */\nfunction defaultSpawner(input: HookSpawnInput): Promise<HookSpawnResult> {\n return new Promise<HookSpawnResult>((resolve) => {\n const child = spawn(input.command, {\n cwd: input.cwd,\n shell: true,\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n });\n let stdout = \"\";\n let stderr = \"\";\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n child.kill(\"SIGTERM\");\n // SIGTERM may not land on Windows for shell children — followed\n // by a hard kill a moment later if the process is still around.\n setTimeout(() => {\n try {\n child.kill(\"SIGKILL\");\n } catch {\n /* already gone */\n }\n }, 500);\n }, input.timeoutMs);\n\n child.stdout.on(\"data\", (chunk: Buffer) => {\n stdout += chunk.toString(\"utf8\");\n });\n child.stderr.on(\"data\", (chunk: Buffer) => {\n stderr += chunk.toString(\"utf8\");\n });\n child.once(\"error\", (err) => {\n clearTimeout(timer);\n resolve({\n exitCode: null,\n stdout,\n stderr,\n timedOut: false,\n spawnError: err,\n });\n });\n child.once(\"close\", (code) => {\n clearTimeout(timer);\n resolve({\n exitCode: code,\n stdout: stdout.trim(),\n stderr: stderr.trim(),\n timedOut,\n });\n });\n\n try {\n child.stdin.write(input.stdin);\n child.stdin.end();\n } catch {\n /* stdin write can race with spawn errors; the close handler\n * still fires with exit 0/null */\n }\n });\n}\n\n/**\n * Format a hook outcome as a single-line UI string. Used by both the\n * loop (for `warning` events) and the App (for UserPromptSubmit /\n * Stop outcomes). Centralizing keeps the language consistent across\n * scopes.\n */\nexport function formatHookOutcomeMessage(outcome: HookOutcome): string {\n if (outcome.decision === \"pass\") return \"\";\n const detail = (outcome.stderr || outcome.stdout || \"\").trim();\n const tag = `${outcome.hook.scope}/${outcome.hook.event}`;\n const cmd =\n outcome.hook.command.length > 60\n ? `${outcome.hook.command.slice(0, 60)}…`\n : outcome.hook.command;\n const head = `hook ${tag} \\`${cmd}\\` ${outcome.decision}`;\n return detail ? `${head}: ${detail}` : head;\n}\n\n/**\n * Decide the hook's outcome decision from raw spawn results.\n * Pulled out as a pure function so tests can pin the matrix.\n */\nexport function decideOutcome(\n event: HookEvent,\n raw: HookSpawnResult,\n): \"pass\" | \"block\" | \"warn\" | \"timeout\" | \"error\" {\n if (raw.spawnError) return \"error\";\n if (raw.timedOut) return BLOCKING_EVENTS.has(event) ? \"block\" : \"warn\";\n if (raw.exitCode === 0) return \"pass\";\n if (raw.exitCode === 2 && BLOCKING_EVENTS.has(event)) return \"block\";\n return \"warn\";\n}\n\nexport interface RunHooksOptions {\n payload: HookPayload;\n hooks: ResolvedHook[];\n /** Test seam — defaults to a real `spawn`. */\n spawner?: HookSpawner;\n}\n\n/**\n * Filter hooks down to the ones that match `payload.event` (and\n * `payload.toolName`, for tool events), then run them in order.\n * Stops at the first `block` outcome on a blocking event so a\n * gating hook can prevent later hooks from incorrectly seeing a\n * success that wasn't going to happen.\n */\nexport async function runHooks(opts: RunHooksOptions): Promise<HookReport> {\n const spawner = opts.spawner ?? defaultSpawner;\n const event = opts.payload.event;\n const toolName = opts.payload.toolName ?? \"\";\n const matching = opts.hooks.filter((h) => h.event === event && matchesTool(h, toolName));\n\n const outcomes: HookOutcome[] = [];\n let blocked = false;\n const stdin = `${JSON.stringify(opts.payload)}\\n`;\n\n for (const hook of matching) {\n const start = Date.now();\n const timeoutMs = hook.timeout ?? DEFAULT_TIMEOUTS_MS[event];\n const cwd = hook.cwd ?? opts.payload.cwd;\n const raw = await spawner({ command: hook.command, cwd, stdin, timeoutMs });\n const decision = decideOutcome(event, raw);\n outcomes.push({\n hook,\n decision,\n exitCode: raw.exitCode,\n stdout: raw.stdout,\n stderr:\n raw.stderr ||\n (raw.spawnError ? raw.spawnError.message : \"\") ||\n (raw.timedOut ? `hook timed out after ${timeoutMs}ms` : \"\"),\n durationMs: Date.now() - start,\n });\n if (decision === \"block\") {\n blocked = true;\n break;\n }\n }\n\n return { event, outcomes, blocked };\n}\n","/**\n * Pure-TS port of DeepSeek's V3 tokenizer. Reads the slimmed+gzipped\n * HuggingFace-format tokenizer data shipped at\n * `data/deepseek-tokenizer.json.gz` and implements enough of the HF\n * pipeline (Split pre-tokenizers → ByteLevel → BPE) to count tokens\n * offline without pulling the `@lenml/tokenizers` or native Rust deps.\n *\n * Accuracy target: within ~3% of the API-returned `usage.prompt_tokens`\n * for mixed CJK+English+code input. Exact-to-API match would also\n * require replaying the Jinja chat template (role markers / tool call\n * framing); we intentionally skip that — for a gauge/UI estimate the\n * raw-text count is the useful number.\n *\n * Scope: ENCODE-SIDE ONLY. We don't need decode for counting; adding\n * it later is trivial via the inverse byte-level table.\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { gunzipSync } from \"node:zlib\";\n\ninterface AddedToken {\n id: number;\n content: string;\n special: boolean;\n normalized: boolean;\n}\n\ninterface SplitPretokenizer {\n type: \"Split\";\n pattern: { Regex: string };\n behavior: \"Isolated\" | \"Removed\" | string;\n invert: boolean;\n}\n\ninterface ByteLevelPretokenizer {\n type: \"ByteLevel\";\n add_prefix_space: boolean;\n trim_offsets: boolean;\n use_regex: boolean;\n}\n\ntype Pretokenizer = SplitPretokenizer | ByteLevelPretokenizer;\n\ninterface TokenizerData {\n added_tokens: AddedToken[];\n pre_tokenizer: {\n type: \"Sequence\";\n pretokenizers: Pretokenizer[];\n };\n model: {\n type: \"BPE\";\n vocab: Record<string, number>;\n merges: string[];\n };\n}\n\ninterface LoadedTokenizer {\n vocab: Record<string, number>;\n mergeRank: Map<string, number>;\n splitRegexes: RegExp[];\n byteToChar: string[];\n /**\n * Non-special added tokens (e.g. `<think>`, `<|fim▁hole|>`) that the\n * HF tokenizer recognizes as atomic units when they appear inline in\n * the text. Special tokens like `<|begin▁of▁sentence|>` are NOT in\n * this list — the model ignores them when they appear in user text\n * (the default HF `split_special_tokens=False` behavior), so we do\n * the same: they get tokenized byte-by-byte, not as the special ID.\n */\n addedPattern: RegExp | null;\n addedMap: Map<string, number>;\n}\n\n/**\n * GPT-2 byte-to-unicode mapping. Covers every byte 0..255 with a\n * deterministic visible-printable unicode char — this is what lets the\n * byte-level BPE show up in JSON vocabs as readable strings (`Ġ` for\n * space, `Ċ` for `\\n`, etc). Identical across every byte-level BPE\n * tokenizer DeepSeek ships.\n */\nfunction buildByteToChar(): string[] {\n const result: string[] = new Array(256);\n const bs: number[] = [];\n for (let b = 33; b <= 126; b++) bs.push(b);\n for (let b = 161; b <= 172; b++) bs.push(b);\n for (let b = 174; b <= 255; b++) bs.push(b);\n const cs = bs.slice();\n let n = 0;\n for (let b = 0; b < 256; b++) {\n if (!bs.includes(b)) {\n bs.push(b);\n cs.push(256 + n);\n n++;\n }\n }\n for (let i = 0; i < bs.length; i++) {\n result[bs[i]!] = String.fromCodePoint(cs[i]!);\n }\n return result;\n}\n\nlet cached: LoadedTokenizer | null = null;\n\n/**\n * Find the bundled tokenizer data file. Resolution order:\n * 1. `REASONIX_TOKENIZER_PATH` env var (for tests / custom builds).\n * 2. `../data/deepseek-tokenizer.json.gz` relative to this module —\n * works both in dev (src/) and after tsup bundling (dist/).\n */\nfunction resolveDataPath(): string {\n if (process.env.REASONIX_TOKENIZER_PATH) return process.env.REASONIX_TOKENIZER_PATH;\n try {\n const here = dirname(fileURLToPath(import.meta.url));\n return join(here, \"..\", \"data\", \"deepseek-tokenizer.json.gz\");\n } catch {\n // CJS fallback — `require.resolve` finds the package root.\n const req = createRequire(import.meta.url);\n return join(\n dirname(req.resolve(\"reasonix/package.json\")),\n \"data\",\n \"deepseek-tokenizer.json.gz\",\n );\n }\n}\n\nfunction loadTokenizer(): LoadedTokenizer {\n if (cached) return cached;\n const buf = readFileSync(resolveDataPath());\n const json = gunzipSync(buf).toString(\"utf8\");\n const data = JSON.parse(json) as TokenizerData;\n\n const mergeRank = new Map<string, number>();\n for (let i = 0; i < data.model.merges.length; i++) {\n mergeRank.set(data.model.merges[i]!, i);\n }\n\n const splitRegexes: RegExp[] = [];\n for (const p of data.pre_tokenizer.pretokenizers) {\n if (p.type === \"Split\") {\n // All three Split rules use Isolated — matches become their own\n // pre-tokens and so do the in-between stretches. The ByteLevel\n // stage in the Sequence does no extra splitting here\n // (use_regex:false), so our 3 Split regexes are the whole story.\n splitRegexes.push(new RegExp(p.pattern.Regex, \"gu\"));\n }\n }\n\n const addedMap = new Map<string, number>();\n const addedContents: string[] = [];\n for (const t of data.added_tokens) {\n if (!t.special) {\n addedMap.set(t.content, t.id);\n addedContents.push(t.content);\n }\n }\n // Longest-first ensures greedy matching doesn't lose a longer token\n // to a shorter prefix (e.g. `<think>` before `<`).\n addedContents.sort((a, b) => b.length - a.length);\n const addedPattern = addedContents.length\n ? new RegExp(addedContents.map(escapeRegex).join(\"|\"), \"g\")\n : null;\n\n cached = {\n vocab: data.model.vocab,\n mergeRank,\n splitRegexes,\n byteToChar: buildByteToChar(),\n addedPattern,\n addedMap,\n };\n return cached;\n}\n\nfunction escapeRegex(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * Apply one \"Isolated\" Split: the matches become their own pre-tokens,\n * stretches between matches pass through unchanged. Empty pre-tokens\n * are dropped so downstream stages don't see them.\n */\nfunction applySplit(chunks: string[], re: RegExp): string[] {\n const out: string[] = [];\n for (const chunk of chunks) {\n if (!chunk) continue;\n // Reset lastIndex — reusing a /g regex across matchAll iterations\n // is safe (matchAll internally advances), but across different\n // input strings we want a clean start.\n re.lastIndex = 0;\n let last = 0;\n for (const m of chunk.matchAll(re)) {\n const idx = m.index ?? 0;\n if (idx > last) out.push(chunk.slice(last, idx));\n if (m[0].length > 0) out.push(m[0]);\n last = idx + m[0].length;\n }\n if (last < chunk.length) out.push(chunk.slice(last));\n }\n return out;\n}\n\n/** UTF-8 bytes of `s`, each mapped to its byte-level visible char. */\nfunction byteLevelEncode(s: string, byteToChar: string[]): string {\n const bytes = new TextEncoder().encode(s);\n let out = \"\";\n for (let i = 0; i < bytes.length; i++) out += byteToChar[bytes[i]!];\n return out;\n}\n\n/**\n * Standard BPE merge loop. Starts from single byte-level chars and\n * repeatedly applies the lowest-rank merge until none remain. O(n²)\n * in chunk length, which is fine because chunks are ≤ a few hundred\n * byte-level chars after pre-tokenization (and most are <50).\n */\nfunction bpeEncode(piece: string, mergeRank: Map<string, number>): string[] {\n if (piece.length <= 1) return piece ? [piece] : [];\n let word: string[] = Array.from(piece);\n while (true) {\n let bestIdx = -1;\n let bestRank = Number.POSITIVE_INFINITY;\n for (let i = 0; i < word.length - 1; i++) {\n const pair = `${word[i]} ${word[i + 1]}`;\n const rank = mergeRank.get(pair);\n if (rank !== undefined && rank < bestRank) {\n bestRank = rank;\n bestIdx = i;\n if (rank === 0) break; // 0 is already the best possible\n }\n }\n if (bestIdx < 0) break;\n word = [\n ...word.slice(0, bestIdx),\n word[bestIdx]! + word[bestIdx + 1]!,\n ...word.slice(bestIdx + 2),\n ];\n if (word.length === 1) break;\n }\n return word;\n}\n\n/**\n * Tokenize a UTF-8 string into DeepSeek token IDs. Mirrors the HF\n * pipeline: (1) isolate non-special added tokens so they stay atomic,\n * (2) for each in-between segment run the three Split regexes, (3)\n * byte-level encode, (4) BPE merge, (5) look up vocab IDs.\n *\n * Not reentrancy-hazardous: loads a module-level singleton on first\n * call and reuses it. Subsequent calls are pure compute.\n */\nexport function encode(text: string): number[] {\n if (!text) return [];\n const t = loadTokenizer();\n const ids: number[] = [];\n\n const process = (segment: string) => {\n if (!segment) return;\n let chunks: string[] = [segment];\n for (const re of t.splitRegexes) chunks = applySplit(chunks, re);\n for (const chunk of chunks) {\n if (!chunk) continue;\n const byteLevel = byteLevelEncode(chunk, t.byteToChar);\n const pieces = bpeEncode(byteLevel, t.mergeRank);\n for (const p of pieces) {\n const id = t.vocab[p];\n // If not in vocab we silently skip: shouldn't happen for\n // byte-level BPE (every single byte has its own vocab entry),\n // but if a future tokenizer update breaks that invariant we'd\n // rather under-count than throw from a UI gauge.\n if (id !== undefined) ids.push(id);\n }\n }\n };\n\n if (t.addedPattern) {\n t.addedPattern.lastIndex = 0;\n let last = 0;\n for (const m of text.matchAll(t.addedPattern)) {\n const idx = m.index ?? 0;\n if (idx > last) process(text.slice(last, idx));\n const id = t.addedMap.get(m[0]);\n if (id !== undefined) ids.push(id);\n last = idx + m[0].length;\n }\n if (last < text.length) process(text.slice(last));\n } else {\n process(text);\n }\n return ids;\n}\n\n/**\n * Fast path for UI: we only need the count, not the IDs. Saves a\n * per-call array allocation and lets callers batch large logs\n * without holding the full ID stream.\n */\nexport function countTokens(text: string): number {\n return encode(text).length;\n}\n\n/**\n * Estimate the tokens a full conversation would cost. Sums raw-text\n * counts for every message's content; we do NOT add overhead for the\n * chat template's role markers (`<|User|>`, `<|Assistant|>`) because\n * the exact framing varies between the chat/reasoner templates and\n * DeepSeek applies them server-side anyway. Empirically adds ~3-6%\n * to the real `prompt_tokens` — callers who care can post-multiply.\n */\nexport function estimateConversationTokens(\n messages: Array<{ content?: string | null; tool_calls?: unknown }>,\n): number {\n let total = 0;\n for (const m of messages) {\n if (typeof m.content === \"string\" && m.content) {\n total += countTokens(m.content);\n }\n // Tool-call arguments are serialized as JSON in the prompt by the\n // chat template; their bytes WILL count upstream, so we count\n // them too. Stringify-once is cheap relative to the tokenize.\n if (m.tool_calls && Array.isArray(m.tool_calls) && m.tool_calls.length > 0) {\n total += countTokens(JSON.stringify(m.tool_calls));\n }\n }\n return total;\n}\n\n/**\n * Estimate the tokens a full DeepSeek request would cost: the\n * conversation-side tokens (what `estimateConversationTokens` already\n * counts) PLUS the serialized tool-spec payload. Tool specs ride in\n * their own JSON blob in the request body, not folded into any\n * message's `content`, so they need a separate count to land an\n * accurate preflight estimate.\n *\n * Returned number matches what `/context` displays for \"next request\"\n * — reuse this helper anywhere (preflight guard, diagnostics, UI) to\n * keep the two values from drifting.\n */\nexport function estimateRequestTokens(\n messages: Array<{ content?: string | null; tool_calls?: unknown }>,\n toolSpecs?: ReadonlyArray<unknown> | null,\n): number {\n let total = estimateConversationTokens(messages);\n if (toolSpecs && toolSpecs.length > 0) {\n total += countTokens(JSON.stringify(toolSpecs));\n }\n return total;\n}\n\n/** Exposed for tests — resets the lazy-load singleton. */\nexport function _resetForTests(): void {\n cached = null;\n}\n","/**\n * Schema flattening for DeepSeek tool calls.\n *\n * DeepSeek loses arguments on schemas that are deep (>2 levels of nesting) or\n * wide (>10 leaf parameters). This module transforms such schemas into a\n * dot-notation flat schema and re-nests the model's arguments before dispatch.\n *\n * Example:\n * { user: { profile: { name, age } } } ⇄ \"user.profile.name\", \"user.profile.age\"\n */\n\nimport type { JSONSchema } from \"../types.js\";\n\nexport interface FlattenDecision {\n shouldFlatten: boolean;\n leafCount: number;\n maxDepth: number;\n}\n\nexport function analyzeSchema(schema: JSONSchema | undefined): FlattenDecision {\n if (!schema) return { shouldFlatten: false, leafCount: 0, maxDepth: 0 };\n let leafCount = 0;\n let maxDepth = 0;\n walk(schema, 0, (depth, isLeaf) => {\n if (isLeaf) leafCount++;\n if (depth > maxDepth) maxDepth = depth;\n });\n return {\n shouldFlatten: leafCount > 10 || maxDepth > 2,\n leafCount,\n maxDepth,\n };\n}\n\nexport function flattenSchema(schema: JSONSchema): JSONSchema {\n const flatProps: Record<string, JSONSchema> = {};\n const required: string[] = [];\n collect(\"\", schema, flatProps, required, true);\n return {\n type: \"object\",\n properties: flatProps,\n required,\n };\n}\n\nexport function nestArguments(flatArgs: Record<string, unknown>): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(flatArgs)) {\n setByPath(out, key.split(\".\"), value);\n }\n return out;\n}\n\nfunction walk(\n schema: JSONSchema,\n depth: number,\n visit: (depth: number, isLeaf: boolean) => void,\n): void {\n if (schema.type === \"object\" && schema.properties) {\n for (const child of Object.values(schema.properties)) {\n walk(child, depth + 1, visit);\n }\n return;\n }\n if (schema.type === \"array\" && schema.items) {\n walk(schema.items, depth + 1, visit);\n return;\n }\n visit(depth, true);\n}\n\nfunction collect(\n prefix: string,\n schema: JSONSchema,\n out: Record<string, JSONSchema>,\n required: string[],\n isRootRequired: boolean,\n): void {\n if (schema.type === \"object\" && schema.properties) {\n const requiredSet = new Set(schema.required ?? []);\n for (const [key, child] of Object.entries(schema.properties)) {\n const nextPrefix = prefix ? `${prefix}.${key}` : key;\n const childRequired = isRootRequired && requiredSet.has(key);\n collect(nextPrefix, child, out, required, childRequired);\n }\n return;\n }\n // Treat anything non-object (including arrays) as a leaf for flattening purposes.\n out[prefix] = schema;\n if (isRootRequired) required.push(prefix);\n}\n\nfunction setByPath(target: Record<string, unknown>, path: string[], value: unknown): void {\n let cur: any = target;\n for (let i = 0; i < path.length - 1; i++) {\n const key = path[i]!;\n if (typeof cur[key] !== \"object\" || cur[key] === null) cur[key] = {};\n cur = cur[key];\n }\n cur[path[path.length - 1]!] = value;\n}\n","import { truncateForModel, truncateForModelByTokens } from \"./mcp/registry.js\";\nimport { analyzeSchema, flattenSchema, nestArguments } from \"./repair/flatten.js\";\nimport type { JSONSchema, ToolSpec } from \"./types.js\";\n\n/**\n * Per-call context a tool `fn` can optionally consume. Today the only\n * field is `signal`, plumbed through so long-running tools (MCP calls,\n * HTTP requests) can abort when the user presses Esc. Omitted fields\n * stay optional — tools written against the pre-0.4.9 signature keep\n * working; they just ignore cancellation, which is fine for fast\n * local work where \"await finishes\" happens before the next tick anyway.\n */\nexport interface ToolCallContext {\n signal?: AbortSignal;\n}\n\nexport interface ToolDefinition<A = any, R = any> {\n name: string;\n description?: string;\n parameters?: JSONSchema;\n /**\n * Marks a tool as read-only: safe to invoke during plan mode. `true`\n * for tools that only observe (read_file, list_directory, search, web\n * fetch/search). Leave undefined / `false` for anything that can write,\n * execute, or mutate state.\n *\n * The registry enforces this at dispatch: non-readonly tools called\n * while `planMode` is on return a refusal string the model can\n * learn from, instead of actually running.\n */\n readOnly?: boolean;\n /**\n * Dynamic read-only check for tools whose safety depends on arguments\n * — `run_command` with an allowlisted argv is safe, `run_command\n * rm -rf` isn't. Called with the parsed arguments; `true` means \"treat\n * as read-only for plan mode\". Takes precedence over `readOnly` when\n * both are set.\n */\n readOnlyCheck?: (args: A) => boolean;\n fn: (args: A, ctx?: ToolCallContext) => R | Promise<R>;\n}\n\ninterface InternalTool extends ToolDefinition {\n /**\n * Pillar 3 — flatten metadata. Set when the registered schema is deep\n * (>2 levels) or wide (>10 leaf params), conditions on which DeepSeek\n * V3/R1 are known to drop arguments. We advertise the flattened schema\n * to the model, then re-nest the model's args before calling fn.\n */\n flatSchema?: JSONSchema;\n}\n\nexport interface ToolRegistryOptions {\n /**\n * Auto-flatten schemas that exceed depth/width thresholds before sending\n * them to the model. Re-nests arguments transparently on dispatch.\n * Default: true. Pass false to opt out.\n */\n autoFlatten?: boolean;\n}\n\nexport class ToolRegistry {\n private readonly _tools = new Map<string, InternalTool>();\n private readonly _autoFlatten: boolean;\n /**\n * When true, `dispatch` refuses any tool whose `readOnly` flag isn't\n * set (and whose `readOnlyCheck` doesn't pass on the specific args).\n * Drives `reasonix code`'s Plan Mode — the model can still explore\n * via read tools but its writes and non-allowlisted shell calls are\n * bounced until the user approves a submitted plan.\n */\n private _planMode = false;\n\n constructor(opts: ToolRegistryOptions = {}) {\n this._autoFlatten = opts.autoFlatten !== false;\n }\n\n /** Enable / disable plan-mode enforcement at dispatch. */\n setPlanMode(on: boolean): void {\n this._planMode = Boolean(on);\n }\n\n /** True when the registry is currently refusing non-readonly calls. */\n get planMode(): boolean {\n return this._planMode;\n }\n\n register<A, R>(def: ToolDefinition<A, R>): this {\n if (!def.name) throw new Error(\"tool requires a name\");\n const internal: InternalTool = { ...(def as ToolDefinition) };\n if (this._autoFlatten && def.parameters) {\n const decision = analyzeSchema(def.parameters);\n if (decision.shouldFlatten) {\n internal.flatSchema = flattenSchema(def.parameters);\n }\n }\n this._tools.set(def.name, internal);\n return this;\n }\n\n has(name: string): boolean {\n return this._tools.has(name);\n }\n\n get(name: string): ToolDefinition | undefined {\n return this._tools.get(name);\n }\n\n get size(): number {\n return this._tools.size;\n }\n\n /** True if a registered tool's schema was flattened for the model. */\n wasFlattened(name: string): boolean {\n return Boolean(this._tools.get(name)?.flatSchema);\n }\n\n specs(): ToolSpec[] {\n return [...this._tools.values()].map((t) => ({\n type: \"function\",\n function: {\n name: t.name,\n description: t.description ?? \"\",\n parameters: t.flatSchema ?? t.parameters ?? { type: \"object\", properties: {} },\n },\n }));\n }\n\n async dispatch(\n name: string,\n argumentsRaw: string | Record<string, unknown>,\n opts: { signal?: AbortSignal; maxResultChars?: number; maxResultTokens?: number } = {},\n ): Promise<string> {\n const tool = this._tools.get(name);\n if (!tool) {\n return JSON.stringify({ error: `unknown tool: ${name}` });\n }\n let args: Record<string, unknown>;\n try {\n args =\n typeof argumentsRaw === \"string\"\n ? argumentsRaw.trim()\n ? (JSON.parse(argumentsRaw) ?? {})\n : {}\n : (argumentsRaw ?? {});\n } catch (err) {\n return JSON.stringify({\n error: `invalid tool arguments JSON: ${(err as Error).message}`,\n });\n }\n\n // Re-nest dot-notation args back to the original shape, but only when\n // (a) we flattened this tool's schema, AND\n // (b) the incoming args actually use dot keys.\n // The second condition handles the case where a model ignores the flat\n // spec and emits nested args anyway — we shouldn't double-process them.\n if (tool.flatSchema && args && typeof args === \"object\" && hasDotKey(args)) {\n args = nestArguments(args);\n }\n\n // Plan-mode enforcement — runs AFTER arg parsing so a tool with a\n // runtime `readOnlyCheck` can inspect the actual args (e.g.\n // `run_command` is read-only iff the command matches its allowlist).\n if (this._planMode && !isReadOnlyCall(tool, args)) {\n return JSON.stringify({\n error: `${name}: unavailable in plan mode — this is a read-only exploration phase. Use read_file / list_directory / search_files / directory_tree / web_search / allowlisted shell commands to investigate. Call submit_plan with your proposed plan when you're ready for the user's review.`,\n });\n }\n\n try {\n const result = await tool.fn(args, { signal: opts.signal });\n const str = typeof result === \"string\" ? result : JSON.stringify(result);\n // Pre-clip at dispatch so a single fat result can't balloon the\n // log (and disk session file) on its way in. Healing at load time\n // still catches pre-existing oversize entries; this closes the\n // door on new ones.\n //\n // Two caps available: `maxResultTokens` (preferred — bounds the\n // real context footprint, so CJK doesn't slip past at 2× density)\n // and `maxResultChars` (legacy). If both are set, apply both and\n // the tighter one wins; char-only callers keep their old behavior.\n let clipped = str;\n if (opts.maxResultTokens !== undefined) {\n clipped = truncateForModelByTokens(clipped, opts.maxResultTokens);\n }\n if (opts.maxResultChars !== undefined) {\n clipped = truncateForModel(clipped, opts.maxResultChars);\n }\n return clipped;\n } catch (err) {\n const e = err as Error & { toToolResult?: () => unknown };\n // Errors may opt into a richer tool-result shape by implementing\n // `toToolResult()`. Used by `PlanProposedError` to smuggle the\n // submitted plan text out to the UI without stuffing it into the\n // error message (which the dispatcher truncates at no fixed limit,\n // but keeping payloads structured is cleaner for UI parsing).\n if (typeof e.toToolResult === \"function\") {\n try {\n return JSON.stringify(e.toToolResult());\n } catch {\n /* fall through to the default shape */\n }\n }\n return JSON.stringify({\n error: `${e.name}: ${e.message}`,\n });\n }\n }\n}\n\nfunction isReadOnlyCall(tool: InternalTool, args: Record<string, unknown>): boolean {\n if (tool.readOnlyCheck) {\n try {\n return Boolean(tool.readOnlyCheck(args as never));\n } catch {\n return false;\n }\n }\n return tool.readOnly === true;\n}\n\nfunction hasDotKey(obj: Record<string, unknown>): boolean {\n for (const k of Object.keys(obj)) {\n if (k.includes(\".\")) return true;\n }\n return false;\n}\n","/**\n * Bridge: register an MCP server's tools into a Reasonix ToolRegistry.\n *\n * This is the integration surface. Once done, `CacheFirstLoop` sees the\n * MCP tools as if they were native — they inherit Cache-First + repair\n * (scavenge / truncation / storm) automatically. That's the payoff: any\n * MCP ecosystem tool, wrapped in Reasonix's Pillar 1 + Pillar 3 benefits.\n */\n\nimport { countTokens } from \"../tokenizer.js\";\nimport { ToolRegistry } from \"../tools.js\";\nimport type { JSONSchema } from \"../types.js\";\nimport type { McpClient } from \"./client.js\";\nimport type { CallToolResult, McpContentBlock } from \"./types.js\";\n\nexport interface BridgeOptions {\n /**\n * Prefix prepended to every MCP tool name when registered. Defaults to\n * empty (no prefix). Useful when bridging multiple servers into one\n * registry and names collide — e.g. `fs` + `gh` both exposing `search`.\n */\n namePrefix?: string;\n /** Registry to populate. Creates a fresh one if omitted. */\n registry?: ToolRegistry;\n /** Auto-flatten deep schemas (Pillar 3). Defaults to the registry's own default (true). */\n autoFlatten?: boolean;\n /**\n * Per-tool-call result cap, in characters. If a tool returns more than\n * this, the result is truncated and a `[…truncated N chars…]` marker is\n * appended before the last KB so the model still sees a useful tail.\n * Defaults to {@link DEFAULT_MAX_RESULT_CHARS}.\n *\n * Why this exists: DeepSeek V3's context is 131,072 tokens. A single\n * `read_file` against a big source file can return >3 MB of text\n * (~900k tokens) and permanently poison the session — every subsequent\n * turn rebuilds the history and 400s. This cap is a floor. Users who\n * legitimately want bigger payloads can raise it explicitly.\n */\n maxResultChars?: number;\n /**\n * Callback fired for every `notifications/progress` frame the server\n * emits during any bridged tool call. Includes the registered\n * (prefix-applied) tool name so a multi-server UI can attribute\n * progress correctly. Absent → no `_meta.progressToken` is sent and\n * the server won't emit progress for these calls.\n */\n onProgress?: (info: {\n toolName: string;\n progress: number;\n total?: number;\n message?: string;\n }) => void;\n}\n\n/**\n * 32,000 chars ≈ 8k English tokens, or ~16k CJK tokens. Small enough to\n * fit comfortably in history even across 5–10 tool calls, large enough\n * that most file reads and directory listings fit un-truncated.\n */\nexport const DEFAULT_MAX_RESULT_CHARS = 32_000;\n\n/**\n * Token-aware cap for tool results, in DeepSeek V3 tokens.\n *\n * 8,000 tokens ≈ 6% of DeepSeek V3's 131K context. One oversized tool\n * result can't eat more than that no matter what character density the\n * content has. The char cap (32K chars) only bounds tokens for English\n * — CJK text at 1 char/token blows past 16K tokens under the same\n * ceiling. With the tokenizer shipped in 0.5.0 we can cap the thing\n * that actually matters.\n */\nexport const DEFAULT_MAX_RESULT_TOKENS = 8_000;\n\nexport interface BridgeResult {\n registry: ToolRegistry;\n /** Names actually registered (may differ from MCP names when a prefix is applied). */\n registeredNames: string[];\n /** Names the server listed but the bridge skipped (e.g. invalid schemas). */\n skipped: Array<{ name: string; reason: string }>;\n}\n\n/**\n * Walk a connected `McpClient`'s tools/list result, register each into a\n * Reasonix `ToolRegistry`. Each registered `fn` proxies through the\n * client's tools/call. Tool results are flattened into a string (joining\n * text blocks with newlines, prefixing image blocks as placeholders) so\n * they fit Reasonix's existing tool-dispatch contract.\n */\nexport async function bridgeMcpTools(\n client: McpClient,\n opts: BridgeOptions = {},\n): Promise<BridgeResult> {\n const registry = opts.registry ?? new ToolRegistry({ autoFlatten: opts.autoFlatten });\n const prefix = opts.namePrefix ?? \"\";\n const maxResultChars = opts.maxResultChars ?? DEFAULT_MAX_RESULT_CHARS;\n const result: BridgeResult = { registry, registeredNames: [], skipped: [] };\n\n const listed = await client.listTools();\n for (const mcpTool of listed.tools) {\n if (!mcpTool.name) {\n result.skipped.push({ name: \"?\", reason: \"empty tool name\" });\n continue;\n }\n const registeredName = `${prefix}${mcpTool.name}`;\n registry.register({\n name: registeredName,\n description: mcpTool.description ?? \"\",\n parameters: mcpTool.inputSchema as JSONSchema,\n fn: async (args: Record<string, unknown>, ctx) => {\n const toolResult = await client.callTool(mcpTool.name, args, {\n // Forward server-side progress frames to the bridge caller,\n // tagged with the registered name so multi-server UIs can\n // disambiguate. No-op when `onProgress` isn't configured —\n // the client then also omits the _meta.progressToken and\n // the server won't emit progress.\n onProgress: opts.onProgress\n ? (info) => opts.onProgress!({ toolName: registeredName, ...info })\n : undefined,\n // Thread the tool-dispatch AbortSignal all the way down to\n // the MCP request so Esc truly cancels in flight — the\n // client will emit notifications/cancelled AND reject the\n // pending promise immediately, no \"wait for subprocess\".\n signal: ctx?.signal,\n });\n return flattenMcpResult(toolResult, { maxChars: maxResultChars });\n },\n });\n result.registeredNames.push(registeredName);\n }\n return result;\n}\n\nexport interface FlattenOptions {\n /** Cap the flattened string at this many characters. Default: no cap. */\n maxChars?: number;\n}\n\n/**\n * Turn an MCP CallToolResult into a string — the contract Reasonix's\n * ToolRegistry.dispatch returns. We:\n * - join text blocks with newlines (most common case)\n * - stringify image blocks as placeholders (LLM can't use bytes anyway\n * in Reasonix's current surface; image support comes with multimodal\n * prompts later)\n * - prefix error results with \"ERROR: \" so the calling model sees the\n * failure clearly even through JSON mode\n * - optionally truncate to `maxChars` so a single oversized tool result\n * (e.g. a big `read_file`) can't poison the session by blowing past\n * the model's context window\n */\nexport function flattenMcpResult(result: CallToolResult, opts: FlattenOptions = {}): string {\n const parts = result.content.map(blockToString);\n const joined = parts.join(\"\\n\").trim();\n const prefixed = result.isError ? `ERROR: ${joined || \"(no error message from server)\"}` : joined;\n return opts.maxChars ? truncateForModel(prefixed, opts.maxChars) : prefixed;\n}\n\n/**\n * Keep the head AND a short tail so the model sees both \"what the tool\n * started returning\" and \"how it ended\". Head-only loses file endings\n * (e.g. an error message appended at the bottom of a stack trace); the\n * 1KB tail window covers that while costing almost nothing. Exported for\n * tests and reuse by non-MCP tool adapters that want the same policy.\n */\nexport function truncateForModel(s: string, maxChars: number): string {\n if (s.length <= maxChars) return s;\n const tailBudget = Math.min(1024, Math.floor(maxChars * 0.1));\n const headBudget = Math.max(0, maxChars - tailBudget);\n const head = s.slice(0, headBudget);\n const tail = s.slice(-tailBudget);\n const dropped = s.length - head.length - tail.length;\n return `${head}\\n\\n[…truncated ${dropped} chars — raise BridgeOptions.maxResultChars, or call the tool with a narrower scope (filter, head, pagination)…]\\n\\n${tail}`;\n}\n\n/**\n * Token-aware truncation. Same head+tail policy as `truncateForModel`,\n * but sizes the slices against a DeepSeek V3 token budget instead of a\n * raw character count — so CJK text (which previously survived at 2×\n * the token cost per char) gets capped at the same effective context\n * footprint as English.\n *\n * Strategy: fast path when `s.length <= maxTokens` (every token is ≥1\n * char, so this bounds tokens ≤ maxTokens — skip tokenize entirely).\n * Short-ish strings are confirmed against the real token count.\n * Long strings go straight to char-sliced head+tail with one or two\n * tokenize-verify-and-shrink rounds per slice — we deliberately never\n * tokenize the full input, because pathological repetitive text\n * (megabytes of `AAAA…`) can cost 30s+ on the pure-TS BPE port.\n */\nexport function truncateForModelByTokens(s: string, maxTokens: number): string {\n if (maxTokens <= 0) return \"\";\n // Every token is ≥1 char — if length ≤ budget, tokens ≤ budget.\n if (s.length <= maxTokens) return s;\n // Small enough to tokenize-check without pathological cost: confirm\n // whether we're actually over budget. (Threshold is the char-bound\n // worst case for English/code — ~4 chars/token.)\n if (s.length <= maxTokens * 4) {\n const tokens = countTokens(s);\n if (tokens <= maxTokens) return s;\n }\n\n const markerOverhead = 48; // rough token cost of the truncation marker\n const contentBudget = Math.max(0, maxTokens - markerOverhead);\n const tailBudget = Math.min(256, Math.floor(contentBudget * 0.1));\n const headBudget = Math.max(0, contentBudget - tailBudget);\n\n const head = sizePrefixToTokens(s, headBudget);\n const tail = sizeSuffixToTokens(s, tailBudget);\n const droppedChars = s.length - head.length - tail.length;\n // Estimate dropped tokens from the per-slice char/token ratio we\n // already measured, rather than paying another full-string tokenize.\n // The marker says \"~N tokens\" so the ≤10% slop is visible to readers.\n const headTokens = head ? countTokens(head) : 0;\n const tailTokens = tail ? countTokens(tail) : 0;\n const sampleChars = head.length + tail.length;\n const sampleTokens = headTokens + tailTokens;\n const ratio = sampleChars > 0 ? sampleTokens / sampleChars : 0.3;\n const estTotalTokens = Math.ceil(s.length * ratio);\n const droppedTokens = Math.max(0, estTotalTokens - sampleTokens);\n return `${head}\\n\\n[…truncated ~${droppedTokens} tokens (${droppedChars} chars) — raise BridgeOptions.maxResultTokens, or call the tool with a narrower scope (filter, head, pagination)…]\\n\\n${tail}`;\n}\n\n/**\n * Slice `s` from the start to the largest prefix that fits `budget`\n * tokens. Never tokenizes the full input: starts with a char-bound\n * estimate, then verifies and shrinks. Converges in 1–2 iterations.\n */\nfunction sizePrefixToTokens(s: string, budget: number): string {\n if (budget <= 0 || s.length === 0) return \"\";\n // Optimistic starting size: assume ~4 chars/token (English/code\n // average). If the content is denser (CJK ~1 char/token), the first\n // tokenize will show we're over and we shrink.\n let size = Math.min(s.length, budget * 4);\n for (let iter = 0; iter < 6; iter++) {\n if (size <= 0) return \"\";\n const slice = s.slice(0, size);\n const count = countTokens(slice);\n if (count <= budget) return slice;\n // Shrink by the overshoot fraction plus a small safety margin.\n const next = Math.floor(size * (budget / count) * 0.95);\n if (next >= size) return s.slice(0, Math.max(0, size - 1));\n size = next;\n }\n return s.slice(0, Math.max(0, size));\n}\n\n/** Slice `s` from the end to the largest suffix that fits `budget` tokens. */\nfunction sizeSuffixToTokens(s: string, budget: number): string {\n if (budget <= 0 || s.length === 0) return \"\";\n let size = Math.min(s.length, budget * 4);\n for (let iter = 0; iter < 6; iter++) {\n if (size <= 0) return \"\";\n const slice = s.slice(-size);\n const count = countTokens(slice);\n if (count <= budget) return slice;\n const next = Math.floor(size * (budget / count) * 0.95);\n if (next >= size) return s.slice(-Math.max(0, size - 1));\n size = next;\n }\n return s.slice(-Math.max(0, size));\n}\n\nfunction blockToString(block: McpContentBlock): string {\n if (block.type === \"text\") return block.text;\n if (block.type === \"image\") return `[image ${block.mimeType}, ${block.data.length} chars base64]`;\n // Unknown block type — preserve for diagnostics.\n return `[unknown block: ${JSON.stringify(block)}]`;\n}\n","import { createHash } from \"node:crypto\";\nimport type { ChatMessage, ToolSpec } from \"./types.js\";\n\nexport interface ImmutablePrefixOptions {\n system: string;\n toolSpecs?: readonly ToolSpec[];\n fewShots?: readonly ChatMessage[];\n}\n\nexport class ImmutablePrefix {\n readonly system: string;\n readonly toolSpecs: readonly ToolSpec[];\n readonly fewShots: readonly ChatMessage[];\n\n constructor(opts: ImmutablePrefixOptions) {\n this.system = opts.system;\n this.toolSpecs = Object.freeze([...(opts.toolSpecs ?? [])]);\n this.fewShots = Object.freeze([...(opts.fewShots ?? [])]);\n }\n\n toMessages(): ChatMessage[] {\n return [{ role: \"system\", content: this.system }, ...this.fewShots.map((m) => ({ ...m }))];\n }\n\n tools(): ToolSpec[] {\n return this.toolSpecs.map((t) => structuredClone(t) as ToolSpec);\n }\n\n get fingerprint(): string {\n const blob = JSON.stringify({\n system: this.system,\n tools: this.toolSpecs,\n shots: this.fewShots,\n });\n return createHash(\"sha256\").update(blob).digest(\"hex\").slice(0, 16);\n }\n}\n\nexport class AppendOnlyLog {\n private _entries: ChatMessage[] = [];\n\n append(message: ChatMessage): void {\n if (!message || typeof message !== \"object\" || !(\"role\" in message)) {\n throw new Error(`invalid log entry: ${JSON.stringify(message)}`);\n }\n this._entries.push(message);\n }\n\n extend(messages: ChatMessage[]): void {\n for (const m of messages) this.append(m);\n }\n\n /**\n * Bulk-replace entries. Intentionally named to be hard to reach for —\n * this is the one mutation path that breaks the log's append-only\n * spirit, reserved for compaction flows (`/compact`) and recovery\n * where the caller has consciously decided to drop old history. Any\n * other use is almost certainly wrong; append() is what you want.\n */\n compactInPlace(replacement: ChatMessage[]): void {\n this._entries = [...replacement];\n }\n\n get entries(): readonly ChatMessage[] {\n return this._entries;\n }\n\n toMessages(): ChatMessage[] {\n return this._entries.map((e) => ({ ...e }));\n }\n\n get length(): number {\n return this._entries.length;\n }\n}\n\nexport class VolatileScratch {\n reasoning: string | null = null;\n planState: Record<string, unknown> | null = null;\n notes: string[] = [];\n\n reset(): void {\n this.reasoning = null;\n this.planState = null;\n this.notes = [];\n }\n}\n","/**\n * Scavenge tool calls leaked into reasoning_content.\n *\n * R1 sometimes emits tool-call JSON inside <think>…</think> and then forgets\n * to surface it in `tool_calls`. This pass extracts plausible calls and\n * proposes them to the loop, which decides whether to merge them with the\n * declared calls.\n */\n\nimport type { ToolCall } from \"../types.js\";\n\nexport interface ScavengeOptions {\n /** Names of tools the model may legitimately call. Other names are ignored. */\n allowedNames: ReadonlySet<string>;\n /** Maximum number of calls to scavenge per pass (defence against runaway). */\n maxCalls?: number;\n}\n\nexport interface ScavengeResult {\n calls: ToolCall[];\n notes: string[];\n}\n\nexport function scavengeToolCalls(\n reasoningContent: string | null | undefined,\n opts: ScavengeOptions,\n): ScavengeResult {\n if (!reasoningContent) return { calls: [], notes: [] };\n const max = opts.maxCalls ?? 4;\n const notes: string[] = [];\n const out: ToolCall[] = [];\n\n // Pattern A: DSML invoke blocks. R1 sometimes emits tool calls as\n // its chat-template markup in the content channel instead of the\n // proper `tool_calls` field. 0.4.3 stripped these from display;\n // here we actually turn them back into proper ToolCalls so the\n // model's intent isn't lost.\n for (const invoke of iterateDsmlInvokes(reasoningContent)) {\n if (out.length >= max) break;\n if (!opts.allowedNames.has(invoke.name)) continue;\n out.push({\n function: {\n name: invoke.name,\n arguments: JSON.stringify(invoke.args),\n },\n });\n notes.push(`scavenged DSML call: ${invoke.name}`);\n }\n\n // Pattern B: raw JSON objects (the original three shapes). Strip\n // any DSML blocks we already processed so parameter JSON buried\n // inside them doesn't get re-scavenged as a standalone call.\n const nonDsml = stripDsmlBlocks(reasoningContent);\n for (const candidate of iterateJsonObjects(nonDsml)) {\n if (out.length >= max) break;\n const call = coerceToToolCall(candidate, opts.allowedNames);\n if (call) {\n out.push(call);\n notes.push(`scavenged call: ${call.function.name}`);\n }\n }\n return { calls: out, notes };\n}\n\ninterface DsmlInvoke {\n name: string;\n args: Record<string, unknown>;\n}\n\n/**\n * Yield DeepSeek DSML invoke blocks scavenged from text. R1's chat\n * template uses these when the server-side tool-call serializer\n * misfires — we see them verbatim in the content channel:\n *\n * <|DSML|function_calls>\n * <|DSML|invoke name=\"filesystem_edit_file\">\n * <|DSML|parameter name=\"path\" string=\"true\">F:/x.html</|DSML|parameter>\n * <|DSML|parameter name=\"edits\" string=\"false\">[…]</|DSML|parameter>\n * </|DSML|invoke>\n * </|DSML|function_calls>\n *\n * The wrapper class (| U+FF5C vs ASCII |) varies by model build, so\n * we accept both. `string=\"true\"` means the parameter value is a\n * literal string; `string=\"false\"` means it's JSON.\n */\n/**\n * Remove DSML invoke/function_calls blocks from text so the raw-JSON\n * scanner below doesn't see parameter payloads as standalone calls.\n * Mirrors the strip pass in `stripHallucinatedToolMarkup` but scoped\n * to scavenge (we also want the `function_calls` wrapper gone —\n * nothing useful to scavenge there).\n */\nfunction stripDsmlBlocks(text: string): string {\n let out = text;\n out = out.replace(/<[||]DSML[||]function_calls>[\\s\\S]*?<\\/?[||]DSML[||]function_calls>/g, \"\");\n out = out.replace(/<[||]DSML[||]invoke\\s+[^>]*>[\\s\\S]*?<\\/[||]DSML[||]invoke>/g, \"\");\n return out;\n}\n\nfunction* iterateDsmlInvokes(text: string): Generator<DsmlInvoke> {\n // `|` (U+FF5C) in practice; `|` (ASCII) as a fallback seen in a\n // minority of builds. `[||]` inside the regex covers both.\n const INVOKE_RE = /<[||]DSML[||]invoke\\s+name=\"([^\"]+)\">([\\s\\S]*?)<\\/[||]DSML[||]invoke>/g;\n for (const match of text.matchAll(INVOKE_RE)) {\n const name = match[1];\n const body = match[2];\n if (!name || body === undefined) continue;\n yield { name, args: parseDsmlParameters(body) };\n }\n}\n\n/**\n * Parse the parameter children of a DSML invoke body into a plain\n * object. We tolerate:\n * - `string=\"true\"` → literal text; whitespace trimmed at the edges.\n * - `string=\"false\"` → JSON-parsed; falls back to literal text if the\n * payload turns out to be malformed (better to hand a string\n * through than lose the parameter entirely).\n * - no `string=\"…\"` attribute → treat as literal text (older/shorter\n * DSML shapes we haven't formally seen but want to handle).\n */\nfunction parseDsmlParameters(body: string): Record<string, unknown> {\n const PARAM_RE =\n /<[||]DSML[||]parameter\\s+name=\"([^\"]+)\"(?:\\s+string=\"(true|false)\")?\\s*>([\\s\\S]*?)<\\/[||]DSML[||]parameter>/g;\n const args: Record<string, unknown> = {};\n for (const m of body.matchAll(PARAM_RE)) {\n const key = m[1];\n const stringFlag = m[2];\n const raw = (m[3] ?? \"\").trim();\n if (!key) continue;\n if (stringFlag === \"false\") {\n try {\n args[key] = JSON.parse(raw);\n continue;\n } catch {\n // Fall through — keep as literal so the information isn't lost.\n }\n }\n args[key] = raw;\n }\n return args;\n}\n\n/** Yield every top-level JSON object substring in `text`. */\nfunction* iterateJsonObjects(text: string): Generator<string> {\n for (let i = 0; i < text.length; i++) {\n if (text[i] !== \"{\") continue;\n let depth = 0;\n let inString = false;\n let escaped = false;\n for (let j = i; j < text.length; j++) {\n const c = text[j]!;\n if (escaped) {\n escaped = false;\n continue;\n }\n if (inString) {\n if (c === \"\\\\\") {\n escaped = true;\n continue;\n }\n if (c === '\"') inString = false;\n continue;\n }\n if (c === '\"') inString = true;\n else if (c === \"{\") depth++;\n else if (c === \"}\") {\n depth--;\n if (depth === 0) {\n yield text.slice(i, j + 1);\n i = j;\n break;\n }\n }\n }\n }\n}\n\nfunction coerceToToolCall(\n candidateJson: string,\n allowedNames: ReadonlySet<string>,\n): ToolCall | null {\n let parsed: any;\n try {\n parsed = JSON.parse(candidateJson);\n } catch {\n return null;\n }\n if (!parsed || typeof parsed !== \"object\") return null;\n\n // Pattern 1: { name, arguments }\n if (typeof parsed.name === \"string\" && allowedNames.has(parsed.name)) {\n const args = parsed.arguments;\n return {\n function: {\n name: parsed.name,\n arguments: typeof args === \"string\" ? args : JSON.stringify(args ?? {}),\n },\n };\n }\n\n // Pattern 2: OpenAI-style { type: \"function\", function: { name, arguments } }\n if (\n parsed.type === \"function\" &&\n parsed.function &&\n typeof parsed.function.name === \"string\" &&\n allowedNames.has(parsed.function.name)\n ) {\n const args = parsed.function.arguments;\n return {\n type: \"function\",\n function: {\n name: parsed.function.name,\n arguments: typeof args === \"string\" ? args : JSON.stringify(args ?? {}),\n },\n };\n }\n\n // Pattern 3: { tool_name, tool_args } (R1 free-form variant)\n if (typeof parsed.tool_name === \"string\" && allowedNames.has(parsed.tool_name)) {\n return {\n function: {\n name: parsed.tool_name,\n arguments: JSON.stringify(parsed.tool_args ?? {}),\n },\n };\n }\n\n return null;\n}\n","import type { ToolCall } from \"../types.js\";\n\n/**\n * Call-storm breaker.\n *\n * Detects (tool, args) tuples repeating within a sliding window and suppresses\n * the offending call. Surfaces a synthetic tool_result advising the model to\n * change strategy on its next turn.\n */\nexport class StormBreaker {\n private readonly windowSize: number;\n private readonly threshold: number;\n private readonly recent: Array<readonly [string, string]> = [];\n\n constructor(windowSize = 6, threshold = 3) {\n this.windowSize = windowSize;\n this.threshold = threshold;\n }\n\n inspect(call: ToolCall): { suppress: boolean; reason?: string } {\n const sig = signature(call);\n if (!sig) return { suppress: false };\n const count = this.recent.reduce(\n (n, [name, args]) => (name === sig[0] && args === sig[1] ? n + 1 : n),\n 0,\n );\n if (count >= this.threshold - 1) {\n return {\n suppress: true,\n reason: `call-storm suppressed: ${sig[0]} called with identical args ${count + 1} times within window=${this.windowSize}`,\n };\n }\n this.recent.push(sig);\n while (this.recent.length > this.windowSize) this.recent.shift();\n return { suppress: false };\n }\n\n reset(): void {\n this.recent.length = 0;\n }\n}\n\nfunction signature(call: ToolCall): readonly [string, string] | null {\n const name = call.function?.name;\n if (!name) return null;\n return [name, call.function?.arguments ?? \"\"] as const;\n}\n","/**\n * Truncation recovery for tool-call argument JSON cut off mid-structure\n * (typically when the model hits max_tokens before finishing the JSON object).\n *\n * Strategy is purely local: balance braces, close strings, fill missing values\n * with `null`. We deliberately do NOT make a continuation API call here — that\n * decision belongs to the loop, which knows about budgets.\n */\n\nexport interface TruncationRepairResult {\n repaired: string;\n changed: boolean;\n notes: string[];\n}\n\nexport function repairTruncatedJson(input: string): TruncationRepairResult {\n const notes: string[] = [];\n if (!input || !input.trim()) {\n return { repaired: \"{}\", changed: input !== \"{}\", notes: [\"empty input → {}\"] };\n }\n // Fast path: already parseable.\n try {\n JSON.parse(input);\n return { repaired: input, changed: false, notes: [] };\n } catch {\n /* fall through */\n }\n\n const stack: (\"{\" | \"[\" | '\"')[] = [];\n let escaped = false;\n let inString = false;\n let lastSignificant = -1;\n\n for (let i = 0; i < input.length; i++) {\n const c = input[i]!;\n if (!/\\s/.test(c)) lastSignificant = i;\n if (escaped) {\n escaped = false;\n continue;\n }\n if (inString) {\n if (c === \"\\\\\") {\n escaped = true;\n continue;\n }\n if (c === '\"') {\n inString = false;\n stack.pop();\n }\n continue;\n }\n if (c === '\"') {\n inString = true;\n stack.push('\"');\n continue;\n }\n if (c === \"{\" || c === \"[\") stack.push(c);\n else if (c === \"}\" || c === \"]\") stack.pop();\n }\n\n let s = input.slice(0, lastSignificant + 1);\n\n // Trim a trailing comma which would block re-parse.\n if (/,$/.test(s)) {\n s = s.replace(/,$/, \"\");\n notes.push(\"trimmed trailing comma\");\n }\n\n // If we ended on a key without a value: \"foo\": → \"foo\": null\n if (/\"\\s*:\\s*$/.test(s)) {\n s += \" null\";\n notes.push(\"filled dangling key with null\");\n }\n\n // If we ended inside a string, close it.\n if (inString) {\n s += '\"';\n stack.pop();\n notes.push(\"closed unterminated string\");\n }\n\n // Pop remaining open structures in reverse order.\n while (stack.length > 0) {\n const top = stack.pop();\n if (top === \"{\") s += \"}\";\n else if (top === \"[\") s += \"]\";\n else if (top === '\"') s += '\"';\n }\n\n try {\n JSON.parse(s);\n return { repaired: s, changed: true, notes };\n } catch (err) {\n notes.push(`fallback to {}: ${(err as Error).message}`);\n return { repaired: \"{}\", changed: true, notes };\n }\n}\n","/**\n * Pillar 3 — Tool-Call Repair pipeline.\n *\n * Order of passes per turn:\n * 1. scavenge — recover tool calls leaked into <think>\n * 2. truncation — close any half-emitted argument JSON\n * 3. storm breaker — drop call-storm repeats\n *\n * Schema flattening is applied during loop construction (it changes what we\n * advertise to the model), not per-turn.\n */\n\nimport type { ToolCall } from \"../types.js\";\nimport { scavengeToolCalls } from \"./scavenge.js\";\nimport { StormBreaker } from \"./storm.js\";\nimport { repairTruncatedJson } from \"./truncation.js\";\n\nexport { analyzeSchema, flattenSchema, nestArguments } from \"./flatten.js\";\nexport type { FlattenDecision } from \"./flatten.js\";\nexport { repairTruncatedJson } from \"./truncation.js\";\nexport type { TruncationRepairResult } from \"./truncation.js\";\nexport { scavengeToolCalls } from \"./scavenge.js\";\nexport type { ScavengeOptions, ScavengeResult } from \"./scavenge.js\";\nexport { StormBreaker } from \"./storm.js\";\n\nexport interface RepairReport {\n scavenged: number;\n truncationsFixed: number;\n stormsBroken: number;\n notes: string[];\n}\n\nexport interface ToolCallRepairOptions {\n allowedToolNames: ReadonlySet<string>;\n stormWindow?: number;\n stormThreshold?: number;\n maxScavenge?: number;\n}\n\nexport class ToolCallRepair {\n private readonly storm: StormBreaker;\n private readonly opts: ToolCallRepairOptions;\n\n constructor(opts: ToolCallRepairOptions) {\n this.opts = opts;\n this.storm = new StormBreaker(opts.stormWindow ?? 6, opts.stormThreshold ?? 3);\n }\n\n /**\n * Drop the StormBreaker's sliding window of recent (name, args)\n * signatures. Called at the start of every user turn — a fresh user\n * message is a new intent, so carrying old repetition state into it\n * would turn a valid \"try again with different input\" flow into a\n * false-positive block.\n */\n resetStorm(): void {\n this.storm.reset();\n }\n\n process(\n declaredCalls: ToolCall[],\n reasoningContent: string | null,\n content: string | null = null,\n ): { calls: ToolCall[]; report: RepairReport } {\n const report: RepairReport = {\n scavenged: 0,\n truncationsFixed: 0,\n stormsBroken: 0,\n notes: [],\n };\n\n // 1. Scavenge — only add calls whose (name,args) signature is novel.\n // Scan both channels: reasoning (where R1 leaks JSON calls into\n // <think>) AND content (where it emits DSML markup in regular\n // turns). Joined with a newline so the scanners see the blobs as\n // independent bodies. Dedup below keeps us from inflating if the\n // same call shows up in both — first seen wins.\n const combined = [reasoningContent ?? \"\", content ?? \"\"].filter(Boolean).join(\"\\n\");\n const scavenged = scavengeToolCalls(combined || null, {\n allowedNames: this.opts.allowedToolNames,\n maxCalls: this.opts.maxScavenge ?? 4,\n });\n const seenSignatures = new Set(declaredCalls.map(signature));\n const merged = [...declaredCalls];\n for (const sc of scavenged.calls) {\n if (!seenSignatures.has(signature(sc))) {\n merged.push(sc);\n report.scavenged++;\n seenSignatures.add(signature(sc));\n }\n }\n report.notes.push(...scavenged.notes);\n\n // 2. Truncation repair on argument JSON.\n for (const call of merged) {\n const args = call.function?.arguments ?? \"\";\n const r = repairTruncatedJson(args);\n if (r.changed) {\n call.function.arguments = r.repaired;\n report.truncationsFixed++;\n report.notes.push(...r.notes.map((n) => `[${call.function.name}] ${n}`));\n }\n }\n\n // 3. Storm breaker.\n const filtered: ToolCall[] = [];\n for (const call of merged) {\n const verdict = this.storm.inspect(call);\n if (verdict.suppress) {\n report.stormsBroken++;\n if (verdict.reason) report.notes.push(verdict.reason);\n continue;\n }\n filtered.push(call);\n }\n\n return { calls: filtered, report };\n }\n}\n\nfunction signature(call: ToolCall): string {\n return `${call.function?.name ?? \"\"}::${call.function?.arguments ?? \"\"}`;\n}\n","/**\n * Session persistence.\n *\n * Every turn's log entries (user / assistant / tool messages) are appended to\n * a JSONL file under `~/.reasonix/sessions/<name>.jsonl`. Next time the user\n * starts the CLI with the same session name, the loop pre-loads the file\n * into its AppendOnlyLog so the new turn has full prior context.\n *\n * Design notes:\n * - JSONL rather than JSON so concurrent writes don't corrupt.\n * - 0600 permissions on Unix (chmod no-ops on Windows).\n * - Name sanitization keeps paths safe: only [\\w-] and CJK letters pass;\n * anything else is replaced with underscore, max 64 chars.\n * - The loop's stats/session aren't persisted — only the message log.\n * Cost accounting resets each run (by design — old costs are sunk).\n */\n\nimport {\n appendFileSync,\n chmodSync,\n existsSync,\n mkdirSync,\n readFileSync,\n readdirSync,\n statSync,\n unlinkSync,\n writeFileSync,\n} from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport type { ChatMessage } from \"./types.js\";\n\nexport interface SessionInfo {\n name: string;\n path: string;\n size: number;\n messageCount: number;\n mtime: Date;\n}\n\nexport function sessionsDir(): string {\n return join(homedir(), \".reasonix\", \"sessions\");\n}\n\nexport function sessionPath(name: string): string {\n return join(sessionsDir(), `${sanitizeName(name)}.jsonl`);\n}\n\nexport function sanitizeName(name: string): string {\n const cleaned = name.replace(/[^\\w\\-\\u4e00-\\u9fa5]/g, \"_\").slice(0, 64);\n return cleaned || \"default\";\n}\n\nexport function loadSessionMessages(name: string): ChatMessage[] {\n const path = sessionPath(name);\n if (!existsSync(path)) return [];\n try {\n const raw = readFileSync(path, \"utf8\");\n const out: ChatMessage[] = [];\n for (const line of raw.split(/\\r?\\n/)) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n try {\n const msg = JSON.parse(trimmed) as ChatMessage;\n if (msg && typeof msg === \"object\" && \"role\" in msg) out.push(msg);\n } catch {\n /* skip malformed line */\n }\n }\n return out;\n } catch {\n return [];\n }\n}\n\nexport function appendSessionMessage(name: string, message: ChatMessage): void {\n const path = sessionPath(name);\n mkdirSync(dirname(path), { recursive: true });\n appendFileSync(path, `${JSON.stringify(message)}\\n`, \"utf8\");\n try {\n chmodSync(path, 0o600);\n } catch {\n /* chmod not supported on this platform */\n }\n}\n\nexport function listSessions(): SessionInfo[] {\n const dir = sessionsDir();\n if (!existsSync(dir)) return [];\n try {\n const files = readdirSync(dir).filter((f) => f.endsWith(\".jsonl\"));\n return files\n .map((file) => {\n const path = join(dir, file);\n const stat = statSync(path);\n const name = file.replace(/\\.jsonl$/, \"\");\n const messageCount = countLines(path);\n return { name, path, size: stat.size, messageCount, mtime: stat.mtime };\n })\n .sort((a, b) => b.mtime.getTime() - a.mtime.getTime());\n } catch {\n return [];\n }\n}\n\nexport function deleteSession(name: string): boolean {\n const path = sessionPath(name);\n try {\n unlinkSync(path);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Overwrite the session file with a fresh message list. Used by\n * `/compact` so the compacted in-memory log persists across restarts\n * instead of being re-healed from a huge on-disk file every launch.\n * We accept the brief non-atomic window between truncate and write —\n * worst case: a concurrent crash loses the session, which is what\n * `/forget` would have done anyway.\n */\nexport function rewriteSession(name: string, messages: ChatMessage[]): void {\n const path = sessionPath(name);\n mkdirSync(dirname(path), { recursive: true });\n const body = messages.map((m) => JSON.stringify(m)).join(\"\\n\");\n writeFileSync(path, body ? `${body}\\n` : \"\", \"utf8\");\n try {\n chmodSync(path, 0o600);\n } catch {\n /* chmod not supported */\n }\n}\n\nfunction countLines(path: string): number {\n try {\n const raw = readFileSync(path, \"utf8\");\n return raw.split(/\\r?\\n/).filter((l) => l.trim()).length;\n } catch {\n return 0;\n }\n}\n","import type { Usage } from \"./client.js\";\n\n/**\n * USD per 1M tokens. Source of truth is DeepSeek's CNY price sheet at\n * https://api-docs.deepseek.com/zh-cn/quick_start/pricing (as of\n * 2026-04-23): chat and reasoner are unified at ¥0.2 / ¥2 / ¥3 per 1M\n * tokens (cache-hit input / cache-miss input / output). Converted at\n * a fixed 7.2 CNY/USD rate so stats stay stable across the daily FX\n * drift; revisit if the rate moves more than ±5%.\n *\n * Historical note: the pre-unification prices were chat $0.07/$0.27/$1.10\n * and reasoner $0.14/$0.55/$2.19. Sessions logged under those values\n * in `~/.reasonix/usage.jsonl` remain as-is (USD frozen at record time)\n * — we never retroactively rewrite billing history.\n */\nexport const DEEPSEEK_PRICING: Record<\n string,\n { inputCacheHit: number; inputCacheMiss: number; output: number }\n> = {\n \"deepseek-chat\": { inputCacheHit: 0.028, inputCacheMiss: 0.28, output: 0.42 },\n \"deepseek-reasoner\": { inputCacheHit: 0.028, inputCacheMiss: 0.28, output: 0.42 },\n};\n\n/** Reference Claude Sonnet 4.6 pricing (USD per 1M tokens). */\nexport const CLAUDE_SONNET_PRICING = { input: 3.0, output: 15.0 };\n\n/**\n * Maximum prompt-side context window per DeepSeek model, in tokens.\n * Both V3 (`deepseek-chat`) and R1 (`deepseek-reasoner`) currently expose\n * a 131,072-token prompt limit per the OpenAPI spec; completion caps\n * differ but don't affect the prompt budget the StatsPanel shows.\n */\nexport const DEEPSEEK_CONTEXT_TOKENS: Record<string, number> = {\n \"deepseek-chat\": 131_072,\n \"deepseek-reasoner\": 131_072,\n};\n\n/** Fallback when the caller's model id isn't in the table — safe lower bound. */\nexport const DEFAULT_CONTEXT_TOKENS = 131_072;\n\nexport function costUsd(model: string, usage: Usage): number {\n const p = DEEPSEEK_PRICING[model];\n if (!p) return 0;\n return (\n (usage.promptCacheHitTokens * p.inputCacheHit +\n usage.promptCacheMissTokens * p.inputCacheMiss +\n usage.completionTokens * p.output) /\n 1_000_000\n );\n}\n\n/** Input-side cost only (prompt, cache hit + miss). Used for the panel breakdown. */\nexport function inputCostUsd(model: string, usage: Usage): number {\n const p = DEEPSEEK_PRICING[model];\n if (!p) return 0;\n return (\n (usage.promptCacheHitTokens * p.inputCacheHit +\n usage.promptCacheMissTokens * p.inputCacheMiss) /\n 1_000_000\n );\n}\n\n/** Output-side cost only (completion tokens). Used for the panel breakdown. */\nexport function outputCostUsd(model: string, usage: Usage): number {\n const p = DEEPSEEK_PRICING[model];\n if (!p) return 0;\n return (usage.completionTokens * p.output) / 1_000_000;\n}\n\nexport function claudeEquivalentCost(usage: Usage): number {\n return (\n (usage.promptTokens * CLAUDE_SONNET_PRICING.input +\n usage.completionTokens * CLAUDE_SONNET_PRICING.output) /\n 1_000_000\n );\n}\n\nexport interface TurnStats {\n turn: number;\n model: string;\n usage: Usage;\n cost: number;\n cacheHitRatio: number;\n}\n\nexport interface SessionSummary {\n turns: number;\n totalCostUsd: number;\n /**\n * Input-side (prompt) cost aggregated across the session. Split\n * from totalCostUsd so the panel can render \"cost $X (in $Y · out\n * $Z)\" — users asked for visibility into where the spend lands.\n */\n totalInputCostUsd: number;\n /** Output-side (completion) cost aggregated across the session. */\n totalOutputCostUsd: number;\n /** @deprecated Claude reference; kept for benchmarks + replay compat, no longer surfaced in the TUI. */\n claudeEquivalentUsd: number;\n /** @deprecated. Same as claudeEquivalentUsd — synthetic ratio, not a real measurement. */\n savingsVsClaudePct: number;\n cacheHitRatio: number;\n /**\n * Most recent turn's prompt-token count. Used by the TUI's context\n * gauge: we can't know the next call's cost without making it, but\n * the last turn's prompt tokens is the floor (next call is last\n * prompt + user delta + any new tool outputs).\n */\n lastPromptTokens: number;\n}\n\nexport class SessionStats {\n readonly turns: TurnStats[] = [];\n\n record(turn: number, model: string, usage: Usage): TurnStats {\n const cost = costUsd(model, usage);\n const stats: TurnStats = {\n turn,\n model,\n usage,\n cost,\n cacheHitRatio: usage.cacheHitRatio,\n };\n this.turns.push(stats);\n return stats;\n }\n\n get totalCost(): number {\n return this.turns.reduce((sum, t) => sum + t.cost, 0);\n }\n\n get totalClaudeEquivalent(): number {\n return this.turns.reduce((sum, t) => sum + claudeEquivalentCost(t.usage), 0);\n }\n\n get savingsVsClaude(): number {\n const c = this.totalClaudeEquivalent;\n return c > 0 ? 1 - this.totalCost / c : 0;\n }\n\n get totalInputCost(): number {\n return this.turns.reduce((sum, t) => sum + inputCostUsd(t.model, t.usage), 0);\n }\n\n get totalOutputCost(): number {\n return this.turns.reduce((sum, t) => sum + outputCostUsd(t.model, t.usage), 0);\n }\n\n get aggregateCacheHitRatio(): number {\n let hit = 0;\n let miss = 0;\n for (const t of this.turns) {\n hit += t.usage.promptCacheHitTokens;\n miss += t.usage.promptCacheMissTokens;\n }\n const denom = hit + miss;\n return denom > 0 ? hit / denom : 0;\n }\n\n summary(): SessionSummary {\n const last = this.turns[this.turns.length - 1];\n return {\n turns: this.turns.length,\n totalCostUsd: round(this.totalCost, 6),\n totalInputCostUsd: round(this.totalInputCost, 6),\n totalOutputCostUsd: round(this.totalOutputCost, 6),\n claudeEquivalentUsd: round(this.totalClaudeEquivalent, 6),\n savingsVsClaudePct: round(this.savingsVsClaude * 100, 2),\n cacheHitRatio: round(this.aggregateCacheHitRatio, 4),\n lastPromptTokens: last?.usage.promptTokens ?? 0,\n };\n }\n}\n\nfunction round(n: number, digits: number): number {\n const f = 10 ** digits;\n return Math.round(n * f) / f;\n}\n","import { type DeepSeekClient, Usage } from \"./client.js\";\nimport {\n type BranchOptions,\n type BranchSample,\n aggregateBranchUsage,\n runBranches,\n} from \"./consistency.js\";\nimport { type HarvestOptions, type TypedPlanState, emptyPlanState, harvest } from \"./harvest.js\";\nimport {\n type HookOutcome,\n type HookPayload,\n type ResolvedHook,\n formatHookOutcomeMessage,\n runHooks,\n} from \"./hooks.js\";\nimport {\n DEFAULT_MAX_RESULT_CHARS,\n DEFAULT_MAX_RESULT_TOKENS,\n truncateForModel,\n truncateForModelByTokens,\n} from \"./mcp/registry.js\";\nimport { AppendOnlyLog, type ImmutablePrefix, VolatileScratch } from \"./memory.js\";\nimport { type RepairReport, ToolCallRepair } from \"./repair/index.js\";\nimport { appendSessionMessage, loadSessionMessages, rewriteSession } from \"./session.js\";\nimport {\n DEEPSEEK_CONTEXT_TOKENS,\n DEFAULT_CONTEXT_TOKENS,\n SessionStats,\n type TurnStats,\n} from \"./telemetry.js\";\nimport { countTokens, estimateRequestTokens } from \"./tokenizer.js\";\nimport { ToolRegistry } from \"./tools.js\";\nimport type { ChatMessage, ToolCall } from \"./types.js\";\n\nexport type EventRole =\n | \"assistant_delta\"\n | \"assistant_final\"\n /**\n * Emitted as `tool_calls[].function.arguments` streams in. A tool\n * call with a large arguments payload produces no `content` or\n * `reasoning_content` bytes — this is the only signal the UI has\n * that the stream is alive during that window.\n */\n | \"tool_call_delta\"\n /**\n * Yielded immediately before a tool is dispatched. Lets the TUI put\n * up a \"▸ tool<X> running…\" spinner while the tool's Promise is\n * pending — otherwise the UI looks frozen whenever a tool call\n * takes more than a few hundred ms (a big `filesystem_edit_file`\n * is a typical trigger).\n */\n | \"tool_start\"\n | \"tool\"\n | \"done\"\n | \"error\"\n | \"warning\"\n /**\n * Transient \"what's happening right now\" indicator. Emitted during\n * silent phases — between a tool result and the next iteration's\n * first streaming byte, and right before harvest — so the TUI can\n * show a spinner with explanatory text instead of looking frozen.\n * The UI clears it on the next primary event (assistant_delta,\n * tool_start, tool, assistant_final, error).\n */\n | \"status\"\n | \"branch_start\"\n | \"branch_progress\"\n | \"branch_done\";\n\nexport interface BranchSummary {\n budget: number;\n chosenIndex: number;\n uncertainties: number[]; // per-sample uncertainty counts\n temperatures: number[];\n}\n\nexport interface BranchProgress {\n completed: number;\n total: number;\n latestIndex: number;\n latestTemperature: number;\n latestUncertainties: number;\n}\n\nexport interface LoopEvent {\n turn: number;\n role: EventRole;\n content: string;\n reasoningDelta?: string;\n toolName?: string;\n /**\n * Raw JSON-string arguments the model sent for a tool call (role === \"tool\").\n * Populated so transcripts can persist *why* a tool was called, not just\n * what it returned. Needed by `reasonix diff` to explain divergences.\n */\n toolArgs?: string;\n /** Cumulative arguments-string length for `role === \"tool_call_delta\"`. */\n toolCallArgsChars?: number;\n stats?: TurnStats;\n planState?: TypedPlanState;\n repair?: RepairReport;\n branch?: BranchSummary;\n branchProgress?: BranchProgress;\n error?: string;\n /**\n * True on `assistant_final` events emitted by the no-tools fallback\n * when the loop hit its budget, was aborted, or tripped the\n * token-context guard. Consumers that act on assistant text (notably\n * the code-mode edit applier) MUST treat these as display-only —\n * the model is \"wrapping up,\" not proposing new work. Applying\n * SEARCH/REPLACE blocks found in a forced summary caused the\n * \"analysis became edits\" bug in v0.4.1 and earlier.\n */\n forcedSummary?: boolean;\n}\n\nexport interface CacheFirstLoopOptions {\n client: DeepSeekClient;\n prefix: ImmutablePrefix;\n tools?: ToolRegistry;\n model?: string;\n maxToolIters?: number;\n stream?: boolean;\n /**\n * Pillar 2 — structured harvesting of R1 reasoning into a typed plan state.\n * Pass `true` for defaults or an options object. Off by default (adds a\n * cheap but non-zero V3 call per turn).\n */\n harvest?: boolean | HarvestOptions;\n /**\n * Self-consistency branching. Pass a number for just a budget (e.g. 3) or\n * a full `BranchOptions` object. Disables streaming for the branched turn\n * because all samples must complete before selection. Auto-enables harvest\n * since the default selector scores samples by plan-state uncertainty.\n */\n branch?: number | BranchOptions;\n /**\n * Session name. When set, the loop pre-loads the session's prior messages\n * into its log on construction, and appends every new log entry to\n * `~/.reasonix/sessions/<name>.jsonl` so the next run can resume.\n */\n session?: string;\n /**\n * Resolved hook list — loaded from `<project>/.reasonix/settings.json`\n * + `~/.reasonix/settings.json` by the CLI before constructing the loop.\n * The loop dispatches `PreToolUse` and `PostToolUse` events itself; the\n * CLI handles `UserPromptSubmit` and `Stop` since they live at the App\n * boundary. Empty / unset → no hooks fire (the runtime cost of an empty\n * filter is one ms). See `src/hooks.ts` for the full contract.\n */\n hooks?: ResolvedHook[];\n /**\n * `cwd` reported to hooks via the stdin payload. Defaults to `process.cwd()`.\n * `reasonix code` overrides this to the sandbox root so a hook that does\n * `cd $REASONIX_CWD` lands in the project, not in the user's shell home.\n */\n hookCwd?: string;\n}\n\n/**\n * Pillar 1 — Cache-First Loop.\n *\n * - prefix is immutable (cache target)\n * - log is append-only (preserves prior-turn prefix)\n * - scratch is per-turn volatile (never sent upstream)\n *\n * Yields a stream of events so a TUI can render progressively.\n */\nexport interface ReconfigurableOptions {\n model?: string;\n harvest?: boolean | HarvestOptions;\n branch?: number | BranchOptions;\n stream?: boolean;\n}\n\nexport class CacheFirstLoop {\n readonly client: DeepSeekClient;\n readonly prefix: ImmutablePrefix;\n readonly tools: ToolRegistry;\n readonly maxToolIters: number;\n readonly log = new AppendOnlyLog();\n readonly scratch = new VolatileScratch();\n readonly stats = new SessionStats();\n readonly repair: ToolCallRepair;\n\n // Mutable via configure() — slash commands in the TUI / library callers tweak\n // these mid-session so users don't have to restart to try harvest or branch.\n model: string;\n stream: boolean;\n harvestEnabled: boolean;\n harvestOptions: HarvestOptions;\n branchEnabled: boolean;\n branchOptions: BranchOptions;\n sessionName: string | null;\n\n /**\n * Hook list, mutable so `/hooks reload` can swap it without\n * reconstructing the loop. Default empty — the filter cost on a\n * tool call is one array length check.\n */\n hooks: ResolvedHook[];\n /** `cwd` reported to hook stdin. Resolved once at construction. */\n readonly hookCwd: string;\n\n /** Number of messages that were pre-loaded from the session file. */\n readonly resumedMessageCount: number;\n\n private _turn = 0;\n private _streamPreference: boolean;\n /**\n * AbortController per active turn. Threaded through the DeepSeek\n * HTTP calls AND every tool dispatch so Esc actually cancels the\n * in-flight network/subprocess work — not \"we'll get to it after\n * the current call finishes.\" Re-created at the start of each\n * `step()` (the prior turn's signal has already fired).\n */\n private _turnAbort: AbortController = new AbortController();\n\n constructor(opts: CacheFirstLoopOptions) {\n this.client = opts.client;\n this.prefix = opts.prefix;\n this.tools = opts.tools ?? new ToolRegistry();\n this.model = opts.model ?? \"deepseek-chat\";\n // Iter cap is a safety net, not the primary stop condition. The\n // primary stop is the token-context guard inside step(): after\n // every model response we check whether the prompt is already past\n // 80% of the model's context window, and if so divert to the\n // forced-summary path. 64 is high enough that exploration almost\n // never exhausts it before the token guard fires first — which\n // is the point: let the real constraint (context window) drive\n // the decision, keep the iter cap as a last-resort backstop for\n // the case where something spins without growing the prompt.\n this.maxToolIters = opts.maxToolIters ?? 64;\n this.hooks = opts.hooks ?? [];\n this.hookCwd = opts.hookCwd ?? process.cwd();\n\n // Resolve branch config first (since it forces harvest on).\n if (typeof opts.branch === \"number\") {\n this.branchOptions = { budget: opts.branch };\n } else if (opts.branch && typeof opts.branch === \"object\") {\n this.branchOptions = opts.branch;\n } else {\n this.branchOptions = {};\n }\n this.branchEnabled = (this.branchOptions.budget ?? 1) > 1;\n\n // Branching requires harvest for its default selector to work.\n const harvestForced = this.branchEnabled;\n this.harvestEnabled =\n harvestForced ||\n opts.harvest === true ||\n (typeof opts.harvest === \"object\" && opts.harvest !== null);\n this.harvestOptions =\n typeof opts.harvest === \"object\" && opts.harvest !== null\n ? opts.harvest\n : (this.branchOptions.harvestOptions ?? {});\n\n // Streaming is incompatible with branching (need all samples to select).\n this._streamPreference = opts.stream ?? true;\n this.stream = this.branchEnabled ? false : this._streamPreference;\n\n const allowedNames = new Set([...this.prefix.toolSpecs.map((s) => s.function.name)]);\n this.repair = new ToolCallRepair({ allowedToolNames: allowedNames });\n\n // Session resume: pre-load prior messages into the log if a session name\n // is provided. New messages appended to the log are also persisted.\n //\n // Heal-on-load: if a previous run (or a pre-alpha.6 client) stored a\n // tool result bigger than the cap, the next API call would blow past\n // DeepSeek's 131k-token limit *before the user even types anything*.\n // Truncating here lets the user pick up their session history without\n // losing the conversational context around the oversized call.\n this.sessionName = opts.session ?? null;\n if (this.sessionName) {\n const prior = loadSessionMessages(this.sessionName);\n const { messages, healedCount, healedFrom } = healLoadedMessages(\n prior,\n DEFAULT_MAX_RESULT_CHARS,\n );\n for (const msg of messages) this.log.append(msg);\n this.resumedMessageCount = messages.length;\n if (healedCount > 0) {\n // Persist the healed log back to disk so the damage doesn't\n // re-surface on the next session load — otherwise `heal →\n // append → resume → heal → …` would keep noticing the same\n // broken tail every restart. Non-fatal on I/O error: the\n // in-memory log is already healed so this session still works.\n try {\n rewriteSession(this.sessionName, messages);\n } catch {\n /* disk full / perms — skip, in-memory heal still applies */\n }\n process.stderr.write(\n `▸ session \"${this.sessionName}\": healed ${healedCount} entr${healedCount === 1 ? \"y\" : \"ies\"}${healedFrom > 0 ? ` (was ${healedFrom.toLocaleString()} chars oversized)` : \" (dropped dangling tool_calls tail)\"}. Rewrote session file.\\n`,\n );\n }\n } else {\n this.resumedMessageCount = 0;\n }\n }\n\n /**\n * Shrink the log by re-truncating oversized tool results to a tighter\n * token cap, and persist the result back to disk so the next launch\n * doesn't re-inherit a fat session file. Returns a summary the TUI\n * can display.\n *\n * The cap is in DeepSeek V3 tokens (not chars) — so CJK text gets\n * capped at the same effective context footprint as English instead\n * of slipping past a char cap at 2× the token cost. Default 4000\n * tokens, matching the token-aware dispatch cap from 0.5.2.\n *\n * Only tool-role messages are touched (same rationale as\n * {@link healLoadedMessages}). User and assistant messages carry\n * authored intent we can't mechanically shrink without losing\n * meaning.\n */\n compact(maxTokens = 4000): {\n healedCount: number;\n tokensSaved: number;\n charsSaved: number;\n } {\n const before = this.log.toMessages();\n // Use `shrinkOversizedToolResultsByTokens` (not `healLoadedMessages`)\n // — the full heal would also strip a dangling `assistant.tool_calls`\n // tail, which during an active turn is legitimate state we still\n // need (tools haven't been dispatched yet). Structural healing is\n // only appropriate at session LOAD; mid-session `/compact` is\n // strictly about shrinking oversized tool payloads.\n const { messages, healedCount, tokensSaved, charsSaved } = shrinkOversizedToolResultsByTokens(\n before,\n maxTokens,\n );\n if (healedCount > 0) {\n this.log.compactInPlace(messages);\n if (this.sessionName) {\n try {\n rewriteSession(this.sessionName, messages);\n } catch {\n /* disk full or perms — compaction still applies in-memory */\n }\n }\n }\n return { healedCount, tokensSaved, charsSaved };\n }\n\n private appendAndPersist(message: ChatMessage): void {\n this.log.append(message);\n if (this.sessionName) {\n try {\n appendSessionMessage(this.sessionName, message);\n } catch {\n /* disk full or permission denied shouldn't kill the chat */\n }\n }\n }\n\n /**\n * Start a fresh conversation WITHOUT exiting. Drops every message\n * in the in-memory log AND rewrites the session file to empty so\n * a resume won't re-hydrate the old turns. Unlike `/forget`, which\n * deletes the session entirely, this keeps the session name and\n * config intact — it's the \"new chat\" button.\n *\n * The immutable prefix (system prompt + tool specs) is preserved\n * — that's the cache-first invariant, not part of the conversation.\n * Returns the number of messages dropped so the UI can show it.\n */\n clearLog(): { dropped: number } {\n const dropped = this.log.length;\n this.log.compactInPlace([]);\n if (this.sessionName) {\n try {\n rewriteSession(this.sessionName, []);\n } catch {\n /* disk issue shouldn't block the in-memory clear */\n }\n }\n this.scratch.reset();\n return { dropped };\n }\n\n /**\n * Reconfigure model/harvest/branch/stream mid-session. The loop's log,\n * scratch, and stats are preserved — only the per-turn behavior changes.\n * Used by the TUI's slash commands and by library callers who want to\n * flip a knob between turns.\n */\n configure(opts: ReconfigurableOptions): void {\n if (opts.model !== undefined) this.model = opts.model;\n if (opts.stream !== undefined) this._streamPreference = opts.stream;\n\n if (opts.branch !== undefined) {\n if (typeof opts.branch === \"number\") {\n this.branchOptions = { budget: opts.branch };\n } else if (opts.branch && typeof opts.branch === \"object\") {\n this.branchOptions = opts.branch;\n } else {\n this.branchOptions = {};\n }\n this.branchEnabled = (this.branchOptions.budget ?? 1) > 1;\n }\n\n if (opts.harvest !== undefined) {\n const want =\n opts.harvest === true || (typeof opts.harvest === \"object\" && opts.harvest !== null);\n this.harvestEnabled = want || this.branchEnabled;\n if (typeof opts.harvest === \"object\" && opts.harvest !== null) {\n this.harvestOptions = opts.harvest;\n }\n } else if (this.branchEnabled) {\n // branch turned on without explicit harvest → force it on\n this.harvestEnabled = true;\n }\n\n // Branching always forces non-streaming; otherwise honor preference.\n this.stream = this.branchEnabled ? false : this._streamPreference;\n }\n\n private buildMessages(pendingUser: string | null): ChatMessage[] {\n // Full tool_calls ↔ tool pairing validation. DeepSeek 400s on\n // both sides of this contract — unpaired assistant.tool_calls\n // (\"insufficient tool messages following\") OR stray tool entries\n // (\"tool must be a response to a preceding tool_calls\"). A corrupted\n // session from an earlier build can have either. Rather than\n // applying a bunch of narrow tail-trim heuristics, rebuild the\n // message stream through the same validator used at load time so\n // the payload we hand to the API is well-formed by construction.\n const healed = healLoadedMessages(this.log.toMessages(), DEFAULT_MAX_RESULT_CHARS);\n const msgs: ChatMessage[] = [...this.prefix.toMessages(), ...healed.messages];\n if (pendingUser !== null) msgs.push({ role: \"user\", content: pendingUser });\n return msgs;\n }\n\n /**\n * Signal the currently-running {@link step} to stop **now**. Cancels\n * the in-flight network request (DeepSeek HTTP/SSE) AND any tool call\n * currently dispatching (MCP `notifications/cancelled` + promise\n * reject). The loop itself also sees `signal.aborted` at each\n * iteration boundary and exits quickly instead of looping again.\n * Called by the TUI on Esc.\n */\n abort(): void {\n this._turnAbort.abort();\n }\n\n /**\n * Drop everything in the log after (and including) the most recent\n * user message. Used by `/retry` so the caller can re-send that\n * message with a fresh turn instead of layering another response on\n * top of the prior exchange. Returns the content of the dropped user\n * message, or `null` if there isn't one yet.\n *\n * Persists by rewriting the session file — otherwise the next\n * launch would rehydrate the old exchange and `/retry` would seem\n * to have done nothing.\n */\n retryLastUser(): string | null {\n const entries = this.log.entries;\n let lastUserIdx = -1;\n for (let i = entries.length - 1; i >= 0; i--) {\n if (entries[i]!.role === \"user\") {\n lastUserIdx = i;\n break;\n }\n }\n if (lastUserIdx < 0) return null;\n const raw = entries[lastUserIdx]!.content;\n const userText = typeof raw === \"string\" ? raw : \"\";\n // Keep everything strictly before the user message. The caller\n // will submit the text again through the normal path, which\n // re-appends the user turn on first successful API response.\n const preserved = entries.slice(0, lastUserIdx).map((m) => ({ ...m }));\n this.log.compactInPlace(preserved);\n if (this.sessionName) {\n try {\n rewriteSession(this.sessionName, preserved);\n } catch {\n /* disk-full / perms — in-memory compaction still applies */\n }\n }\n return userText;\n }\n\n async *step(userInput: string): AsyncGenerator<LoopEvent> {\n this._turn++;\n this.scratch.reset();\n // A fresh user turn is a new intent — don't let StormBreaker's\n // old sliding window of (name, args) signatures keep blocking\n // calls that are now legitimately on-task. The window repopulates\n // naturally as this turn's tool calls flow through.\n this.repair.resetStorm();\n // Fresh controller for this turn: the prior step's signal has\n // already fired (or stayed clean); either way we don't want its\n // state to bleed into the new turn.\n this._turnAbort = new AbortController();\n const signal = this._turnAbort.signal;\n let pendingUser: string | null = userInput;\n const toolSpecs = this.prefix.tools();\n // 70% of the iter budget is the \"you're getting close\" threshold. We\n // only warn once per step so the user sees a single signal, not a\n // string of identical yellow lines stacked up.\n const warnAt = Math.max(1, Math.floor(this.maxToolIters * 0.7));\n let warnedForIterBudget = false;\n\n for (let iter = 0; iter < this.maxToolIters; iter++) {\n if (signal.aborted) {\n // Esc means \"stop now\" — not \"stop and force another 30-90s\n // reasoner call to produce a summary I didn't ask for\". The\n // user's mental model of cancel is immediate. We emit a\n // synthetic assistant_final (tagged forcedSummary so the\n // code-mode applier ignores it) with a short stopped\n // message, then done. The prior tool outputs are still in\n // the log if the user wants to continue — asking again\n // will hit a warm cache and be cheap.\n //\n // Budget / context-guard still call forceSummaryAfterIterLimit\n // because there the USER didn't choose to stop — we did —\n // and leaving them staring at nothing is worse than one extra\n // call.\n yield {\n turn: this._turn,\n role: \"warning\",\n content: `aborted at iter ${iter}/${this.maxToolIters} — stopped without producing a summary (press ↑ + Enter or /retry to resume)`,\n };\n const stoppedMsg =\n \"[aborted by user (Esc) — no summary produced. Ask again or /retry when ready; prior tool output is still in the log.]\";\n this.appendAndPersist({ role: \"assistant\", content: stoppedMsg });\n yield {\n turn: this._turn,\n role: \"assistant_final\",\n content: stoppedMsg,\n forcedSummary: true,\n };\n yield { turn: this._turn, role: \"done\", content: stoppedMsg };\n return;\n }\n // Bridge the silence between the PREVIOUS iter's tool result and\n // THIS iter's first streaming byte. R1 can spend 20-90s reasoning\n // about tool output before the first delta lands, and prior to\n // this hint the UI had nothing to render. Only emit on iter > 0\n // because iter 0's \"thinking\" phase is already covered by the\n // streaming row / StreamingAssistant's placeholder.\n //\n // Wording is explicit about the two things happening: the tool\n // result IS being uploaded (it's now part of the next prompt) and\n // the model IS thinking. Users were reading \"thinking about the\n // tool result\" as the model-only phase, but the wait also covers\n // the upload round-trip.\n if (iter > 0) {\n yield {\n turn: this._turn,\n role: \"status\",\n content: \"tool result uploaded · model thinking before next response…\",\n };\n }\n if (!warnedForIterBudget && iter >= warnAt) {\n warnedForIterBudget = true;\n yield {\n turn: this._turn,\n role: \"warning\",\n content: `${iter}/${this.maxToolIters} tool calls used — approaching budget. Press Esc to force a summary now.`,\n };\n }\n let messages = this.buildMessages(pendingUser);\n\n // Preflight context check. Reactive auto-compact at 60%/80%\n // keys off the PREVIOUS turn's server-reported prompt_tokens,\n // so a single new oversized tool result (or a fresh resumed\n // session) can push this turn's request straight past 131,072\n // tokens before we ever see a usage number — DeepSeek 400s with\n // \"maximum context length\". Here we estimate the outgoing\n // payload locally and compact preemptively when it's in the red\n // zone (>95% of the model's context window). One cheap\n // tokenize-pass per iter, only on our side.\n {\n const ctxMax = DEEPSEEK_CONTEXT_TOKENS[this.model] ?? DEFAULT_CONTEXT_TOKENS;\n const estimate = estimateRequestTokens(messages, this.prefix.toolSpecs);\n if (estimate / ctxMax > 0.95) {\n const result = this.compact(1_000);\n if (result.healedCount > 0) {\n yield {\n turn: this._turn,\n role: \"warning\",\n content: `preflight: request ~${estimate.toLocaleString()}/${ctxMax.toLocaleString()} tokens (${Math.round(\n (estimate / ctxMax) * 100,\n )}%) — pre-compacted ${result.healedCount} tool result(s), saved ${result.tokensSaved.toLocaleString()} tokens. Sending.`,\n };\n // Rebuild with the compacted log so we send the smaller payload.\n messages = this.buildMessages(pendingUser);\n } else {\n yield {\n turn: this._turn,\n role: \"warning\",\n content: `preflight: request ~${estimate.toLocaleString()}/${ctxMax.toLocaleString()} tokens (${Math.round(\n (estimate / ctxMax) * 100,\n )}%) and nothing to auto-compact — DeepSeek will likely 400. Run /forget or /clear to start fresh.`,\n };\n }\n }\n }\n\n let assistantContent = \"\";\n let reasoningContent = \"\";\n let toolCalls: ToolCall[] = [];\n let usage: TurnStats[\"usage\"] | null = null;\n\n let branchSummary: BranchSummary | undefined;\n let preHarvestedPlanState: TypedPlanState | undefined;\n\n try {\n if (this.branchEnabled) {\n const budget = this.branchOptions.budget ?? 1;\n yield {\n turn: this._turn,\n role: \"branch_start\",\n content: \"\",\n branchProgress: {\n completed: 0,\n total: budget,\n latestIndex: -1,\n latestTemperature: -1,\n latestUncertainties: -1,\n },\n };\n\n // Queue samples as they complete so we can yield progress events\n // in resolution order (not launch order).\n const queue: BranchSample[] = [];\n let waiter: ((s: BranchSample) => void) | null = null;\n\n const onSampleDone = (sample: BranchSample) => {\n if (waiter) {\n const w = waiter;\n waiter = null;\n w(sample);\n } else {\n queue.push(sample);\n }\n };\n\n const branchPromise = runBranches(\n this.client,\n {\n model: this.model,\n messages,\n tools: toolSpecs.length ? toolSpecs : undefined,\n signal,\n },\n {\n ...this.branchOptions,\n harvestOptions: this.harvestOptions,\n onSampleDone,\n },\n );\n\n for (let k = 0; k < budget; k++) {\n const sample: BranchSample =\n queue.shift() ??\n (await new Promise<BranchSample>((resolve) => {\n waiter = resolve;\n }));\n yield {\n turn: this._turn,\n role: \"branch_progress\",\n content: \"\",\n branchProgress: {\n completed: k + 1,\n total: budget,\n latestIndex: sample.index,\n latestTemperature: sample.temperature,\n latestUncertainties: sample.planState.uncertainties.length,\n },\n };\n }\n\n const result = await branchPromise;\n assistantContent = result.chosen.response.content;\n reasoningContent = result.chosen.response.reasoningContent ?? \"\";\n toolCalls = result.chosen.response.toolCalls;\n\n // Cost accounting: sum usage across ALL samples, not just the winner.\n // (We paid for all three.) Harvest-call tokens are not tracked; they\n // amount to rounding error compared to the main R1 calls.\n const agg = aggregateBranchUsage(result.samples);\n usage = new Usage(\n agg.promptTokens,\n agg.completionTokens,\n agg.totalTokens,\n agg.promptCacheHitTokens,\n agg.promptCacheMissTokens,\n );\n preHarvestedPlanState = result.chosen.planState;\n branchSummary = summarizeBranch(result.chosen, result.samples);\n yield {\n turn: this._turn,\n role: \"branch_done\",\n content: \"\",\n branch: branchSummary,\n };\n } else if (this.stream) {\n const callBuf: Map<number, ToolCall> = new Map();\n for await (const chunk of this.client.stream({\n model: this.model,\n messages,\n tools: toolSpecs.length ? toolSpecs : undefined,\n signal,\n })) {\n if (chunk.contentDelta) {\n assistantContent += chunk.contentDelta;\n yield {\n turn: this._turn,\n role: \"assistant_delta\",\n content: chunk.contentDelta,\n };\n }\n if (chunk.reasoningDelta) {\n reasoningContent += chunk.reasoningDelta;\n yield {\n turn: this._turn,\n role: \"assistant_delta\",\n content: \"\",\n reasoningDelta: chunk.reasoningDelta,\n };\n }\n if (chunk.toolCallDelta) {\n const d = chunk.toolCallDelta;\n const cur = callBuf.get(d.index) ?? {\n id: d.id,\n type: \"function\" as const,\n function: { name: \"\", arguments: \"\" },\n };\n if (d.id) cur.id = d.id;\n if (d.name) cur.function.name = (cur.function.name ?? \"\") + d.name;\n if (d.argumentsDelta)\n cur.function.arguments = (cur.function.arguments ?? \"\") + d.argumentsDelta;\n callBuf.set(d.index, cur);\n // Skip the id-only opener: name is empty until the next chunk.\n if (cur.function.name) {\n yield {\n turn: this._turn,\n role: \"tool_call_delta\",\n content: \"\",\n toolName: cur.function.name,\n toolCallArgsChars: (cur.function.arguments ?? \"\").length,\n };\n }\n }\n if (chunk.usage) usage = chunk.usage;\n }\n toolCalls = [...callBuf.values()];\n } else {\n const resp = await this.client.chat({\n model: this.model,\n messages,\n tools: toolSpecs.length ? toolSpecs : undefined,\n signal,\n });\n assistantContent = resp.content;\n reasoningContent = resp.reasoningContent ?? \"\";\n toolCalls = resp.toolCalls;\n usage = resp.usage;\n }\n } catch (err) {\n // An aborted signal here is almost always our own doing —\n // either Esc, or App.tsx calling `loop.abort()` to switch to a\n // queued synthetic input (ShellConfirm \"always allow\", PlanConfirm\n // approve, etc.). The DeepSeek client's fetch path translates\n // the abort into a generic `AbortError(\"This operation was\n // aborted\")`, which used to bubble up here and render as a\n // scary red \"error\" row even though nothing actually broke.\n // Treat it as a clean early-exit instead: the next turn (queued\n // synthetic OR user re-prompt) starts immediately and gets to\n // produce its own answer.\n if (signal.aborted) {\n yield { turn: this._turn, role: \"done\", content: \"\" };\n return;\n }\n yield {\n turn: this._turn,\n role: \"error\",\n content: \"\",\n error: formatLoopError(err as Error),\n };\n return;\n }\n\n const turnStats = this.stats.record(this._turn, this.model, usage ?? new Usage());\n\n // Commit the user turn to the log only on success of the first round-trip.\n if (pendingUser !== null) {\n this.appendAndPersist({ role: \"user\", content: pendingUser });\n pendingUser = null;\n }\n\n this.scratch.reasoning = reasoningContent || null;\n // Harvest is a second API round-trip (cheap model, but still\n // 1-10s) that was previously silent. Bridge the gap with a\n // status indicator so the TUI shows *something* instead of\n // \"reasoning finished, now staring at the wall.\"\n if (\n !preHarvestedPlanState &&\n this.harvestEnabled &&\n (reasoningContent?.trim().length ?? 0) >= 40\n ) {\n yield {\n turn: this._turn,\n role: \"status\",\n content: \"extracting plan state from reasoning…\",\n };\n }\n const planState = preHarvestedPlanState\n ? preHarvestedPlanState\n : this.harvestEnabled\n ? await harvest(reasoningContent || null, this.client, this.harvestOptions, signal)\n : emptyPlanState();\n\n const { calls: repairedCalls, report } = this.repair.process(\n toolCalls,\n reasoningContent || null,\n assistantContent || null,\n );\n\n this.appendAndPersist(this.assistantMessage(assistantContent, repairedCalls));\n\n yield {\n turn: this._turn,\n role: \"assistant_final\",\n content: assistantContent,\n stats: turnStats,\n planState,\n repair: report,\n branch: branchSummary,\n };\n\n // Loud signal when the storm breaker caught a repeat pattern.\n // The `repair` field on assistant_final already carries the\n // count as a subtext on the assistant row, but a dedicated\n // warning row is far more noticeable — and critical when ALL\n // calls were suppressed, because the turn then ends with no\n // visible explanation of why nothing happened.\n if (report.stormsBroken > 0) {\n const noteTail = report.notes.length ? ` — ${report.notes[report.notes.length - 1]}` : \"\";\n const allSuppressed = repairedCalls.length === 0 && toolCalls.length > 0;\n const phrase = allSuppressed\n ? `stopped the model from calling the same tool with identical args repeatedly (all ${toolCalls.length} call(s) this turn were already in the recent-repeat window). Likely a stuck retry — reword your instruction, rule out the underlying blocker, or try /retry after fixing it`\n : `suppressed ${report.stormsBroken} repeat tool call(s) that had fired 3+ times with identical args in a sliding window`;\n yield {\n turn: this._turn,\n role: \"warning\",\n content: `${phrase}${noteTail}`,\n };\n }\n\n if (repairedCalls.length === 0) {\n yield { turn: this._turn, role: \"done\", content: assistantContent };\n return;\n }\n\n // Token-budget guard — the real stop condition. Iter count is a\n // proxy that misses the actual constraint: how close the prompt\n // already is to DeepSeek's 131k context. If we're over 80%, the\n // NEXT call (with the just-executed tools' results stuffed into\n // history) will be worse, and fairly soon it'll 400 with\n // \"maximum context length\".\n //\n // Strategy, in order:\n // 1. Try auto-compacting the log (shrink oversized tool\n // results). If that gets us back under 80% we keep going —\n // the user doesn't lose their turn to a premature summary.\n // 2. If still over after compact, divert to the forced-summary\n // path. BUT first drop the trailing assistant-with-tool_calls\n // that we just appended — we haven't executed the tools yet,\n // so sending this to the summary call with no matching tool\n // responses would 400 (\"insufficient tool messages following\n // tool_calls\"). The summary is about what was LEARNED so far,\n // not what we intended to do next.\n const ctxMax = DEEPSEEK_CONTEXT_TOKENS[this.model] ?? DEFAULT_CONTEXT_TOKENS;\n // Proactive tier: between 60% and 80%, pre-shrink oversized tool\n // results to a moderate cap (4k tokens) so the next iter doesn't\n // slam straight into the 80% reactive path — which shrinks far\n // more aggressively (1k tokens) and risks losing useful tail\n // info. This catches the slow-growth pattern (lots of medium\n // reads) before it compounds.\n if (usage) {\n const ratio = usage.promptTokens / ctxMax;\n if (ratio > 0.6 && ratio <= 0.8) {\n const before = usage.promptTokens;\n const soft = this.compact(4_000);\n if (soft.healedCount > 0) {\n const after = Math.max(0, before - soft.tokensSaved);\n yield {\n turn: this._turn,\n role: \"warning\",\n content: `context ${before.toLocaleString()}/${ctxMax.toLocaleString()} (${Math.round(\n ratio * 100,\n )}%) — proactively compacted ${soft.healedCount} tool result(s) to 4k tokens, saved ${soft.tokensSaved.toLocaleString()} tokens (now ~${after.toLocaleString()}). Staying ahead of the 80% guard.`,\n };\n }\n }\n }\n if (usage && usage.promptTokens / ctxMax > 0.8) {\n const before = usage.promptTokens;\n const compactResult = this.compact(1_000);\n if (compactResult.healedCount > 0) {\n const after = Math.max(0, before - compactResult.tokensSaved);\n yield {\n turn: this._turn,\n role: \"warning\",\n content: `context ${before.toLocaleString()}/${ctxMax.toLocaleString()} — auto-compacted ${compactResult.healedCount} oversized tool result(s), saved ${compactResult.tokensSaved.toLocaleString()} tokens (now ~${after.toLocaleString()}). Continuing.`,\n };\n // Intentionally don't re-check the threshold here: even if\n // compaction didn't fully clear us under 80%, one more tool\n // call's overhead isn't going to overflow, and the NEXT\n // iter's fresh `usage` from the API will catch real danger.\n } else {\n yield {\n turn: this._turn,\n role: \"warning\",\n content: `context ${before.toLocaleString()}/${ctxMax.toLocaleString()} (${Math.round(\n (before / ctxMax) * 100,\n )}%) — nothing to auto-compact. Forcing summary from what was gathered.`,\n };\n // Drop the trailing assistant-with-tool_calls we just\n // appended. The forced-summary call would otherwise trip\n // DeepSeek's \"insufficient tool messages following tool_calls\"\n // validator, since we bail BEFORE dispatching the tools.\n const tail = this.log.entries[this.log.entries.length - 1];\n if (\n tail &&\n tail.role === \"assistant\" &&\n Array.isArray(tail.tool_calls) &&\n tail.tool_calls.length > 0\n ) {\n const kept = this.log.entries.slice(0, -1);\n this.log.compactInPlace([...kept]);\n if (this.sessionName) {\n try {\n rewriteSession(this.sessionName, kept);\n } catch {\n /* disk issue shouldn't block the summary path */\n }\n }\n }\n yield* this.forceSummaryAfterIterLimit({ reason: \"context-guard\" });\n return;\n }\n }\n\n for (const call of repairedCalls) {\n const name = call.function?.name ?? \"\";\n const args = call.function?.arguments ?? \"{}\";\n // Announce the tool BEFORE awaiting it so the TUI can render a\n // \"running…\" indicator. Without this, the window between\n // assistant_final and the tool-result yield is silent from the\n // UI's perspective — which makes long tool calls feel like the\n // app has hung.\n yield {\n turn: this._turn,\n role: \"tool_start\",\n content: \"\",\n toolName: name,\n toolArgs: args,\n };\n\n // PreToolUse hooks. A `block` decision (exit 2) skips dispatch\n // and surfaces the hook's stderr as the tool result so the model\n // sees a structured refusal instead of a silent omission. Non-\n // block non-zero outcomes are warnings: the loop continues, the\n // UI gets a yellow row.\n const parsedArgs = safeParseToolArgs(args);\n const preReport = await runHooks({\n hooks: this.hooks,\n payload: {\n event: \"PreToolUse\",\n cwd: this.hookCwd,\n toolName: name,\n toolArgs: parsedArgs,\n },\n });\n for (const w of hookWarnings(preReport.outcomes, this._turn)) yield w;\n\n let result: string;\n if (preReport.blocked) {\n const blocking = preReport.outcomes[preReport.outcomes.length - 1];\n const reason = (\n blocking?.stderr ||\n blocking?.stdout ||\n \"blocked by PreToolUse hook\"\n ).trim();\n result = `[hook block] ${blocking?.hook.command ?? \"<unknown>\"}\\n${reason}`;\n } else {\n result = await this.tools.dispatch(name, args, {\n signal,\n maxResultTokens: DEFAULT_MAX_RESULT_TOKENS,\n });\n\n // PostToolUse hooks — block is meaningless after the fact, so\n // every non-pass outcome is a warning. Hooks here are the\n // natural place for \"after every edit, run the formatter.\"\n const postReport = await runHooks({\n hooks: this.hooks,\n payload: {\n event: \"PostToolUse\",\n cwd: this.hookCwd,\n toolName: name,\n toolArgs: parsedArgs,\n toolResult: result,\n },\n });\n for (const w of hookWarnings(postReport.outcomes, this._turn)) yield w;\n }\n\n this.appendAndPersist({\n role: \"tool\",\n tool_call_id: call.id ?? \"\",\n name,\n content: result,\n });\n yield {\n turn: this._turn,\n role: \"tool\",\n content: result,\n toolName: name,\n toolArgs: args,\n };\n }\n }\n\n // We exhausted the tool-call budget while the model still wanted to\n // call more tools. Rather than stopping silently (which leaves the\n // user staring at a blank prompt), force one final no-tools call so\n // the model must produce a text summary from everything it has\n // already seen.\n yield* this.forceSummaryAfterIterLimit({ reason: \"budget\" });\n }\n\n private async *forceSummaryAfterIterLimit(\n opts: { reason: \"budget\" | \"aborted\" | \"context-guard\" } = { reason: \"budget\" },\n ): AsyncGenerator<LoopEvent> {\n try {\n // The summary call is non-streaming (reasoner, 30-60s typical).\n // Without this status the user sees nothing happening after the\n // yellow \"budget reached\" warning until the summary arrives.\n yield {\n turn: this._turn,\n role: \"status\",\n content: \"summarizing what was gathered…\",\n };\n const messages = this.buildMessages(null);\n // Passing `tools: undefined` was supposed to force a text\n // response, but R1 can still hallucinate tool-call markup\n // (e.g. DSML `<|DSML|function_calls>…</|DSML|function_calls>`)\n // in prose when it's been primed by prior tool use. An explicit\n // user-role instruction plus post-hoc stripping of known\n // hallucination shapes keeps the user from seeing raw markup.\n messages.push({\n role: \"user\",\n content:\n \"I'm out of tool-call budget for this turn. Summarize in plain prose what you learned from the tool results above. Do NOT emit any tool calls, function-call markup, DSML invocations, or SEARCH/REPLACE edit blocks — they will be silently discarded. Just plain text.\",\n });\n const resp = await this.client.chat({\n model: this.model,\n messages,\n // no tools → model is forced to answer in text\n signal: this._turnAbort.signal,\n });\n const rawContent = resp.content?.trim() ?? \"\";\n const cleaned = stripHallucinatedToolMarkup(rawContent);\n const summary =\n cleaned ||\n \"(model emitted fake tool-call markup instead of a prose summary — try /retry with a narrower question, or /think to inspect R1's reasoning)\";\n const reasonPrefix = reasonPrefixFor(opts.reason, this.maxToolIters);\n const annotated = `${reasonPrefix}\\n\\n${summary}`;\n const summaryStats = this.stats.record(this._turn, this.model, resp.usage ?? new Usage());\n this.appendAndPersist({ role: \"assistant\", content: summary });\n yield {\n turn: this._turn,\n role: \"assistant_final\",\n content: annotated,\n stats: summaryStats,\n forcedSummary: true,\n };\n yield { turn: this._turn, role: \"done\", content: summary };\n } catch (err) {\n const label = errorLabelFor(opts.reason, this.maxToolIters);\n yield {\n turn: this._turn,\n role: \"error\",\n content: \"\",\n error: `${label} and the fallback summary call failed: ${(err as Error).message}. Run /clear and retry with a narrower question, or raise --max-tool-iters.`,\n };\n yield { turn: this._turn, role: \"done\", content: \"\" };\n }\n }\n\n async run(userInput: string, onEvent?: (ev: LoopEvent) => void): Promise<string> {\n let final = \"\";\n for await (const ev of this.step(userInput)) {\n onEvent?.(ev);\n if (ev.role === \"assistant_final\") final = ev.content;\n if (ev.role === \"done\") break;\n }\n return final;\n }\n\n private assistantMessage(content: string, toolCalls: ToolCall[]): ChatMessage {\n const msg: ChatMessage = { role: \"assistant\", content };\n if (toolCalls.length > 0) msg.tool_calls = toolCalls;\n return msg;\n }\n}\n\n/**\n * R1 occasionally hallucinates tool-call markup as plain text when the\n * real tool channel has been closed — typically our forced-summary\n * path, where `tools: undefined` is supposed to force prose but isn't\n * always respected. The markup isn't parsed by our tool-call path\n * (the API response's structured `tool_calls` field is empty), so\n * it's just noise in the user's view. Strip known envelope shapes.\n *\n * Exported so tests can exercise it against concrete R1 outputs.\n */\nexport function stripHallucinatedToolMarkup(s: string): string {\n let out = s;\n // DeepSeek's DSML envelope (both the full-width \"|\" character and\n // the ASCII-only fallback we've seen — the full-width form is the\n // one R1 emits in practice)\n out = out.replace(/<|DSML|function_calls>[\\s\\S]*?<\\/?|DSML|function_calls>/g, \"\");\n out = out.replace(/<\\|DSML\\|function_calls>[\\s\\S]*?<\\/?\\|DSML\\|function_calls>/g, \"\");\n // Anthropic / generic XML-ish envelope\n out = out.replace(/<function_calls>[\\s\\S]*?<\\/function_calls>/g, \"\");\n // Lone unpaired DSML opener left over after the closer was on a\n // different line (seen when R1 truncates mid-call).\n out = out.replace(/<|DSML|[\\s\\S]*$/g, \"\");\n return out.trim();\n}\n\n/**\n * Try to JSON-decode the model's tool-call arguments so PreToolUse /\n * PostToolUse hooks get a structured object instead of a string.\n * Falls back to the raw string when the model emits malformed JSON\n * (the loop's own dispatch already tolerates that — keep parity).\n */\nfunction safeParseToolArgs(raw: string): unknown {\n try {\n return JSON.parse(raw);\n } catch {\n return raw;\n }\n}\n\n/** Format non-pass hook outcomes as `LoopEvent`s of role `warning`. */\nfunction* hookWarnings(outcomes: HookOutcome[], turn: number): Generator<LoopEvent> {\n for (const o of outcomes) {\n if (o.decision === \"pass\") continue;\n yield { turn, role: \"warning\", content: formatHookOutcomeMessage(o) };\n }\n}\n\nfunction reasonPrefixFor(reason: \"budget\" | \"aborted\" | \"context-guard\", iterCap: number): string {\n if (reason === \"aborted\") return \"[aborted by user (Esc) — summarizing what I found so far]\";\n if (reason === \"context-guard\") {\n return \"[context budget running low — summarizing before the next call would overflow]\";\n }\n return `[tool-call budget (${iterCap}) reached — forcing summary from what I found]`;\n}\n\nfunction errorLabelFor(reason: \"budget\" | \"aborted\" | \"context-guard\", iterCap: number): string {\n if (reason === \"aborted\") return \"aborted by user\";\n if (reason === \"context-guard\") return \"context-guard triggered (prompt > 80% of window)\";\n return `tool-call budget (${iterCap}) reached`;\n}\n\nfunction summarizeBranch(chosen: BranchSample, samples: BranchSample[]): BranchSummary {\n return {\n budget: samples.length,\n chosenIndex: chosen.index,\n uncertainties: samples.map((s) => s.planState.uncertainties.length),\n temperatures: samples.map((s) => s.temperature),\n };\n}\n\n/**\n * Truncate any tool-role message whose content exceeds the cap. User\n * and assistant messages are left alone because (a) they're almost\n * always small, (b) truncating user prompts would corrupt conversational\n * intent in a way the user didn't author. Exported for tests.\n */\n/**\n * Shrink oversized tool results only — the original compact concern.\n * Separated from `healLoadedMessages` so `/compact` (live, mid-session)\n * doesn't accidentally strip structural tail that belongs in the\n * current turn's state.\n */\nexport function shrinkOversizedToolResults(\n messages: ChatMessage[],\n maxChars: number,\n): { messages: ChatMessage[]; healedCount: number; healedFrom: number } {\n let healedCount = 0;\n let healedFrom = 0;\n const out = messages.map((msg) => {\n if (msg.role !== \"tool\") return msg;\n const content = typeof msg.content === \"string\" ? msg.content : \"\";\n if (content.length <= maxChars) return msg;\n healedCount += 1;\n healedFrom += content.length;\n return { ...msg, content: truncateForModel(content, maxChars) };\n });\n return { messages: out, healedCount, healedFrom };\n}\n\n/**\n * Token-aware variant of `shrinkOversizedToolResults`. Used by live\n * `/compact` and auto-compact so the shrink cap bounds the REAL\n * context footprint (CJK at 1 char/token would otherwise survive a\n * char cap at 2× the intended token cost). Session-load heal still\n * uses the char version for backward-compat on stored session files.\n *\n * Per-message token accounting: we tokenize each shrink candidate\n * twice (before + after) so `tokensSaved` is exact. At typical log\n * sizes (≤20 tool results) this is bounded; at pathological sizes\n * the `truncateForModelByTokens` call internally never tokenizes the\n * full input, so worst-case stays bounded too.\n */\nexport function shrinkOversizedToolResultsByTokens(\n messages: ChatMessage[],\n maxTokens: number,\n): {\n messages: ChatMessage[];\n healedCount: number;\n tokensSaved: number;\n charsSaved: number;\n} {\n let healedCount = 0;\n let tokensSaved = 0;\n let charsSaved = 0;\n const out = messages.map((msg) => {\n if (msg.role !== \"tool\") return msg;\n const content = typeof msg.content === \"string\" ? msg.content : \"\";\n // Fast path: length ≤ maxTokens ⇒ tokens ≤ maxTokens (every token\n // is ≥1 char). Skip the per-message tokenize for small results.\n if (content.length <= maxTokens) return msg;\n const beforeTokens = countTokens(content);\n if (beforeTokens <= maxTokens) return msg;\n const truncated = truncateForModelByTokens(content, maxTokens);\n const afterTokens = countTokens(truncated);\n healedCount += 1;\n tokensSaved += Math.max(0, beforeTokens - afterTokens);\n charsSaved += Math.max(0, content.length - truncated.length);\n return { ...msg, content: truncated };\n });\n return { messages: out, healedCount, tokensSaved, charsSaved };\n}\n\nexport function healLoadedMessages(\n messages: ChatMessage[],\n maxChars: number,\n): { messages: ChatMessage[]; healedCount: number; healedFrom: number } {\n // Pass 1: shrink oversized tool results (original heal purpose).\n const shrunk = shrinkOversizedToolResults(messages, maxChars);\n let healedCount = shrunk.healedCount;\n // Pass 2: enforce tool_calls ↔ tool pairing across the full log.\n //\n // DeepSeek rejects two shapes at the API boundary:\n // (a) assistant with tool_calls not followed by matching tool\n // responses (\"insufficient tool messages following tool_calls\")\n // (b) tool message without a preceding assistant.tool_calls with\n // the matching tool_call_id (\"must be a response to a preceding\n // message with 'tool_calls'\")\n //\n // Corrupted session files from earlier builds have hit both. Rebuild\n // the message stream so only well-formed (assistant.tool_calls + all\n // matching responses) groups survive. Plain user/assistant messages\n // (no tool_calls) always pass through.\n const out: ChatMessage[] = [];\n const openCallIds = new Set<string>();\n let droppedAssistantCalls = 0;\n let droppedStrayTools = 0;\n for (let i = 0; i < shrunk.messages.length; i++) {\n const msg = shrunk.messages[i]!;\n if (msg.role === \"assistant\" && Array.isArray(msg.tool_calls) && msg.tool_calls.length > 0) {\n // Look ahead for tool responses matching every id in this\n // assistant's tool_calls. If all present (in any order, but\n // contiguous after this message), include the whole group.\n const needed = new Set<string>();\n for (const call of msg.tool_calls) {\n if (call?.id) needed.add(call.id);\n }\n const candidates: ChatMessage[] = [];\n let j = i + 1;\n while (j < shrunk.messages.length && needed.size > 0) {\n const nxt = shrunk.messages[j]!;\n if (nxt.role !== \"tool\") break;\n const id = nxt.tool_call_id ?? \"\";\n if (!needed.has(id)) break;\n needed.delete(id);\n candidates.push(nxt);\n j++;\n }\n if (needed.size === 0) {\n // Every call has a response — emit the whole group.\n out.push(msg);\n for (const r of candidates) out.push(r);\n i = j - 1; // for-loop ++ will advance past the last response\n } else {\n // Drop the assistant entry and anything that was speculatively\n // its responses — they'd become stray tool messages.\n droppedAssistantCalls += 1;\n droppedStrayTools += candidates.length;\n i = j - 1;\n }\n continue;\n }\n if (msg.role === \"tool\") {\n // Any tool message that reaches here did NOT get consumed by\n // the assistant-with-tool_calls branch above, so it's stray.\n // Drop it — surfacing it would 400 the next API call.\n droppedStrayTools += 1;\n continue;\n }\n // Plain user/assistant/system message — pass through.\n out.push(msg);\n }\n healedCount += droppedAssistantCalls + droppedStrayTools;\n return { messages: out, healedCount, healedFrom: shrunk.healedFrom };\n}\n\n/**\n * Annotate the `DeepSeek 400: … maximum context length …` error the API\n * returns when a session's history has grown past 131,072 tokens. The\n * raw message is a JSON blob; we surface a short actionable hint on top\n * so the user knows to `/forget` or `/clear` rather than parsing the\n * JSON themselves. Other errors pass through unchanged — the loop's\n * error channel already formats them well enough.\n */\nexport function formatLoopError(err: Error): string {\n const msg = err.message ?? \"\";\n if (msg.includes(\"maximum context length\")) {\n // Pull the \"requested X tokens\" figure out of the JSON for scale.\n const reqMatch = msg.match(/requested\\s+(\\d+)\\s+tokens/);\n const requested = reqMatch\n ? `${Number(reqMatch[1]).toLocaleString()} tokens`\n : \"too many tokens\";\n return `Context overflow (DeepSeek 400): session history is ${requested}, past the 131,072-token limit. Usually this means a single tool call returned a huge payload. v0.3.0-alpha.6+ caps new tool results at 32k chars, AND auto-heals oversized history on session load — restart Reasonix and this session should come back trimmed. If it still overflows, run /forget (delete the session) or /clear (drop the displayed history) to start fresh.`;\n }\n return msg;\n}\n","/**\n * Project memory — a user-authored `REASONIX.md` in the project root\n * that gets pinned into the immutable-prefix system prompt.\n *\n * Design notes:\n *\n * - The file lands in `ImmutablePrefix.system`, so the whole memory\n * block is hashed into the cache prefix fingerprint. Editing the\n * file invalidates the prefix; unchanged memory across sessions\n * keeps the DeepSeek prefix cache warm. That matches Pillar 1 —\n * memory is a deliberate, stable prefix, not per-turn drift.\n * - Only one source: the working-root `REASONIX.md`. No parent walk,\n * no `~/.reasonix/REASONIX.md`, no CLAUDE.md fallback. User-global\n * memory can come later; for v1 one file == one mental model.\n * - Truncated at 8 000 chars (≈ 2k tokens). `.gitignore` gets 2 000\n * because it's a constraint dump; memory gets more headroom because\n * it's deliberate instructions.\n * - Opt-out via `REASONIX_MEMORY=off|false|0`. No CLI flag — memory\n * is a file, `rm REASONIX.md` is the other opt-out.\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nexport const PROJECT_MEMORY_FILE = \"REASONIX.md\";\nexport const PROJECT_MEMORY_MAX_CHARS = 8000;\n\nexport interface ProjectMemory {\n /** Absolute path the memory was read from. */\n path: string;\n /** Post-truncation content (may include a \"… (truncated N chars)\" marker). */\n content: string;\n /** Original byte length before truncation. */\n originalChars: number;\n /** True iff `originalChars > PROJECT_MEMORY_MAX_CHARS`. */\n truncated: boolean;\n}\n\n/**\n * Read `REASONIX.md` from `rootDir`. Returns `null` when the file is\n * missing, unreadable, or empty (whitespace-only counts as empty — an\n * empty memory file shouldn't perturb the cache prefix).\n */\nexport function readProjectMemory(rootDir: string): ProjectMemory | null {\n const path = join(rootDir, PROJECT_MEMORY_FILE);\n if (!existsSync(path)) return null;\n let raw: string;\n try {\n raw = readFileSync(path, \"utf8\");\n } catch {\n return null;\n }\n const trimmed = raw.trim();\n if (!trimmed) return null;\n const originalChars = trimmed.length;\n const truncated = originalChars > PROJECT_MEMORY_MAX_CHARS;\n const content = truncated\n ? `${trimmed.slice(0, PROJECT_MEMORY_MAX_CHARS)}\\n… (truncated ${\n originalChars - PROJECT_MEMORY_MAX_CHARS\n } chars)`\n : trimmed;\n return { path, content, originalChars, truncated };\n}\n\n/**\n * Resolve whether project memory should be read. Default: on.\n * `REASONIX_MEMORY=off|false|0` turns it off (CI, reproducing issues,\n * intentional offline runs).\n */\nexport function memoryEnabled(): boolean {\n const env = process.env.REASONIX_MEMORY;\n if (env === \"off\" || env === \"false\" || env === \"0\") return false;\n return true;\n}\n\n/**\n * Return `basePrompt` with the project's `REASONIX.md` appended as a\n * \"Project memory\" section. No-op when the file is absent, empty, or\n * memory is disabled via env.\n *\n * The appended block is deterministic — identical input ⇒ identical\n * output — so every session that opens against the same memory file\n * gets the same prefix hash.\n */\nexport function applyProjectMemory(basePrompt: string, rootDir: string): string {\n if (!memoryEnabled()) return basePrompt;\n const mem = readProjectMemory(rootDir);\n if (!mem) return basePrompt;\n return `${basePrompt}\n\n# Project memory (REASONIX.md)\n\nThe user pinned these notes about this project — treat them as authoritative context for every turn:\n\n\\`\\`\\`\n${mem.content}\n\\`\\`\\`\n`;\n}\n","/**\n * User memory — `~/.reasonix/memory/` markdown notes pinned into the\n * immutable-prefix system prompt across sessions.\n *\n * Two scopes:\n * - `global` → `~/.reasonix/memory/global/` (cross-project)\n * - `project` → `~/.reasonix/memory/<hash>/` (per sandbox root)\n *\n * Each scope has an always-loaded `MEMORY.md` index plus zero-or-more\n * `<name>.md` detail files loaded on demand via `recall_memory`.\n *\n * Distinct from `src/project-memory.ts` (REASONIX.md) in purpose:\n * REASONIX.md is committable, team-shared project memory.\n * ~/.reasonix/memory is user-private memory, never committed.\n */\n\nimport { createHash } from \"node:crypto\";\nimport {\n existsSync,\n mkdirSync,\n readFileSync,\n readdirSync,\n unlinkSync,\n writeFileSync,\n} from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join, resolve } from \"node:path\";\nimport { applyProjectMemory, memoryEnabled } from \"./project-memory.js\";\nimport { applySkillsIndex } from \"./skills.js\";\n\nexport const USER_MEMORY_DIR = \"memory\";\nexport const MEMORY_INDEX_FILE = \"MEMORY.md\";\n/** Cap on the index file content loaded into the prefix, per scope. */\nexport const MEMORY_INDEX_MAX_CHARS = 4000;\n\nexport type MemoryType = \"user\" | \"feedback\" | \"project\" | \"reference\";\nexport type MemoryScope = \"global\" | \"project\";\n\nexport interface MemoryEntry {\n name: string;\n type: MemoryType;\n scope: MemoryScope;\n description: string;\n body: string;\n /** ISO date string (YYYY-MM-DD). */\n createdAt: string;\n}\n\nexport interface MemoryStoreOptions {\n /** Override `~/.reasonix` — tests set this to a tmpdir. */\n homeDir?: string;\n /** Absolute sandbox root. Required to use `scope: \"project\"`. */\n projectRoot?: string;\n}\n\nexport interface WriteInput {\n name: string;\n type: MemoryType;\n scope: MemoryScope;\n description: string;\n body: string;\n}\n\nconst VALID_NAME = /^[a-zA-Z0-9_-][a-zA-Z0-9_.-]{1,38}[a-zA-Z0-9]$/;\n\n/**\n * Throws on filename injection attempts (`../foo`, `foo/bar`, leading\n * dots, etc.). Allowed: 3-40 chars, alnum + `_` + `-` + interior `.`.\n */\nexport function sanitizeMemoryName(raw: string): string {\n const trimmed = String(raw ?? \"\").trim();\n if (!VALID_NAME.test(trimmed)) {\n throw new Error(\n `invalid memory name: ${JSON.stringify(raw)} — must be 3-40 chars, alnum/_/-, no path separators`,\n );\n }\n return trimmed;\n}\n\n/** Stable 16-hex-char hash of an absolute sandbox root path. */\nexport function projectHash(rootDir: string): string {\n const abs = resolve(rootDir);\n return createHash(\"sha1\").update(abs).digest(\"hex\").slice(0, 16);\n}\n\nfunction scopeDir(opts: { homeDir: string; scope: MemoryScope; projectRoot?: string }): string {\n if (opts.scope === \"global\") {\n return join(opts.homeDir, USER_MEMORY_DIR, \"global\");\n }\n if (!opts.projectRoot) {\n throw new Error(\"scope=project requires a projectRoot on MemoryStore\");\n }\n return join(opts.homeDir, USER_MEMORY_DIR, projectHash(opts.projectRoot));\n}\n\nfunction ensureDir(p: string): void {\n if (!existsSync(p)) mkdirSync(p, { recursive: true });\n}\n\n/**\n * Parse a `---` frontmatter block off the top of a markdown string.\n * Tolerates missing frontmatter, returning `{}` for data and the full\n * string as body. Only recognizes the simple `key: value` shape — no\n * quoting, no multi-line, no YAML features. Matches what we emit.\n */\nfunction parseFrontmatter(raw: string): { data: Record<string, string>; body: string } {\n const lines = raw.split(/\\r?\\n/);\n if (lines[0] !== \"---\") return { data: {}, body: raw };\n const end = lines.indexOf(\"---\", 1);\n if (end < 0) return { data: {}, body: raw };\n const data: Record<string, string> = {};\n for (let i = 1; i < end; i++) {\n const line = lines[i];\n if (!line) continue;\n const m = line.match(/^([a-zA-Z_][a-zA-Z0-9_-]*):\\s*(.*)$/);\n if (m?.[1]) data[m[1]] = (m[2] ?? \"\").trim();\n }\n return {\n data,\n body: lines\n .slice(end + 1)\n .join(\"\\n\")\n .replace(/^\\n+/, \"\"),\n };\n}\n\nfunction formatFrontmatter(e: WriteInput & { createdAt: string }): string {\n return [\n \"---\",\n `name: ${e.name}`,\n `description: ${e.description.replace(/\\n/g, \" \")}`,\n `type: ${e.type}`,\n `scope: ${e.scope}`,\n `created: ${e.createdAt}`,\n \"---\",\n \"\",\n ].join(\"\\n\");\n}\n\nfunction todayIso(): string {\n const d = new Date();\n return d.toISOString().slice(0, 10);\n}\n\n/**\n * A `MEMORY.md` index line for one entry. One-liner, under ~150 chars.\n * `description` is truncated if it would push past the soft limit.\n */\nfunction indexLine(e: Pick<MemoryEntry, \"name\" | \"description\">): string {\n const safeDesc = e.description.replace(/\\n/g, \" \").trim();\n const max = 130 - e.name.length;\n const clipped = safeDesc.length > max ? `${safeDesc.slice(0, Math.max(1, max - 1))}…` : safeDesc;\n return `- [${e.name}](${e.name}.md) — ${clipped}`;\n}\n\nexport class MemoryStore {\n private readonly homeDir: string;\n private readonly projectRoot: string | undefined;\n\n constructor(opts: MemoryStoreOptions = {}) {\n this.homeDir = opts.homeDir ?? join(homedir(), \".reasonix\");\n this.projectRoot = opts.projectRoot ? resolve(opts.projectRoot) : undefined;\n }\n\n /** Directory this store writes `scope` files into, creating it if needed. */\n dir(scope: MemoryScope): string {\n const d = scopeDir({ homeDir: this.homeDir, scope, projectRoot: this.projectRoot });\n ensureDir(d);\n return d;\n }\n\n /** Absolute path to a memory file (no existence check). */\n pathFor(scope: MemoryScope, name: string): string {\n return join(this.dir(scope), `${sanitizeMemoryName(name)}.md`);\n }\n\n /** True iff this store is configured with a project scope available. */\n hasProjectScope(): boolean {\n return this.projectRoot !== undefined;\n }\n\n /**\n * Read the `MEMORY.md` index for a scope. Returns post-cap content\n * (with a truncation marker if clipped), or `null` when absent / empty.\n */\n loadIndex(\n scope: MemoryScope,\n ): { content: string; originalChars: number; truncated: boolean } | null {\n if (scope === \"project\" && !this.projectRoot) return null;\n const file = join(\n scopeDir({ homeDir: this.homeDir, scope, projectRoot: this.projectRoot }),\n MEMORY_INDEX_FILE,\n );\n if (!existsSync(file)) return null;\n let raw: string;\n try {\n raw = readFileSync(file, \"utf8\");\n } catch {\n return null;\n }\n const trimmed = raw.trim();\n if (!trimmed) return null;\n const originalChars = trimmed.length;\n const truncated = originalChars > MEMORY_INDEX_MAX_CHARS;\n const content = truncated\n ? `${trimmed.slice(0, MEMORY_INDEX_MAX_CHARS)}\\n… (truncated ${originalChars - MEMORY_INDEX_MAX_CHARS} chars)`\n : trimmed;\n return { content, originalChars, truncated };\n }\n\n /** Read one memory file's body (frontmatter stripped). Throws if missing. */\n read(scope: MemoryScope, name: string): MemoryEntry {\n const file = this.pathFor(scope, name);\n if (!existsSync(file)) {\n throw new Error(`memory not found: scope=${scope} name=${name}`);\n }\n const raw = readFileSync(file, \"utf8\");\n const { data, body } = parseFrontmatter(raw);\n return {\n name: data.name ?? name,\n type: (data.type as MemoryType) ?? \"project\",\n scope: (data.scope as MemoryScope) ?? scope,\n description: data.description ?? \"\",\n body: body.trim(),\n createdAt: data.created ?? \"\",\n };\n }\n\n /**\n * List every memory in this store. Scans both scopes (skips project\n * scope if unconfigured). Silently skips malformed files; the index\n * must stay queryable even if one file is hand-edited into nonsense.\n */\n list(): MemoryEntry[] {\n const out: MemoryEntry[] = [];\n const scopes: MemoryScope[] = this.projectRoot ? [\"global\", \"project\"] : [\"global\"];\n for (const scope of scopes) {\n const dir = scopeDir({ homeDir: this.homeDir, scope, projectRoot: this.projectRoot });\n if (!existsSync(dir)) continue;\n let entries: string[];\n try {\n entries = readdirSync(dir);\n } catch {\n continue;\n }\n for (const entry of entries) {\n if (entry === MEMORY_INDEX_FILE) continue;\n if (!entry.endsWith(\".md\")) continue;\n const name = entry.slice(0, -3);\n try {\n out.push(this.read(scope, name));\n } catch {\n // malformed file — skip rather than fail the whole list\n }\n }\n }\n return out;\n }\n\n /**\n * Write a new memory (or overwrite existing). Creates the scope dir,\n * writes the `.md` file, and regenerates `MEMORY.md`. Returns the\n * absolute path written to.\n */\n write(input: WriteInput): string {\n if (input.scope === \"project\" && !this.projectRoot) {\n throw new Error(\"cannot write project-scoped memory: no projectRoot configured\");\n }\n const name = sanitizeMemoryName(input.name);\n const desc = String(input.description ?? \"\").trim();\n if (!desc) throw new Error(\"memory description cannot be empty\");\n const body = String(input.body ?? \"\").trim();\n if (!body) throw new Error(\"memory body cannot be empty\");\n const entry: WriteInput & { createdAt: string } = {\n ...input,\n name,\n description: desc,\n body,\n createdAt: todayIso(),\n };\n const dir = this.dir(input.scope);\n const file = join(dir, `${name}.md`);\n const content = `${formatFrontmatter(entry)}${body}\\n`;\n writeFileSync(file, content, \"utf8\");\n this.regenerateIndex(input.scope);\n return file;\n }\n\n /** Delete one memory + its index line. No-op if the file is already gone. */\n delete(scope: MemoryScope, rawName: string): boolean {\n if (scope === \"project\" && !this.projectRoot) {\n throw new Error(\"cannot delete project-scoped memory: no projectRoot configured\");\n }\n const file = this.pathFor(scope, rawName);\n if (!existsSync(file)) return false;\n unlinkSync(file);\n this.regenerateIndex(scope);\n return true;\n }\n\n /**\n * Rebuild `MEMORY.md` from the `.md` files currently in the scope dir.\n * Called after every write/delete. Sorted by name for stable prefix\n * hashing — two stores with the same set of files produce byte-identical\n * MEMORY.md content, keeping the cache prefix reproducible.\n */\n private regenerateIndex(scope: MemoryScope): void {\n const dir = scopeDir({ homeDir: this.homeDir, scope, projectRoot: this.projectRoot });\n if (!existsSync(dir)) return;\n let files: string[];\n try {\n files = readdirSync(dir);\n } catch {\n return;\n }\n const mdFiles = files\n .filter((f) => f !== MEMORY_INDEX_FILE && f.endsWith(\".md\"))\n .sort((a, b) => a.localeCompare(b));\n const indexPath = join(dir, MEMORY_INDEX_FILE);\n if (mdFiles.length === 0) {\n if (existsSync(indexPath)) unlinkSync(indexPath);\n return;\n }\n const lines: string[] = [];\n for (const f of mdFiles) {\n const name = f.slice(0, -3);\n try {\n const entry = this.read(scope, name);\n lines.push(indexLine({ name: entry.name || name, description: entry.description }));\n } catch {\n // Malformed: still surface it in the index so the user notices.\n lines.push(`- [${name}](${name}.md) — (malformed, check frontmatter)`);\n }\n }\n writeFileSync(indexPath, `${lines.join(\"\\n\")}\\n`, \"utf8\");\n }\n}\n\n/**\n * Append `MEMORY_GLOBAL` and (optionally) `MEMORY_PROJECT` blocks to\n * `basePrompt`. Omits a block entirely when its index is absent — an\n * empty tag would add bytes to the prefix hash without content.\n * Respects `REASONIX_MEMORY=off` via `memoryEnabled()` from\n * `project-memory.ts`.\n */\nexport function applyUserMemory(\n basePrompt: string,\n opts: { homeDir?: string; projectRoot?: string } = {},\n): string {\n if (!memoryEnabled()) return basePrompt;\n const store = new MemoryStore(opts);\n const global = store.loadIndex(\"global\");\n const project = store.hasProjectScope() ? store.loadIndex(\"project\") : null;\n if (!global && !project) return basePrompt;\n const parts: string[] = [basePrompt];\n if (global) {\n parts.push(\n \"\",\n \"# User memory — global (~/.reasonix/memory/global/MEMORY.md)\",\n \"\",\n \"Cross-project facts and preferences the user has told you in prior sessions. TREAT AS AUTHORITATIVE — don't re-verify via filesystem or web. One-liners index detail files; call `recall_memory` for full bodies only when the one-liner isn't enough.\",\n \"\",\n \"```\",\n global.content,\n \"```\",\n );\n }\n if (project) {\n parts.push(\n \"\",\n \"# User memory — this project\",\n \"\",\n \"Per-project facts the user established in prior sessions (not committed to the repo). TREAT AS AUTHORITATIVE. Same recall pattern as global memory.\",\n \"\",\n \"```\",\n project.content,\n \"```\",\n );\n }\n return parts.join(\"\\n\");\n}\n\n/**\n * Compose every lazy-loaded prefix block in one call: REASONIX.md,\n * user memory (global + project), and the skills index. Drop-in\n * replacement for `applyProjectMemory` at CLI entry points. Stacking\n * order is stable — the prefix hash only changes when block *content*\n * changes, not when this helper is called a second time with the same\n * filesystem state.\n */\nexport function applyMemoryStack(basePrompt: string, rootDir: string): string {\n const withProject = applyProjectMemory(basePrompt, rootDir);\n const withMemory = applyUserMemory(withProject, { projectRoot: rootDir });\n return applySkillsIndex(withMemory, { projectRoot: rootDir });\n}\n","/**\n * Skills — user-defined prompt packs pinned (by name) into the\n * immutable prefix and loaded (by body) on demand.\n *\n * Two scopes mirror the user-memory layout:\n * - `project` → `<projectRoot>/.reasonix/skills/` (this repo only)\n * - `global` → `~/.reasonix/skills/` (every session)\n *\n * Project scope wins on a name collision. Deliberately NOT tied to\n * any specific client's directory convention (`.claude/`, `.glm/`,\n * etc.) — Reasonix is model-agnostic at the conversation layer, so\n * coupling the skill filesystem to one vendor would break any user\n * running a different backend.\n *\n * Accepted file layouts (both emit the same `Skill`):\n * - `{dir}/<name>/SKILL.md` (preferred — lets a skill bundle\n * additional assets alongside)\n * - `{dir}/<name>.md` (flat, one-file shorthand)\n *\n * Frontmatter keys we read:\n * - `name` — optional, defaults to the file / dir name\n * - `description` — one-line index description (REQUIRED for listing)\n * - `allowed-tools` — parsed but UNUSED in v1 (see tools/skills.ts)\n *\n * Cache-First contract (Pillar 1):\n * - The PREFIX sees only names + descriptions (one line each).\n * - Bodies enter the APPEND-ONLY LOG lazily, via `run_skill` or\n * `/skill <name>` — never the prefix. That keeps the prefix hash\n * stable across skill additions to the body store.\n */\n\nimport { existsSync, readFileSync, readdirSync, statSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join, resolve } from \"node:path\";\n\nexport const SKILLS_DIRNAME = \"skills\";\nexport const SKILL_FILE = \"SKILL.md\";\n/** Cap on the pinned skills-index block, mirrors memory-index cap. */\nexport const SKILLS_INDEX_MAX_CHARS = 4000;\n/** Skill identifier shape — alnum + `_` + `-` + interior `.`, 1-64 chars. */\nconst VALID_SKILL_NAME = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/;\n\nexport type SkillScope = \"project\" | \"global\" | \"builtin\";\n\n/**\n * Execution mode for a skill. `inline` (default) returns the body as a\n * tool result so the body enters the parent's append-only log — the\n * model continues the loop using the loaded instructions. `subagent`\n * spawns an isolated child loop with the body as the system prompt and\n * the user-supplied `arguments` as the task; only the child's final\n * answer comes back. Use `subagent` for big-context exploration / research\n * playbooks where the parent doesn't need to see the trail.\n */\nexport type SkillRunAs = \"inline\" | \"subagent\";\n\nexport interface Skill {\n /** Canonical name — sanitized, matches the directory / filename stem. */\n name: string;\n /** One-line description shown in the pinned index. */\n description: string;\n /** Full markdown body (post-frontmatter). Loaded on demand. */\n body: string;\n /** Which scope this skill was loaded from. */\n scope: SkillScope;\n /** Absolute path to the SKILL.md (or {name}.md) file, or \"(builtin)\" for shipped defaults. */\n path: string;\n /** Raw `allowed-tools` field from frontmatter, if any. Unused in v1. */\n allowedTools?: string;\n /**\n * Execution mode (frontmatter `runAs`). Defaults to `inline` for\n * backwards compatibility with skills written before this field\n * existed.\n */\n runAs: SkillRunAs;\n /**\n * Frontmatter `model` — when set, overrides the default model the\n * subagent runs on. Only meaningful when `runAs === \"subagent\"`.\n * Accept any DeepSeek model id; the subagent layer falls back to its\n * own default if this is missing or invalid.\n */\n model?: string;\n}\n\nexport interface SkillStoreOptions {\n /** Override `$HOME` — tests point this at a tmpdir. */\n homeDir?: string;\n /**\n * Absolute project root. Required to surface project-scope skills;\n * omit (e.g. in `reasonix chat` without `code`) and the store only\n * reads the global scope.\n */\n projectRoot?: string;\n /**\n * Suppress the bundled built-in skills (`explore`, `research`).\n * Used by unit tests that want to assert exact list contents\n * without the +2 builtins distorting counts. Production callers\n * leave this off so users always get the bundled defaults.\n */\n disableBuiltins?: boolean;\n}\n\n/**\n * Parse a `---` frontmatter block. Same minimal shape as user-memory:\n * `key: value` lines, no quoting, no nesting. Returns `{}` data and the\n * full input as body when no frontmatter fence is present — so hand-\n * written files without frontmatter still surface (with empty desc).\n */\nfunction parseFrontmatter(raw: string): { data: Record<string, string>; body: string } {\n const lines = raw.split(/\\r?\\n/);\n if (lines[0] !== \"---\") return { data: {}, body: raw };\n const end = lines.indexOf(\"---\", 1);\n if (end < 0) return { data: {}, body: raw };\n const data: Record<string, string> = {};\n for (let i = 1; i < end; i++) {\n const line = lines[i];\n if (!line) continue;\n const m = line.match(/^([a-zA-Z_][a-zA-Z0-9_-]*):\\s*(.*)$/);\n if (m?.[1]) data[m[1]] = (m[2] ?? \"\").trim();\n }\n return {\n data,\n body: lines\n .slice(end + 1)\n .join(\"\\n\")\n .replace(/^\\n+/, \"\"),\n };\n}\n\nfunction isValidSkillName(name: string): boolean {\n return VALID_SKILL_NAME.test(name);\n}\n\nexport class SkillStore {\n private readonly homeDir: string;\n private readonly projectRoot: string | undefined;\n private readonly disableBuiltins: boolean;\n\n constructor(opts: SkillStoreOptions = {}) {\n this.homeDir = opts.homeDir ?? homedir();\n this.projectRoot = opts.projectRoot ? resolve(opts.projectRoot) : undefined;\n this.disableBuiltins = opts.disableBuiltins === true;\n }\n\n /** True iff this store was configured with a project root. */\n hasProjectScope(): boolean {\n return this.projectRoot !== undefined;\n }\n\n /**\n * Root directories scanned, in priority order. Project scope first\n * so a per-repo skill overrides a global one with the same name —\n * users expect the local copy to win when both exist.\n */\n roots(): Array<{ dir: string; scope: SkillScope }> {\n const out: Array<{ dir: string; scope: SkillScope }> = [];\n if (this.projectRoot) {\n out.push({\n dir: join(this.projectRoot, \".reasonix\", SKILLS_DIRNAME),\n scope: \"project\",\n });\n }\n out.push({ dir: join(this.homeDir, \".reasonix\", SKILLS_DIRNAME), scope: \"global\" });\n return out;\n }\n\n /**\n * List every skill visible to this store. On name collisions the\n * higher-priority root (project over global over builtin) wins.\n * Sorted by name for stable prefix hashing.\n */\n list(): Skill[] {\n const byName = new Map<string, Skill>();\n for (const { dir, scope } of this.roots()) {\n if (!existsSync(dir)) continue;\n let entries: import(\"node:fs\").Dirent[];\n try {\n entries = readdirSync(dir, { withFileTypes: true });\n } catch {\n continue;\n }\n for (const entry of entries) {\n const skill = this.readEntry(dir, scope, entry);\n if (!skill) continue;\n if (!byName.has(skill.name)) byName.set(skill.name, skill);\n }\n }\n // Builtins are appended last so user/project files take precedence\n // when names collide. The same priority you'd expect: my-project's\n // \"explore\" overrides the shipped one without forcing a different\n // name.\n if (!this.disableBuiltins) {\n for (const skill of BUILTIN_SKILLS) {\n if (!byName.has(skill.name)) byName.set(skill.name, skill);\n }\n }\n return [...byName.values()].sort((a, b) => a.name.localeCompare(b.name));\n }\n\n /** Resolve one skill by name. Returns `null` if not found or malformed. */\n read(name: string): Skill | null {\n if (!isValidSkillName(name)) return null;\n for (const { dir, scope } of this.roots()) {\n if (!existsSync(dir)) continue;\n const dirCandidate = join(dir, name, SKILL_FILE);\n if (existsSync(dirCandidate) && statSync(dirCandidate).isFile()) {\n return this.parse(dirCandidate, name, scope);\n }\n const flatCandidate = join(dir, `${name}.md`);\n if (existsSync(flatCandidate) && statSync(flatCandidate).isFile()) {\n return this.parse(flatCandidate, name, scope);\n }\n }\n // Fall back to builtins. Same precedence as `list()` — user-authored\n // wins, builtins are the floor.\n if (!this.disableBuiltins) {\n for (const skill of BUILTIN_SKILLS) {\n if (skill.name === name) return skill;\n }\n }\n return null;\n }\n\n private readEntry(dir: string, scope: SkillScope, entry: import(\"node:fs\").Dirent): Skill | null {\n if (entry.isDirectory()) {\n if (!isValidSkillName(entry.name)) return null;\n const file = join(dir, entry.name, SKILL_FILE);\n if (!existsSync(file)) return null;\n return this.parse(file, entry.name, scope);\n }\n if (entry.isFile() && entry.name.endsWith(\".md\")) {\n const stem = entry.name.slice(0, -3);\n if (!isValidSkillName(stem)) return null;\n return this.parse(join(dir, entry.name), stem, scope);\n }\n return null;\n }\n\n private parse(path: string, stem: string, scope: SkillScope): Skill | null {\n let raw: string;\n try {\n raw = readFileSync(path, \"utf8\");\n } catch {\n return null;\n }\n const { data, body } = parseFrontmatter(raw);\n const name = data.name && isValidSkillName(data.name) ? data.name : stem;\n return {\n name,\n description: (data.description ?? \"\").trim(),\n body: body.trim(),\n scope,\n path,\n allowedTools: data[\"allowed-tools\"],\n runAs: parseRunAs(data.runAs),\n model: data.model?.startsWith(\"deepseek-\") ? data.model : undefined,\n };\n }\n}\n\n/**\n * Coerce a frontmatter `runAs` string to the discriminated union. Any\n * value other than the literal \"subagent\" is treated as inline — typos\n * and unknown values default to the safe (non-spawning) mode rather\n * than failing the load.\n */\nfunction parseRunAs(raw: string | undefined): SkillRunAs {\n return raw?.trim() === \"subagent\" ? \"subagent\" : \"inline\";\n}\n\n/**\n * Build a single index line for one skill. Shape mirrors memory's\n * `indexLine` — a bullet suitable for a markdown fenced block in the\n * system prompt. Description is truncated to keep the full line under\n * ~150 chars. Subagent-runAs skills carry a 🧬 marker so the model\n * sees at a glance which skills will spawn an isolated child loop.\n */\nfunction skillIndexLine(s: Pick<Skill, \"name\" | \"description\" | \"runAs\">): string {\n const safeDesc = s.description.replace(/\\n/g, \" \").trim();\n const marker = s.runAs === \"subagent\" ? \"🧬 \" : \"\";\n const max = 130 - s.name.length - marker.length;\n const clipped = safeDesc.length > max ? `${safeDesc.slice(0, Math.max(1, max - 1))}…` : safeDesc;\n return clipped ? `- ${marker}${s.name} — ${clipped}` : `- ${marker}${s.name}`;\n}\n\n/**\n * Append a `# Skills` block to `basePrompt` listing every discovered\n * skill (name + description only). Bodies are NOT inlined — that's the\n * whole point: the prefix stays short and cacheable; full content loads\n * on demand via `run_skill` or `/skill <name>`.\n *\n * Emits nothing when no skills are discovered — keeps the prefix hash\n * stable for users who don't use skills at all.\n */\nexport function applySkillsIndex(basePrompt: string, opts: SkillStoreOptions = {}): string {\n const store = new SkillStore(opts);\n const skills = store.list().filter((s) => s.description);\n if (skills.length === 0) return basePrompt;\n const lines = skills.map(skillIndexLine);\n const joined = lines.join(\"\\n\");\n const truncated =\n joined.length > SKILLS_INDEX_MAX_CHARS\n ? `${joined.slice(0, SKILLS_INDEX_MAX_CHARS)}\\n… (truncated ${\n joined.length - SKILLS_INDEX_MAX_CHARS\n } chars)`\n : joined;\n return [\n basePrompt,\n \"\",\n \"# Skills — playbooks you can invoke\",\n \"\",\n 'One-liner index. Each entry is either a built-in or a user-authored playbook. Call `run_skill({ name: \"<skill-name>\", arguments: \"<task>\" })` to invoke one. Skills marked with 🧬 spawn an **isolated subagent** — its tool calls and reasoning never enter your context, only its final answer does. Use 🧬 skills for tasks that would otherwise flood your context (deep exploration, multi-step research, anything where you only need the conclusion). Plain skills are inlined: their body becomes a tool result you read and act on directly. The user can also invoke a skill via `/skill <name>`.',\n \"\",\n \"```\",\n truncated,\n \"```\",\n ].join(\"\\n\");\n}\n\n/**\n * Built-in skills shipped with Reasonix. These are always available\n * (no install step) and live as constants rather than files because:\n * - Zero filesystem coupling — no copy-on-first-run dance, nothing\n * to migrate when we update them.\n * - They participate in the same `byName` priority as user/project\n * skills: write `~/.reasonix/skills/explore.md` to override.\n *\n * Keep this list small and high-leverage. The bar for adding one: it\n * demonstrates a pattern users would otherwise have to invent\n * themselves, and the body fits in a screen.\n */\nconst BUILTIN_EXPLORE_BODY = `You are running as an exploration subagent. Your job is to investigate the codebase the parent agent pointed you at, then return one focused, distilled answer.\n\nHow to operate:\n- Use read_file, search_files, search_content, directory_tree, list_directory, get_file_info as your primary tools. Stay read-only.\n- For \"find all places that call / reference / use X\" questions, use \\`search_content\\` (content grep) — NOT \\`search_files\\` (which only matches file names). This is the most common subagent mistake; using the wrong tool gives empty results and you waste your iter budget chasing a phantom.\n- Cast a wide net first (search_content for symbol references, directory_tree for structure) to map the territory; then read the 3-10 most relevant files in full.\n- Don't read every file — be selective. Aim for breadth on the first pass, depth only where the question demands it.\n- Stop exploring as soon as you can answer the question. The parent doesn't see your tool calls, so over-exploration is pure waste.\n\nYour final answer:\n- One paragraph (or a few short bullets). Lead with the conclusion.\n- Cite specific file paths + line ranges when they support the answer.\n- If the question can't be answered from what you found, say so plainly and suggest where to look next.\n- No follow-up offers, no \"let me know if you need more.\" The parent will ask again if they need more.\n\nFormatting (rendered in a TUI):\n- Tabular data → GitHub-Flavored Markdown tables with ASCII pipes (\\`| col | col |\\` + \\`| --- | --- |\\`). Never use Unicode box-drawing characters (│ ─ ┼) — they break word-wrap.\n- Keep table cells short; if a cell needs a paragraph, use bullets below the table instead.\n- Code, file paths with line ranges, and shell commands → fenced code blocks (\\`\\`\\`).\n- NEVER draw decorative frames around code or text with \\`┌──┐ │ └──┘\\` box-drawing characters. Use plain code blocks; the renderer adds its own border.\n- For flow charts: use a bullet list with \\`→\\` or \\`↓\\` between steps, not ASCII boxes-and-arrows.\n\nThe 'task' the parent gave you is the question you must answer. Treat any other reading of it as scope creep.`;\n\nconst BUILTIN_RESEARCH_BODY = `You are running as a research subagent. Your job is to gather information from code AND the web, synthesize it, and return one focused conclusion.\n\nHow to operate:\n- Combine code reading (read_file, search_files) with web tools (web_search, web_fetch) as appropriate to the question.\n- For \"how does X work\" / \"is Y supported\" questions: web first to find the canonical reference, then verify against the local code.\n- For \"what's our policy on Z\" / \"where do we use Q\": local code first, web only if you need to compare against external standards.\n- Cap yourself at ~10 tool calls. If you can't converge in 10, return what you have plus a note about what's missing.\n\nYour final answer:\n- One paragraph (or short bullets). Lead with the conclusion.\n- Cite both code (file:line) AND web sources (URL) when they back the answer.\n- Distinguish \"I verified this in code\" from \"I read this on a docs page\" — the parent will trust the former more.\n- If the answer is uncertain, say so. Don't invent confidence.\n\nFormatting (rendered in a TUI):\n- Tabular data → GitHub-Flavored Markdown tables with ASCII pipes (\\`| col | col |\\` + \\`| --- | --- |\\`). Never use Unicode box-drawing characters (│ ─ ┼) — they break word-wrap.\n- Keep table cells short; if a cell needs a paragraph, use bullets below the table instead.\n- Code, file paths with line ranges, and shell commands → fenced code blocks (\\`\\`\\`).\n- NEVER draw decorative frames around code or text with \\`┌──┐ │ └──┘\\` box-drawing characters. Use plain code blocks; the renderer adds its own border.\n- For flow charts: use a bullet list with \\`→\\` or \\`↓\\` between steps, not ASCII boxes-and-arrows.\n\nThe 'task' the parent gave you is the research question. Stay on it.`;\n\nconst BUILTIN_SKILLS: readonly Skill[] = Object.freeze([\n Object.freeze<Skill>({\n name: \"explore\",\n description:\n \"Explore the codebase in an isolated subagent — wide-net read-only investigation that returns one distilled answer. Best for: 'find all places that...', 'how does X work across the project', 'survey the code for Y'.\",\n body: BUILTIN_EXPLORE_BODY,\n scope: \"builtin\",\n path: \"(builtin)\",\n runAs: \"subagent\",\n }),\n Object.freeze<Skill>({\n name: \"research\",\n description:\n \"Research a question by combining web search + code reading in an isolated subagent. Best for: 'is X feature supported by lib Y', 'what's the canonical way to do Z', 'compare our impl against the spec'.\",\n body: BUILTIN_RESEARCH_BODY,\n scope: \"builtin\",\n path: \"(builtin)\",\n runAs: \"subagent\",\n }),\n]);\n","/**\n * Built-in filesystem tools for `reasonix code`.\n *\n * Why native instead of the official `@modelcontextprotocol/server-filesystem`:\n * - No subprocess overhead — every call is 50-200 ms cheaper.\n * - Schema shapes tuned for R1: `edit_file` takes a single\n * SEARCH/REPLACE string instead of `string=\"false\"`-encoded\n * JSON arrays, which was the biggest single source of DSML\n * hallucinations in 0.4.x.\n * - Sandbox enforcement lives here so Reasonix can reason about\n * it (tests cover path-traversal, symlink-escape, and the\n * cwd-outside-root case) rather than trusting an external server.\n * - No `npx install` / network dependency in `reasonix code`.\n *\n * Tool names + argument shapes intentionally mirror the official\n * filesystem server so R1's muscle memory carries over. The only\n * intentional divergence is `edit_file`, noted above.\n */\n\nimport { promises as fs } from \"node:fs\";\nimport * as pathMod from \"node:path\";\nimport type { ToolRegistry } from \"../tools.js\";\n\nexport interface FilesystemToolsOptions {\n /** Absolute directory the tools may read/write. Paths outside this are refused. */\n rootDir: string;\n /**\n * When `false`, register only read-side tools (read_file, list_directory,\n * search_files, get_file_info, directory_tree). Useful for read-only\n * workflows where the model should never mutate the tree. Default: true.\n */\n allowWriting?: boolean;\n /**\n * Cap for a single file read, in bytes. Prevents a stray `read_file`\n * on a multi-GB blob from OOM'ing Node. 2 MB is enough for any realistic\n * source file (the biggest single-file TypeScript project checked in to\n * GitHub is ~500 KB); pass higher when working with data files.\n */\n maxReadBytes?: number;\n /**\n * Cap for total bytes returned from search_files / directory_tree /\n * grep, so the model can't accidentally pull down the whole tree as\n * one giant string. 256 KB by default.\n */\n maxListBytes?: number;\n}\n\nconst DEFAULT_MAX_READ_BYTES = 2 * 1024 * 1024;\nconst DEFAULT_MAX_LIST_BYTES = 256 * 1024;\n\n/**\n * Directory names skipped by `search_content` unless `include_deps:true`\n * is passed. The intent is \"user is asking about THEIR code, not the\n * libraries they depend on\" — vendored / generated trees would otherwise\n * dominate every match list. Pass include_deps when you genuinely need\n * to grep a dependency.\n */\nconst SKIP_DIR_NAMES: ReadonlySet<string> = new Set([\n \"node_modules\",\n \".git\",\n \".hg\",\n \".svn\",\n \"dist\",\n \"build\",\n \"out\",\n \".next\",\n \".nuxt\",\n \"target\", // Rust / Java\n \".venv\",\n \"venv\",\n \"__pycache__\",\n \".pytest_cache\",\n \".mypy_cache\",\n \".cache\",\n \"coverage\",\n]);\n\n/**\n * Cheap binary-by-extension check for `search_content`. We err on the\n * side of skipping so a NUL-byte content sniff is the second line of\n * defense (handles e.g. a `.txt` that's actually a binary dump).\n */\nconst BINARY_EXTENSIONS: ReadonlySet<string> = new Set([\n \".png\",\n \".jpg\",\n \".jpeg\",\n \".gif\",\n \".bmp\",\n \".ico\",\n \".webp\",\n \".tiff\",\n \".pdf\",\n \".zip\",\n \".tar\",\n \".gz\",\n \".bz2\",\n \".xz\",\n \".7z\",\n \".rar\",\n \".exe\",\n \".dll\",\n \".so\",\n \".dylib\",\n \".bin\",\n \".class\",\n \".jar\",\n \".war\",\n \".o\",\n \".obj\",\n \".lib\",\n \".a\",\n \".woff\",\n \".woff2\",\n \".ttf\",\n \".otf\",\n \".eot\",\n \".mp3\",\n \".mp4\",\n \".mov\",\n \".avi\",\n \".webm\",\n \".wasm\",\n \".pyc\",\n \".pyo\",\n]);\n\nfunction isLikelyBinaryByName(name: string): boolean {\n const dot = name.lastIndexOf(\".\");\n if (dot < 0) return false;\n return BINARY_EXTENSIONS.has(name.slice(dot).toLowerCase());\n}\n\nexport function registerFilesystemTools(\n registry: ToolRegistry,\n opts: FilesystemToolsOptions,\n): ToolRegistry {\n const rootDir = pathMod.resolve(opts.rootDir);\n const allowWriting = opts.allowWriting !== false;\n const maxReadBytes = opts.maxReadBytes ?? DEFAULT_MAX_READ_BYTES;\n const maxListBytes = opts.maxListBytes ?? DEFAULT_MAX_LIST_BYTES;\n\n /** Resolve path, enforce it's under rootDir, return absolute. */\n const safePath = (raw: unknown): string => {\n if (typeof raw !== \"string\" || raw.length === 0) {\n throw new Error(\"path must be a non-empty string\");\n }\n // Sandbox-root semantics: a leading POSIX-style `/` (or `\\` on\n // Windows) means \"from the project root\", not \"from the filesystem\n // root\". Models routinely write `path: \"/\"` or `path: \"/src/foo.ts\"`\n // intending the sandbox root — without this normalization,\n // path.resolve interprets `/` as the actual drive root (`F:\\` on\n // Windows, `/` on POSIX) and the escape check rightly rejects it,\n // confusing the model. Strip leading separators so the rest of the\n // resolution treats the input as relative to rootDir. Drive-letter\n // absolutes (`C:\\foo`) and Unix absolutes outside rootDir still\n // get caught by the relative-escape check below.\n let normalized = raw;\n while (normalized.startsWith(\"/\") || normalized.startsWith(\"\\\\\")) {\n normalized = normalized.slice(1);\n }\n if (normalized.length === 0) normalized = \".\";\n const resolved = pathMod.resolve(rootDir, normalized);\n const normRoot = pathMod.resolve(rootDir);\n // Use relative() to catch any `..` segments that escape.\n const rel = pathMod.relative(normRoot, resolved);\n if (rel.startsWith(\"..\") || pathMod.isAbsolute(rel)) {\n throw new Error(`path escapes sandbox root (${normRoot}): ${raw}`);\n }\n return resolved;\n };\n\n registry.register({\n name: \"read_file\",\n description:\n \"Read a file under the sandbox root. Returns the full contents (truncated with a notice if larger than the per-call cap). Paths may be relative to the root or absolute-under-root.\",\n readOnly: true,\n parameters: {\n type: \"object\",\n properties: {\n path: { type: \"string\", description: \"Path to read (relative to rootDir or absolute).\" },\n head: { type: \"integer\", description: \"If set, return only the first N lines.\" },\n tail: { type: \"integer\", description: \"If set, return only the last N lines.\" },\n },\n required: [\"path\"],\n },\n fn: async (args: { path: string; head?: number; tail?: number }) => {\n const abs = safePath(args.path);\n const stat = await fs.stat(abs);\n if (stat.isDirectory()) {\n throw new Error(`not a file: ${args.path} (it's a directory)`);\n }\n const raw = await fs.readFile(abs);\n if (raw.length > maxReadBytes) {\n const head = raw.slice(0, maxReadBytes).toString(\"utf8\");\n return `${head}\\n\\n[…truncated ${raw.length - maxReadBytes} bytes — file is ${raw.length} B, cap ${maxReadBytes} B. Retry with head/tail for targeted view.]`;\n }\n const text = raw.toString(\"utf8\");\n if (typeof args.head === \"number\" && args.head > 0) {\n return text.split(/\\r?\\n/).slice(0, args.head).join(\"\\n\");\n }\n if (typeof args.tail === \"number\" && args.tail > 0) {\n let lines = text.split(/\\r?\\n/);\n // Most files end with a final '\\n', which splits into an empty\n // trailing string. Drop it before slicing so tail=2 returns the\n // last two *real* lines, not \"last line + empty\".\n if (lines.length > 0 && lines[lines.length - 1] === \"\") lines = lines.slice(0, -1);\n return lines.slice(Math.max(0, lines.length - args.tail)).join(\"\\n\");\n }\n return text;\n },\n });\n\n registry.register({\n name: \"list_directory\",\n description:\n \"List entries in a directory under the sandbox root. Returns one line per entry, marking directories with a trailing slash. Not recursive — use directory_tree for that.\",\n readOnly: true,\n parameters: {\n type: \"object\",\n properties: {\n path: { type: \"string\", description: \"Directory to list (default: root).\" },\n },\n },\n fn: async (args: { path?: string }) => {\n const abs = safePath(args.path ?? \".\");\n const entries = await fs.readdir(abs, { withFileTypes: true });\n const lines: string[] = [];\n for (const e of entries.sort((a, b) => a.name.localeCompare(b.name))) {\n lines.push(e.isDirectory() ? `${e.name}/` : e.name);\n }\n return lines.join(\"\\n\") || \"(empty directory)\";\n },\n });\n\n registry.register({\n name: \"directory_tree\",\n description:\n \"Recursively list entries in a directory. Shows indented tree structure with directories marked '/'. Caps output so a huge tree doesn't drown the context.\",\n readOnly: true,\n parameters: {\n type: \"object\",\n properties: {\n path: { type: \"string\", description: \"Root of the tree (default: sandbox root).\" },\n maxDepth: { type: \"integer\", description: \"Max recursion depth (default 4).\" },\n },\n },\n fn: async (args: { path?: string; maxDepth?: number }) => {\n const startAbs = safePath(args.path ?? \".\");\n const maxDepth = typeof args.maxDepth === \"number\" ? args.maxDepth : 4;\n const lines: string[] = [];\n let totalBytes = 0;\n let truncated = false;\n const walk = async (dir: string, depth: number): Promise<void> => {\n if (truncated) return;\n if (depth > maxDepth) return;\n let entries: import(\"node:fs\").Dirent[];\n try {\n entries = await fs.readdir(dir, { withFileTypes: true });\n } catch {\n return;\n }\n entries.sort((a, b) => a.name.localeCompare(b.name));\n for (const e of entries) {\n if (truncated) return;\n const indent = \" \".repeat(depth);\n const line = e.isDirectory() ? `${indent}${e.name}/` : `${indent}${e.name}`;\n totalBytes += line.length + 1;\n if (totalBytes > maxListBytes) {\n lines.push(` [… tree truncated at ${maxListBytes} bytes …]`);\n truncated = true;\n return;\n }\n lines.push(line);\n if (e.isDirectory()) {\n await walk(pathMod.join(dir, e.name), depth + 1);\n }\n }\n };\n await walk(startAbs, 0);\n return lines.join(\"\\n\") || \"(empty tree)\";\n },\n });\n\n registry.register({\n name: \"search_files\",\n description:\n \"Find files whose NAME matches a substring or regex. Case-insensitive. Walks the directory recursively under the sandbox root. Returns one path per line.\",\n readOnly: true,\n parameters: {\n type: \"object\",\n properties: {\n path: { type: \"string\", description: \"Directory to start the search at (default: root).\" },\n pattern: {\n type: \"string\",\n description: \"Substring (or regex) to match against filenames.\",\n },\n },\n required: [\"pattern\"],\n },\n fn: async (args: { path?: string; pattern: string }) => {\n const startAbs = safePath(args.path ?? \".\");\n const needle = args.pattern.toLowerCase();\n // Try as regex first (permits users who want patterns); fall\n // back to plain substring when it's not a valid regex. Flag `i`\n // so matching is case-insensitive regardless of path.\n let re: RegExp | null = null;\n try {\n re = new RegExp(args.pattern, \"i\");\n } catch {\n re = null;\n }\n const matches: string[] = [];\n let totalBytes = 0;\n const walk = async (dir: string): Promise<void> => {\n let entries: import(\"node:fs\").Dirent[];\n try {\n entries = await fs.readdir(dir, { withFileTypes: true });\n } catch {\n return;\n }\n for (const e of entries) {\n const full = pathMod.join(dir, e.name);\n const lower = e.name.toLowerCase();\n const hit = re ? re.test(e.name) : lower.includes(needle);\n if (hit) {\n const rel = pathMod.relative(rootDir, full);\n if (totalBytes + rel.length + 1 > maxListBytes) {\n matches.push(\"[… search truncated — refine pattern …]\");\n return;\n }\n matches.push(rel);\n totalBytes += rel.length + 1;\n }\n if (e.isDirectory()) await walk(full);\n }\n };\n await walk(startAbs);\n return matches.length === 0 ? \"(no matches)\" : matches.join(\"\\n\");\n },\n });\n\n registry.register({\n name: \"search_content\",\n description:\n \"Recursively grep file CONTENTS for a substring or regex. This is the right tool for 'find all places that call X', 'where is Y referenced', 'what files contain Z'. Different from search_files (which matches FILE NAMES). Returns one match per line in 'path:line: text' format. Skips dependency / VCS / build directories (node_modules, .git, dist, build, .next, target, .venv) and binary files by default.\",\n readOnly: true,\n parameters: {\n type: \"object\",\n properties: {\n pattern: {\n type: \"string\",\n description: \"Substring (or regex) to search file contents for.\",\n },\n path: {\n type: \"string\",\n description: \"Directory to start the search at (default: sandbox root).\",\n },\n glob: {\n type: \"string\",\n description:\n \"Optional file-name suffix or substring filter. Examples: '.ts' (only TypeScript), 'test' (any file with 'test' in the name). Reduces noise when you know the file shape.\",\n },\n case_sensitive: {\n type: \"boolean\",\n description: \"When true, match case exactly. Default false (case-insensitive).\",\n },\n include_deps: {\n type: \"boolean\",\n description:\n \"When true, also search inside node_modules / .git / dist / build / etc. Off by default — most exploration questions are about the user's own code.\",\n },\n },\n required: [\"pattern\"],\n },\n fn: async (args: {\n pattern: string;\n path?: string;\n glob?: string;\n case_sensitive?: boolean;\n include_deps?: boolean;\n }) => {\n const startAbs = safePath(args.path ?? \".\");\n const caseSensitive = args.case_sensitive === true;\n const includeDeps = args.include_deps === true;\n const nameFilter = typeof args.glob === \"string\" ? args.glob.toLowerCase() : null;\n // Try the pattern as a regex first (lets the model say `\\bdispatch\\(`\n // for a word-bounded match); fall back to literal substring on\n // invalid regex. No `g` flag — we test once per line, so global\n // statefulness (lastIndex tracking) would just be noise.\n let re: RegExp | null = null;\n try {\n re = new RegExp(args.pattern, caseSensitive ? \"\" : \"i\");\n } catch {\n re = null;\n }\n const needle = caseSensitive ? args.pattern : args.pattern.toLowerCase();\n const matches: string[] = [];\n let totalBytes = 0;\n let scanned = 0;\n let truncated = false;\n\n const walk = async (dir: string): Promise<void> => {\n if (truncated) return;\n let entries: import(\"node:fs\").Dirent[];\n try {\n entries = await fs.readdir(dir, { withFileTypes: true });\n } catch {\n return;\n }\n for (const e of entries) {\n if (truncated) return;\n if (e.isDirectory()) {\n if (!includeDeps && SKIP_DIR_NAMES.has(e.name)) continue;\n await walk(pathMod.join(dir, e.name));\n continue;\n }\n if (!e.isFile()) continue;\n if (nameFilter && !e.name.toLowerCase().includes(nameFilter)) continue;\n if (isLikelyBinaryByName(e.name)) continue;\n const full = pathMod.join(dir, e.name);\n let stat: import(\"node:fs\").Stats;\n try {\n stat = await fs.stat(full);\n } catch {\n continue;\n }\n // Per-file size cap so a 50MB log doesn't dominate the search.\n // Anything legitimately interesting fits in 2 MB; bigger files\n // are usually data dumps or generated bundles.\n if (stat.size > 2 * 1024 * 1024) continue;\n let raw: Buffer;\n try {\n raw = await fs.readFile(full);\n } catch {\n continue;\n }\n // Content-based binary sniff: a NUL byte in the first 8KB is\n // a strong indicator. Catches binaries with .json or .txt\n // extensions (yes, this happens).\n const firstNul = raw.indexOf(0);\n if (firstNul !== -1 && firstNul < 8 * 1024) continue;\n const text = raw.toString(\"utf8\");\n const rel = pathMod.relative(rootDir, full);\n const lines = text.split(/\\r?\\n/);\n for (let li = 0; li < lines.length; li++) {\n const line = lines[li]!;\n const lineForCheck = caseSensitive ? line : line.toLowerCase();\n const hit = re ? re.test(line) : lineForCheck.includes(needle);\n if (!hit) continue;\n // Truncate very long lines so one giant minified file\n // doesn't blow the budget on a single match.\n const display = line.length > 200 ? `${line.slice(0, 200)}…` : line;\n const out = `${rel}:${li + 1}: ${display}`;\n if (totalBytes + out.length + 1 > maxListBytes) {\n matches.push(`[… truncated at ${maxListBytes} bytes — refine pattern or path …]`);\n truncated = true;\n return;\n }\n matches.push(out);\n totalBytes += out.length + 1;\n }\n scanned++;\n }\n };\n await walk(startAbs);\n if (matches.length === 0) {\n return scanned === 0\n ? \"(no files scanned — path empty or all files filtered out)\"\n : `(no matches across ${scanned} file${scanned === 1 ? \"\" : \"s\"})`;\n }\n return matches.join(\"\\n\");\n },\n });\n\n registry.register({\n name: \"get_file_info\",\n description:\n \"Stat a path under the sandbox root. Returns type (file|directory|symlink), size in bytes, mtime in ISO-8601.\",\n readOnly: true,\n parameters: {\n type: \"object\",\n properties: {\n path: { type: \"string\" },\n },\n required: [\"path\"],\n },\n fn: async (args: { path: string }) => {\n const abs = safePath(args.path);\n const st = await fs.lstat(abs);\n const type = st.isDirectory() ? \"directory\" : st.isSymbolicLink() ? \"symlink\" : \"file\";\n return JSON.stringify({\n type,\n size: st.size,\n mtime: st.mtime.toISOString(),\n });\n },\n });\n\n if (!allowWriting) return registry;\n\n registry.register({\n name: \"write_file\",\n description:\n \"Create or overwrite a file under the sandbox root with the given content. Parent directories are created as needed.\",\n parameters: {\n type: \"object\",\n properties: {\n path: { type: \"string\" },\n content: { type: \"string\" },\n },\n required: [\"path\", \"content\"],\n },\n fn: async (args: { path: string; content: string }) => {\n const abs = safePath(args.path);\n await fs.mkdir(pathMod.dirname(abs), { recursive: true });\n await fs.writeFile(abs, args.content, \"utf8\");\n return `wrote ${args.content.length} chars to ${pathMod.relative(rootDir, abs)}`;\n },\n });\n\n registry.register({\n name: \"edit_file\",\n description:\n \"Apply a SEARCH/REPLACE edit to an existing file. `search` must match exactly (whitespace sensitive) — no regex. The match must be unique in the file; otherwise the edit is refused to avoid surprise rewrites.\",\n parameters: {\n type: \"object\",\n properties: {\n path: { type: \"string\" },\n search: { type: \"string\", description: \"Exact text to find (must be unique).\" },\n replace: { type: \"string\", description: \"Text to substitute in place of `search`.\" },\n },\n required: [\"path\", \"search\", \"replace\"],\n },\n fn: async (args: { path: string; search: string; replace: string }) => {\n const abs = safePath(args.path);\n const before = await fs.readFile(abs, \"utf8\");\n if (args.search.length === 0) {\n throw new Error(\"edit_file: search cannot be empty\");\n }\n const firstIdx = before.indexOf(args.search);\n if (firstIdx < 0) {\n throw new Error(`edit_file: search text not found in ${pathMod.relative(rootDir, abs)}`);\n }\n const nextIdx = before.indexOf(args.search, firstIdx + 1);\n if (nextIdx >= 0) {\n throw new Error(\n `edit_file: search text appears multiple times in ${pathMod.relative(rootDir, abs)} — include more context to disambiguate`,\n );\n }\n const after =\n before.slice(0, firstIdx) + args.replace + before.slice(firstIdx + args.search.length);\n await fs.writeFile(abs, after, \"utf8\");\n const rel = pathMod.relative(rootDir, abs);\n const header = `edited ${rel} (${args.search.length}→${args.replace.length} chars)`;\n // Starting line number of the search block in the original\n // file. `split/length` on the prefix gives a 1-based line\n // count where the match begins, matching git-diff's @@ -N,M\n // +N,M @@ header convention.\n const startLine = before.slice(0, firstIdx).split(/\\r?\\n/).length;\n const diff = renderEditDiff(args.search, args.replace, startLine);\n return `${header}\\n${diff}`;\n },\n });\n\n registry.register({\n name: \"create_directory\",\n description: \"Create a directory (and any missing parents) under the sandbox root.\",\n parameters: {\n type: \"object\",\n properties: { path: { type: \"string\" } },\n required: [\"path\"],\n },\n fn: async (args: { path: string }) => {\n const abs = safePath(args.path);\n await fs.mkdir(abs, { recursive: true });\n return `created ${pathMod.relative(rootDir, abs)}/`;\n },\n });\n\n registry.register({\n name: \"move_file\",\n description: \"Rename/move a file or directory under the sandbox root.\",\n parameters: {\n type: \"object\",\n properties: {\n source: { type: \"string\" },\n destination: { type: \"string\" },\n },\n required: [\"source\", \"destination\"],\n },\n fn: async (args: { source: string; destination: string }) => {\n const src = safePath(args.source);\n const dst = safePath(args.destination);\n await fs.mkdir(pathMod.dirname(dst), { recursive: true });\n await fs.rename(src, dst);\n return `moved ${pathMod.relative(rootDir, src)} → ${pathMod.relative(rootDir, dst)}`;\n },\n });\n\n return registry;\n}\n\n/**\n * Format an edit_file change as a proper line-level diff, styled\n * like `git diff`. Starts with a unified-diff hunk header —\n * `@@ -startLine,oldCount +startLine,newCount @@` — so the user\n * can tell where in the file the change lands. Body uses LCS\n * (longest common subsequence) to mark lines as removed (`-`),\n * added (`+`), or unchanged context (` `). Users were getting\n * hundreds of `-` followed by hundreds of `+` for tiny changes\n * because the naive \"dump both sides\" format can't tell what\n * actually moved vs. stayed — this fixes that and adds line-\n * number context on top.\n */\nfunction renderEditDiff(search: string, replace: string, startLine: number): string {\n const a = search.split(/\\r?\\n/);\n const b = replace.split(/\\r?\\n/);\n const diff = lineDiff(a, b);\n const hunk = `@@ -${startLine},${a.length} +${startLine},${b.length} @@`;\n const body = diff.map((d) => `${d.op === \" \" ? \" \" : d.op} ${d.line}`).join(\"\\n\");\n return `${hunk}\\n${body}`;\n}\n\n/**\n * Compute a line-level diff via classic LCS dynamic programming.\n * Good enough for SEARCH/REPLACE blocks where both sides are\n * typically under a few hundred lines — O(n*m) space + time. For\n * huge blocks we'd want Myers' algorithm, but the caller already\n * caps the inline-display size and `/tool N` shows the full result,\n * so quadratic is fine in practice.\n *\n * Exported so tests can exercise the diff logic without spinning\n * up the full tool dispatch path.\n */\nexport function lineDiff(\n a: readonly string[],\n b: readonly string[],\n): Array<{ op: \"-\" | \"+\" | \" \"; line: string }> {\n const n = a.length;\n const m = b.length;\n // dp[i][j] = LCS length of a[0..i) and b[0..j).\n const dp: number[][] = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(0));\n for (let i = 1; i <= n; i++) {\n for (let j = 1; j <= m; j++) {\n if (a[i - 1] === b[j - 1]) dp[i]![j] = dp[i - 1]![j - 1]! + 1;\n else dp[i]![j] = Math.max(dp[i - 1]![j]!, dp[i]![j - 1]!);\n }\n }\n // Backtrack to recover the op sequence.\n const out: Array<{ op: \"-\" | \"+\" | \" \"; line: string }> = [];\n let i = n;\n let j = m;\n while (i > 0 && j > 0) {\n if (a[i - 1] === b[j - 1]) {\n out.unshift({ op: \" \", line: a[i - 1]! });\n i--;\n j--;\n } else if ((dp[i - 1]![j] ?? 0) > (dp[i]![j - 1] ?? 0)) {\n out.unshift({ op: \"-\", line: a[i - 1]! });\n i--;\n } else {\n // Tie-break goes here (strictly less or equal): take the\n // insertion first during backtrack so the final forward order\n // renders removals BEFORE additions for a substitution —\n // matches git-diff convention of `- old / + new`.\n out.unshift({ op: \"+\", line: b[j - 1]! });\n j--;\n }\n }\n while (i > 0) {\n out.unshift({ op: \"-\", line: a[i - 1]! });\n i--;\n }\n while (j > 0) {\n out.unshift({ op: \"+\", line: b[j - 1]! });\n j--;\n }\n return out;\n}\n","/**\n * `remember` / `forget` / `recall_memory` — tools that let the model\n * read and write the user-memory store across sessions.\n *\n * Scope rules:\n * - `global` — always available (no sandbox needed).\n * - `project` — requires a `projectRoot` on MemoryStore. In chat mode\n * (no sandbox), the tools still register but a `scope=project` call\n * returns a structured refusal so the model can try `global` instead.\n *\n * Memory changes are written eagerly but NOT re-loaded into the prefix\n * mid-session (cache invariant). The user notices at `/new` or the next\n * launch — or they can read fresh content via `recall_memory` which\n * always hits disk.\n */\n\nimport type { ToolRegistry } from \"../tools.js\";\nimport {\n type MemoryScope,\n MemoryStore,\n type MemoryType,\n sanitizeMemoryName,\n} from \"../user-memory.js\";\n\nexport interface MemoryToolsOptions {\n /** Sandbox root for the `project` scope. Omit for chat mode. */\n projectRoot?: string;\n /** Override `~/.reasonix` (tests). */\n homeDir?: string;\n}\n\nexport function registerMemoryTools(\n registry: ToolRegistry,\n opts: MemoryToolsOptions = {},\n): ToolRegistry {\n const store = new MemoryStore({ homeDir: opts.homeDir, projectRoot: opts.projectRoot });\n const hasProject = store.hasProjectScope();\n\n registry.register({\n name: \"remember\",\n description:\n \"Save a memory for future sessions. Use when the user states a preference, corrects your approach, shares a non-obvious fact about this project, or explicitly asks you to remember something. Don't remember transient task state — only things worth recalling next session. The memory is written now but won't re-load into the system prompt until the next `/new` or launch.\",\n parameters: {\n type: \"object\",\n properties: {\n type: {\n type: \"string\",\n enum: [\"user\", \"feedback\", \"project\", \"reference\"],\n description:\n \"'user' = role/skills/prefs; 'feedback' = corrections or confirmed approaches; 'project' = facts/decisions about the current work; 'reference' = pointers to external systems the user uses.\",\n },\n scope: {\n type: \"string\",\n enum: [\"global\", \"project\"],\n description:\n \"'global' = applies across every project (preferences, tooling); 'project' = scoped to the current sandbox (decisions, local facts). Only available in `reasonix code`.\",\n },\n name: {\n type: \"string\",\n description:\n \"filename-safe identifier, 3-40 chars, alnum + _ - . (no path separators, no leading dot).\",\n },\n description: {\n type: \"string\",\n description: \"One-line summary shown in MEMORY.md (under ~150 chars).\",\n },\n content: {\n type: \"string\",\n description:\n \"Full memory body in markdown. For feedback/project types, structure as: rule/fact, then **Why:** line, then **How to apply:** line.\",\n },\n },\n required: [\"type\", \"scope\", \"name\", \"description\", \"content\"],\n },\n fn: async (args: {\n type: MemoryType;\n scope: MemoryScope;\n name: string;\n description: string;\n content: string;\n }) => {\n if (args.scope === \"project\" && !hasProject) {\n return JSON.stringify({\n error:\n \"scope='project' is unavailable in this session (no sandbox root). Retry with scope='global', or ask the user to switch to `reasonix code` for project-scoped memory.\",\n });\n }\n try {\n const path = store.write({\n name: args.name,\n type: args.type,\n scope: args.scope,\n description: args.description,\n body: args.content,\n });\n const key = sanitizeMemoryName(args.name);\n // The return text is load-bearing: it's the ONLY thing keeping\n // the fact visible within the current session, because the\n // prefix isn't re-hashed mid-session (Pillar 1). R1 reads this\n // on its next turn — the wording is deliberately imperative so\n // it doesn't get ignored in favor of explore-first behavior.\n return [\n `✓ REMEMBERED (${args.scope}/${key}): ${args.description}`,\n \"\",\n \"TREAT THIS AS ESTABLISHED FACT for the rest of this session.\",\n \"The user just told you — don't re-explore the filesystem to re-derive it.\",\n `(Saved to ${path}; pins into the system prompt on next /new or launch.)`,\n ].join(\"\\n\");\n } catch (err) {\n return JSON.stringify({ error: `remember failed: ${(err as Error).message}` });\n }\n },\n });\n\n registry.register({\n name: \"forget\",\n description:\n \"Delete a memory file and remove it from MEMORY.md. Use when the user explicitly asks to forget something, or when a previously-remembered fact has become wrong. Irreversible — no tombstone.\",\n parameters: {\n type: \"object\",\n properties: {\n name: { type: \"string\", description: \"Memory name (the identifier used in `remember`).\" },\n scope: { type: \"string\", enum: [\"global\", \"project\"] },\n },\n required: [\"name\", \"scope\"],\n },\n fn: async (args: { name: string; scope: MemoryScope }) => {\n if (args.scope === \"project\" && !hasProject) {\n return JSON.stringify({\n error: \"scope='project' is unavailable in this session (no sandbox root).\",\n });\n }\n try {\n const existed = store.delete(args.scope, args.name);\n return existed\n ? `forgot (${args.scope}/${sanitizeMemoryName(args.name)}). Re-load on next /new or launch.`\n : `no such memory: ${args.scope}/${args.name} (nothing to forget).`;\n } catch (err) {\n return JSON.stringify({ error: `forget failed: ${(err as Error).message}` });\n }\n },\n });\n\n registry.register({\n name: \"recall_memory\",\n description:\n \"Read the full body of a memory file when its MEMORY.md one-liner (already in the system prompt) isn't enough detail. Most of the time the index suffices — only call this when the user's question genuinely requires the full context.\",\n readOnly: true,\n parameters: {\n type: \"object\",\n properties: {\n name: { type: \"string\" },\n scope: { type: \"string\", enum: [\"global\", \"project\"] },\n },\n required: [\"name\", \"scope\"],\n },\n fn: async (args: { name: string; scope: MemoryScope }) => {\n if (args.scope === \"project\" && !hasProject) {\n return JSON.stringify({\n error: \"scope='project' is unavailable in this session (no sandbox root).\",\n });\n }\n try {\n const entry = store.read(args.scope, args.name);\n return [\n `# ${entry.name} (${entry.scope}/${entry.type}, created ${entry.createdAt || \"?\"})`,\n entry.description ? `> ${entry.description}` : \"\",\n \"\",\n entry.body,\n ]\n .filter(Boolean)\n .join(\"\\n\");\n } catch (err) {\n return JSON.stringify({ error: `recall failed: ${(err as Error).message}` });\n }\n },\n });\n\n return registry;\n}\n","/**\n * Plan Mode — read-only exploration phase for `reasonix code`.\n *\n * Shape (mirrors claude-code's plan/act split, adapted for Reasonix):\n *\n * 1. User types `/plan` → registry switches to plan-mode enforcement\n * (write tools refused at dispatch; reads + allowlisted shell\n * still work).\n * 2. Model explores, then calls `submit_plan` with a markdown plan.\n * 3. `submit_plan` throws `PlanProposedError`, which the TUI renders\n * as a picker: Approve / Refine / Cancel.\n * 4. Approve → registry leaves plan mode, a synthetic user message\n * \"The plan has been approved. Implement it now.\" is pushed into\n * the loop so the next turn executes.\n *\n * The read-only enforcement lives in `ToolRegistry.dispatch` via\n * `readOnly` / `readOnlyCheck`; this file only ships the `submit_plan`\n * escape hatch and the error type that carries the plan out of the\n * registry without stuffing it into the message.\n *\n * We do not change `ImmutablePrefix.toolSpecs` when plan mode toggles —\n * that would break Pillar 1's prefix cache. Instead the same full spec\n * list stays pinned, and the registry enforces mode at dispatch time.\n * The refusal string teaches the model the rule; cache hits stay\n * intact.\n */\n\nimport type { ToolRegistry } from \"../tools.js\";\n\n/**\n * Thrown by `submit_plan` when plan mode is active, carrying the plan\n * text the TUI will render for the user's approval.\n *\n * Implements the `toToolResult` protocol so `ToolRegistry.dispatch`\n * serializes the full plan into the tool-result JSON (not just the\n * error message). The TUI parses `{ error, plan }` from the tool event\n * and mounts the `PlanConfirm` picker.\n */\nexport class PlanProposedError extends Error {\n readonly plan: string;\n constructor(plan: string) {\n super(\n \"PlanProposedError: plan submitted. STOP calling tools now — the TUI has shown the plan to the user. Wait for their next message; it will either approve (you'll then implement the plan), request a refinement (you should explore more and submit an updated plan), or cancel (drop the plan and ask what they want instead). Don't call any tools in the meantime.\",\n );\n this.name = \"PlanProposedError\";\n this.plan = plan;\n }\n\n /**\n * Structured tool-result shape. Consumed by the TUI to extract the\n * plan without regex-scraping the error message.\n */\n toToolResult(): { error: string; plan: string } {\n return { error: `${this.name}: ${this.message}`, plan: this.plan };\n }\n}\n\nexport interface PlanToolOptions {\n /**\n * Optional side-channel callback fired when the model submits a plan.\n * The TUI uses this to preview the plan in real time (the tool-result\n * event is also emitted; this is just earlier and friendlier to\n * test harnesses that don't want to parse JSON).\n */\n onPlanSubmitted?: (plan: string) => void;\n}\n\nexport function registerPlanTool(registry: ToolRegistry, opts: PlanToolOptions = {}): ToolRegistry {\n registry.register({\n name: \"submit_plan\",\n description:\n \"Submit a concrete plan to the user for review before executing. Use this for tasks that warrant a review gate — multi-file refactors, architecture changes, anything that would be expensive or confusing to undo. Skip it for small fixes (one-line typo, obvious bug with a clear fix) — just make the change. The user will either approve (you then implement it), ask for refinement, or cancel. If the user has already enabled /plan mode, writes are blocked at dispatch and you MUST use this. Write the plan as markdown with a one-line summary, a bulleted list of files to touch and what will change, and any risks or open questions.\",\n readOnly: true,\n parameters: {\n type: \"object\",\n properties: {\n plan: {\n type: \"string\",\n description:\n \"Markdown-formatted plan. Lead with a one-sentence summary. Then a file-by-file breakdown of what you'll change and why. Flag any risks or open questions at the end so the user can weigh in before you start.\",\n },\n },\n required: [\"plan\"],\n },\n fn: async (args: { plan: string }) => {\n const plan = (args?.plan ?? \"\").trim();\n if (!plan) {\n throw new Error(\"submit_plan: empty plan — write a markdown plan and try again.\");\n }\n // Always fire the picker, not just inside plan mode. Plan mode's\n // role is the *stronger* constraint — it forces you into read-only\n // until you submit. Outside plan mode, submit_plan is your own\n // call: use it when the task is large enough to deserve a review\n // gate (multi-file refactors, architecture changes, anything\n // that would be expensive to undo), skip it for small fixes.\n opts.onPlanSubmitted?.(plan);\n throw new PlanProposedError(plan);\n },\n });\n return registry;\n}\n","/**\n * Subagent runtime — isolated child loops for offloading exploration or\n * self-contained subtasks.\n *\n * Two surfaces sit on top of the same `spawnSubagent` core:\n *\n * 1. `registerSubagentTool` — exposes a low-level `spawn_subagent`\n * function-call tool. Library API. NOT registered into the model\n * tool list by `reasonix code` since 0.4.26 — Skills (with\n * `runAs: subagent` frontmatter) became the user-facing surface.\n * Kept exported because library callers and tests still want\n * direct access to the primitive.\n *\n * 2. `run_skill` (in src/tools/skills.ts) — when the resolved skill\n * has `runAs: subagent`, it calls `spawnSubagent` with the skill\n * body as the system prompt and the user's `arguments` as the\n * task. Subagent skills are listed in the pinned Skills index\n * with a 🧬 marker, which gives the model a clear pattern-match\n * trigger without forcing it to reason about \"is this task big\n * enough to delegate.\"\n *\n * Why R1 specifically benefits:\n * - R1 reasoning tokens are expensive AND inflate the parent context.\n * A subagent runs its own private loop, then surfaces only the\n * distilled final answer back to the parent — the main session\n * never sees the reasoning trail.\n *\n * Invariants common to both surfaces:\n * - Serial only — no parallel spawn (MVP).\n * - Inherits parent's tool registry MINUS `spawn_subagent` itself\n * (no recursion via the tool API) and MINUS `submit_plan`\n * (subagents don't propose plans to the user).\n * - No hooks, no session — runs are ephemeral.\n * - Lower default `maxToolIters` than the parent (16 vs 64).\n * - Independent prefix cache (subagent's prefix has its own\n * fingerprint).\n * - Parent registry's plan-mode state propagates: subagents can't\n * escape `/plan`.\n * - Non-streaming child loop — the parent isn't watching deltas, so\n * streaming would only add an SSE parser to the critical path.\n * Cancellation still works via the AbortSignal.\n */\n\nimport type { DeepSeekClient } from \"../client.js\";\nimport { CacheFirstLoop } from \"../loop.js\";\nimport { ImmutablePrefix } from \"../memory.js\";\nimport { applyProjectMemory } from \"../project-memory.js\";\nimport { ToolRegistry } from \"../tools.js\";\n\n/**\n * Live event emitted by a running subagent. Surfaced via the optional\n * `sink` ref the TUI attaches its handler to. Side-channel only — these\n * events do NOT pass through the parent loop's `LoopEvent` stream\n * because subagents run inside a tool-dispatch frame, after the parent's\n * `step()` has already yielded `tool_start` and is awaiting the result.\n */\nexport interface SubagentEvent {\n kind: \"start\" | \"progress\" | \"end\";\n /** First ~30 chars of the task prompt — used for the TUI status row. */\n task: string;\n /** Iteration count inside the child loop (number of tool results so far). */\n iter?: number;\n /** Wall-clock ms since the subagent started. */\n elapsedMs?: number;\n /** First ~120 chars of the final assistant message. Set on `end`. */\n summary?: string;\n /** Error message if the subagent failed. Set on `end`. */\n error?: string;\n /** Total turns the subagent took. Set on `end`. */\n turns?: number;\n}\n\n/**\n * Mutable ref the registration writes through. The TUI sets `.current`\n * to its own handler on mount; nothing receives events before that\n * happens (and headless callers leave `.current = null`, which is the\n * library-mode default — they read the final result from the helper's\n * return value instead).\n */\nexport interface SubagentSink {\n current: ((ev: SubagentEvent) => void) | null;\n}\n\n/**\n * Per-spawn options for {@link spawnSubagent}. All but `parentRegistry`\n * + `client` + `system` + `task` are tunables with sensible defaults.\n */\nexport interface SpawnSubagentOptions {\n /** Shared DeepSeek client. The subagent reuses it (same auth, same retries). */\n client: DeepSeekClient;\n /**\n * Parent registry — the subagent inherits a copy of its tools (minus\n * the never-inherited set: `spawn_subagent`, `submit_plan`).\n */\n parentRegistry: ToolRegistry;\n /**\n * System prompt for the child loop. Skills' subagent path passes\n * the skill body here; the spawn_subagent tool passes its default\n * (or the model's `system` argument override).\n */\n system: string;\n /** The task / question / instruction the subagent must address. */\n task: string;\n /** Model id for the child loop. Defaults to `deepseek-chat`. */\n model?: string;\n /** Iteration ceiling for the child loop. Defaults to 16. */\n maxToolIters?: number;\n /**\n * Maximum chars of the final assistant message returned. Long answers\n * are truncated with a notice — the parent's prompt budget shouldn't\n * be blown out by an over-eager subagent.\n */\n maxResultChars?: number;\n /** Optional sink for TUI live updates. */\n sink?: SubagentSink;\n /**\n * Parent's per-tool-dispatch AbortSignal. When the parent aborts (Esc),\n * we forward the cancel into the child loop. Omit for headless callers\n * that don't care about cancellation.\n */\n parentSignal?: AbortSignal;\n}\n\n/**\n * Structured result of a subagent run. The two convenience JSON wrappers\n * (`spawn_subagent` tool, `run_skill` subagent path) serialize this for\n * the model; library callers can read the typed object directly.\n */\nexport interface SubagentResult {\n success: boolean;\n /** Final assistant message (possibly truncated). Empty on error. */\n output: string;\n /** Set when the run failed (network, child-loop error, etc.). */\n error?: string;\n /** Turns the child loop took. */\n turns: number;\n /** Tool calls dispatched inside the child loop. */\n toolIters: number;\n /** Wall-clock ms. */\n elapsedMs: number;\n /** USD spent in the child loop, summed across its turns. */\n costUsd: number;\n}\n\nexport interface SubagentToolOptions {\n /** Shared DeepSeek client. */\n client: DeepSeekClient;\n /**\n * Default system prompt used when the model doesn't pass one. Project\n * memory (REASONIX.md) is appended automatically when `projectRoot` is\n * set.\n */\n defaultSystem?: string;\n /** Project root for `applyProjectMemory` lookup. Omit in chat mode. */\n projectRoot?: string;\n /** Default model. `deepseek-chat` (V3) by default. */\n defaultModel?: string;\n /** Iteration ceiling. Lower than the parent (16 by default). */\n maxToolIters?: number;\n /** Maximum chars returned in the tool result. */\n maxResultChars?: number;\n /** Optional sink the TUI attaches its handler to for live updates. */\n sink?: SubagentSink;\n}\n\nconst DEFAULT_SUBAGENT_SYSTEM = `You are a Reasonix subagent. The parent agent spawned you to handle one focused subtask, then return.\n\nRules:\n- Stay on the task you were given. Do not expand scope.\n- Use tools as needed. You share the parent's sandbox + safety rules.\n- When you're done, your final assistant message is the only thing the parent will see — make it complete and self-contained. No follow-up offers, no questions, no \"let me know if you need more.\"\n- Prefer one clear, distilled answer over a long log of what you tried.\n\nFormatting rules (the parent renders your reply in a TUI with a real markdown renderer):\n- For tabular data use GitHub-Flavored Markdown tables with ASCII pipes: \\`| col | col |\\` headers, \\`| --- | --- |\\` separator. NEVER draw tables with Unicode box-drawing characters (│ ─ ┼ ┌ ┐ └ ┘ ├ ┤). They look intentional but break terminal word-wrap and produce garbled output.\n- Keep table cells short — one short phrase per cell, not multi-line paragraphs. If a description doesn't fit in ~40 chars, use bullets below the table instead.\n- Use fenced code blocks (\\`\\`\\`) for any code, file paths with line ranges, or shell commands.\n- NEVER draw decorative frames around content with \\`┌──┐ │ └──┘\\` box-drawing characters. The renderer handles code blocks and headings on its own — extra ASCII art adds noise without value and breaks at narrow terminal widths.\n- For flow charts and diagrams: use a markdown bullet list with \\`→\\` or \\`↓\\` between steps. Don't try to draw boxes-and-arrows in ASCII; it never survives word-wrap.`;\n\nconst DEFAULT_MAX_RESULT_CHARS = 8000;\nconst DEFAULT_MAX_ITERS = 16;\nconst DEFAULT_SUBAGENT_MODEL = \"deepseek-chat\";\n\nconst SUBAGENT_TOOL_NAME = \"spawn_subagent\";\n/**\n * Tools the subagent never inherits from the parent registry:\n * - spawn_subagent itself: would allow unbounded recursion via the\n * tool API. Depth=1 hard cap by construction.\n * - submit_plan: only the parent talks to the user about plan\n * approval; a subagent submitting a plan would surface a picker\n * midway through the parent's turn, which the user did not ask for.\n */\nconst NEVER_INHERITED_TOOLS = new Set<string>([SUBAGENT_TOOL_NAME, \"submit_plan\"]);\n\n/**\n * Run one subagent to completion. The unified primitive both\n * `spawn_subagent` (function-call tool) and `run_skill` (subagent\n * skills) call into.\n *\n * Headless: returns a `SubagentResult` regardless of success/failure.\n * Errors are captured in the structured shape, never thrown — the\n * caller decides how to surface them (tool result JSON, log line, etc.).\n */\nexport async function spawnSubagent(opts: SpawnSubagentOptions): Promise<SubagentResult> {\n const model = opts.model ?? DEFAULT_SUBAGENT_MODEL;\n const maxToolIters = opts.maxToolIters ?? DEFAULT_MAX_ITERS;\n const maxResultChars = opts.maxResultChars ?? DEFAULT_MAX_RESULT_CHARS;\n const sink = opts.sink;\n\n const startedAt = Date.now();\n const taskPreview = opts.task.length > 30 ? `${opts.task.slice(0, 30)}…` : opts.task;\n sink?.current?.({\n kind: \"start\",\n task: taskPreview,\n iter: 0,\n elapsedMs: 0,\n });\n\n const childTools = forkRegistryExcluding(opts.parentRegistry, NEVER_INHERITED_TOOLS);\n const childPrefix = new ImmutablePrefix({\n system: opts.system,\n toolSpecs: childTools.specs(),\n });\n const childLoop = new CacheFirstLoop({\n client: opts.client,\n prefix: childPrefix,\n tools: childTools,\n model,\n maxToolIters,\n hooks: [],\n stream: false,\n });\n\n const onParentAbort = () => childLoop.abort();\n opts.parentSignal?.addEventListener(\"abort\", onParentAbort, { once: true });\n\n let final = \"\";\n let errorMessage: string | undefined;\n let toolIter = 0;\n try {\n for await (const ev of childLoop.step(opts.task)) {\n if (ev.role === \"tool\") {\n toolIter++;\n sink?.current?.({\n kind: \"progress\",\n task: taskPreview,\n iter: toolIter,\n elapsedMs: Date.now() - startedAt,\n });\n }\n if (ev.role === \"assistant_final\") {\n final = ev.content ?? \"\";\n }\n if (ev.role === \"error\") {\n errorMessage = ev.error ?? \"subagent error\";\n }\n }\n } catch (err) {\n errorMessage = (err as Error).message;\n } finally {\n opts.parentSignal?.removeEventListener(\"abort\", onParentAbort);\n }\n // The loop yields `done` without an `error` event when its API call\n // is aborted mid-flight (intentional UX — see the matching catch in\n // CacheFirstLoop.step). From a SUBAGENT consumer's perspective that\n // still counts as a failure: no answer came back, the parent has\n // nothing to render. Synthesize an error so `success: false` and the\n // UI surfaces the abort instead of returning empty output.\n if (!errorMessage && !final) {\n errorMessage = opts.parentSignal?.aborted\n ? \"subagent aborted before producing an answer\"\n : \"subagent ended without producing an answer\";\n }\n\n const elapsedMs = Date.now() - startedAt;\n const turns = childLoop.stats.turns.length;\n const costUsd = childLoop.stats.totalCost;\n\n const truncated =\n final.length > maxResultChars\n ? `${final.slice(0, maxResultChars)}\\n\\n[…truncated ${final.length - maxResultChars} chars; ask the subagent for a tighter summary if you need more.]`\n : final;\n\n sink?.current?.({\n kind: \"end\",\n task: taskPreview,\n iter: toolIter,\n elapsedMs,\n summary: errorMessage ? undefined : truncated.slice(0, 120),\n error: errorMessage,\n turns,\n });\n\n return {\n success: !errorMessage,\n output: errorMessage ? \"\" : truncated,\n error: errorMessage,\n turns,\n toolIters: toolIter,\n elapsedMs,\n costUsd,\n };\n}\n\n/**\n * Serialize a {@link SubagentResult} into the JSON tool-result shape\n * the model consumes. Both the spawn_subagent tool and the run_skill\n * subagent path return this string verbatim, so the schema stays\n * stable across both surfaces.\n */\nexport function formatSubagentResult(r: SubagentResult): string {\n if (!r.success) {\n return JSON.stringify({\n success: false,\n error: r.error ?? \"unknown subagent error\",\n turns: r.turns,\n tool_iters: r.toolIters,\n elapsed_ms: r.elapsedMs,\n });\n }\n return JSON.stringify({\n success: true,\n output: r.output,\n turns: r.turns,\n tool_iters: r.toolIters,\n elapsed_ms: r.elapsedMs,\n cost_usd: r.costUsd,\n });\n}\n\n/**\n * Register the spawn_subagent tool into the parent registry. Library\n * surface — `reasonix code` does NOT call this since 0.4.26 (Skills\n * with `runAs: subagent` are the user-facing surface), but library\n * consumers who want the low-level tool can opt in.\n */\nexport function registerSubagentTool(\n parentRegistry: ToolRegistry,\n opts: SubagentToolOptions,\n): ToolRegistry {\n const baseSystem = opts.defaultSystem ?? DEFAULT_SUBAGENT_SYSTEM;\n // Bake project memory into the default once — re-reading on every\n // spawn would (a) make the child prefix unstable when REASONIX.md\n // changes mid-session, defeating cache reuse across multiple\n // subagent calls, and (b) cost a stat() per call. The parent itself\n // also reads memory once at startup; matching that semantics keeps\n // subagent and parent on the same page.\n const defaultSystem = opts.projectRoot\n ? applyProjectMemory(baseSystem, opts.projectRoot)\n : baseSystem;\n const defaultModel = opts.defaultModel ?? DEFAULT_SUBAGENT_MODEL;\n const maxToolIters = opts.maxToolIters ?? DEFAULT_MAX_ITERS;\n const maxResultChars = opts.maxResultChars ?? DEFAULT_MAX_RESULT_CHARS;\n const sink = opts.sink;\n\n parentRegistry.register({\n name: SUBAGENT_TOOL_NAME,\n description:\n \"Spawn an isolated subagent to handle a self-contained subtask in a fresh context, returning only its final answer. Use for: deep codebase exploration that would flood the main context, multi-step research where you only need the conclusion, or any focused subtask whose intermediate reasoning the user does not need to see. The subagent inherits all your tools (filesystem, shell, web, MCP, etc.) but runs in its own isolated message log — its tool calls and reasoning never enter your context. Only the final assistant message comes back as this tool's result. Keep tasks focused; the subagent has a stricter iter budget than you do.\",\n parameters: {\n type: \"object\",\n properties: {\n task: {\n type: \"string\",\n description:\n \"The subtask the subagent should perform. Be specific and self-contained — the subagent has none of your conversation context, only what you write here.\",\n },\n system: {\n type: \"string\",\n description:\n \"Optional override for the subagent's system prompt. The default tells it to stay focused and return a concise answer; override only when the subtask needs a specialized persona.\",\n },\n model: {\n type: \"string\",\n enum: [\"deepseek-chat\", \"deepseek-reasoner\"],\n description:\n \"Which DeepSeek model the subagent runs on. 'deepseek-chat' (V3) is the default — fast and cheap. Use 'deepseek-reasoner' (R1) only when the subtask genuinely needs planning or multi-step reasoning; it is roughly 5-10x more expensive.\",\n },\n },\n required: [\"task\"],\n },\n fn: async (args: { task?: unknown; system?: unknown; model?: unknown }, ctx) => {\n const task = typeof args.task === \"string\" ? args.task.trim() : \"\";\n if (!task) {\n return JSON.stringify({\n error: \"spawn_subagent requires a non-empty 'task' argument.\",\n });\n }\n const system =\n typeof args.system === \"string\" && args.system.trim().length > 0\n ? args.system.trim()\n : defaultSystem;\n const model =\n typeof args.model === \"string\" && args.model.startsWith(\"deepseek-\")\n ? args.model\n : defaultModel;\n const result = await spawnSubagent({\n client: opts.client,\n parentRegistry,\n system,\n task,\n model,\n maxToolIters,\n maxResultChars,\n sink,\n parentSignal: ctx?.signal,\n });\n return formatSubagentResult(result);\n },\n });\n\n return parentRegistry;\n}\n\n/**\n * Build a child ToolRegistry that copies every tool from `parent` except\n * those whose names are in `exclude`. Plan-mode state propagates so a\n * subagent spawned while the parent is under `/plan` cannot escape it.\n *\n * Exported for tests + library callers who want the same fork behavior\n * for their own nested-loop patterns.\n */\nexport function forkRegistryExcluding(\n parent: ToolRegistry,\n exclude: ReadonlySet<string>,\n): ToolRegistry {\n const child = new ToolRegistry();\n for (const spec of parent.specs()) {\n const name = spec.function.name;\n if (exclude.has(name)) continue;\n const def = parent.get(name);\n if (!def) continue;\n // Re-register copies the public ToolDefinition fields. The child\n // re-runs auto-flatten analysis on its own, which produces an\n // identical flatSchema for the same input — no surprise.\n child.register(def);\n }\n if (parent.planMode) child.setPlanMode(true);\n return child;\n}\n","/**\n * Native shell tool — lets the model run commands inside the sandbox\n * root so it can actually verify its own work (run tests, check git\n * status, inspect a lockfile, etc.). Without this the coding-mode\n * loop is \"write code, hope it works, ask the user to run it\" —\n * defeats the purpose.\n *\n * Safety model:\n * - Commands run with `cwd` pinned to the registered root. No\n * path traversal via the command itself is enforced (users can\n * `cat ../outside.txt`); the trust boundary is the directory\n * you opened Reasonix from.\n * - Commands are matched against a read-only / testing allowlist.\n * Allowlisted commands execute immediately and return stdout +\n * stderr merged. Everything else throws with a clear message —\n * the UI translates that into an `/apply`-style confirm gate so\n * the user sees the exact command before it runs.\n * - Default timeout: 60s. Output cap: matches tool-result budget.\n * - Every command that DOES run is spawned with `shell: false` and\n * a tokenized argv — no string-to-shell interpolation, so the\n * model can't accidentally construct a chained `rm` via quoting.\n *\n * This is intentionally narrower than what Claude Code / Aider ship:\n * we gate more commands behind confirmation by default. Users who\n * trust the model can widen the allowlist by instantiating their\n * own tool registry.\n */\n\nimport { type SpawnOptions, spawn } from \"node:child_process\";\nimport { existsSync, statSync } from \"node:fs\";\nimport * as pathMod from \"node:path\";\nimport type { ToolRegistry } from \"../tools.js\";\n\nexport interface ShellToolsOptions {\n /** Directory to run commands in. Must be an absolute path. */\n rootDir: string;\n /** Seconds before an individual command is killed. Default: 60. */\n timeoutSec?: number;\n /**\n * Per-command stdout+stderr cap in characters. Default: 32_000 to\n * match the tool-result budget.\n */\n maxOutputChars?: number;\n /**\n * Extra command-name prefixes the user explicitly trusts. Added on\n * top of the built-in allowlist. Examples: `[\"my-ci-script\", \"lint\"]`.\n *\n * Accepts either a fixed array (captured once at registration) or a\n * getter called on every dispatch. The getter form is load-bearing:\n * when the TUI's `ShellConfirm` writes a new prefix to config mid-\n * session, the running `run_command` must pick it up immediately —\n * otherwise the same command gets re-prompted until the next launch.\n */\n extraAllowed?: readonly string[] | (() => readonly string[]);\n /**\n * When true, skip the allowlist entirely and auto-run every command.\n * Off by default — this is an escape hatch for non-interactive use\n * (CI, benchmarks) where a human can't be in the loop to confirm.\n */\n allowAll?: boolean;\n}\n\nconst DEFAULT_TIMEOUT_SEC = 60;\nconst DEFAULT_MAX_OUTPUT_CHARS = 32_000;\n\n/**\n * Command prefixes we consider safe to run without asking the user.\n * Rule of thumb: read-only reports, or test runners whose failure mode\n * is \"exit 1 with output.\" Nothing that can rewrite state, escalate,\n * or touch the network.\n */\nconst BUILTIN_ALLOWLIST: ReadonlyArray<string> = [\n // Repo inspection\n \"git status\",\n \"git diff\",\n \"git log\",\n \"git show\",\n \"git blame\",\n \"git branch\",\n \"git remote\",\n \"git rev-parse\",\n \"git config --get\",\n // Filesystem inspection\n \"ls\",\n \"pwd\",\n \"cat\",\n \"head\",\n \"tail\",\n \"wc\",\n \"file\",\n \"tree\",\n \"find\",\n \"grep\",\n \"rg\",\n // Language version probes\n \"node --version\",\n \"node -v\",\n \"npm --version\",\n \"npx --version\",\n \"python --version\",\n \"python3 --version\",\n \"cargo --version\",\n \"go version\",\n \"rustc --version\",\n \"deno --version\",\n \"bun --version\",\n // Test runners (non-destructive by convention)\n \"npm test\",\n \"npm run test\",\n \"npx vitest run\",\n \"npx vitest\",\n \"npx jest\",\n \"pytest\",\n \"python -m pytest\",\n \"cargo test\",\n \"cargo check\",\n \"cargo clippy\",\n \"go test\",\n \"go vet\",\n \"deno test\",\n \"bun test\",\n // Linters / typecheckers (read-only by convention)\n \"npm run lint\",\n \"npm run typecheck\",\n \"npx tsc --noEmit\",\n \"npx biome check\",\n \"npx eslint\",\n \"npx prettier --check\",\n \"ruff\",\n \"mypy\",\n];\n\n/**\n * Tokenize a shell-ish command string into argv. Handles single/double\n * quoting; rejects unclosed quotes. Does NOT expand env vars, globs,\n * backticks, or `$(…)` — the goal is to prevent the model from\n * accidentally (or not) sneaking arbitrary shells past the allowlist\n * via concatenation. Exported for testing.\n */\nexport function tokenizeCommand(cmd: string): string[] {\n const out: string[] = [];\n let cur = \"\";\n let quote: '\"' | \"'\" | null = null;\n for (let i = 0; i < cmd.length; i++) {\n const ch = cmd[i]!;\n if (quote) {\n if (ch === quote) {\n quote = null;\n } else if (ch === \"\\\\\" && quote === '\"' && i + 1 < cmd.length) {\n cur += cmd[++i];\n } else {\n cur += ch;\n }\n continue;\n }\n if (ch === '\"' || ch === \"'\") {\n quote = ch;\n continue;\n }\n if (ch === \" \" || ch === \"\\t\") {\n if (cur.length > 0) {\n out.push(cur);\n cur = \"\";\n }\n continue;\n }\n cur += ch;\n }\n if (quote) throw new Error(`unclosed ${quote} in command`);\n if (cur.length > 0) out.push(cur);\n return out;\n}\n\n/**\n * Scan `cmd` for a shell operator (`|`, `||`, `>`, `>>`, `<`, `<<`,\n * `&`, `&&`, `2>`, `2>>`, `2>&1`, `&>`) that appears unquoted at a\n * token boundary. Returns the operator string, or null if none.\n *\n * Why this exists: `run_command` documents \"no shell expansion, no\n * pipes, no redirects\" (the tool spawns argv directly, not through a\n * shell), but when the model writes `dir | findstr foo` the `|`\n * survives tokenization as a standalone token and gets quoted as the\n * literal string `\"|\"` by `quoteForCmdExe` — cmd.exe sees it as an\n * argument, not an operator, so the pipe silently fails. Detecting\n * operators up front lets us throw a clear error (\"split into separate\n * calls\") instead of letting the command run with surprising results.\n *\n * Quoted operators (`grep \"a|b\"`) and operator characters embedded in\n * larger tokens (`--flag=1&2`) are NOT flagged — those are literal\n * argv bytes and are safe to pass through.\n *\n * Exported for testing.\n */\nexport function detectShellOperator(cmd: string): string | null {\n const opPrefix = /^(?:2>&1|&>|\\|{1,2}|&{1,2}|2>{1,2}|>{1,2}|<{1,2})/;\n let cur = \"\";\n let curQuoted = false;\n let quote: '\"' | \"'\" | null = null;\n const check = (): string | null => {\n if (cur.length === 0 && !curQuoted) return null;\n if (!curQuoted) {\n const m = opPrefix.exec(cur);\n if (m) return m[0] ?? null;\n }\n return null;\n };\n for (let i = 0; i < cmd.length; i++) {\n const ch = cmd[i]!;\n if (quote) {\n if (ch === quote) {\n quote = null;\n } else if (ch === \"\\\\\" && quote === '\"' && i + 1 < cmd.length) {\n cur += cmd[++i];\n curQuoted = true;\n } else {\n cur += ch;\n curQuoted = true;\n }\n continue;\n }\n if (ch === '\"' || ch === \"'\") {\n quote = ch;\n curQuoted = true;\n continue;\n }\n if (ch === \" \" || ch === \"\\t\") {\n const op = check();\n if (op) return op;\n cur = \"\";\n curQuoted = false;\n continue;\n }\n cur += ch;\n }\n if (quote) return null; // let tokenizeCommand throw the unclosed-quote error\n return check();\n}\n\n/**\n * Return true when `cmd` matches an allowlisted prefix. Exported for\n * testing. Match is on the space-normalized leading tokens so\n * `git status -s ` and `git status` both match `git status`.\n */\nexport function isAllowed(cmd: string, extra: readonly string[] = []): boolean {\n const normalized = cmd.trim().replace(/\\s+/g, \" \");\n const allowlist = [...BUILTIN_ALLOWLIST, ...extra];\n for (const prefix of allowlist) {\n if (normalized === prefix) return true;\n if (normalized.startsWith(`${prefix} `)) return true;\n }\n return false;\n}\n\nexport interface RunCommandResult {\n exitCode: number | null;\n /** Combined stdout+stderr, truncated to `maxOutputChars` with a marker. */\n output: string;\n /** True when the process was killed for exceeding `timeoutSec`. */\n timedOut: boolean;\n}\n\nexport async function runCommand(\n cmd: string,\n opts: {\n cwd: string;\n timeoutSec?: number;\n maxOutputChars?: number;\n signal?: AbortSignal;\n },\n): Promise<RunCommandResult> {\n const argv = tokenizeCommand(cmd);\n if (argv.length === 0) throw new Error(\"run_command: empty command\");\n const operator = detectShellOperator(cmd);\n if (operator !== null) {\n throw new Error(\n `run_command: shell operator \"${operator}\" is not supported — this tool spawns one process, no shell expansion. Split into separate run_command calls and combine the output in your reasoning (e.g. instead of \\`grep foo *.ts | wc -l\\`, call \\`grep -c foo *.ts\\` or two separate commands). To pass \"${operator}\" as a literal argument, wrap it in quotes.`,\n );\n }\n const timeoutMs = (opts.timeoutSec ?? DEFAULT_TIMEOUT_SEC) * 1000;\n const maxChars = opts.maxOutputChars ?? DEFAULT_MAX_OUTPUT_CHARS;\n\n const spawnOpts: SpawnOptions = {\n cwd: opts.cwd,\n shell: false, // no shell-expansion — see header comment\n windowsHide: true,\n env: process.env,\n };\n\n // Windows: two layered fixes on top of shell:false —\n // 1. Resolve bare command names via PATH × PATHEXT (CreateProcess\n // ignores PATHEXT, so `npm` alone misses `npm.cmd`).\n // 2. Node 21.7.3+ (CVE-2024-27980) refuses to spawn `.cmd`/`.bat`\n // directly even with shell:false and safe args — throws\n // EINVAL at invocation time. Wrap those via `cmd.exe /d /s /c`\n // with verbatim args + manual quoting, so shell metacharacters\n // in arguments stay literal.\n // Unix path is unchanged.\n const { bin, args, spawnOverrides } = prepareSpawn(argv);\n const effectiveSpawnOpts = { ...spawnOpts, ...spawnOverrides };\n\n return await new Promise<RunCommandResult>((resolve, reject) => {\n let child: import(\"node:child_process\").ChildProcess;\n try {\n child = spawn(bin, args, effectiveSpawnOpts);\n } catch (err) {\n reject(err);\n return;\n }\n let buf = \"\";\n let timedOut = false;\n const killTimer = setTimeout(() => {\n timedOut = true;\n child.kill(\"SIGKILL\");\n }, timeoutMs);\n const onAbort = () => child.kill(\"SIGKILL\");\n opts.signal?.addEventListener(\"abort\", onAbort, { once: true });\n\n const onData = (chunk: Buffer | string) => {\n buf += chunk.toString();\n // Soft cap: we let the process keep running (killing early could\n // hide a real failure), but we stop growing the buffer past 2×\n // the cap so a chatty test can't OOM us.\n if (buf.length > maxChars * 2) buf = `${buf.slice(0, maxChars * 2)}`;\n };\n child.stdout?.on(\"data\", onData);\n child.stderr?.on(\"data\", onData);\n child.on(\"error\", (err) => {\n clearTimeout(killTimer);\n opts.signal?.removeEventListener(\"abort\", onAbort);\n reject(err);\n });\n child.on(\"close\", (code) => {\n clearTimeout(killTimer);\n opts.signal?.removeEventListener(\"abort\", onAbort);\n const output =\n buf.length > maxChars\n ? `${buf.slice(0, maxChars)}\\n\\n[… truncated ${buf.length - maxChars} chars …]`\n : buf;\n resolve({ exitCode: code, output, timedOut });\n });\n });\n}\n\n/**\n * Test/override hooks for {@link resolveExecutable}. Omitting any field\n * falls through to the real process globals — the runtime call path\n * uses defaults; tests inject `platform` + `env` + `isFile` to exercise\n * Windows-specific lookup from a Linux CI runner without touching\n * actual fs.\n */\nexport interface ResolveExecutableOptions {\n platform?: NodeJS.Platform;\n env?: { PATH?: string; PATHEXT?: string };\n /** Predicate swapped in by tests to avoid creating real files. */\n isFile?: (path: string) => boolean;\n /** Path.join used for the lookup. Defaults to Windows semantics on Windows. */\n pathDelimiter?: string;\n}\n\n/**\n * Resolve a bare command name (e.g. `npm`) to its on-disk path via\n * PATH × PATHEXT on Windows. Returns the input unchanged on non-Windows\n * platforms, when the input is already a path (contains `/`, `\\`, or is\n * absolute), or when no match is found in PATH × PATHEXT (caller gets a\n * natural ENOENT from spawn, which surfaces cleanly).\n *\n * Why this exists: `child_process.spawn` with `shell: false` invokes\n * Windows `CreateProcess`, which does not honor `PATHEXT` and does not\n * search for `.cmd` / `.bat` wrappers. Node-ecosystem tools ship as\n * `npm.cmd`, `npx.cmd`, `yarn.cmd`, etc., so a bare `npm` fails with\n * ENOENT under `shell: false`. Flipping to `shell: true` would work\n * but reintroduces shell-expansion (pipes, redirects, chained cmds)\n * that the tool was explicitly designed to forbid. This resolver\n * threads the needle.\n */\nexport function resolveExecutable(cmd: string, opts: ResolveExecutableOptions = {}): string {\n const platform = opts.platform ?? process.platform;\n if (platform !== \"win32\") return cmd;\n if (!cmd) return cmd;\n // Already a path fragment — spawn handles these natively.\n if (cmd.includes(\"/\") || cmd.includes(\"\\\\\") || pathMod.isAbsolute(cmd)) return cmd;\n // If the model wrote `npm.cmd` explicitly, respect that verbatim.\n if (pathMod.extname(cmd)) return cmd;\n\n const env = opts.env ?? process.env;\n const pathExt = (env.PATHEXT ?? \".COM;.EXE;.BAT;.CMD\")\n .split(\";\")\n .map((e) => e.trim())\n .filter(Boolean);\n const delimiter = opts.pathDelimiter ?? (platform === \"win32\" ? \";\" : pathMod.delimiter);\n const pathDirs = (env.PATH ?? \"\").split(delimiter).filter(Boolean);\n const isFile = opts.isFile ?? defaultIsFile;\n\n for (const dir of pathDirs) {\n for (const ext of pathExt) {\n // Force win32 join so CI tests that pass `platform: \"win32\"`\n // from a Linux runner get backslash-joined paths; the real-\n // Windows runtime path lands here too and gets the correct\n // separator regardless of where pathMod defaults.\n const full = pathMod.win32.join(dir, cmd + ext);\n if (isFile(full)) return full;\n }\n }\n return cmd;\n}\n\nfunction defaultIsFile(full: string): boolean {\n try {\n return existsSync(full) && statSync(full).isFile();\n } catch {\n return false;\n }\n}\n\n/**\n * Prepare `(bin, args, spawnOpts)` for the runCommand spawn call,\n * applying Windows-specific workarounds for (a) PATHEXT lookup and\n * (b) the CVE-2024-27980 prohibition on direct `.cmd`/`.bat` spawns.\n *\n * Exported so tests can assert the transformation without booting an\n * actual child process.\n */\nexport function prepareSpawn(\n argv: readonly string[],\n opts: ResolveExecutableOptions = {},\n): { bin: string; args: string[]; spawnOverrides: SpawnOptions } {\n const head = argv[0] ?? \"\";\n const tail = argv.slice(1);\n const platform = opts.platform ?? process.platform;\n const resolved = resolveExecutable(head, opts);\n\n if (platform !== \"win32\") {\n return { bin: resolved, args: [...tail], spawnOverrides: {} };\n }\n\n // `.cmd` / `.bat` wrappers require cmd.exe on post-CVE Node.\n if (/\\.(cmd|bat)$/i.test(resolved)) {\n const cmdline = [resolved, ...tail].map(quoteForCmdExe).join(\" \");\n return {\n bin: \"cmd.exe\",\n args: [\"/d\", \"/s\", \"/c\", withUtf8Codepage(cmdline)],\n // windowsVerbatimArguments prevents Node from re-quoting the /c\n // payload — we've already composed an exact cmd.exe command\n // line. Without this Node wraps our already-quoted string in\n // another round of quotes and cmd.exe can't parse it.\n spawnOverrides: { windowsVerbatimArguments: true },\n };\n }\n\n // Bare command names that PATH × PATHEXT couldn't resolve to an\n // on-disk file — these are almost always cmd.exe built-ins (`dir`,\n // `echo`, `type`, `ver`, `vol`, `where`, `help`, …) which don't\n // exist as standalone executables. Direct spawn crashes with ENOENT;\n // routing through cmd.exe lets the built-in resolve, and if it's\n // genuinely unknown the user gets the standard \"'foo' is not\n // recognized\" message instead of a raw spawn failure.\n if (isBareWindowsName(resolved) && resolved === head) {\n const cmdline = [head, ...tail].map(quoteForCmdExe).join(\" \");\n return {\n bin: \"cmd.exe\",\n args: [\"/d\", \"/s\", \"/c\", withUtf8Codepage(cmdline)],\n spawnOverrides: { windowsVerbatimArguments: true },\n };\n }\n\n // PowerShell variants: chcp 65001 doesn't help here because PowerShell\n // sets its own [Console]::OutputEncoding at startup — usually system\n // codepage (CP936/CP932/CP949 on CJK Windows) or UTF-16. The result\n // is mojibake when our `chunk.toString()` UTF-8-decodes its stdout.\n // Inject a UTF-8 setup prelude into the `-Command` (or `-c`) arg so\n // any output produced thereafter is UTF-8.\n if (isPowerShellExe(resolved)) {\n const patched = injectPowerShellUtf8(tail);\n if (patched) {\n return { bin: resolved, args: patched, spawnOverrides: {} };\n }\n }\n\n return { bin: resolved, args: [...tail], spawnOverrides: {} };\n}\n\n/** Resolved bin path looks like Windows PowerShell or PowerShell Core. */\nfunction isPowerShellExe(resolved: string): boolean {\n return /(?:^|[\\\\/])(?:powershell|pwsh)(?:\\.exe)?$/i.test(resolved);\n}\n\n/**\n * Locate `-Command` / `-c` in `args` and prepend the UTF-8 setup prelude\n * to its value. Returns the patched args, or `null` when no `-Command`\n * arg is present (in which case we leave the invocation untouched —\n * inline-expression and script-file modes have their own conventions\n * we don't want to silently rewrite).\n *\n * Why not always wrap: PowerShell's quoting semantics are finicky enough\n * that adding a prelude to a script file invocation could break it.\n * `-Command` is the case the model actually uses, and where mojibake\n * matters; targeting just it keeps the blast radius small.\n *\n * Exported for tests.\n */\nexport function injectPowerShellUtf8(args: readonly string[]): string[] | null {\n const prelude =\n \"[Console]::OutputEncoding=[System.Text.Encoding]::UTF8;$OutputEncoding=[System.Text.Encoding]::UTF8;\";\n for (let i = 0; i < args.length; i++) {\n const a = args[i] ?? \"\";\n if (/^-(?:Command|c)$/i.test(a) && i + 1 < args.length) {\n const out = [...args];\n out[i + 1] = `${prelude}${args[i + 1] ?? \"\"}`;\n return out;\n }\n }\n return null;\n}\n\n/**\n * Prefix a cmd.exe command line with `chcp 65001 >nul &` so output\n * (from cmd.exe and any child it spawns) is UTF-8-encoded. Without\n * this, on Chinese / Japanese / Korean Windows, `dir`, `findstr`,\n * `where`, etc. emit text in the system codepage (CP936, CP932,\n * CP949, …) and `chunk.toString()` — which decodes as UTF-8 — produces\n * garbled mojibake the model then sees as poisoned input on the next\n * turn.\n *\n * Scope: chcp affects ONLY this cmd.exe instance, which exits after\n * `/c`. No global console state changes. Single `&` (not `&&`) so the\n * command still runs even on the rare Windows builds where chcp\n * itself returns a non-zero exit (Win7 quirks; harmless on Win10+).\n *\n * Exported so tests can verify the wrapping shape.\n */\nexport function withUtf8Codepage(cmdline: string): string {\n return `chcp 65001 >nul & ${cmdline}`;\n}\n\n/**\n * True when `s` looks like a bare executable name — no path separator,\n * no drive letter, no extension. Such names on Windows, when absent\n * from PATH × PATHEXT, are almost always cmd.exe built-ins.\n */\nfunction isBareWindowsName(s: string): boolean {\n if (!s) return false;\n if (s.includes(\"/\") || s.includes(\"\\\\\")) return false;\n if (pathMod.isAbsolute(s)) return false;\n if (pathMod.extname(s)) return false;\n return true;\n}\n\n/**\n * Quote an argument so cmd.exe parses it back as a single token. We\n * always wrap in double quotes when the arg contains whitespace or\n * any cmd.exe metacharacter, doubling embedded quotes per cmd.exe's\n * `\"\"` escape rule. Bare alphanumeric args pass through unquoted for\n * readability in logs.\n *\n * Exported for test coverage of the quoting semantics.\n */\nexport function quoteForCmdExe(arg: string): string {\n if (arg === \"\") return '\"\"';\n if (!/[\\s\"&|<>^%(),;!]/.test(arg)) return arg;\n return `\"${arg.replace(/\"/g, '\"\"')}\"`;\n}\n\n/** Error thrown by `run_command` when the command isn't allowlisted. */\nexport class NeedsConfirmationError extends Error {\n readonly command: string;\n constructor(command: string) {\n super(\n `run_command: \"${command}\" needs the user's approval before it runs. STOP calling tools now — the TUI has already prompted the user to press y (run) or n (deny). Wait for their next message; it will either be the command's output (if they approved) or an instruction to continue without it (if they denied). Don't retry the command or call other shell commands in the meantime.`,\n );\n this.name = \"NeedsConfirmationError\";\n this.command = command;\n }\n}\n\nexport function registerShellTools(registry: ToolRegistry, opts: ShellToolsOptions): ToolRegistry {\n const rootDir = pathMod.resolve(opts.rootDir);\n const timeoutSec = opts.timeoutSec ?? DEFAULT_TIMEOUT_SEC;\n const maxOutputChars = opts.maxOutputChars ?? DEFAULT_MAX_OUTPUT_CHARS;\n // Resolved on every dispatch so newly-persisted \"always allow\"\n // prefixes take effect inside the session that added them, not just\n // on the next launch. Static arrays are wrapped into a constant\n // getter so the call site below is uniform.\n const getExtraAllowed: () => readonly string[] =\n typeof opts.extraAllowed === \"function\"\n ? opts.extraAllowed\n : (() => {\n const snapshot = opts.extraAllowed ?? [];\n return () => snapshot;\n })();\n const allowAll = opts.allowAll ?? false;\n\n registry.register({\n name: \"run_command\",\n description:\n \"Run a shell command in the project root and return its combined stdout+stderr. Common read-only inspection and test/lint/typecheck commands run immediately; anything that could mutate state, install dependencies, or touch the network is refused until the user confirms it in the TUI. Prefer this over asking the user to run a command manually — after edits, run the project's tests to verify.\",\n // Plan-mode gate: allow allowlisted commands through (git status,\n // cargo check, ls, grep …) so the model can actually investigate\n // during planning. Anything that would otherwise trigger a\n // confirmation prompt is treated as \"not read-only\" and bounced.\n readOnlyCheck: (args: { command?: unknown }) => {\n if (allowAll) return true;\n const cmd = typeof args?.command === \"string\" ? args.command.trim() : \"\";\n if (!cmd) return false;\n return isAllowed(cmd, getExtraAllowed());\n },\n parameters: {\n type: \"object\",\n properties: {\n command: {\n type: \"string\",\n description:\n 'Full command line. Tokenized with POSIX-ish quoting; no shell expansion. Pipes (`|`), redirects (`>`, `<`, `2>`), and `&&`/`||` chaining are rejected with an error — split into separate calls instead. To pass an operator character as a literal argument (e.g. a regex), wrap it in quotes: `grep \"a|b\" file.txt`.',\n },\n timeoutSec: {\n type: \"integer\",\n description: `Override the default ${timeoutSec}s timeout for a single command.`,\n },\n },\n required: [\"command\"],\n },\n fn: async (args: { command: string; timeoutSec?: number }, ctx) => {\n const cmd = args.command.trim();\n if (!cmd) throw new Error(\"run_command: empty command\");\n if (!allowAll && !isAllowed(cmd, getExtraAllowed())) {\n throw new NeedsConfirmationError(cmd);\n }\n const effectiveTimeout = Math.max(1, Math.min(600, args.timeoutSec ?? timeoutSec));\n const result = await runCommand(cmd, {\n cwd: rootDir,\n timeoutSec: effectiveTimeout,\n maxOutputChars,\n signal: ctx?.signal,\n });\n return formatCommandResult(cmd, result);\n },\n });\n\n return registry;\n}\n\nexport function formatCommandResult(cmd: string, r: RunCommandResult): string {\n const header = r.timedOut\n ? `$ ${cmd}\\n[killed after timeout]`\n : `$ ${cmd}\\n[exit ${r.exitCode ?? \"?\"}]`;\n return r.output ? `${header}\\n${r.output}` : header;\n}\n","/**\n * Built-in web search + fetch tools.\n *\n * - `web_search(query, topK?)` — Mojeek's public search page. No API\n * key, no signup. We originally shipped this backed by DuckDuckGo's\n * HTML endpoint, but DDG started serving anti-bot interstitials\n * (HTTP 202 with a challenge page) for every unauthenticated POST.\n * Mojeek runs its own independent index, is bot-friendly, and\n * returns parseable HTML.\n * - `web_fetch(url)` — HTTP GET + naïve HTML-to-text extraction.\n *\n * Both are registered by default on `reasonix chat` / `reasonix code`;\n * set `search: false` in config (or `REASONIX_SEARCH=off`) to turn\n * them off. The model decides when to call them based on the query —\n * no slash command required.\n */\n\nimport type { ToolRegistry } from \"../tools.js\";\n\nexport interface SearchResult {\n title: string;\n url: string;\n snippet: string;\n}\n\nexport interface PageContent {\n url: string;\n title?: string;\n text: string;\n /** True when the extracted text was clipped to fit the cap. */\n truncated: boolean;\n}\n\nexport interface WebFetchOptions {\n /** Max bytes of extracted text. Defaults to 32_000 to match tool-result cap. */\n maxChars?: number;\n /** Timeout in ms. Defaults to 15_000. */\n timeoutMs?: number;\n signal?: AbortSignal;\n}\n\nexport interface WebSearchOptions {\n topK?: number;\n signal?: AbortSignal;\n}\n\nconst DEFAULT_FETCH_MAX_CHARS = 32_000;\nconst DEFAULT_FETCH_TIMEOUT_MS = 15_000;\nconst DEFAULT_TOPK = 5;\n// Real-browser UA. Servers like Mojeek are bot-friendly but still gate\n// obvious scraper UAs; a stock Chrome string avoids the fast-path block.\nconst USER_AGENT =\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36\";\nconst MOJEEK_ENDPOINT = \"https://www.mojeek.com/search\";\n\n/**\n * Search the public web via Mojeek. Returns up to `topK` ranked\n * results with title, url, snippet.\n *\n * Mojeek is an independent index (not a Google/Bing front-end) which\n * means coverage on niche or very recent topics can be thinner, but\n * it's reliable from scripts and doesn't gate on cookies or sessions.\n * If the response has 0 results we distinguish \"truly empty\" from\n * \"layout changed or blocked\" so the caller isn't left guessing.\n */\nexport async function webSearch(\n query: string,\n opts: WebSearchOptions = {},\n): Promise<SearchResult[]> {\n const topK = Math.max(1, Math.min(10, opts.topK ?? DEFAULT_TOPK));\n const resp = await fetch(`${MOJEEK_ENDPOINT}?q=${encodeURIComponent(query)}`, {\n headers: {\n \"User-Agent\": USER_AGENT,\n Accept: \"text/html,application/xhtml+xml,application/xml;q=0.9\",\n \"Accept-Language\": \"en-US,en;q=0.9\",\n },\n signal: opts.signal,\n redirect: \"follow\",\n });\n if (!resp.ok) throw new Error(`web_search ${resp.status}`);\n const html = await resp.text();\n const results = parseMojeekResults(html).slice(0, topK);\n if (results.length === 0) {\n if (/no results found|did not match any documents/i.test(html)) return [];\n if (/captcha|verify you are human|access denied|forbidden/i.test(html)) {\n throw new Error(\"web_search: Mojeek anti-bot page — rate-limited or blocked\");\n }\n throw new Error(\n `web_search: 0 results but response doesn't look like a real empty page (${html.length} chars, first 120: ${html.slice(0, 120).replace(/\\s+/g, \" \")})`,\n );\n }\n return results;\n}\n\n/**\n * Extract results from a Mojeek search page.\n *\n * Mojeek's stable shape (as of April 2026):\n * <a … class=\"ob\" href=\"URL\"> … breadcrumb … </a>\n * <h2><a class=\"title\" href=\"URL\">Title</a></h2>\n * <p class=\"s\">snippet text …</p>\n *\n * We do two tolerant passes — title anchors, then snippet paragraphs —\n * and pair them positionally. Attribute order inside a tag varies\n * between versions, so each pass captures the whole element and we\n * re-extract href / inner text with a second regex. Exported for\n * unit testing against a fixture.\n */\nexport function parseMojeekResults(html: string): SearchResult[] {\n const titles: string[] = [];\n const titleAnchorRe = /<a\\b[^>]*\\bclass=\"title\"[^>]*>[\\s\\S]*?<\\/a>/g;\n let m: RegExpExecArray | null;\n while (true) {\n m = titleAnchorRe.exec(html);\n if (m === null) break;\n titles.push(m[0]);\n }\n\n const snippets: string[] = [];\n const snippetRe = /<p\\b[^>]*\\bclass=\"s\"[^>]*>([\\s\\S]*?)<\\/p>/g;\n while (true) {\n m = snippetRe.exec(html);\n if (m === null) break;\n snippets.push(m[1] ?? \"\");\n }\n\n const hrefRe = /href=\"([^\"]+)\"/;\n const innerRe = /<a\\b[^>]*>([\\s\\S]*?)<\\/a>/;\n const results: SearchResult[] = [];\n for (let i = 0; i < titles.length; i++) {\n const anchor = titles[i]!;\n const hrefMatch = anchor.match(hrefRe);\n const innerMatch = anchor.match(innerRe);\n if (!hrefMatch?.[1]) continue;\n results.push({\n title: decodeHtmlEntities(stripHtml(innerMatch?.[1] ?? \"\")).trim(),\n url: hrefMatch[1],\n snippet: decodeHtmlEntities(stripHtml(snippets[i] ?? \"\"))\n .replace(/\\s+/g, \" \")\n .trim(),\n });\n }\n return results;\n}\n\n/**\n * Download a URL, strip HTML down to readable text, return it. Times\n * out at 15s, caps extracted text at 32k chars to fit the tool-result\n * budget.\n */\nexport async function webFetch(url: string, opts: WebFetchOptions = {}): Promise<PageContent> {\n const maxChars = opts.maxChars ?? DEFAULT_FETCH_MAX_CHARS;\n const timeoutMs = opts.timeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS;\n const ctl = new AbortController();\n const timer = setTimeout(() => ctl.abort(), timeoutMs);\n // Forward the caller's abort too so an Esc during a long fetch is respected.\n const cancel = () => ctl.abort();\n opts.signal?.addEventListener(\"abort\", cancel, { once: true });\n let resp: Response;\n try {\n resp = await fetch(url, {\n headers: { \"User-Agent\": USER_AGENT, Accept: \"text/html,text/plain,*/*\" },\n signal: ctl.signal,\n redirect: \"follow\",\n });\n } finally {\n clearTimeout(timer);\n opts.signal?.removeEventListener(\"abort\", cancel);\n }\n if (!resp.ok) throw new Error(`web_fetch ${resp.status} for ${url}`);\n const contentType = resp.headers.get(\"content-type\") ?? \"\";\n const raw = await resp.text();\n const title = extractTitle(raw);\n const text = contentType.includes(\"text/html\") ? htmlToText(raw) : raw;\n const truncated = text.length > maxChars;\n const finalText = truncated\n ? `${text.slice(0, maxChars)}\\n\\n[… truncated ${text.length - maxChars} chars …]`\n : text;\n return { url, title, text: finalText, truncated };\n}\n\n/**\n * Strip HTML to readable text. Removes scripts/styles/nav/footer/aside\n * blocks first, then tags, then collapses whitespace. Not a Readability\n * clone — purpose-built to keep the extracted text small enough for the\n * tool-result budget while preserving paragraph breaks.\n */\nexport function htmlToText(html: string): string {\n let s = html;\n s = s.replace(/<script[\\s\\S]*?<\\/script>/gi, \"\");\n s = s.replace(/<style[\\s\\S]*?<\\/style>/gi, \"\");\n s = s.replace(/<noscript[\\s\\S]*?<\\/noscript>/gi, \"\");\n s = s.replace(/<nav[\\s\\S]*?<\\/nav>/gi, \"\");\n s = s.replace(/<footer[\\s\\S]*?<\\/footer>/gi, \"\");\n s = s.replace(/<aside[\\s\\S]*?<\\/aside>/gi, \"\");\n s = s.replace(/<svg[\\s\\S]*?<\\/svg>/gi, \"\");\n // Preserve paragraph breaks by turning common block tags into newlines.\n s = s.replace(/<\\/?(p|div|br|h[1-6]|li|tr|section|article)\\b[^>]*>/gi, \"\\n\");\n s = s.replace(/<[^>]+>/g, \"\");\n s = decodeHtmlEntities(s);\n s = s.replace(/[ \\t]+/g, \" \");\n s = s.replace(/\\n[ \\t]+/g, \"\\n\");\n s = s.replace(/\\n{3,}/g, \"\\n\\n\");\n return s.trim();\n}\n\nfunction stripHtml(s: string): string {\n return s.replace(/<[^>]+>/g, \"\");\n}\n\nfunction decodeHtmlEntities(s: string): string {\n return s\n .replace(/&nbsp;/g, \" \")\n .replace(/&amp;/g, \"&\")\n .replace(/&lt;/g, \"<\")\n .replace(/&gt;/g, \">\")\n .replace(/&quot;/g, '\"')\n .replace(/&#39;/g, \"'\");\n}\n\nfunction extractTitle(html: string): string | undefined {\n const m = html.match(/<title[^>]*>([\\s\\S]*?)<\\/title>/i);\n if (!m?.[1]) return undefined;\n return m[1].replace(/\\s+/g, \" \").trim() || undefined;\n}\n\nexport interface WebToolsOptions {\n /** Default top-K for `web_search` when the model doesn't specify. */\n defaultTopK?: number;\n /** Byte cap for `web_fetch` extracted text. */\n maxFetchChars?: number;\n}\n\n/**\n * Register `web_search` + `web_fetch` on a ToolRegistry. The model\n * invokes them automatically when a question needs current info —\n * no slash command from the user is required.\n */\nexport function registerWebTools(registry: ToolRegistry, opts: WebToolsOptions = {}): ToolRegistry {\n const defaultTopK = opts.defaultTopK ?? DEFAULT_TOPK;\n const maxFetchChars = opts.maxFetchChars ?? DEFAULT_FETCH_MAX_CHARS;\n\n registry.register({\n name: \"web_search\",\n description:\n \"Search the public web. Returns ranked results with title, url, and snippet. Use this when the question needs information more current than your training data, when you're unsure of a factual detail, or when the user asks about a specific webpage/library/release you haven't seen.\",\n readOnly: true,\n parameters: {\n type: \"object\",\n properties: {\n query: { type: \"string\", description: \"Natural-language search query.\" },\n topK: {\n type: \"integer\",\n description: `Number of results to return (1..10). Default ${defaultTopK}.`,\n },\n },\n required: [\"query\"],\n },\n fn: async (args: { query: string; topK?: number }, ctx) => {\n const results = await webSearch(args.query, {\n topK: args.topK ?? defaultTopK,\n signal: ctx?.signal,\n });\n return formatSearchResults(args.query, results);\n },\n });\n\n registry.register({\n name: \"web_fetch\",\n description:\n \"Download a URL and return its visible text content (HTML pages get scripts/styles/nav stripped). Truncated at the tool-result cap. Use after web_search when a snippet isn't enough.\",\n readOnly: true,\n parameters: {\n type: \"object\",\n properties: {\n url: { type: \"string\", description: \"Absolute http:// or https:// URL.\" },\n },\n required: [\"url\"],\n },\n fn: async (args: { url: string }, ctx) => {\n if (!/^https?:\\/\\//i.test(args.url)) {\n throw new Error(\"web_fetch: url must start with http:// or https://\");\n }\n const page = await webFetch(args.url, { maxChars: maxFetchChars, signal: ctx?.signal });\n const header = page.title ? `${page.title}\\n${page.url}` : page.url;\n return `${header}\\n\\n${page.text}`;\n },\n });\n\n return registry;\n}\n\nexport function formatSearchResults(query: string, results: SearchResult[]): string {\n const lines: string[] = [`query: ${query}`, `\\nresults (${results.length}):`];\n results.forEach((r, i) => {\n lines.push(`\\n${i + 1}. ${r.title}`);\n lines.push(` ${r.url}`);\n if (r.snippet) lines.push(` ${r.snippet}`);\n });\n return lines.join(\"\\n\");\n}\n","import { readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\n\n/**\n * Minimal `.env` loader; no dependency on dotenv.\n *\n * Reads KEY=VALUE lines and populates `process.env` for keys not already set.\n * Silently no-ops if the file is missing. Safe to call from library entry\n * points, CLI commands, examples, and benchmark runners.\n */\nexport function loadDotenv(path = \".env\"): void {\n let raw: string;\n try {\n raw = readFileSync(resolve(process.cwd(), path), \"utf8\");\n } catch {\n return;\n }\n for (const line of raw.split(/\\r?\\n/)) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith(\"#\")) continue;\n const eq = trimmed.indexOf(\"=\");\n if (eq === -1) continue;\n const key = trimmed.slice(0, eq).trim();\n let value = trimmed.slice(eq + 1).trim();\n if (\n (value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))\n ) {\n value = value.slice(1, -1);\n }\n if (process.env[key] === undefined) process.env[key] = value;\n }\n}\n","/**\n * Transcript format — the canonical \"audit log\" of a Reasonix session.\n *\n * Design split:\n * - Session file (`~/.reasonix/sessions/<name>.jsonl`) stores only the\n * `ChatMessage`s the model needs to resume. See session.ts.\n * - Transcript file (this module) stores every LoopEvent with usage, cost,\n * model, and prefix fingerprint attached where available — enough for\n * replay and diff to reconstruct economics.\n *\n * The two are different contracts: sessions are the user's *memory*;\n * transcripts are the *receipts*. Don't conflate them.\n *\n * Backward compatibility: all fields beyond {ts, turn, role, content} are\n * optional on read. A v0.1 transcript (pre-usage) still parses and renders\n * — it just shows cost/cache as n/a.\n */\n\nimport { type WriteStream, createWriteStream, readFileSync } from \"node:fs\";\nimport type { TypedPlanState } from \"./harvest.js\";\nimport type { LoopEvent } from \"./loop.js\";\nimport type { RawUsage } from \"./types.js\";\n\nexport interface TranscriptRecord {\n /** ISO-8601 timestamp at emit time. */\n ts: string;\n /** 1-based turn number within the session. */\n turn: number;\n /** LoopEvent role — \"assistant_delta\" | \"assistant_final\" | \"tool\" | \"done\" | ... */\n role: string;\n /** For assistant events, the final (or delta) text; for tool events, the tool result. */\n content: string;\n /** Tool name (role === \"tool\"). */\n tool?: string;\n /** JSON-string args the model sent for a tool call (role === \"tool\"). Persisted so diff can explain *why* two runs made different calls. */\n args?: string;\n /** DeepSeek token-usage snapshot (role === \"assistant_final\"). */\n usage?: RawUsage;\n /** USD cost of this turn (role === \"assistant_final\"). */\n cost?: number;\n /** Model id that produced this turn. */\n model?: string;\n /**\n * The ImmutablePrefix fingerprint at this turn. Lets diff prove two runs\n * share a prefix — i.e. any cache-hit delta is attributable to log\n * stability, not to a different system prompt.\n */\n prefixHash?: string;\n /**\n * Structured plan state extracted by the Pillar 2 harvester. Present on\n * assistant_final records when harvest was enabled and produced non-empty\n * state. Omitted entirely when harvest is off or produced nothing —\n * absence means \"no data\", not \"empty plan\".\n */\n planState?: TypedPlanState;\n /** Optional error message (role === \"error\"). */\n error?: string;\n}\n\nexport interface TranscriptMeta {\n /**\n * Optional metadata written as the first line of a transcript. Lets\n * downstream tooling know what it's reading without guessing.\n * Recognized by a special role \"_meta\".\n */\n version: 1;\n source: string; // e.g. \"reasonix chat\", \"bench/baseline\", \"bench/reasonix\"\n model?: string;\n task?: string;\n mode?: string;\n repeat?: number;\n startedAt: string;\n}\n\ninterface MetaLine {\n role: \"_meta\";\n meta: TranscriptMeta;\n}\n\nexport interface ReadTranscriptResult {\n meta: TranscriptMeta | null;\n records: TranscriptRecord[];\n}\n\n/**\n * Build a TranscriptRecord from a LoopEvent. Extra fields (model,\n * prefixHash) that the LoopEvent doesn't carry are passed in separately\n * because they're session-level, not event-level.\n */\nexport function recordFromLoopEvent(\n ev: LoopEvent,\n extra: { model: string; prefixHash: string },\n): TranscriptRecord {\n const rec: TranscriptRecord = {\n ts: new Date().toISOString(),\n turn: ev.turn,\n role: ev.role,\n content: ev.content,\n };\n if (ev.toolName !== undefined) rec.tool = ev.toolName;\n if (ev.toolArgs !== undefined) rec.args = ev.toolArgs;\n if (ev.error !== undefined) rec.error = ev.error;\n // Only persist non-empty plan state — empty harvest output is indistinguishable\n // from \"harvest was off\" for replay purposes, and saves transcript bytes.\n if (ev.planState && !isPlanStateEmptyShape(ev.planState)) {\n rec.planState = {\n subgoals: [...ev.planState.subgoals],\n hypotheses: [...ev.planState.hypotheses],\n uncertainties: [...ev.planState.uncertainties],\n rejectedPaths: [...ev.planState.rejectedPaths],\n };\n }\n if (ev.stats) {\n rec.usage = {\n prompt_tokens: ev.stats.usage.promptTokens,\n completion_tokens: ev.stats.usage.completionTokens,\n total_tokens: ev.stats.usage.totalTokens,\n prompt_cache_hit_tokens: ev.stats.usage.promptCacheHitTokens,\n prompt_cache_miss_tokens: ev.stats.usage.promptCacheMissTokens,\n };\n rec.cost = ev.stats.cost;\n rec.model = ev.stats.model;\n rec.prefixHash = extra.prefixHash;\n } else if (ev.role === \"assistant_final\") {\n // assistant_final without stats (shouldn't happen in the live loop but\n // might in test fixtures) — still persist model + prefix for continuity.\n rec.model = extra.model;\n rec.prefixHash = extra.prefixHash;\n }\n return rec;\n}\n\n/**\n * Append a record to an open write stream. Caller owns the stream lifecycle.\n */\nexport function writeRecord(stream: WriteStream, record: TranscriptRecord): void {\n stream.write(`${JSON.stringify(record)}\\n`);\n}\n\n/**\n * Write a _meta line to an open write stream. Call exactly once, at the top.\n */\nexport function writeMeta(stream: WriteStream, meta: TranscriptMeta): void {\n const line: MetaLine = { role: \"_meta\", meta };\n stream.write(`${JSON.stringify(line)}\\n`);\n}\n\n/**\n * Convenience: open a stream, write meta, return stream.\n */\nexport function openTranscriptFile(path: string, meta: TranscriptMeta): WriteStream {\n const stream = createWriteStream(path, { flags: \"a\" });\n writeMeta(stream, meta);\n return stream;\n}\n\n/**\n * Parse a transcript file. Returns meta (if the first line is a _meta record)\n * and the full record list.\n *\n * Robustness contract:\n * - Empty lines are skipped.\n * - Malformed JSON lines are skipped silently (do not crash on partial\n * files — live chats may be mid-write).\n * - Records missing optional fields still parse — they're just rendered\n * with n/a where the optional value would go.\n */\nexport function readTranscript(path: string): ReadTranscriptResult {\n const raw = readFileSync(path, \"utf8\");\n return parseTranscript(raw);\n}\n\nfunction isPlanStateEmptyShape(s: TypedPlanState): boolean {\n return (\n s.subgoals.length === 0 &&\n s.hypotheses.length === 0 &&\n s.uncertainties.length === 0 &&\n s.rejectedPaths.length === 0\n );\n}\n\nexport function parseTranscript(raw: string): ReadTranscriptResult {\n const out: ReadTranscriptResult = { meta: null, records: [] };\n for (const line of raw.split(/\\r?\\n/)) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n let obj: unknown;\n try {\n obj = JSON.parse(trimmed);\n } catch {\n continue;\n }\n if (!obj || typeof obj !== \"object\") continue;\n const rec = obj as Record<string, unknown>;\n if (rec.role === \"_meta\" && rec.meta && typeof rec.meta === \"object\") {\n out.meta = rec.meta as TranscriptMeta;\n continue;\n }\n if (\n typeof rec.ts === \"string\" &&\n typeof rec.turn === \"number\" &&\n typeof rec.role === \"string\" &&\n typeof rec.content === \"string\"\n ) {\n out.records.push(rec as unknown as TranscriptRecord);\n }\n }\n return out;\n}\n","/**\n * Replay — reconstruct session economics from a transcript file.\n *\n * Given a transcript written by App.tsx or the bench runner, rebuild a\n * SessionSummary-compatible aggregate (turn count, total cost, cache-hit\n * ratio, vs-Claude estimate) without replaying the LLM calls.\n *\n * The whole point is offline auditing: a reader should be able to reproduce\n * the headline numbers from a transcript alone, without an API key.\n */\n\nimport { Usage } from \"./client.js\";\nimport {\n type SessionSummary,\n type TurnStats,\n claudeEquivalentCost,\n costUsd,\n inputCostUsd,\n outputCostUsd,\n} from \"./telemetry.js\";\nimport { type ReadTranscriptResult, type TranscriptRecord, readTranscript } from \"./transcript.js\";\n\n/**\n * A single turn's worth of records — the unit of navigation in replay TUI.\n * Records are grouped by their `turn` field, preserving file order within\n * each group (so tool events interleave with assistant_final events the\n * way they were actually emitted).\n */\nexport interface TurnPage {\n turn: number;\n records: TranscriptRecord[];\n}\n\n/**\n * Group transcript records into turn-pages. Pages are returned in ascending\n * turn order. Records without a numeric turn (meta lines, malformed) are\n * already filtered by the transcript reader, so this sees clean input.\n */\nexport function groupRecordsByTurn(records: TranscriptRecord[]): TurnPage[] {\n const byTurn = new Map<number, TranscriptRecord[]>();\n for (const rec of records) {\n const list = byTurn.get(rec.turn);\n if (list) list.push(rec);\n else byTurn.set(rec.turn, [rec]);\n }\n return [...byTurn.entries()]\n .sort(([a], [b]) => a - b)\n .map(([turn, records]) => ({ turn, records }));\n}\n\n/**\n * Cumulative replay stats up to and including pages[0..upToIdx]. Returns\n * empty stats if upToIdx < 0. Used by replay TUI's sidebar to show \"stats\n * so far\" as the user scrolls through a transcript.\n */\nexport function computeCumulativeStats(pages: TurnPage[], upToIdx: number): ReplayStats {\n if (upToIdx < 0) return computeReplayStats([]);\n const flat: TranscriptRecord[] = [];\n for (let i = 0; i <= upToIdx && i < pages.length; i++) {\n const records = pages[i]?.records;\n if (records) flat.push(...records);\n }\n return computeReplayStats(flat);\n}\n\nexport interface ReplayStats extends SessionSummary {\n /** Per-turn stats, in turn order. Only assistant_final records contribute. */\n perTurn: TurnStats[];\n /** Unique models that appeared in the transcript's assistant_final records. */\n models: string[];\n /** Unique prefix hashes that appeared. Length > 1 means the prefix churned (cache-hostile). */\n prefixHashes: string[];\n /** Count of user-role records (user turns issued). */\n userTurns: number;\n /** Count of tool-role records (tool calls executed). */\n toolCalls: number;\n /** Count of assistant_final records that carry a non-empty planState (harvest signal). */\n harvestedTurns: number;\n /** Sum of uncertainties across all harvested turns — a proxy for \"how much did R1 hedge?\" */\n totalUncertainties: number;\n /** Sum of subgoals across all harvested turns. */\n totalSubgoals: number;\n}\n\n/**\n * Parse a transcript file and compute replay stats. Throws only on I/O\n * errors; malformed lines inside the file are skipped silently.\n */\nexport function replayFromFile(path: string): { parsed: ReadTranscriptResult; stats: ReplayStats } {\n const parsed = readTranscript(path);\n return { parsed, stats: computeReplayStats(parsed.records) };\n}\n\nexport function computeReplayStats(records: TranscriptRecord[]): ReplayStats {\n const turns: TurnStats[] = [];\n const models = new Set<string>();\n const prefixHashes = new Set<string>();\n let userTurns = 0;\n let toolCalls = 0;\n let harvestedTurns = 0;\n let totalUncertainties = 0;\n let totalSubgoals = 0;\n\n for (const rec of records) {\n if (rec.role === \"user\") userTurns++;\n else if (rec.role === \"tool\") toolCalls++;\n else if (rec.role === \"assistant_final\") {\n if (rec.model) models.add(rec.model);\n if (rec.prefixHash) prefixHashes.add(rec.prefixHash);\n if (rec.planState) {\n harvestedTurns++;\n totalUncertainties += rec.planState.uncertainties.length;\n totalSubgoals += rec.planState.subgoals.length;\n }\n if (rec.usage && rec.model) {\n const u = new Usage(\n rec.usage.prompt_tokens ?? 0,\n rec.usage.completion_tokens ?? 0,\n rec.usage.total_tokens ?? 0,\n rec.usage.prompt_cache_hit_tokens ?? 0,\n rec.usage.prompt_cache_miss_tokens ?? 0,\n );\n turns.push({\n turn: rec.turn,\n model: rec.model,\n usage: u,\n // `rec.cost` wins when present — honors whatever the writer computed\n // even if pricing tables have since changed. Only recompute when\n // the transcript didn't record it (old format).\n cost: rec.cost ?? costUsd(rec.model, u),\n cacheHitRatio: u.cacheHitRatio,\n });\n }\n }\n }\n\n return {\n perTurn: turns,\n models: [...models],\n prefixHashes: [...prefixHashes],\n userTurns,\n toolCalls,\n harvestedTurns,\n totalUncertainties,\n totalSubgoals,\n ...summarizeTurns(turns),\n };\n}\n\nfunction summarizeTurns(turns: TurnStats[]): SessionSummary {\n const totalCost = turns.reduce((s, t) => s + t.cost, 0);\n const totalInput = turns.reduce((s, t) => s + inputCostUsd(t.model, t.usage), 0);\n const totalOutput = turns.reduce((s, t) => s + outputCostUsd(t.model, t.usage), 0);\n const totalClaude = turns.reduce((s, t) => s + claudeEquivalentCost(t.usage), 0);\n let hit = 0;\n let miss = 0;\n for (const t of turns) {\n hit += t.usage.promptCacheHitTokens;\n miss += t.usage.promptCacheMissTokens;\n }\n const cacheHitRatio = hit + miss > 0 ? hit / (hit + miss) : 0;\n const savingsVsClaude = totalClaude > 0 ? 1 - totalCost / totalClaude : 0;\n const lastTurn = turns[turns.length - 1];\n return {\n turns: turns.length,\n totalCostUsd: round(totalCost, 6),\n totalInputCostUsd: round(totalInput, 6),\n totalOutputCostUsd: round(totalOutput, 6),\n claudeEquivalentUsd: round(totalClaude, 6),\n savingsVsClaudePct: round(savingsVsClaude * 100, 2),\n cacheHitRatio: round(cacheHitRatio, 4),\n lastPromptTokens: lastTurn?.usage.promptTokens ?? 0,\n };\n}\n\nfunction round(n: number, digits: number): number {\n const f = 10 ** digits;\n return Math.round(n * f) / f;\n}\n","/**\n * Diff — compare two transcripts and produce a summary + divergence report.\n *\n * Two transcripts are \"comparable\" when they stem from the same task (or\n * the same user prompt). Alignment is by turn number: assistant_final #N\n * in A pairs with assistant_final #N in B. If one side ran more turns, the\n * extras are labeled \"only in A\" / \"only in B\".\n *\n * What we compute:\n * - Aggregate deltas: turns, tool calls, cache hit, cost, token counts\n * - First divergence: the lowest turn where A and B's tool calls or\n * assistant text differ meaningfully\n * - Prefix-stability story: how many unique prefix hashes each side used\n *\n * Non-goals (deliberately):\n * - LLM-judge quality comparison\n * - Per-token delta rendering — not useful at the fidelity we're at\n * - Embedding similarity — Levenshtein ratio is cheap and good enough\n */\n\nimport { type ReplayStats, computeReplayStats } from \"./replay.js\";\nimport type { ReadTranscriptResult, TranscriptRecord } from \"./transcript.js\";\n\nexport interface DiffSide {\n label: string;\n meta: ReadTranscriptResult[\"meta\"];\n records: TranscriptRecord[];\n stats: ReplayStats;\n}\n\nexport interface TurnPair {\n turn: number;\n aAssistant?: TranscriptRecord;\n bAssistant?: TranscriptRecord;\n aTools: TranscriptRecord[];\n bTools: TranscriptRecord[];\n /**\n * Classification of the pair:\n * \"match\" — both sides present, text & tool calls within threshold\n * \"diverge\" — both sides present, but text or tool calls differ\n * \"only_in_a\" — assistant_final in A but not B\n * \"only_in_b\" — assistant_final in B but not A\n */\n kind: \"match\" | \"diverge\" | \"only_in_a\" | \"only_in_b\";\n /** When kind === \"diverge\", a short one-liner pointing at what differs. */\n divergenceNote?: string;\n}\n\nexport interface DiffReport {\n a: DiffSide;\n b: DiffSide;\n pairs: TurnPair[];\n firstDivergenceTurn: number | null;\n}\n\n// ---------- navigation helpers (used by the Ink diff TUI) ----------\n\n/**\n * Find the next pair (strictly after `fromIdx`) whose kind is not \"match\".\n * Returns -1 when no later divergence exists. Used by DiffApp's `n` key.\n */\nexport function findNextDivergence(pairs: TurnPair[], fromIdx: number): number {\n for (let i = fromIdx + 1; i < pairs.length; i++) {\n if (pairs[i]!.kind !== \"match\") return i;\n }\n return -1;\n}\n\n/**\n * Find the previous pair (strictly before `fromIdx`) whose kind is not\n * \"match\". Returns -1 when no earlier divergence exists. Used by\n * DiffApp's `N` / `p` key.\n */\nexport function findPrevDivergence(pairs: TurnPair[], fromIdx: number): number {\n const start = Math.min(fromIdx - 1, pairs.length - 1);\n for (let i = start; i >= 0; i--) {\n if (pairs[i]!.kind !== \"match\") return i;\n }\n return -1;\n}\n\nexport function diffTranscripts(\n a: { label: string; parsed: ReadTranscriptResult },\n b: { label: string; parsed: ReadTranscriptResult },\n): DiffReport {\n const aSide: DiffSide = {\n label: a.label,\n meta: a.parsed.meta,\n records: a.parsed.records,\n stats: computeReplayStats(a.parsed.records),\n };\n const bSide: DiffSide = {\n label: b.label,\n meta: b.parsed.meta,\n records: b.parsed.records,\n stats: computeReplayStats(b.parsed.records),\n };\n\n const aByTurn = groupByTurn(a.parsed.records);\n const bByTurn = groupByTurn(b.parsed.records);\n const turns = [...new Set([...aByTurn.keys(), ...bByTurn.keys()])].sort((x, y) => x - y);\n\n const pairs: TurnPair[] = [];\n let firstDivergenceTurn: number | null = null;\n for (const turn of turns) {\n const aGroup = aByTurn.get(turn) ?? { assistant: undefined, tools: [] };\n const bGroup = bByTurn.get(turn) ?? { assistant: undefined, tools: [] };\n const aAssistant = aGroup.assistant;\n const bAssistant = bGroup.assistant;\n const aTools = aGroup.tools;\n const bTools = bGroup.tools;\n\n let kind: TurnPair[\"kind\"];\n let divergenceNote: string | undefined;\n if (!aAssistant && bAssistant) kind = \"only_in_b\";\n else if (aAssistant && !bAssistant) kind = \"only_in_a\";\n else if (!aAssistant && !bAssistant)\n kind = \"diverge\"; // tool-only turn (rare)\n else {\n divergenceNote = classifyDivergence(aAssistant!, bAssistant!, aTools, bTools);\n kind = divergenceNote ? \"diverge\" : \"match\";\n }\n\n if (kind !== \"match\" && firstDivergenceTurn === null) firstDivergenceTurn = turn;\n pairs.push({ turn, aAssistant, bAssistant, aTools, bTools, kind, divergenceNote });\n }\n\n return { a: aSide, b: bSide, pairs, firstDivergenceTurn };\n}\n\n// ---------- divergence classification ----------\n\n/**\n * Return a short reason string if two sides meaningfully disagree, or\n * undefined if they're close enough to call a match.\n *\n * Ranking of divergence signals (cheapest first):\n * 1. Different set of tool names → clearest diff\n * 2. Different tool args for the same tool → second-clearest\n * 3. Text similarity below threshold → fuzziest\n */\nfunction classifyDivergence(\n a: TranscriptRecord,\n b: TranscriptRecord,\n aTools: TranscriptRecord[],\n bTools: TranscriptRecord[],\n): string | undefined {\n const aNames = aTools.map((t) => t.tool ?? \"\").sort();\n const bNames = bTools.map((t) => t.tool ?? \"\").sort();\n if (aNames.join(\",\") !== bNames.join(\",\")) {\n return `tool calls differ: A=[${aNames.join(\",\") || \"—\"}] B=[${bNames.join(\",\") || \"—\"}]`;\n }\n // Same tool names — did they pass different args?\n for (let i = 0; i < aTools.length; i++) {\n const at = aTools[i]!;\n const bt = bTools[i]!;\n if (at.tool !== bt.tool) continue;\n if ((at.args ?? \"\") !== (bt.args ?? \"\")) {\n return `\"${at.tool}\" args differ`;\n }\n }\n const simRatio = similarity(a.content, b.content);\n if (simRatio < 0.75) return `text similarity ${(simRatio * 100).toFixed(0)}%`;\n return undefined;\n}\n\n/**\n * Normalized Levenshtein similarity ratio in [0, 1]. 1 = identical.\n * Early-exits for long strings (> 2000 chars) with a cheap token-overlap\n * estimate to keep diff fast on chatty transcripts.\n */\nexport function similarity(a: string, b: string): number {\n if (a === b) return 1;\n if (!a && !b) return 1;\n if (!a || !b) return 0;\n const maxLen = Math.max(a.length, b.length);\n if (maxLen > 2000) return tokenOverlap(a, b);\n const dist = levenshtein(a, b);\n return 1 - dist / maxLen;\n}\n\nfunction tokenOverlap(a: string, b: string): number {\n const ta = new Set(a.toLowerCase().split(/\\s+/).filter(Boolean));\n const tb = new Set(b.toLowerCase().split(/\\s+/).filter(Boolean));\n if (ta.size === 0 && tb.size === 0) return 1;\n let shared = 0;\n for (const t of ta) if (tb.has(t)) shared++;\n return (2 * shared) / (ta.size + tb.size);\n}\n\nfunction levenshtein(a: string, b: string): number {\n const m = a.length;\n const n = b.length;\n if (m === 0) return n;\n if (n === 0) return m;\n let prev = new Array(n + 1);\n let curr = new Array(n + 1);\n for (let j = 0; j <= n; j++) prev[j] = j;\n for (let i = 1; i <= m; i++) {\n curr[0] = i;\n for (let j = 1; j <= n; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1;\n curr[j] = Math.min(curr[j - 1] + 1, prev[j] + 1, prev[j - 1] + cost);\n }\n [prev, curr] = [curr, prev];\n }\n return prev[n];\n}\n\n// ---------- grouping ----------\n\ninterface TurnGroup {\n assistant?: TranscriptRecord;\n tools: TranscriptRecord[];\n}\n\nfunction groupByTurn(records: TranscriptRecord[]): Map<number, TurnGroup> {\n const out = new Map<number, TurnGroup>();\n for (const rec of records) {\n if (rec.role === \"user\") continue; // user msg is input to the turn, not its output\n const g = out.get(rec.turn) ?? { tools: [] };\n if (rec.role === \"assistant_final\") g.assistant = rec;\n else if (rec.role === \"tool\") g.tools.push(rec);\n out.set(rec.turn, g);\n }\n return out;\n}\n\n// ---------- rendering ----------\n\nexport interface RenderOptions {\n /** Monochrome output (for file redirection or piping). Defaults to true. */\n monochrome?: boolean;\n}\n\nexport function renderSummaryTable(report: DiffReport, _opts: RenderOptions = {}): string {\n const a = report.a;\n const b = report.b;\n const lines: string[] = [];\n lines.push(\"Comparing:\");\n lines.push(` A ${a.label}`);\n lines.push(` B ${b.label}`);\n lines.push(\"\");\n lines.push(row([\"\", \"A\", \"B\", \"Δ\"], [20, 14, 14, 14]));\n lines.push(\n row([\"─\".repeat(20), \"─\".repeat(14), \"─\".repeat(14), \"─\".repeat(14)], [20, 14, 14, 14]),\n );\n lines.push(statRow(\"model calls\", a.stats.turns, b.stats.turns));\n lines.push(statRow(\"user turns\", a.stats.userTurns, b.stats.userTurns));\n lines.push(statRow(\"tool calls\", a.stats.toolCalls, b.stats.toolCalls));\n lines.push(\n row(\n [\n \"cache hit\",\n `${pct(a.stats.cacheHitRatio)}`,\n `${pct(b.stats.cacheHitRatio)}`,\n signPct(b.stats.cacheHitRatio - a.stats.cacheHitRatio),\n ],\n [20, 14, 14, 14],\n ),\n );\n lines.push(\n row(\n [\n \"cost (USD)\",\n `$${a.stats.totalCostUsd.toFixed(6)}`,\n `$${b.stats.totalCostUsd.toFixed(6)}`,\n costDelta(a.stats.totalCostUsd, b.stats.totalCostUsd),\n ],\n [20, 14, 14, 14],\n ),\n );\n lines.push(statRow(\"prefix hashes\", a.stats.prefixHashes.length, b.stats.prefixHashes.length));\n // Harvest signal row — only surface when at least one side carries plan\n // state. Keeps no-harvest diffs visually identical to pre-v0.3 output.\n if (a.stats.harvestedTurns > 0 || b.stats.harvestedTurns > 0) {\n lines.push(\n row(\n [\n \"harvest turns\",\n `${a.stats.harvestedTurns}`,\n `${b.stats.harvestedTurns}`,\n signed(b.stats.harvestedTurns - a.stats.harvestedTurns),\n ],\n [20, 14, 14, 14],\n ),\n );\n lines.push(\n row(\n [\n \" subgoals\",\n `${a.stats.totalSubgoals}`,\n `${b.stats.totalSubgoals}`,\n signed(b.stats.totalSubgoals - a.stats.totalSubgoals),\n ],\n [20, 14, 14, 14],\n ),\n );\n lines.push(\n row(\n [\n \" uncertainties\",\n `${a.stats.totalUncertainties}`,\n `${b.stats.totalUncertainties}`,\n signed(b.stats.totalUncertainties - a.stats.totalUncertainties),\n ],\n [20, 14, 14, 14],\n ),\n );\n }\n lines.push(\"\");\n\n // Prefix stability story — the headline finding when comparing bench modes.\n const aPrefixStable = a.stats.prefixHashes.length <= 1;\n const bPrefixStable = b.stats.prefixHashes.length <= 1;\n if (aPrefixStable !== bPrefixStable) {\n const stable = aPrefixStable ? \"A\" : \"B\";\n const churn = aPrefixStable ? \"B\" : \"A\";\n const churnCount = aPrefixStable ? b.stats.prefixHashes.length : a.stats.prefixHashes.length;\n lines.push(\n `prefix stability: ${stable} stayed byte-stable across ${Math.max(\n a.stats.turns,\n b.stats.turns,\n )} turns; ${churn} churned ${churnCount} distinct prefixes.`,\n );\n lines.push(\"\");\n } else if (a.stats.prefixHashes[0] && a.stats.prefixHashes[0] === b.stats.prefixHashes[0]) {\n lines.push(\n `prefix: A and B share the same prefix hash (${a.stats.prefixHashes[0].slice(0, 12)}…) — cache delta is attributable to log stability, not prompt change.`,\n );\n lines.push(\"\");\n }\n\n if (report.firstDivergenceTurn !== null) {\n const p = report.pairs.find((p) => p.turn === report.firstDivergenceTurn);\n lines.push(\n `first divergence: turn ${report.firstDivergenceTurn} — ${p?.divergenceNote ?? \"?\"}`,\n );\n if (p?.aAssistant) lines.push(` A → ${truncate(p.aAssistant.content, 100)}`);\n if (p?.bAssistant) lines.push(` B → ${truncate(p.bAssistant.content, 100)}`);\n } else {\n lines.push(\"no material divergence detected (texts within similarity threshold).\");\n }\n\n return lines.join(\"\\n\");\n}\n\nexport function renderMarkdown(report: DiffReport): string {\n const a = report.a;\n const b = report.b;\n const out: string[] = [];\n out.push(`# Transcript diff: ${a.label} vs ${b.label}`);\n out.push(\"\");\n if (a.meta || b.meta) {\n out.push(\"## Meta\");\n out.push(\"\");\n out.push(`| | ${a.label} | ${b.label} |`);\n out.push(\"|---|---|---|\");\n out.push(`| source | ${a.meta?.source ?? \"—\"} | ${b.meta?.source ?? \"—\"} |`);\n out.push(`| model | ${a.meta?.model ?? \"—\"} | ${b.meta?.model ?? \"—\"} |`);\n out.push(`| task | ${a.meta?.task ?? \"—\"} | ${b.meta?.task ?? \"—\"} |`);\n out.push(`| startedAt | ${a.meta?.startedAt ?? \"—\"} | ${b.meta?.startedAt ?? \"—\"} |`);\n out.push(\"\");\n }\n\n out.push(\"## Summary\");\n out.push(\"\");\n out.push(`| metric | ${a.label} | ${b.label} | delta |`);\n out.push(\"|---|---:|---:|---:|\");\n out.push(\n `| model calls | ${a.stats.turns} | ${b.stats.turns} | ${signed(b.stats.turns - a.stats.turns)} |`,\n );\n out.push(\n `| user turns | ${a.stats.userTurns} | ${b.stats.userTurns} | ${signed(b.stats.userTurns - a.stats.userTurns)} |`,\n );\n out.push(\n `| tool calls | ${a.stats.toolCalls} | ${b.stats.toolCalls} | ${signed(b.stats.toolCalls - a.stats.toolCalls)} |`,\n );\n out.push(\n `| cache hit | ${pct(a.stats.cacheHitRatio)} | ${pct(b.stats.cacheHitRatio)} | **${signPct(b.stats.cacheHitRatio - a.stats.cacheHitRatio)}** |`,\n );\n out.push(\n `| cost (USD) | $${a.stats.totalCostUsd.toFixed(6)} | $${b.stats.totalCostUsd.toFixed(6)} | ${costDelta(a.stats.totalCostUsd, b.stats.totalCostUsd)} |`,\n );\n out.push(\n `| prefix hashes | ${a.stats.prefixHashes.length} | ${b.stats.prefixHashes.length} | — |`,\n );\n if (a.stats.harvestedTurns > 0 || b.stats.harvestedTurns > 0) {\n out.push(\n `| harvest turns | ${a.stats.harvestedTurns} | ${b.stats.harvestedTurns} | ${signed(b.stats.harvestedTurns - a.stats.harvestedTurns)} |`,\n );\n out.push(\n `| harvest subgoals | ${a.stats.totalSubgoals} | ${b.stats.totalSubgoals} | ${signed(b.stats.totalSubgoals - a.stats.totalSubgoals)} |`,\n );\n out.push(\n `| harvest uncertainties | ${a.stats.totalUncertainties} | ${b.stats.totalUncertainties} | ${signed(b.stats.totalUncertainties - a.stats.totalUncertainties)} |`,\n );\n }\n out.push(\"\");\n\n out.push(\"## Turn-by-turn\");\n out.push(\"\");\n out.push(`| turn | kind | ${a.label} tool calls | ${b.label} tool calls | note |`);\n out.push(\"|---:|:---:|---|---|---|\");\n for (const p of report.pairs) {\n const aTools =\n p.aTools\n .map((t) => t.tool)\n .filter(Boolean)\n .join(\", \") || \"—\";\n const bTools =\n p.bTools\n .map((t) => t.tool)\n .filter(Boolean)\n .join(\", \") || \"—\";\n out.push(`| ${p.turn} | ${p.kind} | ${aTools} | ${bTools} | ${p.divergenceNote ?? \"\"} |`);\n }\n out.push(\"\");\n\n if (report.firstDivergenceTurn !== null) {\n const p = report.pairs.find((x) => x.turn === report.firstDivergenceTurn);\n out.push(`## First divergence (turn ${report.firstDivergenceTurn})`);\n out.push(\"\");\n out.push(p?.divergenceNote ?? \"\");\n out.push(\"\");\n if (p?.aAssistant) {\n out.push(`**${a.label}:**`);\n out.push(\"\");\n out.push(\"```\");\n out.push(p.aAssistant.content);\n out.push(\"```\");\n out.push(\"\");\n }\n if (p?.bAssistant) {\n out.push(`**${b.label}:**`);\n out.push(\"\");\n out.push(\"```\");\n out.push(p.bAssistant.content);\n out.push(\"```\");\n out.push(\"\");\n }\n }\n return out.join(\"\\n\");\n}\n\n// ---------- formatting helpers ----------\n\nfunction row(cols: string[], widths: number[]): string {\n return cols.map((c, i) => padRight(c, widths[i] ?? c.length)).join(\" \");\n}\n\nfunction statRow(label: string, av: number, bv: number): string {\n return row([label, `${av}`, `${bv}`, signed(bv - av)], [20, 14, 14, 14]);\n}\n\nfunction padRight(s: string, w: number): string {\n return s.length >= w ? s : s + \" \".repeat(w - s.length);\n}\n\nfunction signed(n: number): string {\n if (n === 0) return \"0\";\n return `${n > 0 ? \"+\" : \"\"}${n}`;\n}\n\nfunction signPct(diff: number): string {\n if (diff === 0) return \"0pp\";\n const s = (diff * 100).toFixed(1);\n return `${diff > 0 ? \"+\" : \"\"}${s}pp`;\n}\n\nfunction pct(x: number): string {\n return `${(x * 100).toFixed(1)}%`;\n}\n\nfunction costDelta(a: number, b: number): string {\n if (a === 0 && b === 0) return \"—\";\n if (a === 0) return \"new\";\n const pctChange = ((b - a) / a) * 100;\n return `${pctChange > 0 ? \"+\" : \"\"}${pctChange.toFixed(1)}%`;\n}\n\nfunction truncate(s: string, n: number): string {\n return s.length > n ? `${s.slice(0, n)}…` : s;\n}\n","/**\n * MCP (Model Context Protocol) type definitions.\n *\n * Hand-rolled rather than importing @modelcontextprotocol/sdk because:\n * - Reasonix's value-add isn't reimplementing the protocol, but *caching*\n * it. Owning the types lets us tune them for our integration (strip\n * fields we don't use, add the ones we do like Reasonix's prefixHash).\n * - Zero dependencies — consistent with how we wrote the DeepSeek client.\n * - If Anthropic bumps the SDK and introduces a breaking change, we're\n * insulated as long as we keep up with the spec itself.\n *\n * Spec reference: https://spec.modelcontextprotocol.io/ (2024-11-05 draft\n * at time of writing). Reasonix models the subset it consumes: tools\n * list/call, resources list/read, prompts list/get, plus the init\n * handshake. Sampling and progress notifications remain deferred.\n *\n * Transport note: the wire format for stdio MCP is **newline-delimited\n * JSON** (NDJSON), not the LSP-style Content-Length header framing that\n * some readers might expect. One JSON-RPC message per line.\n */\n\n// ---------- JSON-RPC 2.0 base ----------\n\nexport type JsonRpcId = string | number;\n\nexport interface JsonRpcRequest<P = unknown> {\n jsonrpc: \"2.0\";\n id: JsonRpcId;\n method: string;\n params?: P;\n}\n\nexport interface JsonRpcNotification<P = unknown> {\n jsonrpc: \"2.0\";\n method: string;\n params?: P;\n}\n\nexport interface JsonRpcSuccess<R = unknown> {\n jsonrpc: \"2.0\";\n id: JsonRpcId;\n result: R;\n}\n\nexport interface JsonRpcError {\n jsonrpc: \"2.0\";\n id: JsonRpcId | null;\n error: {\n /** JSON-RPC standard codes: -32700 parse, -32600 invalid request, -32601 method not found, -32602 invalid params, -32603 internal. MCP also defines its own range. */\n code: number;\n message: string;\n data?: unknown;\n };\n}\n\nexport type JsonRpcResponse<R = unknown> = JsonRpcSuccess<R> | JsonRpcError;\n\nexport type JsonRpcMessage = JsonRpcRequest | JsonRpcNotification | JsonRpcSuccess | JsonRpcError;\n\n// ---------- MCP initialize ----------\n\nexport interface McpClientInfo {\n name: string;\n version: string;\n}\n\nexport interface McpClientCapabilities {\n /** Empty object advertises support without any optional sub-features. */\n tools?: Record<string, never>;\n /** Advertised when the client can consume `resources/list` + `resources/read`. */\n resources?: Record<string, never>;\n /** Advertised when the client can consume `prompts/list` + `prompts/get`. */\n prompts?: Record<string, never>;\n // sampling would go here — deferred.\n}\n\nexport interface InitializeParams {\n protocolVersion: string;\n capabilities: McpClientCapabilities;\n clientInfo: McpClientInfo;\n}\n\nexport interface InitializeResult {\n protocolVersion: string;\n serverInfo: { name: string; version: string };\n capabilities: {\n tools?: { listChanged?: boolean };\n resources?: unknown;\n prompts?: unknown;\n };\n instructions?: string;\n}\n\n// ---------- MCP tools ----------\n\nexport interface McpToolSchema {\n /** JSON Schema — compatible with Reasonix's tools.ts JSONSchema shape. */\n type?: string;\n properties?: Record<string, unknown>;\n required?: string[];\n [extra: string]: unknown;\n}\n\nexport interface McpTool {\n name: string;\n description?: string;\n /** MCP calls this `inputSchema`. Reasonix's `parameters` field is the same concept. */\n inputSchema: McpToolSchema;\n}\n\nexport interface ListToolsResult {\n tools: McpTool[];\n nextCursor?: string;\n}\n\nexport interface CallToolParams {\n name: string;\n arguments?: Record<string, unknown>;\n /**\n * MCP's `_meta` envelope carries out-of-band protocol metadata.\n * Setting `progressToken` here tells the server \"send me progress\n * notifications back using this token\"; the server must then emit\n * `notifications/progress` frames until the response arrives.\n */\n _meta?: { progressToken?: string | number };\n}\n\n/**\n * Server → client notification emitted during a long-running request\n * that the client subscribed to via `_meta.progressToken`. `progress`\n * and `total` are typically matched units (files scanned, bytes\n * processed, etc.); `total` may be missing when the server can't\n * estimate the upper bound up front.\n */\nexport interface ProgressNotificationParams {\n progressToken: string | number;\n progress: number;\n total?: number;\n message?: string;\n}\n\n/** Values a `ProgressHandler` receives — `progressToken` is already matched away. */\nexport interface McpProgressInfo {\n progress: number;\n total?: number;\n message?: string;\n}\n\nexport type McpProgressHandler = (info: McpProgressInfo) => void;\n\nexport interface McpContentBlockText {\n type: \"text\";\n text: string;\n}\n\nexport interface McpContentBlockImage {\n type: \"image\";\n data: string;\n mimeType: string;\n}\n\n/** MCP result content is an array of typed blocks. Reasonix consumes only text for now — image blocks get stringified with a placeholder. */\nexport type McpContentBlock = McpContentBlockText | McpContentBlockImage;\n\nexport interface CallToolResult {\n content: McpContentBlock[];\n /** True = tool raised an error; the content describes it. */\n isError?: boolean;\n}\n\n// ---------- MCP resources ----------\n\n/**\n * A resource the server can expose — think \"file the model can read.\"\n * The URI is opaque to the client: servers may use `file://`, custom\n * schemes, or bare strings. Reasonix doesn't interpret them.\n */\nexport interface McpResource {\n uri: string;\n name: string;\n description?: string;\n /** Hint for the content type (e.g. \"text/markdown\"). Purely informational. */\n mimeType?: string;\n}\n\nexport interface ListResourcesParams {\n /** Pagination cursor from a previous listResources response. */\n cursor?: string;\n}\n\nexport interface ListResourcesResult {\n resources: McpResource[];\n nextCursor?: string;\n}\n\nexport interface ReadResourceParams {\n uri: string;\n}\n\n/**\n * One resource can return multiple content blobs (e.g. the file + a\n * side-car). `text` is the common case for UTF-8 content; `blob` is\n * base64-encoded bytes for binary content. Servers populate exactly\n * one of the two for each entry.\n */\nexport interface McpResourceContentsText {\n uri: string;\n mimeType?: string;\n text: string;\n}\n\nexport interface McpResourceContentsBlob {\n uri: string;\n mimeType?: string;\n blob: string;\n}\n\nexport type McpResourceContents = McpResourceContentsText | McpResourceContentsBlob;\n\nexport interface ReadResourceResult {\n contents: McpResourceContents[];\n}\n\n// ---------- MCP prompts ----------\n\n/**\n * A parameterizable prompt template the server exposes. Clients fetch\n * it with `prompts/get` and pass the result to the model as-is.\n */\nexport interface McpPromptArgument {\n name: string;\n description?: string;\n required?: boolean;\n}\n\nexport interface McpPrompt {\n name: string;\n description?: string;\n arguments?: McpPromptArgument[];\n}\n\nexport interface ListPromptsParams {\n cursor?: string;\n}\n\nexport interface ListPromptsResult {\n prompts: McpPrompt[];\n nextCursor?: string;\n}\n\nexport interface GetPromptParams {\n name: string;\n arguments?: Record<string, string>;\n}\n\n/**\n * MCP prompt messages are modeled after chat completions: role + content.\n * Content can be a text block OR (per the spec) a resource/image block;\n * Reasonix cares about text in v1, but surfaces the raw array so callers\n * can render other kinds if they need to.\n */\nexport interface McpPromptMessage {\n role: \"user\" | \"assistant\";\n content: McpContentBlock | McpPromptResourceBlock;\n}\n\nexport interface McpPromptResourceBlock {\n type: \"resource\";\n resource: McpResourceContents;\n}\n\nexport interface GetPromptResult {\n description?: string;\n messages: McpPromptMessage[];\n}\n\n// ---------- convenience ----------\n\n/** Current MCP protocol version Reasonix is coded against. */\nexport const MCP_PROTOCOL_VERSION = \"2024-11-05\";\n\n/** Type guard — success vs error response. */\nexport function isJsonRpcError(msg: JsonRpcResponse): msg is JsonRpcError {\n return \"error\" in msg;\n}\n","/**\n * MCP client — request/response correlation, initialize handshake,\n * tools/list, tools/call. Built on top of a McpTransport so the same\n * logic works against a real stdio server or an in-process fake.\n */\n\nimport type { McpTransport } from \"./stdio.js\";\nimport {\n type CallToolParams,\n type CallToolResult,\n type GetPromptParams,\n type GetPromptResult,\n type InitializeParams,\n type InitializeResult,\n type JsonRpcId,\n type JsonRpcMessage,\n type JsonRpcRequest,\n type JsonRpcResponse,\n type ListPromptsParams,\n type ListPromptsResult,\n type ListResourcesParams,\n type ListResourcesResult,\n type ListToolsResult,\n MCP_PROTOCOL_VERSION,\n type McpClientInfo,\n type McpProgressHandler,\n type ProgressNotificationParams,\n type ReadResourceParams,\n type ReadResourceResult,\n isJsonRpcError,\n} from \"./types.js\";\n\nexport interface McpClientOptions {\n transport: McpTransport;\n clientInfo?: McpClientInfo;\n /** Per-request timeout. Default 60s. */\n requestTimeoutMs?: number;\n}\n\ninterface PendingRequest {\n resolve: (value: unknown) => void;\n reject: (err: Error) => void;\n timeout: NodeJS.Timeout;\n}\n\nexport class McpClient {\n private readonly transport: McpTransport;\n private readonly clientInfo: McpClientInfo;\n private readonly requestTimeoutMs: number;\n private readonly pending = new Map<JsonRpcId, PendingRequest>();\n private nextId = 1;\n private readerStarted = false;\n private initialized = false;\n private _serverCapabilities: InitializeResult[\"capabilities\"] = {};\n private _serverInfo: InitializeResult[\"serverInfo\"] = { name: \"\", version: \"\" };\n private _protocolVersion = \"\";\n private _instructions: string | undefined;\n // Progress-token → handler for notifications/progress routing. Tokens\n // are minted per call when the caller supplies an onProgress\n // callback; cleared when the final response lands (or the pending\n // request rejects). No leaks — the `try/finally` in callTool\n // guarantees cleanup even on timeout.\n private readonly progressHandlers = new Map<string | number, McpProgressHandler>();\n private nextProgressToken = 1;\n\n constructor(opts: McpClientOptions) {\n this.transport = opts.transport;\n this.clientInfo = opts.clientInfo ?? { name: \"reasonix\", version: \"0.3.0-dev\" };\n this.requestTimeoutMs = opts.requestTimeoutMs ?? 60_000;\n }\n\n /** Server's advertised capabilities, available after initialize(). */\n get serverCapabilities(): InitializeResult[\"capabilities\"] {\n return this._serverCapabilities;\n }\n\n /** Server's self-reported name + version, available after initialize(). */\n get serverInfo(): InitializeResult[\"serverInfo\"] {\n return this._serverInfo;\n }\n\n /** Protocol version the server agreed to during the handshake. */\n get protocolVersion(): string {\n return this._protocolVersion;\n }\n\n /** Optional free-form instructions the server provides at handshake. */\n get serverInstructions(): string | undefined {\n return this._instructions;\n }\n\n /**\n * Complete the initialize → initialized handshake. Must be called\n * before any other method (otherwise compliant servers reject).\n */\n async initialize(): Promise<InitializeResult> {\n if (this.initialized) throw new Error(\"MCP client already initialized\");\n this.startReaderIfNeeded();\n const result = await this.request<InitializeResult>(\"initialize\", {\n protocolVersion: MCP_PROTOCOL_VERSION,\n // Advertise every method the client can consume so servers know\n // they can send listChanged notifications etc. Sub-feature flags\n // (e.g. `resources.subscribe`) are omitted — we don't implement\n // those yet and the empty object means \"method-level support, no\n // sub-features.\"\n capabilities: { tools: {}, resources: {}, prompts: {} },\n clientInfo: this.clientInfo,\n } satisfies InitializeParams);\n this._serverCapabilities = result.capabilities ?? {};\n this._serverInfo = result.serverInfo ?? { name: \"\", version: \"\" };\n this._protocolVersion = result.protocolVersion ?? \"\";\n this._instructions = result.instructions;\n // Per spec: client sends notifications/initialized after receiving the\n // initialize response. Only then is the connection live for other\n // methods.\n await this.transport.send({\n jsonrpc: \"2.0\",\n method: \"notifications/initialized\",\n });\n this.initialized = true;\n return result;\n }\n\n /** List tools the server exposes. */\n async listTools(): Promise<ListToolsResult> {\n this.assertInitialized();\n return this.request<ListToolsResult>(\"tools/list\", {});\n }\n\n /**\n * Invoke a tool by name. When `onProgress` is supplied, attaches a\n * fresh progress token so the server can send incremental updates\n * via `notifications/progress`; they're routed to the callback until\n * the final response arrives (or the request times out, in which\n * case the handler is simply dropped — no extra notification).\n *\n * When `signal` is supplied, aborting it:\n * 1) fires `notifications/cancelled` to the server (MCP 2024-11-05\n * way of saying \"forget this request, I no longer care\"), and\n * 2) rejects the pending promise immediately with an AbortError,\n * so the caller doesn't have to wait for the subprocess to\n * finish its in-flight file write or network request.\n * The server MAY still emit a late response; we drop it in dispatch\n * since the request id is gone from `pending`.\n */\n async callTool(\n name: string,\n args?: Record<string, unknown>,\n opts: { onProgress?: McpProgressHandler; signal?: AbortSignal } = {},\n ): Promise<CallToolResult> {\n this.assertInitialized();\n const params: CallToolParams = { name, arguments: args ?? {} };\n let token: number | undefined;\n if (opts.onProgress) {\n token = this.nextProgressToken++;\n this.progressHandlers.set(token, opts.onProgress);\n params._meta = { progressToken: token };\n }\n try {\n return await this.request<CallToolResult>(\"tools/call\", params, opts.signal);\n } finally {\n if (token !== undefined) this.progressHandlers.delete(token);\n }\n }\n\n /**\n * List resources the server exposes. Supports a pagination cursor;\n * callers interested in the full set should loop on `nextCursor`.\n * Servers that don't support resources respond with method-not-found\n * (−32601) — we surface that as a thrown Error so callers can gate\n * on the `serverCapabilities.resources` field first.\n */\n async listResources(cursor?: string): Promise<ListResourcesResult> {\n this.assertInitialized();\n return this.request<ListResourcesResult>(\"resources/list\", {\n ...(cursor ? { cursor } : {}),\n } satisfies ListResourcesParams);\n }\n\n /** Read the contents of a resource by URI. */\n async readResource(uri: string): Promise<ReadResourceResult> {\n this.assertInitialized();\n return this.request<ReadResourceResult>(\"resources/read\", {\n uri,\n } satisfies ReadResourceParams);\n }\n\n /** List prompt templates the server exposes. */\n async listPrompts(cursor?: string): Promise<ListPromptsResult> {\n this.assertInitialized();\n return this.request<ListPromptsResult>(\"prompts/list\", {\n ...(cursor ? { cursor } : {}),\n } satisfies ListPromptsParams);\n }\n\n /**\n * Fetch a rendered prompt by name. `args` supplies values for any\n * required template arguments; the server validates. Returns messages\n * ready to prepend to the model's input.\n */\n async getPrompt(name: string, args?: Record<string, string>): Promise<GetPromptResult> {\n this.assertInitialized();\n return this.request<GetPromptResult>(\"prompts/get\", {\n name,\n ...(args ? { arguments: args } : {}),\n } satisfies GetPromptParams);\n }\n\n /** Close the transport and reject any outstanding requests. */\n async close(): Promise<void> {\n for (const [, pending] of this.pending) {\n clearTimeout(pending.timeout);\n pending.reject(new Error(\"MCP client closed\"));\n }\n this.pending.clear();\n await this.transport.close();\n }\n\n // ---------- internals ----------\n\n private assertInitialized(): void {\n if (!this.initialized) throw new Error(\"MCP client not initialized — call initialize() first\");\n }\n\n private async request<R>(method: string, params: unknown, signal?: AbortSignal): Promise<R> {\n const id = this.nextId++;\n const frame: JsonRpcRequest = { jsonrpc: \"2.0\", id, method, params };\n let abortHandler: (() => void) | null = null;\n const promise = new Promise<R>((resolve, reject) => {\n const timeout = setTimeout(() => {\n this.pending.delete(id);\n if (abortHandler && signal) signal.removeEventListener(\"abort\", abortHandler);\n reject(\n new Error(`MCP request ${method} (id=${id}) timed out after ${this.requestTimeoutMs}ms`),\n );\n }, this.requestTimeoutMs);\n this.pending.set(id, {\n resolve: resolve as (value: unknown) => void,\n reject,\n timeout,\n });\n // Wire up cancellation: when signal fires, send an MCP cancellation\n // notification to the server (so it can stop whatever it was doing)\n // and reject the caller immediately — no need to wait for the\n // subprocess to finish its in-flight work. Late responses from the\n // server are dropped by `dispatch` because the id is gone from\n // `pending`.\n if (signal) {\n if (signal.aborted) {\n this.pending.delete(id);\n clearTimeout(timeout);\n reject(new Error(`MCP request ${method} (id=${id}) aborted before send`));\n return;\n }\n abortHandler = () => {\n this.pending.delete(id);\n clearTimeout(timeout);\n void this.transport\n .send({\n jsonrpc: \"2.0\",\n method: \"notifications/cancelled\",\n params: { requestId: id, reason: \"aborted by user\" },\n })\n .catch(() => {\n // Transport may already be closing — swallow; we still\n // reject the caller below so they unblock.\n });\n reject(new Error(`MCP request ${method} (id=${id}) aborted by user`));\n };\n signal.addEventListener(\"abort\", abortHandler, { once: true });\n }\n });\n try {\n await this.transport.send(frame);\n } catch (err) {\n this.pending.delete(id);\n if (abortHandler && signal) signal.removeEventListener(\"abort\", abortHandler);\n throw err;\n }\n try {\n return await promise;\n } finally {\n if (abortHandler && signal) signal.removeEventListener(\"abort\", abortHandler);\n }\n }\n\n private startReaderIfNeeded(): void {\n if (this.readerStarted) return;\n this.readerStarted = true;\n // Fire-and-forget: the reader runs for the lifetime of the client.\n void this.readLoop();\n }\n\n private async readLoop(): Promise<void> {\n try {\n for await (const msg of this.transport.messages()) {\n this.dispatch(msg);\n }\n } catch (err) {\n // Surface as rejections on all pending requests so nobody hangs.\n for (const [, pending] of this.pending) {\n clearTimeout(pending.timeout);\n pending.reject(err as Error);\n }\n this.pending.clear();\n }\n }\n\n private dispatch(msg: JsonRpcMessage): void {\n // Notifications (no `id`): route by method. Progress notifications\n // go to the per-call handler if one was registered; everything\n // else is dropped silently (we don't yet handle tools/list_changed\n // or resources/list_changed).\n if (!(\"id\" in msg) || msg.id === null || msg.id === undefined) {\n if (\"method\" in msg && msg.method === \"notifications/progress\") {\n const p = msg.params as ProgressNotificationParams | undefined;\n if (!p || p.progressToken === undefined) return;\n const handler = this.progressHandlers.get(p.progressToken);\n if (!handler) return; // late notification after the call resolved\n handler({ progress: p.progress, total: p.total, message: p.message });\n }\n return;\n }\n if (!(\"result\" in msg) && !(\"error\" in msg)) return; // it's a request from server\n const pending = this.pending.get(msg.id);\n if (!pending) return; // late response after timeout; drop\n this.pending.delete(msg.id);\n clearTimeout(pending.timeout);\n const resp = msg as JsonRpcResponse;\n if (isJsonRpcError(resp)) {\n pending.reject(new Error(`MCP ${resp.error.code}: ${resp.error.message}`));\n } else {\n pending.resolve(resp.result);\n }\n }\n}\n","/**\n * Stdio transport for MCP.\n *\n * MCP's stdio wire format is **newline-delimited JSON** (one JSON-RPC\n * message per line). We spawn the server as a child process, write\n * frames to its stdin, parse its stdout line-by-line as they arrive.\n *\n * Transport is abstracted behind an interface so unit tests can fake it\n * with an in-process duplex pair — spawning real servers in unit tests\n * is flaky and slow.\n */\n\nimport { type ChildProcess, spawn } from \"node:child_process\";\nimport type { JsonRpcMessage } from \"./types.js\";\n\n/**\n * A transport sends JSON-RPC messages upstream and surfaces messages\n * arriving downstream via an async iterator. One instance per server\n * connection.\n */\nexport interface McpTransport {\n /** Send one JSON-RPC message. Resolves when the bytes are accepted. */\n send(message: JsonRpcMessage): Promise<void>;\n /** Async iterator over incoming messages. Ends when the connection closes. */\n messages(): AsyncIterableIterator<JsonRpcMessage>;\n /** Close the underlying resource (kill child process, close streams). */\n close(): Promise<void>;\n}\n\nexport interface StdioTransportOptions {\n /** Argv to spawn. First element is the command. */\n command: string;\n args?: string[];\n /** Env overlay — merged over process.env unless replaceEnv=true. */\n env?: Record<string, string>;\n /** When true, only the env above is visible to the child. Default false. */\n replaceEnv?: boolean;\n /** CWD for the child. Default: process.cwd(). */\n cwd?: string;\n /**\n * Spawn through a shell. Default: true on win32 (needed to resolve\n * `.cmd` wrappers like `npx.cmd`, `pnpm.cmd`), false elsewhere.\n * Explicitly pass `false` to opt out on Windows; pass `true` to force\n * it on POSIX (rarely needed).\n */\n shell?: boolean;\n}\n\n/**\n * Spawn `command args...` as a child process and use its stdin/stdout as\n * an MCP transport. Stderr is forwarded to the parent's stderr so server\n * diagnostics are still visible.\n */\nexport class StdioTransport implements McpTransport {\n private readonly child: ChildProcess;\n private readonly queue: JsonRpcMessage[] = [];\n private readonly waiters: Array<(m: JsonRpcMessage | null) => void> = [];\n private closed = false;\n private stdoutBuffer = \"\";\n\n constructor(opts: StdioTransportOptions) {\n const env = opts.replaceEnv ? { ...(opts.env ?? {}) } : { ...process.env, ...(opts.env ?? {}) };\n // Windows wraps binaries as .cmd/.bat shims (npx.cmd, pnpm.cmd, …).\n // child_process.spawn without shell:true can't resolve them, which\n // breaks `--mcp \"npx -y some-server\"` — the most common MCP setup.\n // Default shell:true on win32 and leave POSIX alone.\n const shell = opts.shell ?? process.platform === \"win32\";\n\n if (shell) {\n // Node's shell:true + args[] triggers DEP0190 because it concatenates\n // with spaces and doesn't quote args — unsafe if an arg contains\n // shell metacharacters. We build a single command line ourselves,\n // quoting ONLY the args (command stays bare so the shell's PATH /\n // PATHEXT lookup finds `npx` → `npx.cmd` on Windows).\n const line = [\n opts.command,\n ...(opts.args ?? []).map((a) => quoteArg(a, process.platform === \"win32\")),\n ].join(\" \");\n this.child = spawn(line, [], {\n env,\n cwd: opts.cwd,\n stdio: [\"pipe\", \"pipe\", \"inherit\"],\n shell: true,\n });\n } else {\n this.child = spawn(opts.command, opts.args ?? [], {\n env,\n cwd: opts.cwd,\n stdio: [\"pipe\", \"pipe\", \"inherit\"],\n });\n }\n this.child.stdout!.setEncoding(\"utf8\");\n this.child.stdout!.on(\"data\", (chunk: string) => this.onStdout(chunk));\n this.child.on(\"close\", () => this.onClose());\n this.child.on(\"error\", (err) => {\n // Surface spawn errors as a synthetic JsonRpcError so callers don't\n // hang on a stream that never emits anything.\n this.push({\n jsonrpc: \"2.0\",\n id: null,\n error: { code: -32000, message: `transport error: ${err.message}` },\n });\n });\n }\n\n async send(message: JsonRpcMessage): Promise<void> {\n if (this.closed) throw new Error(\"MCP transport is closed\");\n return new Promise((resolve, reject) => {\n const line = `${JSON.stringify(message)}\\n`;\n this.child.stdin!.write(line, \"utf8\", (err) => {\n if (err) reject(err);\n else resolve();\n });\n });\n }\n\n async *messages(): AsyncIterableIterator<JsonRpcMessage> {\n while (true) {\n if (this.queue.length > 0) {\n yield this.queue.shift()!;\n continue;\n }\n if (this.closed) return;\n const next = await new Promise<JsonRpcMessage | null>((resolve) => {\n this.waiters.push(resolve);\n });\n if (next === null) return; // closed while we were waiting\n yield next;\n }\n }\n\n async close(): Promise<void> {\n if (this.closed) return;\n this.closed = true;\n // Signal any pending waiters.\n while (this.waiters.length > 0) this.waiters.shift()!(null);\n try {\n this.child.stdin!.end();\n } catch {\n /* already ended */\n }\n if (this.child.exitCode === null && !this.child.killed) {\n this.child.kill(\"SIGTERM\");\n }\n }\n\n /** Parse incoming stdout chunks into NDJSON messages. */\n private onStdout(chunk: string): void {\n this.stdoutBuffer += chunk;\n let newlineIdx: number;\n // biome-ignore lint/suspicious/noAssignInExpressions: idiomatic loop shape\n while ((newlineIdx = this.stdoutBuffer.indexOf(\"\\n\")) !== -1) {\n const line = this.stdoutBuffer.slice(0, newlineIdx).trim();\n this.stdoutBuffer = this.stdoutBuffer.slice(newlineIdx + 1);\n if (!line) continue;\n try {\n const msg = JSON.parse(line) as JsonRpcMessage;\n this.push(msg);\n } catch {\n // Malformed lines are dropped — some servers emit startup banners\n // before the JSON-RPC loop begins. We surface the noise to stderr\n // via the inherited stderr stream, not our event queue.\n }\n }\n }\n\n private onClose(): void {\n this.closed = true;\n while (this.waiters.length > 0) this.waiters.shift()!(null);\n }\n\n private push(msg: JsonRpcMessage): void {\n const waiter = this.waiters.shift();\n if (waiter) waiter(msg);\n else this.queue.push(msg);\n }\n}\n\n/**\n * Quote a single argument for inclusion in a shell command line.\n * On Windows (cmd.exe): wrap in double quotes, escape internal `\"` as `\"\"`,\n * leave everything else alone. On POSIX: wrap in single quotes, escape\n * internal `'` as `'\\''`. Both handle spaces, wildcards, pipes, and all\n * other metacharacters correctly.\n */\nfunction quoteArg(s: string, windows: boolean): string {\n if (!windows) {\n // POSIX: single-quote, escape single quotes.\n return `'${s.replace(/'/g, \"'\\\\''\")}'`;\n }\n // cmd.exe: double-quote, escape internal quotes by doubling.\n return `\"${s.replace(/\"/g, '\"\"')}\"`;\n}\n","/**\n * HTTP+SSE transport for MCP (spec version 2024-11-05).\n *\n * Wire shape:\n * 1. Client opens GET to the SSE URL with `Accept: text/event-stream`.\n * 2. Server's first SSE event is `event: endpoint`, `data: <url>` — the\n * URL (relative or absolute) the client must POST JSON-RPC requests\n * to. All subsequent server → client messages arrive as `event: message`\n * SSE frames carrying a JSON-RPC response or server-initiated frame.\n * 3. Client POSTs each outgoing JSON-RPC frame to the endpoint URL.\n * The POST response body is ignored — replies land on the SSE stream.\n *\n * This transport exists so Reasonix can talk to hosted/remote MCP servers\n * (e.g. a company's internal knowledge server fronted by auth). Stdio\n * covers local subprocesses; SSE covers everything else.\n *\n * Note: the newer \"Streamable HTTP\" transport (2025 spec) folds the POST\n * and SSE streams onto a single endpoint. We stay on 2024-11-05 here —\n * that's what `MCP_PROTOCOL_VERSION` advertises in the initialize handshake\n * and what currently-published servers implement.\n */\n\nimport { createParser } from \"eventsource-parser\";\nimport type { McpTransport } from \"./stdio.js\";\nimport type { JsonRpcMessage } from \"./types.js\";\n\nexport interface SseTransportOptions {\n /** SSE endpoint URL, e.g. `https://mcp.example.com/sse`. */\n url: string;\n /** Extra headers sent on both the SSE GET and the JSON-RPC POSTs (e.g. `Authorization`). */\n headers?: Record<string, string>;\n}\n\n/**\n * Open an SSE stream to `url`, parse incoming events into JsonRpcMessages,\n * POST outgoing frames to the endpoint URL the server advertises.\n */\nexport class SseTransport implements McpTransport {\n private readonly url: string;\n private readonly headers: Record<string, string>;\n private readonly queue: JsonRpcMessage[] = [];\n private readonly waiters: Array<(m: JsonRpcMessage | null) => void> = [];\n private readonly controller = new AbortController();\n private closed = false;\n private postUrl: string | null = null;\n private readonly endpointReady: Promise<string>;\n private resolveEndpoint!: (url: string) => void;\n private rejectEndpoint!: (err: Error) => void;\n\n constructor(opts: SseTransportOptions) {\n this.url = opts.url;\n this.headers = opts.headers ?? {};\n this.endpointReady = new Promise<string>((resolve, reject) => {\n this.resolveEndpoint = resolve;\n this.rejectEndpoint = reject;\n });\n // Swallow unhandled-rejection noise if nobody ever calls send().\n this.endpointReady.catch(() => undefined);\n void this.runStream();\n }\n\n async send(message: JsonRpcMessage): Promise<void> {\n if (this.closed) throw new Error(\"MCP SSE transport is closed\");\n const postUrl = await this.endpointReady;\n const res = await fetch(postUrl, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", ...this.headers },\n body: JSON.stringify(message),\n signal: this.controller.signal,\n });\n // Drain body so the socket returns to the pool even if the server\n // elected to write one. We explicitly don't parse it — responses\n // arrive on the SSE channel.\n await res.arrayBuffer().catch(() => undefined);\n if (!res.ok) {\n throw new Error(`MCP SSE POST ${postUrl} failed: ${res.status} ${res.statusText}`);\n }\n }\n\n async *messages(): AsyncIterableIterator<JsonRpcMessage> {\n while (true) {\n if (this.queue.length > 0) {\n yield this.queue.shift()!;\n continue;\n }\n if (this.closed) return;\n const next = await new Promise<JsonRpcMessage | null>((resolve) => {\n this.waiters.push(resolve);\n });\n if (next === null) return;\n yield next;\n }\n }\n\n async close(): Promise<void> {\n if (this.closed) return;\n this.closed = true;\n while (this.waiters.length > 0) this.waiters.shift()!(null);\n // Reject any still-pending send() that was waiting for the endpoint.\n this.rejectEndpoint(new Error(\"MCP SSE transport closed before endpoint was ready\"));\n try {\n this.controller.abort();\n } catch {\n /* already aborted */\n }\n }\n\n // ---------- internals ----------\n\n private async runStream(): Promise<void> {\n let res: Response;\n try {\n res = await fetch(this.url, {\n method: \"GET\",\n headers: { accept: \"text/event-stream\", ...this.headers },\n signal: this.controller.signal,\n });\n } catch (err) {\n this.failHandshake(`SSE connect to ${this.url} failed: ${(err as Error).message}`);\n return;\n }\n if (!res.ok || !res.body) {\n // Drain body to free the socket before giving up.\n await res.body?.cancel().catch(() => undefined);\n this.failHandshake(`SSE handshake ${this.url} → ${res.status} ${res.statusText}`);\n return;\n }\n\n const parser = createParser({\n onEvent: (ev) => this.handleEvent(ev.event ?? \"message\", ev.data),\n });\n const decoder = new TextDecoder();\n try {\n for await (const chunk of res.body as AsyncIterable<Uint8Array>) {\n parser.feed(decoder.decode(chunk, { stream: true }));\n }\n } catch (err) {\n if (!this.closed) {\n this.pushError(`SSE stream error: ${(err as Error).message}`);\n }\n } finally {\n this.markClosed();\n }\n }\n\n private handleEvent(type: string, data: string): void {\n if (type === \"endpoint\") {\n if (this.postUrl) return; // ignore repeat announcements\n try {\n this.postUrl = new URL(data, this.url).toString();\n this.resolveEndpoint(this.postUrl);\n } catch (err) {\n this.failHandshake(`SSE endpoint event had bad URL \"${data}\": ${(err as Error).message}`);\n }\n return;\n }\n if (type === \"message\") {\n try {\n const parsed = JSON.parse(data) as JsonRpcMessage;\n this.pushMessage(parsed);\n } catch {\n // Malformed JSON-RPC on an SSE frame — drop it, same as stdio.\n }\n return;\n }\n // Unknown event types (server pings, custom extensions) — ignore.\n }\n\n private failHandshake(reason: string): void {\n this.rejectEndpoint(new Error(reason));\n this.pushError(reason);\n this.markClosed();\n }\n\n private pushMessage(msg: JsonRpcMessage): void {\n const waiter = this.waiters.shift();\n if (waiter) waiter(msg);\n else this.queue.push(msg);\n }\n\n private pushError(message: string): void {\n this.pushMessage({\n jsonrpc: \"2.0\",\n id: null,\n error: { code: -32000, message },\n });\n }\n\n private markClosed(): void {\n if (this.closed) return;\n this.closed = true;\n while (this.waiters.length > 0) this.waiters.shift()!(null);\n }\n}\n","/**\n * Split a shell-style command string into argv, respecting single and\n * double quotes. Intended for parsing the user's `--mcp \"cmd args...\"`\n * flag — NOT a full shell parser (no variable expansion, no subshells,\n * no globs, no `&&` / pipes).\n *\n * The tradeoff: users with paths containing spaces need to quote them\n * (e.g. `--mcp 'npx -y pkg \"/my path/here\"'`), which is how they'd\n * already quote them at the shell level.\n *\n * Throws on unterminated quotes — better than silently dropping half\n * the command.\n */\nexport function shellSplit(input: string): string[] {\n const tokens: string[] = [];\n let cur = \"\";\n let quote: '\"' | \"'\" | null = null;\n let i = 0;\n const s = input;\n\n while (i < s.length) {\n const ch = s[i]!;\n\n if (quote) {\n if (ch === quote) {\n quote = null;\n i++;\n continue;\n }\n // backslash escapes inside double quotes only\n if (ch === \"\\\\\" && quote === '\"' && i + 1 < s.length) {\n cur += s[i + 1];\n i += 2;\n continue;\n }\n cur += ch;\n i++;\n continue;\n }\n\n if (ch === '\"' || ch === \"'\") {\n quote = ch as '\"' | \"'\";\n i++;\n continue;\n }\n\n // Backslash escape ONLY applies inside double quotes (handled above).\n // Outside quotes, backslashes pass through literally — otherwise\n // Windows paths like `C:\\path\\to\\exe` get mangled. POSIX users who\n // want to escape a space outside quotes can use single quotes instead.\n\n if (ch === \" \" || ch === \"\\t\") {\n if (cur.length > 0) {\n tokens.push(cur);\n cur = \"\";\n }\n i++;\n continue;\n }\n\n cur += ch;\n i++;\n }\n\n if (quote) {\n throw new Error(\n `shellSplit: unterminated ${quote === '\"' ? \"double\" : \"single\"} quote in input`,\n );\n }\n if (cur.length > 0) tokens.push(cur);\n return tokens;\n}\n","/**\n * Parse the `--mcp` CLI argument into a transport-tagged spec.\n *\n * Accepted forms:\n * \"name=command args...\" → stdio, namespaced (tools prefixed with `name_`)\n * \"command args...\" → stdio, anonymous\n * \"name=https://host/sse\" → SSE, namespaced\n * \"https://host/sse\" → SSE, anonymous\n * (\"http://\" is also honored — useful for local dev servers.)\n *\n * The identifier regex before `=` is deliberately narrow\n * (`[a-zA-Z_][a-zA-Z0-9_]*`) so Windows drive letters (\"C:\\\\...\") and\n * other strings containing `=` or `:` don't accidentally trigger the\n * namespace branch. If a user ever wants their command to literally start\n * with `foo=...` as a bare command, they can wrap it in quotes inside the\n * shell command string.\n *\n * Transport is selected solely by whether the body begins with `http://`\n * or `https://`. Anything else is stdio — including ws:// (unsupported)\n * which will surface later as a spawn error, keeping the rule local.\n */\n\nimport { shellSplit } from \"./shell-split.js\";\n\nexport interface StdioMcpSpec {\n transport: \"stdio\";\n /** Namespace prefix applied to each registered tool, or null if anonymous. */\n name: string | null;\n /** Argv[0]. */\n command: string;\n /** Remaining argv. */\n args: string[];\n}\n\nexport interface SseMcpSpec {\n transport: \"sse\";\n name: string | null;\n /** Fully qualified SSE endpoint URL. */\n url: string;\n}\n\nexport type McpSpec = StdioMcpSpec | SseMcpSpec;\n\nconst NAME_PREFIX = /^([a-zA-Z_][a-zA-Z0-9_]*)=(.*)$/;\nconst HTTP_URL = /^https?:\\/\\//i;\n\nexport function parseMcpSpec(input: string): McpSpec {\n const trimmed = input.trim();\n if (!trimmed) {\n throw new Error(\"empty MCP spec\");\n }\n\n const nameMatch = NAME_PREFIX.exec(trimmed);\n const name = nameMatch ? nameMatch[1]! : null;\n const body = (nameMatch ? nameMatch[2]! : trimmed).trim();\n\n if (!body) {\n throw new Error(`MCP spec has name but no command: ${input}`);\n }\n\n if (HTTP_URL.test(body)) {\n return { transport: \"sse\", name, url: body };\n }\n\n const argv = shellSplit(body);\n if (argv.length === 0) {\n throw new Error(`MCP spec has name but no command: ${input}`);\n }\n const [command, ...args] = argv;\n return { transport: \"stdio\", name, command: command!, args };\n}\n","/**\n * Gather a full inspection report from an initialized MCP client:\n * server info, capabilities, tools, resources, prompts. Methods the\n * server doesn't support come back as `{ supported: false }` instead\n * of throwing, so a CLI or UI can render a consistent \"what this\n * server exposes\" summary even against minimal implementations.\n *\n * Pure with respect to I/O beyond the passed-in client — the CLI\n * layer owns argument parsing, connection setup, and printing.\n */\n\nimport type { McpClient } from \"./client.js\";\nimport type { McpPrompt, McpResource, McpTool } from \"./types.js\";\n\nexport interface InspectionReport {\n protocolVersion: string;\n serverInfo: { name: string; version: string };\n capabilities: Record<string, unknown>;\n instructions?: string;\n tools: SectionResult<McpTool>;\n resources: SectionResult<McpResource>;\n prompts: SectionResult<McpPrompt>;\n}\n\nexport type SectionResult<T> =\n | { supported: true; items: T[] }\n | { supported: false; reason: string };\n\n/**\n * Run an inspection against a **already-initialized** client. Caller\n * is responsible for `initialize()` before this and `close()` after.\n * We keep this pure so unit tests can feed in a FakeMcpTransport and\n * verify the aggregate shape without spinning up a real process.\n */\nexport async function inspectMcpServer(client: McpClient): Promise<InspectionReport> {\n // We always *try* the three listings so the client learns whether a\n // server without explicit capability flags still serves them —\n // some servers omit capabilities but still respond to the methods.\n const tools = await trySection<McpTool>(() => client.listTools().then((r) => r.tools));\n const resources = await trySection<McpResource>(() =>\n client.listResources().then((r) => r.resources),\n );\n const prompts = await trySection<McpPrompt>(() => client.listPrompts().then((r) => r.prompts));\n\n return {\n protocolVersion: client.protocolVersion || \"(unknown)\",\n serverInfo: client.serverInfo,\n capabilities: client.serverCapabilities ?? {},\n instructions: client.serverInstructions,\n tools,\n resources,\n prompts,\n };\n}\n\nasync function trySection<T>(load: () => Promise<T[]>): Promise<SectionResult<T>> {\n try {\n const items = await load();\n return { supported: true, items };\n } catch (err) {\n const msg = (err as Error).message ?? String(err);\n // -32601 is JSON-RPC \"method not found\" — the canonical response\n // from a server that doesn't implement this family. Treat it as\n // \"not supported\" rather than a hard error, so the CLI can render\n // a clean summary instead of aborting on the first missing method.\n if (/-32601/.test(msg) || /method not found/i.test(msg)) {\n return { supported: false, reason: \"method not found (-32601)\" };\n }\n return { supported: false, reason: msg };\n }\n}\n","/**\n * Aider-style SEARCH/REPLACE edit blocks.\n *\n * The model emits blocks in this exact shape, one or more per response:\n *\n * path/to/file.ts\n * <<<<<<< SEARCH\n * exact existing lines (whitespace-sensitive)\n * =======\n * replacement lines\n * >>>>>>> REPLACE\n *\n * We chose this over unified diffs because:\n * - Models produce it reliably — no line-number drift.\n * - It tolerates multi-edit responses without ambiguity over which\n * hunk belongs to which file.\n * - Aider has years of evidence that this format works even against\n * weaker models than DeepSeek R1, so it's a conservative pick.\n *\n * The SEARCH text must match the file byte-for-byte. Empty SEARCH is a\n * sentinel for \"create new file\" — the REPLACE becomes the whole file.\n * If SEARCH doesn't match we refuse the edit and surface the failure;\n * we do NOT guess or fuzzy-match. A wrong silent edit is worse than a\n * missing one — the user can re-ask with the exact current content.\n */\n\nimport { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from \"node:fs\";\nimport { dirname, resolve } from \"node:path\";\n\nexport interface EditBlock {\n /** Path as written by the model — relative to rootDir, or absolute. */\n path: string;\n /** Literal text to match in the target file. Empty → create new file. */\n search: string;\n /** Replacement text to write in place of `search`. */\n replace: string;\n /** Char offset in the source message where this block started. */\n offset: number;\n}\n\nexport type ApplyStatus =\n /** Edit landed on disk. */\n | \"applied\"\n /** New file created (SEARCH was empty and file didn't exist). */\n | \"created\"\n /** File exists but SEARCH block wasn't found in its content. */\n | \"not-found\"\n /** File doesn't exist and SEARCH was non-empty (can't create without content). */\n | \"file-missing\"\n /** Path escapes rootDir — refused on safety grounds. */\n | \"path-escape\"\n /** fs write / read threw. */\n | \"error\";\n\nexport interface ApplyResult {\n path: string;\n status: ApplyStatus;\n /** Extra detail (e.g. error message) for logs. */\n message?: string;\n}\n\n/**\n * One edit block per match. The regex is anchored to the 7-char marker\n * lines because those are visually distinct and unlikely to appear in\n * normal code.\n *\n * Anchored with `^` + `m` flag so the filename has to live on its own\n * line. Keeps us from matching e.g. a JS-import string that happens to\n * contain `<<<<<<< SEARCH` in inner text.\n */\n// `\\n?` before the =======/REPLACE separators makes the body optional:\n// empty SEARCH (new-file sentinel) works without requiring a gratuitous\n// empty line, and the same holds for empty REPLACE (file-deletion\n// semantics, not yet supported but cheaply representable).\nconst BLOCK_RE = /^(\\S[^\\n]*)\\n<{7} SEARCH\\n([\\s\\S]*?)\\n?={7}\\n([\\s\\S]*?)\\n?>{7} REPLACE/gm;\n\nexport function parseEditBlocks(text: string): EditBlock[] {\n const out: EditBlock[] = [];\n BLOCK_RE.lastIndex = 0;\n let m: RegExpExecArray | null = BLOCK_RE.exec(text);\n while (m !== null) {\n out.push({\n path: m[1]!.trim(),\n search: m[2]!,\n replace: m[3]!,\n offset: m.index,\n });\n m = BLOCK_RE.exec(text);\n }\n return out;\n}\n\nexport function applyEditBlock(block: EditBlock, rootDir: string): ApplyResult {\n const absRoot = resolve(rootDir);\n const absTarget = resolve(absRoot, block.path);\n // Refuse paths that escape rootDir. `resolve` normalizes `..`, so\n // startsWith on the normalized pair is enough.\n if (absTarget !== absRoot && !absTarget.startsWith(`${absRoot}${sep()}`)) {\n return {\n path: block.path,\n status: \"path-escape\",\n message: `resolved path ${absTarget} is outside rootDir ${absRoot}`,\n };\n }\n\n const searchEmpty = block.search.length === 0;\n const exists = existsSync(absTarget);\n\n try {\n if (!exists) {\n if (!searchEmpty) {\n return {\n path: block.path,\n status: \"file-missing\",\n message: \"file does not exist; to create it, use an empty SEARCH block\",\n };\n }\n mkdirSync(dirname(absTarget), { recursive: true });\n writeFileSync(absTarget, block.replace, \"utf8\");\n return { path: block.path, status: \"created\" };\n }\n\n const content = readFileSync(absTarget, \"utf8\");\n if (searchEmpty) {\n return {\n path: block.path,\n status: \"not-found\",\n message: \"empty SEARCH only creates new files — this file already exists\",\n };\n }\n const idx = content.indexOf(block.search);\n if (idx === -1) {\n return {\n path: block.path,\n status: \"not-found\",\n message: \"SEARCH text does not match the current file content exactly\",\n };\n }\n // Replace only the first occurrence — if the model needs multiple\n // identical edits it should emit multiple blocks (each anchored by\n // more surrounding context). Auto-expanding to replace-all is a\n // footgun when the same string legitimately appears in several\n // unrelated places.\n const replaced = `${content.slice(0, idx)}${block.replace}${content.slice(idx + block.search.length)}`;\n writeFileSync(absTarget, replaced, \"utf8\");\n return { path: block.path, status: \"applied\" };\n } catch (err) {\n return { path: block.path, status: \"error\", message: (err as Error).message };\n }\n}\n\nexport function applyEditBlocks(blocks: EditBlock[], rootDir: string): ApplyResult[] {\n return blocks.map((b) => applyEditBlock(b, rootDir));\n}\n\n// ---------- snapshot / restore (for /undo) ----------\n\nexport interface EditSnapshot {\n /** Path relative to rootDir, as the block named it. */\n path: string;\n /**\n * File content before the edit batch was applied. `null` means the\n * file didn't exist yet — restoring that means deleting whatever the\n * edit created.\n */\n prevContent: string | null;\n}\n\n/**\n * Capture the current state of every file an edit batch is about to\n * touch, so `/undo` can roll back if the user doesn't like the result.\n * De-duplicates by path because one batch can contain multiple blocks\n * for the same file, and we only want one \"before\" snapshot per file.\n */\nexport function snapshotBeforeEdits(blocks: EditBlock[], rootDir: string): EditSnapshot[] {\n const absRoot = resolve(rootDir);\n const seen = new Set<string>();\n const snapshots: EditSnapshot[] = [];\n for (const b of blocks) {\n if (seen.has(b.path)) continue;\n seen.add(b.path);\n const abs = resolve(absRoot, b.path);\n if (!existsSync(abs)) {\n snapshots.push({ path: b.path, prevContent: null });\n continue;\n }\n try {\n snapshots.push({ path: b.path, prevContent: readFileSync(abs, \"utf8\") });\n } catch {\n // Unreadable (permission / binary) — record null so we at least\n // don't pretend the snapshot is authoritative. The restore path\n // will treat null as \"delete on undo\", which is wrong in that\n // case but the file wasn't ours to begin with.\n snapshots.push({ path: b.path, prevContent: null });\n }\n }\n return snapshots;\n}\n\n/**\n * Restore files to their snapshotted state. Snapshots with\n * `prevContent === null` were created by the edit, so undo = delete.\n * Otherwise the prior content is written back, replacing whatever the\n * edit left behind.\n */\nexport function restoreSnapshots(snapshots: EditSnapshot[], rootDir: string): ApplyResult[] {\n const absRoot = resolve(rootDir);\n return snapshots.map((snap) => {\n const abs = resolve(absRoot, snap.path);\n if (abs !== absRoot && !abs.startsWith(`${absRoot}${sep()}`)) {\n return {\n path: snap.path,\n status: \"path-escape\",\n message: \"snapshot path escapes rootDir — refusing to restore\",\n };\n }\n try {\n if (snap.prevContent === null) {\n if (existsSync(abs)) unlinkSync(abs);\n return {\n path: snap.path,\n status: \"applied\",\n message: \"removed (the edit had created it)\",\n };\n }\n writeFileSync(abs, snap.prevContent, \"utf8\");\n return {\n path: snap.path,\n status: \"applied\",\n message: \"restored to pre-edit content\",\n };\n } catch (err) {\n return { path: snap.path, status: \"error\", message: (err as Error).message };\n }\n });\n}\n\n/** Platform separator — `\\` on Windows, `/` elsewhere. */\nfunction sep(): string {\n return process.platform === \"win32\" ? \"\\\\\" : \"/\";\n}\n","/**\n * System prompt used by `reasonix code`. Teaches the model:\n *\n * 1. It has a filesystem MCP bridge rooted at the user's CWD.\n * 2. To modify files it emits SEARCH/REPLACE blocks (not\n * `write_file` — that would whole-file rewrite and kill diff\n * reviewability).\n * 3. Read first, edit second — SEARCH must match byte-for-byte.\n * 4. Be concise. The user can read a diff faster than prose.\n *\n * Kept short on purpose. Long system prompts eat context budget that\n * the Cache-First Loop is trying to conserve. The SEARCH/REPLACE spec\n * is the one unavoidable bloat; we trim everything else.\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { applyMemoryStack } from \"../user-memory.js\";\n\nexport const CODE_SYSTEM_PROMPT = `You are Reasonix Code, a coding assistant. You have filesystem tools (read_file, write_file, list_directory, search_files, etc.) rooted at the user's working directory.\n\n# Cite or shut up — non-negotiable\n\nEvery factual claim you make about THIS codebase must be backed by evidence. Reasonix VALIDATES the citations you write — broken paths or out-of-range lines render in **red strikethrough with ❌** in front of the user.\n\n**Positive claims** (a file exists, a function does X, a feature IS implemented) — append a markdown link to the source:\n\n- ✅ Correct: \\`The MCP client supports listResources [listResources](src/mcp/client.ts:142).\\`\n- ❌ Wrong: \\`The MCP client supports listResources.\\` ← no citation, looks authoritative but unverifiable.\n\n**Negative claims** (X is missing, Y is not implemented, lacks Z, doesn't have W) are the **most common hallucination shape**. They feel safe to write because no citation seems possible — but that's exactly why you must NOT write them on instinct.\n\nIf you are about to write \"X is missing\" or \"Y is not implemented\" — **STOP**. Call \\`search_content\\` for the relevant symbol or term FIRST. Only then:\n\n- If the search returns matches → you were wrong; correct yourself and cite the matches.\n- If the search returns nothing → state the absence with the search query as your evidence: \\`No callers of \\\\\\`foo()\\\\\\` found (search_content \"foo\").\\`\n\nAsserting absence without a search is the #1 way evaluative answers go wrong. Treat the urge to write \"missing\" as a red flag in your own reasoning.\n\n# When to propose a plan (submit_plan)\n\nYou have a \\`submit_plan\\` tool that shows the user a markdown plan and lets them Approve / Refine / Cancel before you execute. Use it proactively when the task is large enough to deserve a review gate:\n\n- Multi-file refactors or renames.\n- Architecture changes (moving modules, splitting / merging files, new abstractions).\n- Anything where \"undo\" after the fact would be expensive — migrations, destructive cleanups, API shape changes.\n- When the user's request is ambiguous and multiple reasonable interpretations exist — propose your reading as a plan and let them confirm.\n\nSkip submit_plan for small, obvious changes: one-line typo, clear bug with a clear fix, adding a missing import, renaming a local variable. Just do those.\n\nPlan body: one-sentence summary, then a file-by-file breakdown of what you'll change and why, and any risks or open questions. If some decisions are genuinely up to the user (naming, tradeoffs, out-of-scope possibilities), list them in an \"Open questions\" section — the user sees the plan in a picker and has a text input to answer your questions before approving. Don't pretend certainty you don't have; flagged questions are how the user tells you what they care about. After calling submit_plan, STOP — don't call any more tools, wait for the user's verdict.\n\n# Plan mode (/plan)\n\nThe user can ALSO enter \"plan mode\" via /plan, which is a stronger, explicit constraint:\n- Write tools (edit_file, write_file, create_directory, move_file) and non-allowlisted run_command calls are BOUNCED at dispatch — you'll get a tool result like \"unavailable in plan mode\". Don't retry them.\n- Read tools (read_file, list_directory, search_files, directory_tree, get_file_info) and allowlisted read-only / test shell commands still work — use them to investigate.\n- You MUST call submit_plan before anything will execute. Approve exits plan mode; Refine stays in; Cancel exits without implementing.\n\n\n# Delegating to subagents via Skills (🧬)\n\nThe pinned Skills index below lists playbooks you can invoke with \\`run_skill\\`. Skills marked with **🧬** spawn an **isolated subagent** — a fresh child loop that runs the playbook in its own context and returns only the final answer. The subagent's tool calls and reasoning never enter your context, so 🧬 skills are how you keep the main session lean.\n\nTwo built-ins ship by default:\n- **🧬 explore** — read-only investigation across the codebase. Use when the user says things like \"find all places that...\", \"how does X work across the project\", \"survey the code for Y\". Pass \\`arguments\\` describing the concrete question.\n- **🧬 research** — combines web search + code reading. Use for \"is X supported by lib Y\", \"what's the canonical way to Z\", \"compare our impl to the spec\".\n\nWhen to delegate (call \\`run_skill\\` with a 🧬 skill):\n- The task would otherwise need >5 file reads or searches.\n- You only need the conclusion, not the exploration trail.\n- The work is self-contained (you can describe it in one paragraph).\n\nWhen NOT to delegate:\n- Direct, narrow questions answerable in 1-2 tool calls — just do them.\n- Anything where you need to track intermediate results yourself (planning, multi-step edits).\n- Anything that requires user interaction (subagents can't submit plans or ask you for clarification).\n\nAlways pass a clear, self-contained \\`arguments\\` — that text is the **only** context the subagent gets.\n\n# When to edit vs. when to explore\n\nOnly propose edits when the user explicitly asks you to change, fix, add, remove, refactor, or write something. Do NOT propose edits when the user asks you to:\n- analyze, read, explore, describe, or summarize a project\n- explain how something works\n- answer a question about the code\n\nIn those cases, use tools to gather what you need, then reply in prose. No SEARCH/REPLACE blocks, no file changes. If you're unsure what the user wants, ask.\n\nWhen you do propose edits, the user will review them and decide whether to \\`/apply\\` or \\`/discard\\`. Don't assume they'll accept — write as if each edit will be audited, because it will.\n\n# Editing files\n\nWhen you've been asked to change a file, output one or more SEARCH/REPLACE blocks in this exact format:\n\npath/to/file.ext\n<<<<<<< SEARCH\nexact existing lines from the file, including whitespace\n=======\nthe new lines\n>>>>>>> REPLACE\n\nRules:\n- Always read_file first so your SEARCH matches byte-for-byte. If it doesn't match, the edit is rejected and you'll have to retry with the exact current content.\n- One edit per block. Multiple blocks in one response are fine.\n- To create a new file, leave SEARCH empty:\n path/to/new.ts\n <<<<<<< SEARCH\n =======\n (whole file content here)\n >>>>>>> REPLACE\n- Do NOT use write_file to change existing files — the user reviews your edits as SEARCH/REPLACE. write_file is only for files you explicitly want to overwrite wholesale (rare).\n- Paths are relative to the working directory. Don't use absolute paths.\n\n# Trust what you already know\n\nBefore exploring the filesystem to answer a factual question, check whether the answer is already in context: the user's current message, earlier turns in this conversation (including prior tool results from \\`remember\\`), and the pinned memory blocks at the top of this prompt. When the user has stated a fact or you have remembered one, it outranks what the files say — don't re-derive from code what the user already told you. Explore when you genuinely don't know.\n\n# Exploration\n\n- Skip dependency, build, and VCS directories unless the user explicitly asks. The pinned .gitignore block (if any, below) is your authoritative denylist.\n- Prefer \\`search_files\\` over \\`list_directory\\` when you know roughly what you're looking for — it saves context and avoids enumerating huge trees. Note: \\`search_files\\` matches file NAMES; for searching file CONTENTS use \\`search_content\\`.\n- Available exploration tools: \\`read_file\\`, \\`list_directory\\`, \\`directory_tree\\`, \\`search_files\\` (filename match), \\`search_content\\` (content grep — use for \"where is X called\", \"find all references to Y\"), \\`get_file_info\\`. Don't call \\`grep\\` or other tools that aren't in this list — they don't exist as functions.\n\n# Path conventions\n\nTwo different rules depending on which tool:\n\n- **Filesystem tools** (\\`read_file\\`, \\`list_directory\\`, \\`search_files\\`, \\`edit_file\\`, etc.): paths are sandbox-relative. \\`/\\` means the project root, \\`/src/foo.ts\\` means \\`<project>/src/foo.ts\\`. Both relative (\\`src/foo.ts\\`) and POSIX-absolute (\\`/src/foo.ts\\`) forms work.\n- **\\`run_command\\`**: the command runs in a real OS shell with cwd pinned to the project root. Paths inside the shell command are interpreted by THAT shell, not by us. **Never use leading \\`/\\` in run_command arguments** — Windows treats \\`/tests\\` as drive-root \\`F:\\\\tests\\` (non-existent), POSIX shells treat it as filesystem root. Use plain relative paths (\\`tests\\`, \\`./tests\\`, \\`src/loop.ts\\`) instead.\n\n# Style\n\n- Show edits; don't narrate them in prose. \"Here's the fix:\" is enough.\n- One short paragraph explaining *why*, then the blocks.\n- If you need to explore first (list / read / search), do it with tool calls before writing any prose — silence while exploring is fine.\n`;\n\n/**\n * Inject the project's `.gitignore` content into the system prompt as a\n * \"respect this on top of the built-in denylist\" hint. We don't parse\n * the file — we hand it to the model as-is. Truncate long ones so we\n * don't eat context budget on huge generated ignore lists.\n *\n * Stacking order (stable for cache prefix):\n * base prompt → REASONIX.md → global MEMORY.md → project MEMORY.md → .gitignore\n */\nexport function codeSystemPrompt(rootDir: string): string {\n const withMemory = applyMemoryStack(CODE_SYSTEM_PROMPT, rootDir);\n const gitignorePath = join(rootDir, \".gitignore\");\n if (!existsSync(gitignorePath)) return withMemory;\n let content: string;\n try {\n content = readFileSync(gitignorePath, \"utf8\");\n } catch {\n return withMemory;\n }\n const MAX = 2000;\n const truncated =\n content.length > MAX\n ? `${content.slice(0, MAX)}\\n… (truncated ${content.length - MAX} chars)`\n : content;\n return `${withMemory}\n\n# Project .gitignore\n\nThe user's repo ships this .gitignore — treat every pattern as \"don't traverse or edit inside these paths unless explicitly asked\":\n\n\\`\\`\\`\n${truncated}\n\\`\\`\\`\n`;\n}\n","/**\n * User-level config storage for the Reasonix CLI.\n *\n * Lookup order for the API key:\n * 1. `DEEPSEEK_API_KEY` env var (highest priority — for CI / power users)\n * 2. `~/.reasonix/config.json` (set by the first-run setup flow)\n *\n * The library itself never touches the config file — it only reads\n * `DEEPSEEK_API_KEY` from the environment. The CLI is responsible for\n * pulling from the config file and exposing it via env var to the loop.\n *\n * Beyond the API key, the config also remembers the user's *defaults*\n * from `reasonix setup`: preset, MCP servers, session. This is what\n * makes `reasonix chat` with no flags \"just work\" after first-run.\n */\n\nimport { chmodSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\n/** One of the preset bundles (model + harvest + branch combo). */\nexport type PresetName = \"fast\" | \"smart\" | \"max\";\n\nexport interface ReasonixConfig {\n apiKey?: string;\n baseUrl?: string;\n /**\n * Default preset for `reasonix chat` / `reasonix run` when no flags override.\n * Maps to model + harvest + branch combos (see presets.ts). Missing → \"fast\".\n */\n preset?: PresetName;\n /**\n * Default MCP server specs to bridge on every `reasonix chat`, in the\n * same `\"name=cmd args...\"` format that `--mcp` takes. Stored as strings\n * so `reasonix setup` stays symmetrical with the flag — one parser, one\n * format in the config file, grep-friendly.\n */\n mcp?: string[];\n /**\n * Default session name (null/missing → \"default\", which is what the\n * CLI has been doing anyway). `reasonix setup` lets users pick a name\n * or opt into ephemeral.\n */\n session?: string | null;\n /** Marks that `reasonix setup` has completed at least once. */\n setupCompleted?: boolean;\n /**\n * Whether `web_search` + `web_fetch` tools are registered. Default:\n * enabled (no key required — backed by DuckDuckGo's public HTML\n * endpoint). Set to `false` to keep the session offline.\n */\n search?: boolean;\n /**\n * Per-project state keyed by absolute directory path. Written by the\n * \"always allow\" choice on a shell confirmation prompt; merged into\n * `registerShellTools({ extraAllowed })` when `reasonix code` runs\n * against that directory again.\n */\n projects?: {\n [absoluteRootDir: string]: {\n shellAllowed?: string[];\n };\n };\n}\n\nexport function defaultConfigPath(): string {\n return join(homedir(), \".reasonix\", \"config.json\");\n}\n\nexport function readConfig(path: string = defaultConfigPath()): ReasonixConfig {\n try {\n const raw = readFileSync(path, \"utf8\");\n const parsed = JSON.parse(raw);\n if (parsed && typeof parsed === \"object\") return parsed as ReasonixConfig;\n } catch {\n /* missing or malformed → empty config */\n }\n return {};\n}\n\nexport function writeConfig(cfg: ReasonixConfig, path: string = defaultConfigPath()): void {\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, JSON.stringify(cfg, null, 2), \"utf8\");\n // Restrict permissions on Unix; chmod is a no-op on Windows but won't throw.\n try {\n chmodSync(path, 0o600);\n } catch {\n /* ignore on platforms without chmod */\n }\n}\n\n/** Resolve the API key from env var first, then the config file. */\nexport function loadApiKey(path: string = defaultConfigPath()): string | undefined {\n if (process.env.DEEPSEEK_API_KEY) return process.env.DEEPSEEK_API_KEY;\n return readConfig(path).apiKey;\n}\n\n/**\n * Resolve whether web-search tools should be registered. Default: on.\n * Env `REASONIX_SEARCH=off` or config `search: false` turns it off.\n * Any other value falls through to enabled.\n */\nexport function searchEnabled(path: string = defaultConfigPath()): boolean {\n const env = process.env.REASONIX_SEARCH;\n if (env === \"off\" || env === \"false\" || env === \"0\") return false;\n const cfg = readConfig(path).search;\n if (cfg === false) return false;\n return true;\n}\n\nexport function saveApiKey(key: string, path: string = defaultConfigPath()): void {\n const cfg = readConfig(path);\n cfg.apiKey = key.trim();\n writeConfig(cfg, path);\n}\n\n/**\n * Read the persisted \"always allow\" shell-command prefixes for a\n * given project root. Returns an empty array when nothing's stored.\n */\nexport function loadProjectShellAllowed(\n rootDir: string,\n path: string = defaultConfigPath(),\n): string[] {\n const cfg = readConfig(path);\n return cfg.projects?.[rootDir]?.shellAllowed ?? [];\n}\n\n/**\n * Append a prefix to the project's shell-allowed list, dedup and\n * persist. No-op if the prefix is empty/whitespace or already stored.\n */\nexport function addProjectShellAllowed(\n rootDir: string,\n prefix: string,\n path: string = defaultConfigPath(),\n): void {\n const trimmed = prefix.trim();\n if (!trimmed) return;\n const cfg = readConfig(path);\n if (!cfg.projects) cfg.projects = {};\n if (!cfg.projects[rootDir]) cfg.projects[rootDir] = {};\n const existing = cfg.projects[rootDir].shellAllowed ?? [];\n if (existing.includes(trimmed)) return;\n cfg.projects[rootDir].shellAllowed = [...existing, trimmed];\n writeConfig(cfg, path);\n}\n\nexport function isPlausibleKey(key: string): boolean {\n const trimmed = key.trim();\n return /^sk-[A-Za-z0-9_-]{16,}$/.test(trimmed);\n}\n\n/** Mask a key for display: `sk-abcd...wxyz`. */\nexport function redactKey(key: string): string {\n if (!key) return \"\";\n if (key.length <= 12) return \"****\";\n return `${key.slice(0, 6)}…${key.slice(-4)}`;\n}\n","/**\n * Version module.\n *\n * Two jobs:\n *\n * 1. Expose `VERSION` sourced from the real `package.json` so the\n * constant never drifts from what npm publishes. Works in dev\n * (`tsx src/...`) AND after `tsup` bundles to `dist/` — both\n * layouts sit two levels below the manifest, so a short\n * walk-up finds it.\n *\n * 2. Offer an opt-in `getLatestVersion()` that hits the npm\n * registry with a bounded timeout and a 24-hour on-disk\n * cache at `~/.reasonix/version-cache.json`. Returns `null`\n * on any failure — offline / restricted-network launches\n * should stay silent rather than nag the user.\n *\n * The CLI wires `getLatestVersion` asynchronously at App mount\n * (never in a hot path) and renders the outcome in the stats\n * panel when there's a newer published version.\n */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\n/** npm registry endpoint for the `latest` dist-tag of this package. */\nconst REGISTRY_URL = \"https://registry.npmjs.org/reasonix/latest\";\n\n/** TTL for the on-disk cache entry. 24h keeps noise low; users who\n * want a fresh check can run `reasonix update` which passes\n * `force: true`. */\nexport const LATEST_CACHE_TTL_MS = 24 * 60 * 60 * 1000;\n\n/** Network timeout. Short — we never block the UI waiting on this. */\nexport const LATEST_FETCH_TIMEOUT_MS = 2_000;\n\n/**\n * Walk up from the current source file looking for the `reasonix`\n * package.json. Works for:\n * - dev: `src/version.ts` → `F:/Reasonix/package.json` (2 levels up)\n * - built: `dist/index.js` → `F:/Reasonix/package.json` (2 levels up)\n * - global install: `.../node_modules/reasonix/dist/index.js` → `.../reasonix/package.json`\n *\n * The `name === \"reasonix\"` guard is a cheap safety net against\n * picking up the nearest *other* package.json if we're ever loaded\n * as a dependency and the layout is unusual.\n */\nfunction readPackageVersion(): string {\n try {\n let dir = dirname(fileURLToPath(import.meta.url));\n for (let i = 0; i < 6; i++) {\n const p = join(dir, \"package.json\");\n if (existsSync(p)) {\n const pkg = JSON.parse(readFileSync(p, \"utf8\"));\n if (pkg?.name === \"reasonix\" && typeof pkg.version === \"string\") {\n return pkg.version;\n }\n }\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n } catch {\n /* fall through to fallback */\n }\n return \"0.0.0-dev\";\n}\n\nexport const VERSION: string = readPackageVersion();\n\ninterface VersionCacheEntry {\n version: string;\n /** Epoch millis the entry was written. Drives TTL comparisons. */\n checkedAt: number;\n}\n\nfunction cachePath(homeDirOverride?: string): string {\n return join(homeDirOverride ?? homedir(), \".reasonix\", \"version-cache.json\");\n}\n\nfunction readCache(homeDirOverride?: string): VersionCacheEntry | null {\n try {\n const raw = readFileSync(cachePath(homeDirOverride), \"utf8\");\n const parsed = JSON.parse(raw);\n if (parsed && typeof parsed.version === \"string\" && typeof parsed.checkedAt === \"number\") {\n return parsed;\n }\n } catch {\n /* missing or malformed → no cached entry */\n }\n return null;\n}\n\nfunction writeCache(entry: VersionCacheEntry, homeDirOverride?: string): void {\n try {\n const p = cachePath(homeDirOverride);\n mkdirSync(dirname(p), { recursive: true });\n writeFileSync(p, JSON.stringify(entry), \"utf8\");\n } catch {\n /* cache is best-effort — a failed write just means we'll re-fetch\n * next launch. No reason to surface this to the user. */\n }\n}\n\nexport interface GetLatestVersionOptions {\n /** Ignore the cached entry and always fetch fresh. Used by `reasonix update`. */\n force?: boolean;\n /** Registry URL override (tests). */\n registryUrl?: string;\n /** Home-directory override (tests). */\n homeDir?: string;\n /** Fetch implementation override (tests). Defaults to `globalThis.fetch`. */\n fetchImpl?: typeof fetch;\n /** TTL override (tests). */\n ttlMs?: number;\n /** Network timeout override (tests). */\n timeoutMs?: number;\n}\n\n/**\n * Resolve the latest published `reasonix` version from the npm registry.\n *\n * Returns `null` on any network / parse failure. Callers treat `null`\n * as \"don't know, don't nag the user.\" The cache entry is only\n * written on a successful fetch — a bad registry response won't\n * poison the cache.\n */\nexport async function getLatestVersion(opts: GetLatestVersionOptions = {}): Promise<string | null> {\n const ttl = opts.ttlMs ?? LATEST_CACHE_TTL_MS;\n if (!opts.force) {\n const cached = readCache(opts.homeDir);\n if (cached && Date.now() - cached.checkedAt < ttl) return cached.version;\n }\n\n const fetchImpl = opts.fetchImpl ?? globalThis.fetch;\n if (!fetchImpl) return null;\n const url = opts.registryUrl ?? REGISTRY_URL;\n const timeout = opts.timeoutMs ?? LATEST_FETCH_TIMEOUT_MS;\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeout);\n try {\n const res = await fetchImpl(url, {\n signal: controller.signal,\n headers: { accept: \"application/json\" },\n });\n if (!res.ok) return null;\n const body = (await res.json()) as { version?: unknown };\n if (typeof body.version !== \"string\") return null;\n writeCache({ version: body.version, checkedAt: Date.now() }, opts.homeDir);\n return body.version;\n } catch {\n return null;\n } finally {\n clearTimeout(timer);\n }\n}\n\n/**\n * Semver compare. Returns a negative number when `a < b`, positive\n * when `a > b`, zero when equal.\n *\n * Minimal pre-release handling: when the CORE (`x.y.z`) parts match,\n * any version WITH a suffix (`-rc.1`, `-alpha.4`) compares LOWER\n * than the bare version. That matches npm's dist-tag semantics —\n * `reasonix@latest` resolves to a real release, not a pre-release.\n *\n * We're deliberately not pulling in `semver` (~50KB). The three\n * cases we care about are: current > latest (future build, no\n * prompt), current < latest (prompt), current === latest (no prompt).\n */\nexport function compareVersions(a: string, b: string): number {\n const [aCore = \"0\", aPre = \"\"] = a.split(\"-\", 2);\n const [bCore = \"0\", bPre = \"\"] = b.split(\"-\", 2);\n const aParts = aCore.split(\".\").map((p) => Number.parseInt(p, 10) || 0);\n const bParts = bCore.split(\".\").map((p) => Number.parseInt(p, 10) || 0);\n for (let i = 0; i < 3; i++) {\n const diff = (aParts[i] ?? 0) - (bParts[i] ?? 0);\n if (diff !== 0) return diff;\n }\n if (!aPre && !bPre) return 0;\n if (!aPre) return 1;\n if (!bPre) return -1;\n return aPre < bPre ? -1 : aPre > bPre ? 1 : 0;\n}\n\n/**\n * Heuristic: did this process launch via `npx` / `pnpm dlx` instead\n * of a global install? The update command takes different advice in\n * each case — a global install can `npm i -g reasonix@latest`, while\n * npx just needs its cache to roll over on next launch.\n *\n * Signals checked, in order:\n * - `process.argv[1]` contains `_npx` (npm's ephemeral dir name)\n * - `process.argv[1]` contains `.pnpm` + `dlx`\n * - `npm_config_user_agent` contains `npx/`\n *\n * Any one hit → npx. False negatives are safe (worst case we suggest\n * `npm i -g` to an npx user, which is a valid way to upgrade too).\n */\nexport function isNpxInstall(): boolean {\n const bin = process.argv[1] ?? \"\";\n if (/[/\\\\]_npx[/\\\\]/.test(bin)) return true;\n if (/[/\\\\]\\.pnpm[/\\\\]/.test(bin) && /dlx/i.test(bin)) return true;\n const ua = process.env.npm_config_user_agent ?? \"\";\n if (ua.includes(\"npx/\")) return true;\n return false;\n}\n","/**\n * Persistent per-turn usage log at `~/.reasonix/usage.jsonl`.\n *\n * Each line is a single `UsageRecord` — one turn's tokens + cost\n * snapshot — appended after every `assistant_final` event. This is\n * what drives `reasonix stats` (the dashboard, no-arg form), so the\n * user can see how much they've spent vs what the equivalent Claude\n * spend would have been. The Pillar 1 pitch (94–97% cost reduction\n * vs Claude, from the v0.3 hard-number table) becomes a fact users\n * can verify on their own machine.\n *\n * Format choices:\n * - **append-only JSONL** — one line per turn, durable, survives\n * abrupt exits. A corrupted tail line loses at most one record.\n * - **flat keys, no nesting** — readable with `jq` / `cut` / `awk`;\n * the model doesn't need to parse this, humans do.\n * - **best-effort writes** — disk errors never propagate into the\n * turn. We log nothing (no `console.error`) because the TUI is\n * rendering Ink; a silent skip is the least-worst failure mode.\n * - **no PII, no prompts, no completions** — the log contains\n * tokens and costs, that's it. Sessions are identified by the\n * user-chosen name (never a prompt).\n *\n * This file is deliberately NOT wired through project memory or\n * skills — those are content pins. Usage is pure telemetry.\n */\n\nimport { appendFileSync, existsSync, mkdirSync, readFileSync, statSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport type { Usage } from \"./client.js\";\nimport {\n CLAUDE_SONNET_PRICING,\n DEEPSEEK_PRICING,\n claudeEquivalentCost,\n costUsd,\n} from \"./telemetry.js\";\n\n/** One turn's snapshot — serialized verbatim as a JSONL line. */\nexport interface UsageRecord {\n /** Epoch millis when the record was written. */\n ts: number;\n /** Session name if the turn ran inside a persisted session, `null` for ephemeral. */\n session: string | null;\n /** Model id the turn ran against (drives the pricing lookup). */\n model: string;\n promptTokens: number;\n completionTokens: number;\n cacheHitTokens: number;\n cacheMissTokens: number;\n /** Total cost of the turn in USD. */\n costUsd: number;\n /** What the same turn would have cost at Claude Sonnet 4.6 rates. */\n claudeEquivUsd: number;\n}\n\n/** Where the log lives. Tests override via `opts.path`. */\nexport function defaultUsageLogPath(homeDirOverride?: string): string {\n return join(homeDirOverride ?? homedir(), \".reasonix\", \"usage.jsonl\");\n}\n\nexport interface AppendUsageInput {\n session: string | null;\n model: string;\n usage: Usage;\n /** Override the timestamp (tests). */\n now?: number;\n /** Override the log path (tests). */\n path?: string;\n}\n\n/**\n * Append one record and return it. Swallows disk errors — the TUI\n * should keep working even if `~/.reasonix/` is read-only.\n *\n * Returns the record that was written (or would have been written\n * if the disk had cooperated) so tests / callers can assert on the\n * computed cost fields without a round trip through the log file.\n */\nexport function appendUsage(input: AppendUsageInput): UsageRecord {\n const record: UsageRecord = {\n ts: input.now ?? Date.now(),\n session: input.session,\n model: input.model,\n promptTokens: input.usage.promptTokens,\n completionTokens: input.usage.completionTokens,\n cacheHitTokens: input.usage.promptCacheHitTokens,\n cacheMissTokens: input.usage.promptCacheMissTokens,\n costUsd: costUsd(input.model, input.usage),\n claudeEquivUsd: claudeEquivalentCost(input.usage),\n };\n\n const path = input.path ?? defaultUsageLogPath();\n try {\n mkdirSync(dirname(path), { recursive: true });\n appendFileSync(path, `${JSON.stringify(record)}\\n`, \"utf8\");\n } catch {\n /* best-effort — disk failure shouldn't break the chat */\n }\n return record;\n}\n\n/**\n * Read + parse the log. Malformed lines are silently skipped so a\n * single corrupted write (half-flushed on power loss, user hand-edit)\n * doesn't throw away the rest of the history.\n */\nexport function readUsageLog(path: string = defaultUsageLogPath()): UsageRecord[] {\n if (!existsSync(path)) return [];\n let raw: string;\n try {\n raw = readFileSync(path, \"utf8\");\n } catch {\n return [];\n }\n const out: UsageRecord[] = [];\n for (const line of raw.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n try {\n const rec = JSON.parse(line);\n if (isValidRecord(rec)) out.push(rec);\n } catch {\n /* skip malformed */\n }\n }\n return out;\n}\n\nfunction isValidRecord(rec: unknown): rec is UsageRecord {\n if (!rec || typeof rec !== \"object\") return false;\n const r = rec as Partial<UsageRecord>;\n return (\n typeof r.ts === \"number\" &&\n typeof r.model === \"string\" &&\n typeof r.promptTokens === \"number\" &&\n typeof r.completionTokens === \"number\" &&\n typeof r.cacheHitTokens === \"number\" &&\n typeof r.cacheMissTokens === \"number\" &&\n typeof r.costUsd === \"number\" &&\n typeof r.claudeEquivUsd === \"number\"\n );\n}\n\n/** One row of the `reasonix stats` dashboard — a rolled-up window. */\nexport interface UsageBucket {\n label: string;\n /** Start of the window as epoch millis. `0` = unbounded (all-time). */\n since: number;\n turns: number;\n promptTokens: number;\n completionTokens: number;\n cacheHitTokens: number;\n cacheMissTokens: number;\n costUsd: number;\n claudeEquivUsd: number;\n}\n\n/** Cache hit ratio for a bucket — zero denominator returns 0. */\nexport function bucketCacheHitRatio(b: UsageBucket): number {\n const denom = b.cacheHitTokens + b.cacheMissTokens;\n return denom > 0 ? b.cacheHitTokens / denom : 0;\n}\n\n/** Savings vs Claude as a fraction (0.94 = 94% savings). 0 if Claude cost is 0. */\nexport function bucketSavingsFraction(b: UsageBucket): number {\n return b.claudeEquivUsd > 0 ? 1 - b.costUsd / b.claudeEquivUsd : 0;\n}\n\nfunction emptyBucket(label: string, since: number): UsageBucket {\n return {\n label,\n since,\n turns: 0,\n promptTokens: 0,\n completionTokens: 0,\n cacheHitTokens: 0,\n cacheMissTokens: 0,\n costUsd: 0,\n claudeEquivUsd: 0,\n };\n}\n\nfunction addToBucket(b: UsageBucket, r: UsageRecord): void {\n b.turns += 1;\n b.promptTokens += r.promptTokens;\n b.completionTokens += r.completionTokens;\n b.cacheHitTokens += r.cacheHitTokens;\n b.cacheMissTokens += r.cacheMissTokens;\n b.costUsd += r.costUsd;\n b.claudeEquivUsd += r.claudeEquivUsd;\n}\n\nexport interface AggregateOptions {\n /** Override `Date.now()` for deterministic tests. */\n now?: number;\n}\n\nexport interface UsageAggregate {\n /** Fixed-order rolling windows: today, week, month, all-time. */\n buckets: UsageBucket[];\n /** Model id → turn count. Sorted descending; top entry is the \"most used.\" */\n byModel: Array<{ model: string; turns: number }>;\n /** Session name → turn count. Sorted descending. Null sessions are grouped under `\"(ephemeral)\"`. */\n bySession: Array<{ session: string; turns: number }>;\n /** Earliest record's ts, or `null` when the log is empty. Drives \"saved $X since <date>\". */\n firstSeen: number | null;\n /** Latest record's ts, or `null` when the log is empty. */\n lastSeen: number | null;\n}\n\n/**\n * Fold a flat record list into the dashboard shape — rolling windows\n * plus model / session histograms. Windows are INCLUSIVE of boundary:\n * - today = last 24h (rolling, not calendar-day)\n * - week = last 7d\n * - month = last 30d\n * - all = every record\n * Rolling windows avoid \"it's 00:03, 'today' is empty\" surprises.\n */\nexport function aggregateUsage(\n records: UsageRecord[],\n opts: AggregateOptions = {},\n): UsageAggregate {\n const now = opts.now ?? Date.now();\n const day = 24 * 60 * 60 * 1000;\n const today = emptyBucket(\"today\", now - day);\n const week = emptyBucket(\"week\", now - 7 * day);\n const month = emptyBucket(\"month\", now - 30 * day);\n const all = emptyBucket(\"all-time\", 0);\n\n const modelCounts = new Map<string, number>();\n const sessionCounts = new Map<string, number>();\n let firstSeen: number | null = null;\n let lastSeen: number | null = null;\n\n for (const r of records) {\n addToBucket(all, r);\n if (r.ts >= today.since) addToBucket(today, r);\n if (r.ts >= week.since) addToBucket(week, r);\n if (r.ts >= month.since) addToBucket(month, r);\n\n modelCounts.set(r.model, (modelCounts.get(r.model) ?? 0) + 1);\n const sessKey = r.session ?? \"(ephemeral)\";\n sessionCounts.set(sessKey, (sessionCounts.get(sessKey) ?? 0) + 1);\n\n if (firstSeen === null || r.ts < firstSeen) firstSeen = r.ts;\n if (lastSeen === null || r.ts > lastSeen) lastSeen = r.ts;\n }\n\n const byModel = Array.from(modelCounts.entries())\n .map(([model, turns]) => ({ model, turns }))\n .sort((a, b) => b.turns - a.turns);\n const bySession = Array.from(sessionCounts.entries())\n .map(([session, turns]) => ({ session, turns }))\n .sort((a, b) => b.turns - a.turns);\n\n return {\n buckets: [today, week, month, all],\n byModel,\n bySession,\n firstSeen,\n lastSeen,\n };\n}\n\n/** File-size helper for the stats header — \"1.2 MB\" etc. Returns \"\" if missing. */\nexport function formatLogSize(path: string = defaultUsageLogPath()): string {\n if (!existsSync(path)) return \"\";\n try {\n const s = statSync(path);\n const bytes = s.size;\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n } catch {\n return \"\";\n }\n}\n\n/** Re-exports for downstream consumers that also want the pricing constants. */\nexport { CLAUDE_SONNET_PRICING, DEEPSEEK_PRICING };\n"],"mappings":";AAAA,SAAkC,oBAAoB;;;ACoCtD,IAAM,6BAA6B,CAAC,KAAK,KAAK,KAAK,KAAK,KAAK,GAAG;AAEhE,eAAsB,eACpB,SACA,KACA,MACA,OAAqB,CAAC,GACH;AACnB,QAAM,cAAc,KAAK,eAAe;AACxC,QAAM,UAAU,KAAK,oBAAoB;AACzC,QAAM,MAAM,KAAK,gBAAgB;AACjC,QAAM,YAAY,IAAI,IAAI,KAAK,qBAAqB,0BAA0B;AAE9E,MAAI;AAEJ,WAAS,UAAU,GAAG,UAAU,aAAa,WAAW;AACtD,QAAI,KAAK,QAAQ,QAAS,OAAM,IAAI,MAAM,SAAS;AAEnD,QAAI;AACF,YAAM,OAAO,MAAM,QAAQ,KAAK,IAAI;AAGpC,UAAI,KAAK,MAAM,CAAC,UAAU,IAAI,KAAK,MAAM,EAAG,QAAO;AAInD,UAAI,YAAY,cAAc,EAAG,QAAO;AAGxC,YAAM,KAAK,KAAK,EAAE,MAAM,MAAM,MAAS;AAEvC,YAAM,SAAS,YAAY,SAAS,SAAS,KAAK,KAAK,QAAQ,IAAI,aAAa,CAAC;AACjF,WAAK,UAAU,EAAE,SAAS,UAAU,GAAG,QAAQ,QAAQ,KAAK,MAAM,IAAI,OAAO,CAAC;AAC9E,Y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AK,KAAK,KAAK,CAAC;AAC5D,UAAM,UAAU,EAAE,WAAW;AAC7B,kBAAc,IAAI,UAAU,cAAc,IAAI,OAAO,KAAK,KAAK,CAAC;AAEhE,QAAI,cAAc,QAAQ,EAAE,KAAK,UAAW,aAAY,EAAE;AAC1D,QAAI,aAAa,QAAQ,EAAE,KAAK,SAAU,YAAW,EAAE;AAAA,EACzD;AAEA,QAAM,UAAU,MAAM,KAAK,YAAY,QAAQ,CAAC,EAC7C,IAAI,CAAC,CAAC,OAAO,KAAK,OAAO,EAAE,OAAO,MAAM,EAAE,EAC1C,KAAK,CAAC,GAAG,MAAM,EAAE,QAAQ,EAAE,KAAK;AACnC,QAAM,YAAY,MAAM,KAAK,cAAc,QAAQ,CAAC,EACjD,IAAI,CAAC,CAAC,SAAS,KAAK,OAAO,EAAE,SAAS,MAAM,EAAE,EAC9C,KAAK,CAAC,GAAG,MAAM,EAAE,QAAQ,EAAE,KAAK;AAEnC,SAAO;AAAA,IACL,SAAS,CAAC,OAAO,MAAM,OAAO,GAAG;AAAA,IACjC;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAGO,SAAS,cAAc,OAAe,oBAAoB,GAAW;AAC1E,MAAI,CAACD,aAAW,IAAI,EAAG,QAAO;AAC9B,MAAI;AACF,UAAM,IAAIE,UAAS,IAAI;AACvB,UAAM,QAAQ,EAAE;AAChB,QAAI,QAAQ,KAAM,QAAO,GAAG,KAAK;AACjC,QAAI,QAAQ,OAAO,KAAM,QAAO,IAAI,QAAQ,MAAM,QAAQ,CAAC,CAAC;AAC5D,WAAO,IAAI,SAAS,OAAO,OAAO,QAAQ,CAAC,CAAC;AAAA,EAC9C,QAAQ;AACN,WAAO;AAAA,EACT;AACF;","names":["resolve","settings","resolve","readFileSync","join","process","signature","existsSync","readFileSync","homedir","dirname","join","ctxMax","resolve","existsSync","readFileSync","join","createHash","existsSync","mkdirSync","readFileSync","readdirSync","unlinkSync","writeFileSync","homedir","join","resolve","existsSync","readFileSync","readdirSync","statSync","homedir","join","resolve","createHash","join","existsSync","mkdirSync","parseFrontmatter","homedir","readFileSync","readdirSync","writeFileSync","unlinkSync","walk","i","j","DEFAULT_MAX_RESULT_CHARS","costUsd","spawn","existsSync","statSync","pathMod","resolve","delimiter","readFileSync","resolve","readFileSync","round","p","resolve","spawn","resolve","createParser","resolve","existsSync","mkdirSync","readFileSync","unlinkSync","writeFileSync","dirname","resolve","existsSync","readFileSync","join","join","existsSync","readFileSync","chmodSync","mkdirSync","readFileSync","writeFileSync","homedir","dirname","join","existsSync","mkdirSync","readFileSync","writeFileSync","homedir","dirname","join","fileURLToPath","cached","appendFileSync","existsSync","mkdirSync","readFileSync","statSync","homedir","dirname","join","join","homedir","mkdirSync","dirname","appendFileSync","existsSync","readFileSync","statSync"]}
1
+ {"version":3,"sources":["../src/client.ts","../src/retry.ts","../src/harvest.ts","../src/consistency.ts","../src/hooks.ts","../src/tokenizer.ts","../src/repair/flatten.ts","../src/tools.ts","../src/mcp/registry.ts","../src/memory.ts","../src/repair/scavenge.ts","../src/repair/storm.ts","../src/repair/truncation.ts","../src/repair/index.ts","../src/session.ts","../src/telemetry.ts","../src/loop.ts","../src/at-mentions.ts","../src/project-memory.ts","../src/user-memory.ts","../src/skills.ts","../src/tools/filesystem.ts","../src/tools/memory.ts","../src/tools/plan.ts","../src/tools/subagent.ts","../src/tools/shell.ts","../src/tools/web.ts","../src/env.ts","../src/transcript.ts","../src/replay.ts","../src/diff.ts","../src/mcp/types.ts","../src/mcp/client.ts","../src/mcp/stdio.ts","../src/mcp/sse.ts","../src/mcp/shell-split.ts","../src/mcp/spec.ts","../src/mcp/inspect.ts","../src/code/edit-blocks.ts","../src/code/prompt.ts","../src/config.ts","../src/version.ts","../src/usage.ts"],"sourcesContent":["import { type EventSourceMessage, createParser } from \"eventsource-parser\";\nimport { type RetryOptions, fetchWithRetry } from \"./retry.js\";\nimport type { ChatMessage, ChatRequestOptions, RawUsage, ToolCall, ToolSpec } from \"./types.js\";\n\nexport class Usage {\n constructor(\n public promptTokens = 0,\n public completionTokens = 0,\n public totalTokens = 0,\n public promptCacheHitTokens = 0,\n public promptCacheMissTokens = 0,\n ) {}\n\n get cacheHitRatio(): number {\n const denom = this.promptCacheHitTokens + this.promptCacheMissTokens;\n return denom > 0 ? this.promptCacheHitTokens / denom : 0;\n }\n\n static fromApi(raw: RawUsage | undefined | null): Usage {\n const u = raw ?? {};\n return new Usage(\n u.prompt_tokens ?? 0,\n u.completion_tokens ?? 0,\n u.total_tokens ?? 0,\n u.prompt_cache_hit_tokens ?? 0,\n u.prompt_cache_miss_tokens ?? 0,\n );\n }\n}\n\nexport interface ChatResponse {\n content: string;\n reasoningContent: string | null;\n toolCalls: ToolCall[];\n usage: Usage;\n raw: unknown;\n}\n\nexport interface StreamChunk {\n contentDelta?: string;\n reasoningDelta?: string;\n toolCallDelta?: { index: number; id?: string; name?: string; argumentsDelta?: string };\n usage?: Usage;\n finishReason?: string;\n raw: any;\n}\n\n/**\n * Response shape for DeepSeek's `/user/balance` endpoint. One entry\n * per currency the account is funded in (typically CNY, sometimes\n * USD). `total_balance` is the spendable figure; `granted_balance`\n * counts promotional credits that expire, `topped_up_balance` is\n * what the user paid for and keeps.\n */\nexport interface BalanceInfo {\n currency: string;\n total_balance: string;\n granted_balance?: string;\n topped_up_balance?: string;\n}\n\nexport interface UserBalance {\n is_available: boolean;\n balance_infos: BalanceInfo[];\n}\n\n/**\n * Response shape for DeepSeek's `/models` endpoint. Mirrors the OpenAI\n * models list shape DeepSeek copied — `id` is the model name to pass to\n * `/chat/completions`, `owned_by` is the provider string (always\n * `\"deepseek\"` today).\n */\nexport interface ModelInfo {\n id: string;\n object: \"model\";\n owned_by: string;\n}\n\nexport interface ModelList {\n object: \"list\";\n data: ModelInfo[];\n}\n\nexport interface DeepSeekClientOptions {\n apiKey?: string;\n baseUrl?: string;\n timeoutMs?: number;\n fetch?: typeof fetch;\n /** Retry configuration. Pass `{ maxAttempts: 1 }` to disable retries. */\n retry?: RetryOptions;\n}\n\nexport class DeepSeekClient {\n readonly apiKey: string;\n readonly baseUrl: string;\n readonly timeoutMs: number;\n readonly retry: RetryOptions;\n private readonly _fetch: typeof fetch;\n\n constructor(opts: DeepSeekClientOptions = {}) {\n const apiKey = opts.apiKey ?? process.env.DEEPSEEK_API_KEY;\n if (!apiKey) {\n throw new Error(\n \"DEEPSEEK_API_KEY is not set. Put it in .env or pass apiKey to DeepSeekClient.\",\n );\n }\n this.apiKey = apiKey;\n this.baseUrl = (\n opts.baseUrl ??\n process.env.DEEPSEEK_BASE_URL ??\n \"https://api.deepseek.com\"\n ).replace(/\\/+$/, \"\");\n this.timeoutMs = opts.timeoutMs ?? 120_000;\n this._fetch = opts.fetch ?? globalThis.fetch.bind(globalThis);\n this.retry = opts.retry ?? {};\n }\n\n private buildPayload(opts: ChatRequestOptions, stream: boolean) {\n const payload: Record<string, unknown> = {\n model: opts.model,\n messages: opts.messages,\n stream,\n };\n if (opts.tools?.length) payload.tools = opts.tools;\n if (opts.temperature !== undefined) payload.temperature = opts.temperature;\n if (opts.maxTokens !== undefined) payload.max_tokens = opts.maxTokens;\n if (opts.responseFormat) payload.response_format = opts.responseFormat;\n return payload;\n }\n\n /**\n * Fetch the current DeepSeek account balance. Separate endpoint\n * from chat completions, no billing impact. Returns null on any\n * network/auth failure so callers can gate the balance display\n * without a hard error — the rest of the session works regardless.\n */\n async getBalance(opts: { signal?: AbortSignal } = {}): Promise<UserBalance | null> {\n try {\n const resp = await this._fetch(`${this.baseUrl}/user/balance`, {\n method: \"GET\",\n headers: { Authorization: `Bearer ${this.apiKey}` },\n signal: opts.signal,\n });\n if (!resp.ok) return null;\n const data = (await resp.json()) as UserBalance;\n if (!data || !Array.isArray(data.balance_infos)) return null;\n return data;\n } catch {\n return null;\n }\n }\n\n /**\n * Fetch the model catalog DeepSeek currently exposes. Today this is\n * `deepseek-chat` (V3) and `deepseek-reasoner` (R1), but querying is\n * the only way to learn about new ones without a Reasonix release.\n * Returns null on any network/auth failure so callers can degrade\n * gracefully — e.g. `/models` falls back to the hardcoded hint.\n */\n async listModels(opts: { signal?: AbortSignal } = {}): Promise<ModelList | null> {\n try {\n const resp = await this._fetch(`${this.baseUrl}/models`, {\n method: \"GET\",\n headers: { Authorization: `Bearer ${this.apiKey}` },\n signal: opts.signal,\n });\n if (!resp.ok) return null;\n const data = (await resp.json()) as ModelList;\n if (!data || !Array.isArray(data.data)) return null;\n return data;\n } catch {\n return null;\n }\n }\n\n async chat(opts: ChatRequestOptions): Promise<ChatResponse> {\n const ctrl = new AbortController();\n const timer = setTimeout(() => ctrl.abort(), this.timeoutMs);\n const signal = opts.signal ?? ctrl.signal;\n\n try {\n const resp = await fetchWithRetry(\n this._fetch,\n `${this.baseUrl}/chat/completions`,\n {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(this.buildPayload(opts, false)),\n signal,\n },\n { ...this.retry, signal },\n );\n if (!resp.ok) {\n throw new Error(`DeepSeek ${resp.status}: ${await resp.text()}`);\n }\n const data: any = await resp.json();\n const choice = data.choices?.[0]?.message ?? {};\n return {\n content: choice.content ?? \"\",\n reasoningContent: choice.reasoning_content ?? null,\n toolCalls: choice.tool_calls ?? [],\n usage: Usage.fromApi(data.usage),\n raw: data,\n };\n } finally {\n clearTimeout(timer);\n }\n }\n\n async *stream(opts: ChatRequestOptions): AsyncGenerator<StreamChunk> {\n const ctrl = new AbortController();\n const timer = setTimeout(() => ctrl.abort(), this.timeoutMs);\n const signal = opts.signal ?? ctrl.signal;\n\n let resp: Response;\n try {\n // Only the initial fetch is retried. Once the server has started sending\n // the stream body we do NOT retry — a mid-stream retry would re-bill and\n // desync the session context.\n resp = await fetchWithRetry(\n this._fetch,\n `${this.baseUrl}/chat/completions`,\n {\n method: \"POST\",\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n \"Content-Type\": \"application/json\",\n Accept: \"text/event-stream\",\n },\n body: JSON.stringify(this.buildPayload(opts, true)),\n signal,\n },\n { ...this.retry, signal },\n );\n } catch (err) {\n clearTimeout(timer);\n throw err;\n }\n if (!resp.ok || !resp.body) {\n clearTimeout(timer);\n throw new Error(`DeepSeek ${resp.status}: ${await resp.text().catch(() => \"\")}`);\n }\n\n const queue: StreamChunk[] = [];\n let done = false;\n const parser = createParser({\n onEvent: (ev: EventSourceMessage) => {\n if (!ev.data || ev.data === \"[DONE]\") {\n done = true;\n return;\n }\n try {\n const json = JSON.parse(ev.data);\n const delta = json.choices?.[0]?.delta ?? {};\n const finishReason = json.choices?.[0]?.finish_reason ?? undefined;\n const chunk: StreamChunk = { raw: json, finishReason };\n if (typeof delta.content === \"string\" && delta.content.length > 0) {\n chunk.contentDelta = delta.content;\n }\n if (typeof delta.reasoning_content === \"string\" && delta.reasoning_content.length > 0) {\n chunk.reasoningDelta = delta.reasoning_content;\n }\n if (Array.isArray(delta.tool_calls) && delta.tool_calls.length > 0) {\n const tc = delta.tool_calls[0];\n chunk.toolCallDelta = {\n index: tc.index ?? 0,\n id: tc.id,\n name: tc.function?.name,\n argumentsDelta: tc.function?.arguments,\n };\n }\n if (json.usage) {\n chunk.usage = Usage.fromApi(json.usage);\n }\n queue.push(chunk);\n } catch {\n /* skip malformed sse frame */\n }\n },\n });\n\n const reader = resp.body.getReader();\n const decoder = new TextDecoder();\n try {\n while (true) {\n if (queue.length > 0) {\n yield queue.shift()!;\n continue;\n }\n if (done) break;\n const { value, done: streamDone } = await reader.read();\n if (streamDone) break;\n parser.feed(decoder.decode(value, { stream: true }));\n }\n while (queue.length > 0) yield queue.shift()!;\n } finally {\n clearTimeout(timer);\n reader.releaseLock();\n }\n }\n}\n\nexport type { ChatMessage, ToolCall, ToolSpec };\n","/**\n * Retry layer for DeepSeek API calls.\n *\n * Wraps a `fetch` function so that transient failures (rate limiting, server\n * overload, network blips) don't kill an agent session. We explicitly DO NOT\n * retry:\n * - 4xx client errors other than 408 / 429 (bad key, bad request, ...)\n * - aborted requests (user cancelled)\n * - mid-stream body read errors (retrying costs money AND would desync)\n *\n * Retrying is controlled by attempt count + exponential backoff with jitter.\n * If the server sends a `Retry-After` header we honor it (capped by\n * `maxBackoffMs` so a misconfigured upstream can't park us forever).\n */\n\nexport interface RetryOptions {\n /** Maximum total attempts (including the first). Default 4. */\n maxAttempts?: number;\n /** Initial backoff in ms. Doubles each retry, with jitter. Default 500. */\n initialBackoffMs?: number;\n /** Upper bound on any single backoff delay. Default 10000 (10s). */\n maxBackoffMs?: number;\n /** HTTP statuses to treat as retryable. Default [408, 429, 500, 502, 503, 504]. */\n retryableStatuses?: readonly number[];\n /** Abort signal; we do NOT retry once aborted. */\n signal?: AbortSignal;\n /** Telemetry hook — called before each wait. */\n onRetry?: (info: RetryInfo) => void;\n}\n\nexport interface RetryInfo {\n attempt: number;\n reason: string;\n waitMs: number;\n}\n\nconst DEFAULT_RETRYABLE_STATUSES = [408, 429, 500, 502, 503, 504] as const;\n\nexport async function fetchWithRetry(\n fetchFn: typeof fetch,\n url: string,\n init: RequestInit,\n opts: RetryOptions = {},\n): Promise<Response> {\n const maxAttempts = opts.maxAttempts ?? 4;\n const initial = opts.initialBackoffMs ?? 500;\n const cap = opts.maxBackoffMs ?? 10_000;\n const retryable = new Set(opts.retryableStatuses ?? DEFAULT_RETRYABLE_STATUSES);\n\n let lastError: unknown;\n\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n if (opts.signal?.aborted) throw new Error(\"aborted\");\n\n try {\n const resp = await fetchFn(url, init);\n\n // Success or non-retryable failure: return as-is.\n if (resp.ok || !retryable.has(resp.status)) return resp;\n\n // Retryable but out of attempts: return the last response so the caller\n // can surface the status to the user.\n if (attempt === maxAttempts - 1) return resp;\n\n // Drain the body so the connection can be reused on the next attempt.\n await resp.text().catch(() => undefined);\n\n const waitMs = computeWait(attempt, initial, cap, resp.headers.get(\"Retry-After\"));\n opts.onRetry?.({ attempt: attempt + 1, reason: `http ${resp.status}`, waitMs });\n await sleep(waitMs, opts.signal);\n } catch (err) {\n lastError = err;\n // Respect explicit aborts — do not retry.\n if (isAbortError(err) || opts.signal?.aborted) throw err;\n if (attempt === maxAttempts - 1) throw err;\n\n const waitMs = computeWait(attempt, initial, cap, null);\n opts.onRetry?.({\n attempt: attempt + 1,\n reason: `network: ${messageOf(err)}`,\n waitMs,\n });\n await sleep(waitMs, opts.signal);\n }\n }\n\n throw lastError ?? new Error(\"fetchWithRetry: loop exited unexpectedly\");\n}\n\nfunction computeWait(\n attempt: number,\n initial: number,\n cap: number,\n retryAfter: string | null,\n): number {\n if (retryAfter) {\n const seconds = Number.parseFloat(retryAfter);\n if (Number.isFinite(seconds) && seconds > 0) {\n return Math.min(seconds * 1000, cap);\n }\n }\n const exp = initial * 2 ** attempt;\n // Jitter range [75%, 125%] to spread retries out when many clients hit 429 together.\n const jitter = exp * (0.75 + Math.random() * 0.5);\n return Math.min(Math.max(jitter, 0), cap);\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n if (ms <= 0) return Promise.resolve();\n return new Promise((resolve, reject) => {\n const timer = setTimeout(resolve, ms);\n if (signal) {\n const onAbort = () => {\n clearTimeout(timer);\n reject(new Error(\"aborted\"));\n };\n if (signal.aborted) onAbort();\n else signal.addEventListener(\"abort\", onAbort, { once: true });\n }\n });\n}\n\nfunction isAbortError(err: unknown): boolean {\n if (!err || typeof err !== \"object\") return false;\n const name = (err as { name?: unknown }).name;\n return name === \"AbortError\";\n}\n\nfunction messageOf(err: unknown): string {\n if (err instanceof Error) return err.message;\n try {\n return String(err);\n } catch {\n return \"unknown error\";\n }\n}\n","/**\n * Pillar 2 — R1 Thought Harvesting.\n *\n * Takes the `reasoning_content` emitted by a thinking model (deepseek-reasoner\n * / R1) and extracts a structured plan state by making a cheap secondary call\n * to V3 in JSON mode. The typed state is intended for the orchestrator to\n * branch on — e.g. trigger self-consistency sampling when `uncertainties.length\n * > 2`, or surface the subgoals to the user.\n *\n * Opt-in: loops disable harvesting by default. Failures (bad JSON, API error,\n * empty reasoning) return an empty TypedPlanState — the main turn is never\n * aborted because of a harvest hiccup.\n */\n\nimport type { DeepSeekClient } from \"./client.js\";\n\nexport interface TypedPlanState {\n subgoals: string[];\n hypotheses: string[];\n uncertainties: string[];\n rejectedPaths: string[];\n}\n\nexport interface HarvestOptions {\n /** Model used for the extraction call. Defaults to the cheap chat model. */\n model?: string;\n /** Cap on how many items land in each array. Default 5. */\n maxItems?: number;\n /** Per-item character cap. Default 80. */\n maxItemLen?: number;\n /** Abort the extraction if R1 reasoning is shorter than this. Default 40. */\n minReasoningLen?: number;\n}\n\nexport function emptyPlanState(): TypedPlanState {\n return { subgoals: [], hypotheses: [], uncertainties: [], rejectedPaths: [] };\n}\n\nexport function isPlanStateEmpty(s: TypedPlanState | null | undefined): boolean {\n if (!s) return true;\n return (\n s.subgoals.length === 0 &&\n s.hypotheses.length === 0 &&\n s.uncertainties.length === 0 &&\n s.rejectedPaths.length === 0\n );\n}\n\nconst SYSTEM_PROMPT = `You extract a typed plan state from a reasoning trace produced by another LLM.\nOutput ONLY a JSON object. No markdown, no prose, no backticks.\n\nSchema:\n{\n \"subgoals\": string[], // concrete intermediate objectives the trace identifies\n \"hypotheses\": string[], // candidate approaches or assumptions being weighed\n \"uncertainties\": string[], // facts the trace flags as unclear / to verify\n \"rejectedPaths\": string[] // approaches the trace considered and then abandoned\n}\n\nConstraints:\n- Every field must be present. Use [] if not applicable.\n- Each array has at most {maxItems} items.\n- Each item is plain text, at most {maxItemLen} characters, no markdown.\n- Write in the same language as the trace (Chinese in → Chinese out, etc.).\n- Do not quote back the trace; write short, specific phrases.`;\n\nexport async function harvest(\n reasoningContent: string | null | undefined,\n client?: DeepSeekClient,\n options: HarvestOptions = {},\n signal?: AbortSignal,\n): Promise<TypedPlanState> {\n if (!client || !reasoningContent) return emptyPlanState();\n // Fast-path the already-aborted case so we don't burn a network\n // round-trip for a result the caller no longer wants.\n if (signal?.aborted) return emptyPlanState();\n const minLen = options.minReasoningLen ?? 40;\n const trimmed = reasoningContent.trim();\n if (trimmed.length < minLen) return emptyPlanState();\n\n const model = options.model ?? \"deepseek-chat\";\n const maxItems = options.maxItems ?? 5;\n const maxItemLen = options.maxItemLen ?? 80;\n const system = SYSTEM_PROMPT.replace(\"{maxItems}\", String(maxItems)).replace(\n \"{maxItemLen}\",\n String(maxItemLen),\n );\n\n try {\n const resp = await client.chat({\n model,\n messages: [\n { role: \"system\", content: system },\n { role: \"user\", content: trimmed },\n ],\n responseFormat: { type: \"json_object\" },\n temperature: 0,\n maxTokens: 600,\n signal,\n });\n return parsePlanState(resp.content, maxItems, maxItemLen);\n } catch {\n return emptyPlanState();\n }\n}\n\nfunction parsePlanState(raw: string, maxItems: number, maxItemLen: number): TypedPlanState {\n const text = (raw ?? \"\").trim();\n if (!text) return emptyPlanState();\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n // Occasionally a model wraps JSON in fences despite instructions.\n const match = text.match(/\\{[\\s\\S]*\\}/);\n if (!match) return emptyPlanState();\n try {\n parsed = JSON.parse(match[0]);\n } catch {\n return emptyPlanState();\n }\n }\n if (!parsed || typeof parsed !== \"object\") return emptyPlanState();\n const obj = parsed as Record<string, unknown>;\n return {\n subgoals: sanitizeArray(obj.subgoals, maxItems, maxItemLen),\n hypotheses: sanitizeArray(obj.hypotheses, maxItems, maxItemLen),\n uncertainties: sanitizeArray(obj.uncertainties, maxItems, maxItemLen),\n rejectedPaths: sanitizeArray(obj.rejectedPaths ?? obj.rejected_paths, maxItems, maxItemLen),\n };\n}\n\nfunction sanitizeArray(raw: unknown, maxItems: number, maxItemLen: number): string[] {\n if (!Array.isArray(raw)) return [];\n const out: string[] = [];\n for (const item of raw) {\n if (out.length >= maxItems) break;\n if (typeof item !== \"string\") continue;\n const cleaned = item.trim().replace(/\\s+/g, \" \");\n if (!cleaned) continue;\n out.push(cleaned.length <= maxItemLen ? cleaned : `${cleaned.slice(0, maxItemLen - 1)}…`);\n }\n return out;\n}\n","/**\n * Self-consistency branching.\n *\n * When enabled, the loop fans out into N parallel samples per turn (varied\n * temperatures), runs Pillar 2 harvest on each, and selects the sample with\n * the fewest flagged uncertainties (ties broken by answer length — a crude\n * Occam prior).\n *\n * The unique opportunity here: because DeepSeek is ~20× cheaper than Claude,\n * running N=3–5 samples per turn is still cheaper than a single Claude call,\n * while the majority-confidence selection tends to dominate single-sample\n * answers on fuzzy multi-step reasoning tasks.\n */\n\nimport type { ChatResponse, DeepSeekClient } from \"./client.js\";\nimport { type HarvestOptions, type TypedPlanState, harvest } from \"./harvest.js\";\nimport type { ChatRequestOptions } from \"./types.js\";\n\nexport interface BranchSample {\n index: number;\n temperature: number;\n response: ChatResponse;\n planState: TypedPlanState;\n}\n\nexport type BranchSelector = (samples: BranchSample[]) => BranchSample;\n\nexport interface BranchOptions {\n /** Number of parallel samples. 1 disables branching. Default 1. */\n budget?: number;\n /** Temperatures for each branch. Default spreads across [0, 1]. */\n temperatures?: readonly number[];\n /** Harvest options; the selector needs harvest to score samples. */\n harvestOptions?: HarvestOptions;\n /** Custom selector. Default: min uncertainties, tie-break shortest answer. */\n selector?: BranchSelector;\n /**\n * Fires as each sample finishes (main call + harvest both complete).\n * Useful for progress UI. Not awaited; exceptions are swallowed.\n */\n onSampleDone?: (sample: BranchSample) => void;\n}\n\nexport interface BranchResult {\n chosen: BranchSample;\n samples: BranchSample[];\n}\n\n/** Default: fewest uncertainties wins, ties broken by shorter answer content. */\nexport const defaultSelector: BranchSelector = (samples) => {\n if (samples.length === 0) throw new Error(\"defaultSelector: samples is empty\");\n return samples.slice().sort((a, b) => {\n const uDiff = a.planState.uncertainties.length - b.planState.uncertainties.length;\n if (uDiff !== 0) return uDiff;\n const aLen = a.response.content?.length ?? 0;\n const bLen = b.response.content?.length ?? 0;\n return aLen - bLen;\n })[0]!;\n};\n\nexport async function runBranches(\n client: DeepSeekClient,\n request: ChatRequestOptions,\n opts: BranchOptions = {},\n): Promise<BranchResult> {\n const budget = Math.max(1, opts.budget ?? 1);\n const temperatures = resolveTemperatures(budget, opts.temperatures);\n const selector = opts.selector ?? defaultSelector;\n\n const samples = await Promise.all(\n temperatures.map(async (temperature, index): Promise<BranchSample> => {\n const response = await client.chat({ ...request, temperature });\n const planState = await harvest(response.reasoningContent, client, opts.harvestOptions);\n const sample: BranchSample = { index, temperature, response, planState };\n try {\n opts.onSampleDone?.(sample);\n } catch {\n /* callback errors must not poison the await */\n }\n return sample;\n }),\n );\n\n return { chosen: selector(samples), samples };\n}\n\n/** Sum usage across branch samples for telemetry purposes. */\nexport function aggregateBranchUsage(samples: readonly BranchSample[]) {\n let promptTokens = 0;\n let completionTokens = 0;\n let totalTokens = 0;\n let promptCacheHitTokens = 0;\n let promptCacheMissTokens = 0;\n for (const s of samples) {\n promptTokens += s.response.usage.promptTokens;\n completionTokens += s.response.usage.completionTokens;\n totalTokens += s.response.usage.totalTokens;\n promptCacheHitTokens += s.response.usage.promptCacheHitTokens;\n promptCacheMissTokens += s.response.usage.promptCacheMissTokens;\n }\n return {\n promptTokens,\n completionTokens,\n totalTokens,\n promptCacheHitTokens,\n promptCacheMissTokens,\n };\n}\n\nfunction resolveTemperatures(budget: number, custom?: readonly number[]): number[] {\n if (custom && custom.length >= budget) return [...custom.slice(0, budget)];\n // Spread evenly across [0, 1] to encourage reasoning-path diversity.\n if (budget === 1) return [0];\n const out: number[] = [];\n for (let i = 0; i < budget; i++) {\n out.push(Number((i / (budget - 1)).toFixed(2)));\n }\n return out;\n}\n","/**\n * Hooks — user-defined automation that fires at well-known points in\n * the agent loop. Mirrors the two-scope layout we use for memory and\n * skills:\n *\n * - `<project>/.reasonix/settings.json` — committable per-project\n * - `~/.reasonix/settings.json` — every session\n *\n * A hook is a shell command. We invoke it with stdin = a JSON\n * payload describing the event, and interpret the exit code:\n *\n * - `0` — pass; loop continues normally\n * - `2` — block; for `PreToolUse` / `UserPromptSubmit` the\n * loop refuses to continue with that step and surfaces the\n * hook's stderr as the reason. For `PostToolUse` / `Stop` block\n * is meaningless (the action already happened) — treat as warn.\n * - anything else — warn; loop continues but stderr is rendered\n * to the user as an inline notice.\n *\n * stdin JSON shape (one envelope per event):\n *\n * {\n * \"event\": \"PreToolUse\" | \"PostToolUse\" | \"UserPromptSubmit\" | \"Stop\",\n * \"cwd\": \"<absolute project root or process.cwd()>\",\n * \"toolName\": \"<string>\", // tool events only\n * \"toolArgs\": <unknown>, // tool events only — already JSON-decoded\n * \"toolResult\": \"<string>\", // PostToolUse only — same body the model sees\n * \"prompt\": \"<string>\", // UserPromptSubmit only\n * \"lastAssistantText\": \"<string>\", // Stop only\n * \"turn\": <number>, // Stop only\n * }\n *\n * Hooks are executed in order: project scope first, then global.\n * `Pre*` events stop dispatching at the first block; non-block\n * outcomes accumulate into a single report so the UI can render\n * each warning inline.\n */\n\nimport { spawn } from \"node:child_process\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nexport type HookEvent = \"PreToolUse\" | \"PostToolUse\" | \"UserPromptSubmit\" | \"Stop\";\n\n/** All four events as a const array — drives slash listing + validation. */\nexport const HOOK_EVENTS: readonly HookEvent[] = [\n \"PreToolUse\",\n \"PostToolUse\",\n \"UserPromptSubmit\",\n \"Stop\",\n] as const;\n\n/** Only the gating events can block the loop. */\nconst BLOCKING_EVENTS: ReadonlySet<HookEvent> = new Set([\"PreToolUse\", \"UserPromptSubmit\"]);\n\n/** Per-event default timeout. Tool/prompt hooks gate progress, so they're tight. */\nconst DEFAULT_TIMEOUTS_MS: Record<HookEvent, number> = {\n PreToolUse: 5_000,\n UserPromptSubmit: 5_000,\n PostToolUse: 30_000,\n Stop: 30_000,\n};\n\nexport type HookScope = \"project\" | \"global\";\n\nexport interface HookConfig {\n /**\n * Tool-name pattern (PreToolUse / PostToolUse only). Anchored regex.\n * Omitted or `\"*\"` matches every tool. Ignored for prompt / Stop\n * events (they have no tool name to match against).\n */\n match?: string;\n /** Shell command to run. Spawned through the platform shell. */\n command: string;\n /** Optional human description — surfaced in `/hooks`. */\n description?: string;\n /** Per-hook timeout override in ms. */\n timeout?: number;\n /**\n * Working directory for the spawned process. Defaults to:\n * - project scope → the project root\n * - global scope → process.cwd()\n */\n cwd?: string;\n}\n\n/** Shape of `<scope>/.reasonix/settings.json` — only `hooks` for now. */\nexport interface HookSettings {\n hooks?: Partial<Record<HookEvent, HookConfig[]>>;\n}\n\n/** A loaded hook with its origin scope baked in (used for ordering and `/hooks`). */\nexport interface ResolvedHook extends HookConfig {\n event: HookEvent;\n scope: HookScope;\n /** Absolute path to the settings.json the hook came from. */\n source: string;\n}\n\n/** Outcome of a single hook invocation. */\nexport interface HookOutcome {\n /** Which hook fired. */\n hook: ResolvedHook;\n /**\n * Decision:\n * - `pass` — exit 0\n * - `block` — exit 2 on a blocking event (otherwise downgraded to `warn`)\n * - `warn` — non-zero exit that is not a successful block\n * - `timeout` — the spawn was killed past `timeout`\n * - `error` — could not spawn at all (missing command, etc.)\n */\n decision: \"pass\" | \"block\" | \"warn\" | \"timeout\" | \"error\";\n exitCode: number | null;\n /** Captured stdout (trimmed). May be empty. */\n stdout: string;\n /** Captured stderr (trimmed). The block / warn message comes from here. */\n stderr: string;\n durationMs: number;\n}\n\n/** Aggregate report for `runHooks`. */\nexport interface HookReport {\n event: HookEvent;\n outcomes: HookOutcome[];\n /** True iff at least one outcome was a `block` — only meaningful for blocking events. */\n blocked: boolean;\n}\n\nexport const HOOK_SETTINGS_FILENAME = \"settings.json\";\nexport const HOOK_SETTINGS_DIRNAME = \".reasonix\";\n\n/** Where the global settings.json lives. Equivalent to `~/.reasonix/settings.json`. */\nexport function globalSettingsPath(homeDirOverride?: string): string {\n return join(homeDirOverride ?? homedir(), HOOK_SETTINGS_DIRNAME, HOOK_SETTINGS_FILENAME);\n}\n\n/** Where the project settings.json lives for a given root. */\nexport function projectSettingsPath(projectRoot: string): string {\n return join(projectRoot, HOOK_SETTINGS_DIRNAME, HOOK_SETTINGS_FILENAME);\n}\n\nfunction readSettingsFile(path: string): HookSettings | null {\n if (!existsSync(path)) return null;\n try {\n const raw = readFileSync(path, \"utf8\");\n const parsed = JSON.parse(raw);\n if (parsed && typeof parsed === \"object\") return parsed as HookSettings;\n } catch {\n /* malformed JSON → treat as no hooks; do NOT throw, the user\n * shouldn't lose the whole CLI to a typo in their settings */\n }\n return null;\n}\n\n/**\n * Pull every configured hook out of the project + global settings\n * files, in the order they should fire (project first, global second,\n * within each scope: array order from the file).\n *\n * Returns a flat list — the dispatcher filters by event + match\n * pattern at run time. Loading is cheap (one or two JSON files), so\n * we don't memoize across processes; re-load is allowed via\n * `/hooks reload` and on every fresh App mount.\n */\nexport interface LoadHookSettingsOptions {\n /** Absolute project root, if any. Without it, only global hooks load. */\n projectRoot?: string;\n /** Override `~` for tests. */\n homeDir?: string;\n}\n\nexport function loadHooks(opts: LoadHookSettingsOptions = {}): ResolvedHook[] {\n const out: ResolvedHook[] = [];\n if (opts.projectRoot) {\n const projPath = projectSettingsPath(opts.projectRoot);\n const settings = readSettingsFile(projPath);\n if (settings) appendResolved(out, settings, \"project\", projPath);\n }\n const globalPath = globalSettingsPath(opts.homeDir);\n const settings = readSettingsFile(globalPath);\n if (settings) appendResolved(out, settings, \"global\", globalPath);\n return out;\n}\n\nfunction appendResolved(\n out: ResolvedHook[],\n settings: HookSettings,\n scope: HookScope,\n source: string,\n): void {\n if (!settings.hooks) return;\n for (const event of HOOK_EVENTS) {\n const list = settings.hooks[event];\n if (!Array.isArray(list)) continue;\n for (const cfg of list) {\n if (!cfg || typeof cfg.command !== \"string\" || cfg.command.trim() === \"\") continue;\n out.push({ ...cfg, event, scope, source });\n }\n }\n}\n\n/**\n * True if `toolName` matches the hook's `match` field. `\"*\"` and\n * undefined match everything. Otherwise we anchor the field as a\n * regex — partial-name matches don't fire, so `\"file\"` would not\n * trigger on `read_file` (use `\".*file\"` for that).\n */\nexport function matchesTool(hook: ResolvedHook, toolName: string): boolean {\n if (hook.event !== \"PreToolUse\" && hook.event !== \"PostToolUse\") return true;\n const m = hook.match;\n if (!m || m === \"*\") return true;\n try {\n const re = new RegExp(`^(?:${m})$`);\n return re.test(toolName);\n } catch {\n /* malformed regex → don't fire (safer than firing on every tool) */\n return false;\n }\n}\n\n/** Payload envelope passed to hook stdin. */\nexport interface HookPayload {\n event: HookEvent;\n cwd: string;\n toolName?: string;\n toolArgs?: unknown;\n toolResult?: string;\n prompt?: string;\n lastAssistantText?: string;\n turn?: number;\n}\n\n/** Test seam — same shape as Node's spawn but returns a Promise of the raw outcome bits. */\nexport interface HookSpawnInput {\n command: string;\n cwd: string;\n stdin: string;\n timeoutMs: number;\n}\n\nexport interface HookSpawnResult {\n exitCode: number | null;\n stdout: string;\n stderr: string;\n timedOut: boolean;\n /** True iff spawn() itself failed (ENOENT, EACCES, …). */\n spawnError?: Error;\n}\n\nexport type HookSpawner = (input: HookSpawnInput) => Promise<HookSpawnResult>;\n\n/**\n * Default spawner — runs `command` through the platform shell so\n * `&&`, pipes, env-var expansion all work without a tokenizer.\n * Stdin is the JSON payload, stdout / stderr are buffered.\n *\n * Why `shell: true`? A hook is intentionally a shell command — that's\n * the contract. Treating it like an argv array would surprise users\n * who write `bun run check && eslint .` and expect it to behave the\n * way it does in their terminal.\n */\nfunction defaultSpawner(input: HookSpawnInput): Promise<HookSpawnResult> {\n return new Promise<HookSpawnResult>((resolve) => {\n const child = spawn(input.command, {\n cwd: input.cwd,\n shell: true,\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n });\n let stdout = \"\";\n let stderr = \"\";\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n child.kill(\"SIGTERM\");\n // SIGTERM may not land on Windows for shell children — followed\n // by a hard kill a moment later if the process is still around.\n setTimeout(() => {\n try {\n child.kill(\"SIGKILL\");\n } catch {\n /* already gone */\n }\n }, 500);\n }, input.timeoutMs);\n\n child.stdout.on(\"data\", (chunk: Buffer) => {\n stdout += chunk.toString(\"utf8\");\n });\n child.stderr.on(\"data\", (chunk: Buffer) => {\n stderr += chunk.toString(\"utf8\");\n });\n child.once(\"error\", (err) => {\n clearTimeout(timer);\n resolve({\n exitCode: null,\n stdout,\n stderr,\n timedOut: false,\n spawnError: err,\n });\n });\n child.once(\"close\", (code) => {\n clearTimeout(timer);\n resolve({\n exitCode: code,\n stdout: stdout.trim(),\n stderr: stderr.trim(),\n timedOut,\n });\n });\n\n try {\n child.stdin.write(input.stdin);\n child.stdin.end();\n } catch {\n /* stdin write can race with spawn errors; the close handler\n * still fires with exit 0/null */\n }\n });\n}\n\n/**\n * Format a hook outcome as a single-line UI string. Used by both the\n * loop (for `warning` events) and the App (for UserPromptSubmit /\n * Stop outcomes). Centralizing keeps the language consistent across\n * scopes.\n */\nexport function formatHookOutcomeMessage(outcome: HookOutcome): string {\n if (outcome.decision === \"pass\") return \"\";\n const detail = (outcome.stderr || outcome.stdout || \"\").trim();\n const tag = `${outcome.hook.scope}/${outcome.hook.event}`;\n const cmd =\n outcome.hook.command.length > 60\n ? `${outcome.hook.command.slice(0, 60)}…`\n : outcome.hook.command;\n const head = `hook ${tag} \\`${cmd}\\` ${outcome.decision}`;\n return detail ? `${head}: ${detail}` : head;\n}\n\n/**\n * Decide the hook's outcome decision from raw spawn results.\n * Pulled out as a pure function so tests can pin the matrix.\n */\nexport function decideOutcome(\n event: HookEvent,\n raw: HookSpawnResult,\n): \"pass\" | \"block\" | \"warn\" | \"timeout\" | \"error\" {\n if (raw.spawnError) return \"error\";\n if (raw.timedOut) return BLOCKING_EVENTS.has(event) ? \"block\" : \"warn\";\n if (raw.exitCode === 0) return \"pass\";\n if (raw.exitCode === 2 && BLOCKING_EVENTS.has(event)) return \"block\";\n return \"warn\";\n}\n\nexport interface RunHooksOptions {\n payload: HookPayload;\n hooks: ResolvedHook[];\n /** Test seam — defaults to a real `spawn`. */\n spawner?: HookSpawner;\n}\n\n/**\n * Filter hooks down to the ones that match `payload.event` (and\n * `payload.toolName`, for tool events), then run them in order.\n * Stops at the first `block` outcome on a blocking event so a\n * gating hook can prevent later hooks from incorrectly seeing a\n * success that wasn't going to happen.\n */\nexport async function runHooks(opts: RunHooksOptions): Promise<HookReport> {\n const spawner = opts.spawner ?? defaultSpawner;\n const event = opts.payload.event;\n const toolName = opts.payload.toolName ?? \"\";\n const matching = opts.hooks.filter((h) => h.event === event && matchesTool(h, toolName));\n\n const outcomes: HookOutcome[] = [];\n let blocked = false;\n const stdin = `${JSON.stringify(opts.payload)}\\n`;\n\n for (const hook of matching) {\n const start = Date.now();\n const timeoutMs = hook.timeout ?? DEFAULT_TIMEOUTS_MS[event];\n const cwd = hook.cwd ?? opts.payload.cwd;\n const raw = await spawner({ command: hook.command, cwd, stdin, timeoutMs });\n const decision = decideOutcome(event, raw);\n outcomes.push({\n hook,\n decision,\n exitCode: raw.exitCode,\n stdout: raw.stdout,\n stderr:\n raw.stderr ||\n (raw.spawnError ? raw.spawnError.message : \"\") ||\n (raw.timedOut ? `hook timed out after ${timeoutMs}ms` : \"\"),\n durationMs: Date.now() - start,\n });\n if (decision === \"block\") {\n blocked = true;\n break;\n }\n }\n\n return { event, outcomes, blocked };\n}\n","/**\n * Pure-TS port of DeepSeek's V3 tokenizer. Reads the slimmed+gzipped\n * HuggingFace-format tokenizer data shipped at\n * `data/deepseek-tokenizer.json.gz` and implements enough of the HF\n * pipeline (Split pre-tokenizers → ByteLevel → BPE) to count tokens\n * offline without pulling the `@lenml/tokenizers` or native Rust deps.\n *\n * Accuracy target: within ~3% of the API-returned `usage.prompt_tokens`\n * for mixed CJK+English+code input. Exact-to-API match would also\n * require replaying the Jinja chat template (role markers / tool call\n * framing); we intentionally skip that — for a gauge/UI estimate the\n * raw-text count is the useful number.\n *\n * Scope: ENCODE-SIDE ONLY. We don't need decode for counting; adding\n * it later is trivial via the inverse byte-level table.\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { gunzipSync } from \"node:zlib\";\n\ninterface AddedToken {\n id: number;\n content: string;\n special: boolean;\n normalized: boolean;\n}\n\ninterface SplitPretokenizer {\n type: \"Split\";\n pattern: { Regex: string };\n behavior: \"Isolated\" | \"Removed\" | string;\n invert: boolean;\n}\n\ninterface ByteLevelPretokenizer {\n type: \"ByteLevel\";\n add_prefix_space: boolean;\n trim_offsets: boolean;\n use_regex: boolean;\n}\n\ntype Pretokenizer = SplitPretokenizer | ByteLevelPretokenizer;\n\ninterface TokenizerData {\n added_tokens: AddedToken[];\n pre_tokenizer: {\n type: \"Sequence\";\n pretokenizers: Pretokenizer[];\n };\n model: {\n type: \"BPE\";\n vocab: Record<string, number>;\n merges: string[];\n };\n}\n\ninterface LoadedTokenizer {\n vocab: Record<string, number>;\n mergeRank: Map<string, number>;\n splitRegexes: RegExp[];\n byteToChar: string[];\n /**\n * Non-special added tokens (e.g. `<think>`, `<|fim▁hole|>`) that the\n * HF tokenizer recognizes as atomic units when they appear inline in\n * the text. Special tokens like `<|begin▁of▁sentence|>` are NOT in\n * this list — the model ignores them when they appear in user text\n * (the default HF `split_special_tokens=False` behavior), so we do\n * the same: they get tokenized byte-by-byte, not as the special ID.\n */\n addedPattern: RegExp | null;\n addedMap: Map<string, number>;\n}\n\n/**\n * GPT-2 byte-to-unicode mapping. Covers every byte 0..255 with a\n * deterministic visible-printable unicode char — this is what lets the\n * byte-level BPE show up in JSON vocabs as readable strings (`Ġ` for\n * space, `Ċ` for `\\n`, etc). Identical across every byte-level BPE\n * tokenizer DeepSeek ships.\n */\nfunction buildByteToChar(): string[] {\n const result: string[] = new Array(256);\n const bs: number[] = [];\n for (let b = 33; b <= 126; b++) bs.push(b);\n for (let b = 161; b <= 172; b++) bs.push(b);\n for (let b = 174; b <= 255; b++) bs.push(b);\n const cs = bs.slice();\n let n = 0;\n for (let b = 0; b < 256; b++) {\n if (!bs.includes(b)) {\n bs.push(b);\n cs.push(256 + n);\n n++;\n }\n }\n for (let i = 0; i < bs.length; i++) {\n result[bs[i]!] = String.fromCodePoint(cs[i]!);\n }\n return result;\n}\n\nlet cached: LoadedTokenizer | null = null;\n\n/**\n * Find the bundled tokenizer data file. Resolution order (first hit wins):\n * 1. `REASONIX_TOKENIZER_PATH` env var (tests / custom builds).\n * 2. `../data/deepseek-tokenizer.json.gz` relative to this module —\n * covers dev (src/tokenizer.ts → data/) AND production bundled at\n * dist/index.js → dist/../data = data/.\n * 3. `../../data/deepseek-tokenizer.json.gz` — covers the CLI bundle\n * at dist/cli/index.js → dist/cli/../../data = data/. Without this\n * step 2 resolves to dist/data/ which doesn't exist (the data file\n * is shipped at package root per package.json `files` entry), and\n * every step() preflight crashes the loop with ENOENT.\n * 4. `require.resolve(\"reasonix/package.json\")` — last-resort package\n * root lookup for unusual bundlers.\n */\nfunction resolveDataPath(): string {\n if (process.env.REASONIX_TOKENIZER_PATH) return process.env.REASONIX_TOKENIZER_PATH;\n const candidates: string[] = [];\n try {\n const here = dirname(fileURLToPath(import.meta.url));\n candidates.push(join(here, \"..\", \"data\", \"deepseek-tokenizer.json.gz\"));\n candidates.push(join(here, \"..\", \"..\", \"data\", \"deepseek-tokenizer.json.gz\"));\n } catch {\n /* import.meta.url unavailable — skip to the package resolution step. */\n }\n try {\n const req = createRequire(import.meta.url);\n candidates.push(\n join(dirname(req.resolve(\"reasonix/package.json\")), \"data\", \"deepseek-tokenizer.json.gz\"),\n );\n } catch {\n /* Not installed as `reasonix/` — the earlier candidates still may hit. */\n }\n for (const p of candidates) {\n if (existsSync(p)) return p;\n }\n // Nothing exists — return the first candidate anyway so readFileSync\n // surfaces a concrete path in the ENOENT message (better than silent miss).\n return candidates[0] ?? join(process.cwd(), \"data\", \"deepseek-tokenizer.json.gz\");\n}\n\nfunction loadTokenizer(): LoadedTokenizer {\n if (cached) return cached;\n const buf = readFileSync(resolveDataPath());\n const json = gunzipSync(buf).toString(\"utf8\");\n const data = JSON.parse(json) as TokenizerData;\n\n const mergeRank = new Map<string, number>();\n for (let i = 0; i < data.model.merges.length; i++) {\n mergeRank.set(data.model.merges[i]!, i);\n }\n\n const splitRegexes: RegExp[] = [];\n for (const p of data.pre_tokenizer.pretokenizers) {\n if (p.type === \"Split\") {\n // All three Split rules use Isolated — matches become their own\n // pre-tokens and so do the in-between stretches. The ByteLevel\n // stage in the Sequence does no extra splitting here\n // (use_regex:false), so our 3 Split regexes are the whole story.\n splitRegexes.push(new RegExp(p.pattern.Regex, \"gu\"));\n }\n }\n\n const addedMap = new Map<string, number>();\n const addedContents: string[] = [];\n for (const t of data.added_tokens) {\n if (!t.special) {\n addedMap.set(t.content, t.id);\n addedContents.push(t.content);\n }\n }\n // Longest-first ensures greedy matching doesn't lose a longer token\n // to a shorter prefix (e.g. `<think>` before `<`).\n addedContents.sort((a, b) => b.length - a.length);\n const addedPattern = addedContents.length\n ? new RegExp(addedContents.map(escapeRegex).join(\"|\"), \"g\")\n : null;\n\n cached = {\n vocab: data.model.vocab,\n mergeRank,\n splitRegexes,\n byteToChar: buildByteToChar(),\n addedPattern,\n addedMap,\n };\n return cached;\n}\n\nfunction escapeRegex(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * Apply one \"Isolated\" Split: the matches become their own pre-tokens,\n * stretches between matches pass through unchanged. Empty pre-tokens\n * are dropped so downstream stages don't see them.\n */\nfunction applySplit(chunks: string[], re: RegExp): string[] {\n const out: string[] = [];\n for (const chunk of chunks) {\n if (!chunk) continue;\n // Reset lastIndex — reusing a /g regex across matchAll iterations\n // is safe (matchAll internally advances), but across different\n // input strings we want a clean start.\n re.lastIndex = 0;\n let last = 0;\n for (const m of chunk.matchAll(re)) {\n const idx = m.index ?? 0;\n if (idx > last) out.push(chunk.slice(last, idx));\n if (m[0].length > 0) out.push(m[0]);\n last = idx + m[0].length;\n }\n if (last < chunk.length) out.push(chunk.slice(last));\n }\n return out;\n}\n\n/** UTF-8 bytes of `s`, each mapped to its byte-level visible char. */\nfunction byteLevelEncode(s: string, byteToChar: string[]): string {\n const bytes = new TextEncoder().encode(s);\n let out = \"\";\n for (let i = 0; i < bytes.length; i++) out += byteToChar[bytes[i]!];\n return out;\n}\n\n/**\n * Standard BPE merge loop. Starts from single byte-level chars and\n * repeatedly applies the lowest-rank merge until none remain. O(n²)\n * in chunk length, which is fine because chunks are ≤ a few hundred\n * byte-level chars after pre-tokenization (and most are <50).\n */\nfunction bpeEncode(piece: string, mergeRank: Map<string, number>): string[] {\n if (piece.length <= 1) return piece ? [piece] : [];\n let word: string[] = Array.from(piece);\n while (true) {\n let bestIdx = -1;\n let bestRank = Number.POSITIVE_INFINITY;\n for (let i = 0; i < word.length - 1; i++) {\n const pair = `${word[i]} ${word[i + 1]}`;\n const rank = mergeRank.get(pair);\n if (rank !== undefined && rank < bestRank) {\n bestRank = rank;\n bestIdx = i;\n if (rank === 0) break; // 0 is already the best possible\n }\n }\n if (bestIdx < 0) break;\n word = [\n ...word.slice(0, bestIdx),\n word[bestIdx]! + word[bestIdx + 1]!,\n ...word.slice(bestIdx + 2),\n ];\n if (word.length === 1) break;\n }\n return word;\n}\n\n/**\n * Tokenize a UTF-8 string into DeepSeek token IDs. Mirrors the HF\n * pipeline: (1) isolate non-special added tokens so they stay atomic,\n * (2) for each in-between segment run the three Split regexes, (3)\n * byte-level encode, (4) BPE merge, (5) look up vocab IDs.\n *\n * Not reentrancy-hazardous: loads a module-level singleton on first\n * call and reuses it. Subsequent calls are pure compute.\n */\nexport function encode(text: string): number[] {\n if (!text) return [];\n const t = loadTokenizer();\n const ids: number[] = [];\n\n const process = (segment: string) => {\n if (!segment) return;\n let chunks: string[] = [segment];\n for (const re of t.splitRegexes) chunks = applySplit(chunks, re);\n for (const chunk of chunks) {\n if (!chunk) continue;\n const byteLevel = byteLevelEncode(chunk, t.byteToChar);\n const pieces = bpeEncode(byteLevel, t.mergeRank);\n for (const p of pieces) {\n const id = t.vocab[p];\n // If not in vocab we silently skip: shouldn't happen for\n // byte-level BPE (every single byte has its own vocab entry),\n // but if a future tokenizer update breaks that invariant we'd\n // rather under-count than throw from a UI gauge.\n if (id !== undefined) ids.push(id);\n }\n }\n };\n\n if (t.addedPattern) {\n t.addedPattern.lastIndex = 0;\n let last = 0;\n for (const m of text.matchAll(t.addedPattern)) {\n const idx = m.index ?? 0;\n if (idx > last) process(text.slice(last, idx));\n const id = t.addedMap.get(m[0]);\n if (id !== undefined) ids.push(id);\n last = idx + m[0].length;\n }\n if (last < text.length) process(text.slice(last));\n } else {\n process(text);\n }\n return ids;\n}\n\n/**\n * Fast path for UI: we only need the count, not the IDs. Saves a\n * per-call array allocation and lets callers batch large logs\n * without holding the full ID stream.\n */\nexport function countTokens(text: string): number {\n return encode(text).length;\n}\n\n/**\n * Estimate the tokens a full conversation would cost. Sums raw-text\n * counts for every message's content; we do NOT add overhead for the\n * chat template's role markers (`<|User|>`, `<|Assistant|>`) because\n * the exact framing varies between the chat/reasoner templates and\n * DeepSeek applies them server-side anyway. Empirically adds ~3-6%\n * to the real `prompt_tokens` — callers who care can post-multiply.\n */\nexport function estimateConversationTokens(\n messages: Array<{ content?: string | null; tool_calls?: unknown }>,\n): number {\n let total = 0;\n for (const m of messages) {\n if (typeof m.content === \"string\" && m.content) {\n total += countTokens(m.content);\n }\n // Tool-call arguments are serialized as JSON in the prompt by the\n // chat template; their bytes WILL count upstream, so we count\n // them too. Stringify-once is cheap relative to the tokenize.\n if (m.tool_calls && Array.isArray(m.tool_calls) && m.tool_calls.length > 0) {\n total += countTokens(JSON.stringify(m.tool_calls));\n }\n }\n return total;\n}\n\n/**\n * Estimate the tokens a full DeepSeek request would cost: the\n * conversation-side tokens (what `estimateConversationTokens` already\n * counts) PLUS the serialized tool-spec payload. Tool specs ride in\n * their own JSON blob in the request body, not folded into any\n * message's `content`, so they need a separate count to land an\n * accurate preflight estimate.\n *\n * Returned number matches what `/context` displays for \"next request\"\n * — reuse this helper anywhere (preflight guard, diagnostics, UI) to\n * keep the two values from drifting.\n */\nexport function estimateRequestTokens(\n messages: Array<{ content?: string | null; tool_calls?: unknown }>,\n toolSpecs?: ReadonlyArray<unknown> | null,\n): number {\n let total = estimateConversationTokens(messages);\n if (toolSpecs && toolSpecs.length > 0) {\n total += countTokens(JSON.stringify(toolSpecs));\n }\n return total;\n}\n\n/** Exposed for tests — resets the lazy-load singleton. */\nexport function _resetForTests(): void {\n cached = null;\n}\n","/**\n * Schema flattening for DeepSeek tool calls.\n *\n * DeepSeek loses arguments on schemas that are deep (>2 levels of nesting) or\n * wide (>10 leaf parameters). This module transforms such schemas into a\n * dot-notation flat schema and re-nests the model's arguments before dispatch.\n *\n * Example:\n * { user: { profile: { name, age } } } ⇄ \"user.profile.name\", \"user.profile.age\"\n */\n\nimport type { JSONSchema } from \"../types.js\";\n\nexport interface FlattenDecision {\n shouldFlatten: boolean;\n leafCount: number;\n maxDepth: number;\n}\n\nexport function analyzeSchema(schema: JSONSchema | undefined): FlattenDecision {\n if (!schema) return { shouldFlatten: false, leafCount: 0, maxDepth: 0 };\n let leafCount = 0;\n let maxDepth = 0;\n walk(schema, 0, (depth, isLeaf) => {\n if (isLeaf) leafCount++;\n if (depth > maxDepth) maxDepth = depth;\n });\n return {\n shouldFlatten: leafCount > 10 || maxDepth > 2,\n leafCount,\n maxDepth,\n };\n}\n\nexport function flattenSchema(schema: JSONSchema): JSONSchema {\n const flatProps: Record<string, JSONSchema> = {};\n const required: string[] = [];\n collect(\"\", schema, flatProps, required, true);\n return {\n type: \"object\",\n properties: flatProps,\n required,\n };\n}\n\nexport function nestArguments(flatArgs: Record<string, unknown>): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(flatArgs)) {\n setByPath(out, key.split(\".\"), value);\n }\n return out;\n}\n\nfunction walk(\n schema: JSONSchema,\n depth: number,\n visit: (depth: number, isLeaf: boolean) => void,\n): void {\n if (schema.type === \"object\" && schema.properties) {\n for (const child of Object.values(schema.properties)) {\n walk(child, depth + 1, visit);\n }\n return;\n }\n if (schema.type === \"array\" && schema.items) {\n walk(schema.items, depth + 1, visit);\n return;\n }\n visit(depth, true);\n}\n\nfunction collect(\n prefix: string,\n schema: JSONSchema,\n out: Record<string, JSONSchema>,\n required: string[],\n isRootRequired: boolean,\n): void {\n if (schema.type === \"object\" && schema.properties) {\n const requiredSet = new Set(schema.required ?? []);\n for (const [key, child] of Object.entries(schema.properties)) {\n const nextPrefix = prefix ? `${prefix}.${key}` : key;\n const childRequired = isRootRequired && requiredSet.has(key);\n collect(nextPrefix, child, out, required, childRequired);\n }\n return;\n }\n // Treat anything non-object (including arrays) as a leaf for flattening purposes.\n out[prefix] = schema;\n if (isRootRequired) required.push(prefix);\n}\n\nfunction setByPath(target: Record<string, unknown>, path: string[], value: unknown): void {\n let cur: any = target;\n for (let i = 0; i < path.length - 1; i++) {\n const key = path[i]!;\n if (typeof cur[key] !== \"object\" || cur[key] === null) cur[key] = {};\n cur = cur[key];\n }\n cur[path[path.length - 1]!] = value;\n}\n","import { truncateForModel, truncateForModelByTokens } from \"./mcp/registry.js\";\nimport { analyzeSchema, flattenSchema, nestArguments } from \"./repair/flatten.js\";\nimport type { JSONSchema, ToolSpec } from \"./types.js\";\n\n/**\n * Per-call context a tool `fn` can optionally consume. Today the only\n * field is `signal`, plumbed through so long-running tools (MCP calls,\n * HTTP requests) can abort when the user presses Esc. Omitted fields\n * stay optional — tools written against the pre-0.4.9 signature keep\n * working; they just ignore cancellation, which is fine for fast\n * local work where \"await finishes\" happens before the next tick anyway.\n */\nexport interface ToolCallContext {\n signal?: AbortSignal;\n}\n\nexport interface ToolDefinition<A = any, R = any> {\n name: string;\n description?: string;\n parameters?: JSONSchema;\n /**\n * Marks a tool as read-only: safe to invoke during plan mode. `true`\n * for tools that only observe (read_file, list_directory, search, web\n * fetch/search). Leave undefined / `false` for anything that can write,\n * execute, or mutate state.\n *\n * The registry enforces this at dispatch: non-readonly tools called\n * while `planMode` is on return a refusal string the model can\n * learn from, instead of actually running.\n */\n readOnly?: boolean;\n /**\n * Dynamic read-only check for tools whose safety depends on arguments\n * — `run_command` with an allowlisted argv is safe, `run_command\n * rm -rf` isn't. Called with the parsed arguments; `true` means \"treat\n * as read-only for plan mode\". Takes precedence over `readOnly` when\n * both are set.\n */\n readOnlyCheck?: (args: A) => boolean;\n fn: (args: A, ctx?: ToolCallContext) => R | Promise<R>;\n}\n\ninterface InternalTool extends ToolDefinition {\n /**\n * Pillar 3 — flatten metadata. Set when the registered schema is deep\n * (>2 levels) or wide (>10 leaf params), conditions on which DeepSeek\n * V3/R1 are known to drop arguments. We advertise the flattened schema\n * to the model, then re-nest the model's args before calling fn.\n */\n flatSchema?: JSONSchema;\n}\n\nexport interface ToolRegistryOptions {\n /**\n * Auto-flatten schemas that exceed depth/width thresholds before sending\n * them to the model. Re-nests arguments transparently on dispatch.\n * Default: true. Pass false to opt out.\n */\n autoFlatten?: boolean;\n}\n\nexport class ToolRegistry {\n private readonly _tools = new Map<string, InternalTool>();\n private readonly _autoFlatten: boolean;\n /**\n * When true, `dispatch` refuses any tool whose `readOnly` flag isn't\n * set (and whose `readOnlyCheck` doesn't pass on the specific args).\n * Drives `reasonix code`'s Plan Mode — the model can still explore\n * via read tools but its writes and non-allowlisted shell calls are\n * bounced until the user approves a submitted plan.\n */\n private _planMode = false;\n\n constructor(opts: ToolRegistryOptions = {}) {\n this._autoFlatten = opts.autoFlatten !== false;\n }\n\n /** Enable / disable plan-mode enforcement at dispatch. */\n setPlanMode(on: boolean): void {\n this._planMode = Boolean(on);\n }\n\n /** True when the registry is currently refusing non-readonly calls. */\n get planMode(): boolean {\n return this._planMode;\n }\n\n register<A, R>(def: ToolDefinition<A, R>): this {\n if (!def.name) throw new Error(\"tool requires a name\");\n const internal: InternalTool = { ...(def as ToolDefinition) };\n if (this._autoFlatten && def.parameters) {\n const decision = analyzeSchema(def.parameters);\n if (decision.shouldFlatten) {\n internal.flatSchema = flattenSchema(def.parameters);\n }\n }\n this._tools.set(def.name, internal);\n return this;\n }\n\n has(name: string): boolean {\n return this._tools.has(name);\n }\n\n get(name: string): ToolDefinition | undefined {\n return this._tools.get(name);\n }\n\n get size(): number {\n return this._tools.size;\n }\n\n /** True if a registered tool's schema was flattened for the model. */\n wasFlattened(name: string): boolean {\n return Boolean(this._tools.get(name)?.flatSchema);\n }\n\n specs(): ToolSpec[] {\n return [...this._tools.values()].map((t) => ({\n type: \"function\",\n function: {\n name: t.name,\n description: t.description ?? \"\",\n parameters: t.flatSchema ?? t.parameters ?? { type: \"object\", properties: {} },\n },\n }));\n }\n\n async dispatch(\n name: string,\n argumentsRaw: string | Record<string, unknown>,\n opts: { signal?: AbortSignal; maxResultChars?: number; maxResultTokens?: number } = {},\n ): Promise<string> {\n const tool = this._tools.get(name);\n if (!tool) {\n return JSON.stringify({ error: `unknown tool: ${name}` });\n }\n let args: Record<string, unknown>;\n try {\n args =\n typeof argumentsRaw === \"string\"\n ? argumentsRaw.trim()\n ? (JSON.parse(argumentsRaw) ?? {})\n : {}\n : (argumentsRaw ?? {});\n } catch (err) {\n return JSON.stringify({\n error: `invalid tool arguments JSON: ${(err as Error).message}`,\n });\n }\n\n // Re-nest dot-notation args back to the original shape, but only when\n // (a) we flattened this tool's schema, AND\n // (b) the incoming args actually use dot keys.\n // The second condition handles the case where a model ignores the flat\n // spec and emits nested args anyway — we shouldn't double-process them.\n if (tool.flatSchema && args && typeof args === \"object\" && hasDotKey(args)) {\n args = nestArguments(args);\n }\n\n // Plan-mode enforcement — runs AFTER arg parsing so a tool with a\n // runtime `readOnlyCheck` can inspect the actual args (e.g.\n // `run_command` is read-only iff the command matches its allowlist).\n if (this._planMode && !isReadOnlyCall(tool, args)) {\n return JSON.stringify({\n error: `${name}: unavailable in plan mode — this is a read-only exploration phase. Use read_file / list_directory / search_files / directory_tree / web_search / allowlisted shell commands to investigate. Call submit_plan with your proposed plan when you're ready for the user's review.`,\n });\n }\n\n try {\n const result = await tool.fn(args, { signal: opts.signal });\n const str = typeof result === \"string\" ? result : JSON.stringify(result);\n // Pre-clip at dispatch so a single fat result can't balloon the\n // log (and disk session file) on its way in. Healing at load time\n // still catches pre-existing oversize entries; this closes the\n // door on new ones.\n //\n // Two caps available: `maxResultTokens` (preferred — bounds the\n // real context footprint, so CJK doesn't slip past at 2× density)\n // and `maxResultChars` (legacy). If both are set, apply both and\n // the tighter one wins; char-only callers keep their old behavior.\n let clipped = str;\n if (opts.maxResultTokens !== undefined) {\n clipped = truncateForModelByTokens(clipped, opts.maxResultTokens);\n }\n if (opts.maxResultChars !== undefined) {\n clipped = truncateForModel(clipped, opts.maxResultChars);\n }\n return clipped;\n } catch (err) {\n const e = err as Error & { toToolResult?: () => unknown };\n // Errors may opt into a richer tool-result shape by implementing\n // `toToolResult()`. Used by `PlanProposedError` to smuggle the\n // submitted plan text out to the UI without stuffing it into the\n // error message (which the dispatcher truncates at no fixed limit,\n // but keeping payloads structured is cleaner for UI parsing).\n if (typeof e.toToolResult === \"function\") {\n try {\n return JSON.stringify(e.toToolResult());\n } catch {\n /* fall through to the default shape */\n }\n }\n return JSON.stringify({\n error: `${e.name}: ${e.message}`,\n });\n }\n }\n}\n\nfunction isReadOnlyCall(tool: InternalTool, args: Record<string, unknown>): boolean {\n if (tool.readOnlyCheck) {\n try {\n return Boolean(tool.readOnlyCheck(args as never));\n } catch {\n return false;\n }\n }\n return tool.readOnly === true;\n}\n\nfunction hasDotKey(obj: Record<string, unknown>): boolean {\n for (const k of Object.keys(obj)) {\n if (k.includes(\".\")) return true;\n }\n return false;\n}\n","/**\n * Bridge: register an MCP server's tools into a Reasonix ToolRegistry.\n *\n * This is the integration surface. Once done, `CacheFirstLoop` sees the\n * MCP tools as if they were native — they inherit Cache-First + repair\n * (scavenge / truncation / storm) automatically. That's the payoff: any\n * MCP ecosystem tool, wrapped in Reasonix's Pillar 1 + Pillar 3 benefits.\n */\n\nimport { countTokens } from \"../tokenizer.js\";\nimport { ToolRegistry } from \"../tools.js\";\nimport type { JSONSchema } from \"../types.js\";\nimport type { McpClient } from \"./client.js\";\nimport type { CallToolResult, McpContentBlock } from \"./types.js\";\n\nexport interface BridgeOptions {\n /**\n * Prefix prepended to every MCP tool name when registered. Defaults to\n * empty (no prefix). Useful when bridging multiple servers into one\n * registry and names collide — e.g. `fs` + `gh` both exposing `search`.\n */\n namePrefix?: string;\n /** Registry to populate. Creates a fresh one if omitted. */\n registry?: ToolRegistry;\n /** Auto-flatten deep schemas (Pillar 3). Defaults to the registry's own default (true). */\n autoFlatten?: boolean;\n /**\n * Per-tool-call result cap, in characters. If a tool returns more than\n * this, the result is truncated and a `[…truncated N chars…]` marker is\n * appended before the last KB so the model still sees a useful tail.\n * Defaults to {@link DEFAULT_MAX_RESULT_CHARS}.\n *\n * Why this exists: DeepSeek V3's context is 131,072 tokens. A single\n * `read_file` against a big source file can return >3 MB of text\n * (~900k tokens) and permanently poison the session — every subsequent\n * turn rebuilds the history and 400s. This cap is a floor. Users who\n * legitimately want bigger payloads can raise it explicitly.\n */\n maxResultChars?: number;\n /**\n * Callback fired for every `notifications/progress` frame the server\n * emits during any bridged tool call. Includes the registered\n * (prefix-applied) tool name so a multi-server UI can attribute\n * progress correctly. Absent → no `_meta.progressToken` is sent and\n * the server won't emit progress for these calls.\n */\n onProgress?: (info: {\n toolName: string;\n progress: number;\n total?: number;\n message?: string;\n }) => void;\n}\n\n/**\n * 32,000 chars ≈ 8k English tokens, or ~16k CJK tokens. Small enough to\n * fit comfortably in history even across 5–10 tool calls, large enough\n * that most file reads and directory listings fit un-truncated.\n */\nexport const DEFAULT_MAX_RESULT_CHARS = 32_000;\n\n/**\n * Token-aware cap for tool results, in DeepSeek V3 tokens.\n *\n * 8,000 tokens ≈ 6% of DeepSeek V3's 131K context. One oversized tool\n * result can't eat more than that no matter what character density the\n * content has. The char cap (32K chars) only bounds tokens for English\n * — CJK text at 1 char/token blows past 16K tokens under the same\n * ceiling. With the tokenizer shipped in 0.5.0 we can cap the thing\n * that actually matters.\n */\nexport const DEFAULT_MAX_RESULT_TOKENS = 8_000;\n\nexport interface BridgeResult {\n registry: ToolRegistry;\n /** Names actually registered (may differ from MCP names when a prefix is applied). */\n registeredNames: string[];\n /** Names the server listed but the bridge skipped (e.g. invalid schemas). */\n skipped: Array<{ name: string; reason: string }>;\n}\n\n/**\n * Walk a connected `McpClient`'s tools/list result, register each into a\n * Reasonix `ToolRegistry`. Each registered `fn` proxies through the\n * client's tools/call. Tool results are flattened into a string (joining\n * text blocks with newlines, prefixing image blocks as placeholders) so\n * they fit Reasonix's existing tool-dispatch contract.\n */\nexport async function bridgeMcpTools(\n client: McpClient,\n opts: BridgeOptions = {},\n): Promise<BridgeResult> {\n const registry = opts.registry ?? new ToolRegistry({ autoFlatten: opts.autoFlatten });\n const prefix = opts.namePrefix ?? \"\";\n const maxResultChars = opts.maxResultChars ?? DEFAULT_MAX_RESULT_CHARS;\n const result: BridgeResult = { registry, registeredNames: [], skipped: [] };\n\n const listed = await client.listTools();\n for (const mcpTool of listed.tools) {\n if (!mcpTool.name) {\n result.skipped.push({ name: \"?\", reason: \"empty tool name\" });\n continue;\n }\n const registeredName = `${prefix}${mcpTool.name}`;\n registry.register({\n name: registeredName,\n description: mcpTool.description ?? \"\",\n parameters: mcpTool.inputSchema as JSONSchema,\n fn: async (args: Record<string, unknown>, ctx) => {\n const toolResult = await client.callTool(mcpTool.name, args, {\n // Forward server-side progress frames to the bridge caller,\n // tagged with the registered name so multi-server UIs can\n // disambiguate. No-op when `onProgress` isn't configured —\n // the client then also omits the _meta.progressToken and\n // the server won't emit progress.\n onProgress: opts.onProgress\n ? (info) => opts.onProgress!({ toolName: registeredName, ...info })\n : undefined,\n // Thread the tool-dispatch AbortSignal all the way down to\n // the MCP request so Esc truly cancels in flight — the\n // client will emit notifications/cancelled AND reject the\n // pending promise immediately, no \"wait for subprocess\".\n signal: ctx?.signal,\n });\n return flattenMcpResult(toolResult, { maxChars: maxResultChars });\n },\n });\n result.registeredNames.push(registeredName);\n }\n return result;\n}\n\nexport interface FlattenOptions {\n /** Cap the flattened string at this many characters. Default: no cap. */\n maxChars?: number;\n}\n\n/**\n * Turn an MCP CallToolResult into a string — the contract Reasonix's\n * ToolRegistry.dispatch returns. We:\n * - join text blocks with newlines (most common case)\n * - stringify image blocks as placeholders (LLM can't use bytes anyway\n * in Reasonix's current surface; image support comes with multimodal\n * prompts later)\n * - prefix error results with \"ERROR: \" so the calling model sees the\n * failure clearly even through JSON mode\n * - optionally truncate to `maxChars` so a single oversized tool result\n * (e.g. a big `read_file`) can't poison the session by blowing past\n * the model's context window\n */\nexport function flattenMcpResult(result: CallToolResult, opts: FlattenOptions = {}): string {\n const parts = result.content.map(blockToString);\n const joined = parts.join(\"\\n\").trim();\n const prefixed = result.isError ? `ERROR: ${joined || \"(no error message from server)\"}` : joined;\n return opts.maxChars ? truncateForModel(prefixed, opts.maxChars) : prefixed;\n}\n\n/**\n * Keep the head AND a short tail so the model sees both \"what the tool\n * started returning\" and \"how it ended\". Head-only loses file endings\n * (e.g. an error message appended at the bottom of a stack trace); the\n * 1KB tail window covers that while costing almost nothing. Exported for\n * tests and reuse by non-MCP tool adapters that want the same policy.\n */\nexport function truncateForModel(s: string, maxChars: number): string {\n if (s.length <= maxChars) return s;\n const tailBudget = Math.min(1024, Math.floor(maxChars * 0.1));\n const headBudget = Math.max(0, maxChars - tailBudget);\n const head = s.slice(0, headBudget);\n const tail = s.slice(-tailBudget);\n const dropped = s.length - head.length - tail.length;\n return `${head}\\n\\n[…truncated ${dropped} chars — raise BridgeOptions.maxResultChars, or call the tool with a narrower scope (filter, head, pagination)…]\\n\\n${tail}`;\n}\n\n/**\n * Token-aware truncation. Same head+tail policy as `truncateForModel`,\n * but sizes the slices against a DeepSeek V3 token budget instead of a\n * raw character count — so CJK text (which previously survived at 2×\n * the token cost per char) gets capped at the same effective context\n * footprint as English.\n *\n * Strategy: fast path when `s.length <= maxTokens` (every token is ≥1\n * char, so this bounds tokens ≤ maxTokens — skip tokenize entirely).\n * Short-ish strings are confirmed against the real token count.\n * Long strings go straight to char-sliced head+tail with one or two\n * tokenize-verify-and-shrink rounds per slice — we deliberately never\n * tokenize the full input, because pathological repetitive text\n * (megabytes of `AAAA…`) can cost 30s+ on the pure-TS BPE port.\n */\nexport function truncateForModelByTokens(s: string, maxTokens: number): string {\n if (maxTokens <= 0) return \"\";\n // Every token is ≥1 char — if length ≤ budget, tokens ≤ budget.\n if (s.length <= maxTokens) return s;\n // Small enough to tokenize-check without pathological cost: confirm\n // whether we're actually over budget. (Threshold is the char-bound\n // worst case for English/code — ~4 chars/token.)\n if (s.length <= maxTokens * 4) {\n const tokens = countTokens(s);\n if (tokens <= maxTokens) return s;\n }\n\n const markerOverhead = 48; // rough token cost of the truncation marker\n const contentBudget = Math.max(0, maxTokens - markerOverhead);\n const tailBudget = Math.min(256, Math.floor(contentBudget * 0.1));\n const headBudget = Math.max(0, contentBudget - tailBudget);\n\n const head = sizePrefixToTokens(s, headBudget);\n const tail = sizeSuffixToTokens(s, tailBudget);\n const droppedChars = s.length - head.length - tail.length;\n // Estimate dropped tokens from the per-slice char/token ratio we\n // already measured, rather than paying another full-string tokenize.\n // The marker says \"~N tokens\" so the ≤10% slop is visible to readers.\n const headTokens = head ? countTokens(head) : 0;\n const tailTokens = tail ? countTokens(tail) : 0;\n const sampleChars = head.length + tail.length;\n const sampleTokens = headTokens + tailTokens;\n const ratio = sampleChars > 0 ? sampleTokens / sampleChars : 0.3;\n const estTotalTokens = Math.ceil(s.length * ratio);\n const droppedTokens = Math.max(0, estTotalTokens - sampleTokens);\n return `${head}\\n\\n[…truncated ~${droppedTokens} tokens (${droppedChars} chars) — raise BridgeOptions.maxResultTokens, or call the tool with a narrower scope (filter, head, pagination)…]\\n\\n${tail}`;\n}\n\n/**\n * Slice `s` from the start to the largest prefix that fits `budget`\n * tokens. Never tokenizes the full input: starts with a char-bound\n * estimate, then verifies and shrinks. Converges in 1–2 iterations.\n */\nfunction sizePrefixToTokens(s: string, budget: number): string {\n if (budget <= 0 || s.length === 0) return \"\";\n // Optimistic starting size: assume ~4 chars/token (English/code\n // average). If the content is denser (CJK ~1 char/token), the first\n // tokenize will show we're over and we shrink.\n let size = Math.min(s.length, budget * 4);\n for (let iter = 0; iter < 6; iter++) {\n if (size <= 0) return \"\";\n const slice = s.slice(0, size);\n const count = countTokens(slice);\n if (count <= budget) return slice;\n // Shrink by the overshoot fraction plus a small safety margin.\n const next = Math.floor(size * (budget / count) * 0.95);\n if (next >= size) return s.slice(0, Math.max(0, size - 1));\n size = next;\n }\n return s.slice(0, Math.max(0, size));\n}\n\n/** Slice `s` from the end to the largest suffix that fits `budget` tokens. */\nfunction sizeSuffixToTokens(s: string, budget: number): string {\n if (budget <= 0 || s.length === 0) return \"\";\n let size = Math.min(s.length, budget * 4);\n for (let iter = 0; iter < 6; iter++) {\n if (size <= 0) return \"\";\n const slice = s.slice(-size);\n const count = countTokens(slice);\n if (count <= budget) return slice;\n const next = Math.floor(size * (budget / count) * 0.95);\n if (next >= size) return s.slice(-Math.max(0, size - 1));\n size = next;\n }\n return s.slice(-Math.max(0, size));\n}\n\nfunction blockToString(block: McpContentBlock): string {\n if (block.type === \"text\") return block.text;\n if (block.type === \"image\") return `[image ${block.mimeType}, ${block.data.length} chars base64]`;\n // Unknown block type — preserve for diagnostics.\n return `[unknown block: ${JSON.stringify(block)}]`;\n}\n","import { createHash } from \"node:crypto\";\nimport type { ChatMessage, ToolSpec } from \"./types.js\";\n\nexport interface ImmutablePrefixOptions {\n system: string;\n toolSpecs?: readonly ToolSpec[];\n fewShots?: readonly ChatMessage[];\n}\n\nexport class ImmutablePrefix {\n readonly system: string;\n readonly toolSpecs: readonly ToolSpec[];\n readonly fewShots: readonly ChatMessage[];\n\n constructor(opts: ImmutablePrefixOptions) {\n this.system = opts.system;\n this.toolSpecs = Object.freeze([...(opts.toolSpecs ?? [])]);\n this.fewShots = Object.freeze([...(opts.fewShots ?? [])]);\n }\n\n toMessages(): ChatMessage[] {\n return [{ role: \"system\", content: this.system }, ...this.fewShots.map((m) => ({ ...m }))];\n }\n\n tools(): ToolSpec[] {\n return this.toolSpecs.map((t) => structuredClone(t) as ToolSpec);\n }\n\n get fingerprint(): string {\n const blob = JSON.stringify({\n system: this.system,\n tools: this.toolSpecs,\n shots: this.fewShots,\n });\n return createHash(\"sha256\").update(blob).digest(\"hex\").slice(0, 16);\n }\n}\n\nexport class AppendOnlyLog {\n private _entries: ChatMessage[] = [];\n\n append(message: ChatMessage): void {\n if (!message || typeof message !== \"object\" || !(\"role\" in message)) {\n throw new Error(`invalid log entry: ${JSON.stringify(message)}`);\n }\n this._entries.push(message);\n }\n\n extend(messages: ChatMessage[]): void {\n for (const m of messages) this.append(m);\n }\n\n /**\n * Bulk-replace entries. Intentionally named to be hard to reach for —\n * this is the one mutation path that breaks the log's append-only\n * spirit, reserved for compaction flows (`/compact`) and recovery\n * where the caller has consciously decided to drop old history. Any\n * other use is almost certainly wrong; append() is what you want.\n */\n compactInPlace(replacement: ChatMessage[]): void {\n this._entries = [...replacement];\n }\n\n get entries(): readonly ChatMessage[] {\n return this._entries;\n }\n\n toMessages(): ChatMessage[] {\n return this._entries.map((e) => ({ ...e }));\n }\n\n get length(): number {\n return this._entries.length;\n }\n}\n\nexport class VolatileScratch {\n reasoning: string | null = null;\n planState: Record<string, unknown> | null = null;\n notes: string[] = [];\n\n reset(): void {\n this.reasoning = null;\n this.planState = null;\n this.notes = [];\n }\n}\n","/**\n * Scavenge tool calls leaked into reasoning_content.\n *\n * R1 sometimes emits tool-call JSON inside <think>…</think> and then forgets\n * to surface it in `tool_calls`. This pass extracts plausible calls and\n * proposes them to the loop, which decides whether to merge them with the\n * declared calls.\n */\n\nimport type { ToolCall } from \"../types.js\";\n\nexport interface ScavengeOptions {\n /** Names of tools the model may legitimately call. Other names are ignored. */\n allowedNames: ReadonlySet<string>;\n /** Maximum number of calls to scavenge per pass (defence against runaway). */\n maxCalls?: number;\n}\n\nexport interface ScavengeResult {\n calls: ToolCall[];\n notes: string[];\n}\n\nexport function scavengeToolCalls(\n reasoningContent: string | null | undefined,\n opts: ScavengeOptions,\n): ScavengeResult {\n if (!reasoningContent) return { calls: [], notes: [] };\n const max = opts.maxCalls ?? 4;\n const notes: string[] = [];\n const out: ToolCall[] = [];\n\n // Pattern A: DSML invoke blocks. R1 sometimes emits tool calls as\n // its chat-template markup in the content channel instead of the\n // proper `tool_calls` field. 0.4.3 stripped these from display;\n // here we actually turn them back into proper ToolCalls so the\n // model's intent isn't lost.\n for (const invoke of iterateDsmlInvokes(reasoningContent)) {\n if (out.length >= max) break;\n if (!opts.allowedNames.has(invoke.name)) continue;\n out.push({\n function: {\n name: invoke.name,\n arguments: JSON.stringify(invoke.args),\n },\n });\n notes.push(`scavenged DSML call: ${invoke.name}`);\n }\n\n // Pattern B: raw JSON objects (the original three shapes). Strip\n // any DSML blocks we already processed so parameter JSON buried\n // inside them doesn't get re-scavenged as a standalone call.\n const nonDsml = stripDsmlBlocks(reasoningContent);\n for (const candidate of iterateJsonObjects(nonDsml)) {\n if (out.length >= max) break;\n const call = coerceToToolCall(candidate, opts.allowedNames);\n if (call) {\n out.push(call);\n notes.push(`scavenged call: ${call.function.name}`);\n }\n }\n return { calls: out, notes };\n}\n\ninterface DsmlInvoke {\n name: string;\n args: Record<string, unknown>;\n}\n\n/**\n * Yield DeepSeek DSML invoke blocks scavenged from text. R1's chat\n * template uses these when the server-side tool-call serializer\n * misfires — we see them verbatim in the content channel:\n *\n * <|DSML|function_calls>\n * <|DSML|invoke name=\"filesystem_edit_file\">\n * <|DSML|parameter name=\"path\" string=\"true\">F:/x.html</|DSML|parameter>\n * <|DSML|parameter name=\"edits\" string=\"false\">[…]</|DSML|parameter>\n * </|DSML|invoke>\n * </|DSML|function_calls>\n *\n * The wrapper class (| U+FF5C vs ASCII |) varies by model build, so\n * we accept both. `string=\"true\"` means the parameter value is a\n * literal string; `string=\"false\"` means it's JSON.\n */\n/**\n * Remove DSML invoke/function_calls blocks from text so the raw-JSON\n * scanner below doesn't see parameter payloads as standalone calls.\n * Mirrors the strip pass in `stripHallucinatedToolMarkup` but scoped\n * to scavenge (we also want the `function_calls` wrapper gone —\n * nothing useful to scavenge there).\n */\nfunction stripDsmlBlocks(text: string): string {\n let out = text;\n out = out.replace(/<[||]DSML[||]function_calls>[\\s\\S]*?<\\/?[||]DSML[||]function_calls>/g, \"\");\n out = out.replace(/<[||]DSML[||]invoke\\s+[^>]*>[\\s\\S]*?<\\/[||]DSML[||]invoke>/g, \"\");\n return out;\n}\n\nfunction* iterateDsmlInvokes(text: string): Generator<DsmlInvoke> {\n // `|` (U+FF5C) in practice; `|` (ASCII) as a fallback seen in a\n // minority of builds. `[||]` inside the regex covers both.\n const INVOKE_RE = /<[||]DSML[||]invoke\\s+name=\"([^\"]+)\">([\\s\\S]*?)<\\/[||]DSML[||]invoke>/g;\n for (const match of text.matchAll(INVOKE_RE)) {\n const name = match[1];\n const body = match[2];\n if (!name || body === undefined) continue;\n yield { name, args: parseDsmlParameters(body) };\n }\n}\n\n/**\n * Parse the parameter children of a DSML invoke body into a plain\n * object. We tolerate:\n * - `string=\"true\"` → literal text; whitespace trimmed at the edges.\n * - `string=\"false\"` → JSON-parsed; falls back to literal text if the\n * payload turns out to be malformed (better to hand a string\n * through than lose the parameter entirely).\n * - no `string=\"…\"` attribute → treat as literal text (older/shorter\n * DSML shapes we haven't formally seen but want to handle).\n */\nfunction parseDsmlParameters(body: string): Record<string, unknown> {\n const PARAM_RE =\n /<[||]DSML[||]parameter\\s+name=\"([^\"]+)\"(?:\\s+string=\"(true|false)\")?\\s*>([\\s\\S]*?)<\\/[||]DSML[||]parameter>/g;\n const args: Record<string, unknown> = {};\n for (const m of body.matchAll(PARAM_RE)) {\n const key = m[1];\n const stringFlag = m[2];\n const raw = (m[3] ?? \"\").trim();\n if (!key) continue;\n if (stringFlag === \"false\") {\n try {\n args[key] = JSON.parse(raw);\n continue;\n } catch {\n // Fall through — keep as literal so the information isn't lost.\n }\n }\n args[key] = raw;\n }\n return args;\n}\n\n/** Yield every top-level JSON object substring in `text`. */\nfunction* iterateJsonObjects(text: string): Generator<string> {\n for (let i = 0; i < text.length; i++) {\n if (text[i] !== \"{\") continue;\n let depth = 0;\n let inString = false;\n let escaped = false;\n for (let j = i; j < text.length; j++) {\n const c = text[j]!;\n if (escaped) {\n escaped = false;\n continue;\n }\n if (inString) {\n if (c === \"\\\\\") {\n escaped = true;\n continue;\n }\n if (c === '\"') inString = false;\n continue;\n }\n if (c === '\"') inString = true;\n else if (c === \"{\") depth++;\n else if (c === \"}\") {\n depth--;\n if (depth === 0) {\n yield text.slice(i, j + 1);\n i = j;\n break;\n }\n }\n }\n }\n}\n\nfunction coerceToToolCall(\n candidateJson: string,\n allowedNames: ReadonlySet<string>,\n): ToolCall | null {\n let parsed: any;\n try {\n parsed = JSON.parse(candidateJson);\n } catch {\n return null;\n }\n if (!parsed || typeof parsed !== \"object\") return null;\n\n // Pattern 1: { name, arguments }\n if (typeof parsed.name === \"string\" && allowedNames.has(parsed.name)) {\n const args = parsed.arguments;\n return {\n function: {\n name: parsed.name,\n arguments: typeof args === \"string\" ? args : JSON.stringify(args ?? {}),\n },\n };\n }\n\n // Pattern 2: OpenAI-style { type: \"function\", function: { name, arguments } }\n if (\n parsed.type === \"function\" &&\n parsed.function &&\n typeof parsed.function.name === \"string\" &&\n allowedNames.has(parsed.function.name)\n ) {\n const args = parsed.function.arguments;\n return {\n type: \"function\",\n function: {\n name: parsed.function.name,\n arguments: typeof args === \"string\" ? args : JSON.stringify(args ?? {}),\n },\n };\n }\n\n // Pattern 3: { tool_name, tool_args } (R1 free-form variant)\n if (typeof parsed.tool_name === \"string\" && allowedNames.has(parsed.tool_name)) {\n return {\n function: {\n name: parsed.tool_name,\n arguments: JSON.stringify(parsed.tool_args ?? {}),\n },\n };\n }\n\n return null;\n}\n","import type { ToolCall } from \"../types.js\";\n\n/**\n * Call-storm breaker.\n *\n * Detects (tool, args) tuples repeating within a sliding window and suppresses\n * the offending call. Surfaces a synthetic tool_result advising the model to\n * change strategy on its next turn.\n */\nexport class StormBreaker {\n private readonly windowSize: number;\n private readonly threshold: number;\n private readonly recent: Array<readonly [string, string]> = [];\n\n constructor(windowSize = 6, threshold = 3) {\n this.windowSize = windowSize;\n this.threshold = threshold;\n }\n\n inspect(call: ToolCall): { suppress: boolean; reason?: string } {\n const sig = signature(call);\n if (!sig) return { suppress: false };\n const count = this.recent.reduce(\n (n, [name, args]) => (name === sig[0] && args === sig[1] ? n + 1 : n),\n 0,\n );\n if (count >= this.threshold - 1) {\n return {\n suppress: true,\n reason: `call-storm suppressed: ${sig[0]} called with identical args ${count + 1} times within window=${this.windowSize}`,\n };\n }\n this.recent.push(sig);\n while (this.recent.length > this.windowSize) this.recent.shift();\n return { suppress: false };\n }\n\n reset(): void {\n this.recent.length = 0;\n }\n}\n\nfunction signature(call: ToolCall): readonly [string, string] | null {\n const name = call.function?.name;\n if (!name) return null;\n return [name, call.function?.arguments ?? \"\"] as const;\n}\n","/**\n * Truncation recovery for tool-call argument JSON cut off mid-structure\n * (typically when the model hits max_tokens before finishing the JSON object).\n *\n * Strategy is purely local: balance braces, close strings, fill missing values\n * with `null`. We deliberately do NOT make a continuation API call here — that\n * decision belongs to the loop, which knows about budgets.\n */\n\nexport interface TruncationRepairResult {\n repaired: string;\n changed: boolean;\n notes: string[];\n}\n\nexport function repairTruncatedJson(input: string): TruncationRepairResult {\n const notes: string[] = [];\n if (!input || !input.trim()) {\n return { repaired: \"{}\", changed: input !== \"{}\", notes: [\"empty input → {}\"] };\n }\n // Fast path: already parseable.\n try {\n JSON.parse(input);\n return { repaired: input, changed: false, notes: [] };\n } catch {\n /* fall through */\n }\n\n const stack: (\"{\" | \"[\" | '\"')[] = [];\n let escaped = false;\n let inString = false;\n let lastSignificant = -1;\n\n for (let i = 0; i < input.length; i++) {\n const c = input[i]!;\n if (!/\\s/.test(c)) lastSignificant = i;\n if (escaped) {\n escaped = false;\n continue;\n }\n if (inString) {\n if (c === \"\\\\\") {\n escaped = true;\n continue;\n }\n if (c === '\"') {\n inString = false;\n stack.pop();\n }\n continue;\n }\n if (c === '\"') {\n inString = true;\n stack.push('\"');\n continue;\n }\n if (c === \"{\" || c === \"[\") stack.push(c);\n else if (c === \"}\" || c === \"]\") stack.pop();\n }\n\n let s = input.slice(0, lastSignificant + 1);\n\n // Trim a trailing comma which would block re-parse.\n if (/,$/.test(s)) {\n s = s.replace(/,$/, \"\");\n notes.push(\"trimmed trailing comma\");\n }\n\n // If we ended on a key without a value: \"foo\": → \"foo\": null\n if (/\"\\s*:\\s*$/.test(s)) {\n s += \" null\";\n notes.push(\"filled dangling key with null\");\n }\n\n // If we ended inside a string, close it.\n if (inString) {\n s += '\"';\n stack.pop();\n notes.push(\"closed unterminated string\");\n }\n\n // Pop remaining open structures in reverse order.\n while (stack.length > 0) {\n const top = stack.pop();\n if (top === \"{\") s += \"}\";\n else if (top === \"[\") s += \"]\";\n else if (top === '\"') s += '\"';\n }\n\n try {\n JSON.parse(s);\n return { repaired: s, changed: true, notes };\n } catch (err) {\n notes.push(`fallback to {}: ${(err as Error).message}`);\n return { repaired: \"{}\", changed: true, notes };\n }\n}\n","/**\n * Pillar 3 — Tool-Call Repair pipeline.\n *\n * Order of passes per turn:\n * 1. scavenge — recover tool calls leaked into <think>\n * 2. truncation — close any half-emitted argument JSON\n * 3. storm breaker — drop call-storm repeats\n *\n * Schema flattening is applied during loop construction (it changes what we\n * advertise to the model), not per-turn.\n */\n\nimport type { ToolCall } from \"../types.js\";\nimport { scavengeToolCalls } from \"./scavenge.js\";\nimport { StormBreaker } from \"./storm.js\";\nimport { repairTruncatedJson } from \"./truncation.js\";\n\nexport { analyzeSchema, flattenSchema, nestArguments } from \"./flatten.js\";\nexport type { FlattenDecision } from \"./flatten.js\";\nexport { repairTruncatedJson } from \"./truncation.js\";\nexport type { TruncationRepairResult } from \"./truncation.js\";\nexport { scavengeToolCalls } from \"./scavenge.js\";\nexport type { ScavengeOptions, ScavengeResult } from \"./scavenge.js\";\nexport { StormBreaker } from \"./storm.js\";\n\nexport interface RepairReport {\n scavenged: number;\n truncationsFixed: number;\n stormsBroken: number;\n notes: string[];\n}\n\nexport interface ToolCallRepairOptions {\n allowedToolNames: ReadonlySet<string>;\n stormWindow?: number;\n stormThreshold?: number;\n maxScavenge?: number;\n}\n\nexport class ToolCallRepair {\n private readonly storm: StormBreaker;\n private readonly opts: ToolCallRepairOptions;\n\n constructor(opts: ToolCallRepairOptions) {\n this.opts = opts;\n this.storm = new StormBreaker(opts.stormWindow ?? 6, opts.stormThreshold ?? 3);\n }\n\n /**\n * Drop the StormBreaker's sliding window of recent (name, args)\n * signatures. Called at the start of every user turn — a fresh user\n * message is a new intent, so carrying old repetition state into it\n * would turn a valid \"try again with different input\" flow into a\n * false-positive block.\n */\n resetStorm(): void {\n this.storm.reset();\n }\n\n process(\n declaredCalls: ToolCall[],\n reasoningContent: string | null,\n content: string | null = null,\n ): { calls: ToolCall[]; report: RepairReport } {\n const report: RepairReport = {\n scavenged: 0,\n truncationsFixed: 0,\n stormsBroken: 0,\n notes: [],\n };\n\n // 1. Scavenge — only add calls whose (name,args) signature is novel.\n // Scan both channels: reasoning (where R1 leaks JSON calls into\n // <think>) AND content (where it emits DSML markup in regular\n // turns). Joined with a newline so the scanners see the blobs as\n // independent bodies. Dedup below keeps us from inflating if the\n // same call shows up in both — first seen wins.\n const combined = [reasoningContent ?? \"\", content ?? \"\"].filter(Boolean).join(\"\\n\");\n const scavenged = scavengeToolCalls(combined || null, {\n allowedNames: this.opts.allowedToolNames,\n maxCalls: this.opts.maxScavenge ?? 4,\n });\n const seenSignatures = new Set(declaredCalls.map(signature));\n const merged = [...declaredCalls];\n for (const sc of scavenged.calls) {\n if (!seenSignatures.has(signature(sc))) {\n merged.push(sc);\n report.scavenged++;\n seenSignatures.add(signature(sc));\n }\n }\n report.notes.push(...scavenged.notes);\n\n // 2. Truncation repair on argument JSON.\n for (const call of merged) {\n const args = call.function?.arguments ?? \"\";\n const r = repairTruncatedJson(args);\n if (r.changed) {\n call.function.arguments = r.repaired;\n report.truncationsFixed++;\n report.notes.push(...r.notes.map((n) => `[${call.function.name}] ${n}`));\n }\n }\n\n // 3. Storm breaker.\n const filtered: ToolCall[] = [];\n for (const call of merged) {\n const verdict = this.storm.inspect(call);\n if (verdict.suppress) {\n report.stormsBroken++;\n if (verdict.reason) report.notes.push(verdict.reason);\n continue;\n }\n filtered.push(call);\n }\n\n return { calls: filtered, report };\n }\n}\n\nfunction signature(call: ToolCall): string {\n return `${call.function?.name ?? \"\"}::${call.function?.arguments ?? \"\"}`;\n}\n","/**\n * Session persistence.\n *\n * Every turn's log entries (user / assistant / tool messages) are appended to\n * a JSONL file under `~/.reasonix/sessions/<name>.jsonl`. Next time the user\n * starts the CLI with the same session name, the loop pre-loads the file\n * into its AppendOnlyLog so the new turn has full prior context.\n *\n * Design notes:\n * - JSONL rather than JSON so concurrent writes don't corrupt.\n * - 0600 permissions on Unix (chmod no-ops on Windows).\n * - Name sanitization keeps paths safe: only [\\w-] and CJK letters pass;\n * anything else is replaced with underscore, max 64 chars.\n * - The loop's stats/session aren't persisted — only the message log.\n * Cost accounting resets each run (by design — old costs are sunk).\n */\n\nimport {\n appendFileSync,\n chmodSync,\n existsSync,\n mkdirSync,\n readFileSync,\n readdirSync,\n statSync,\n unlinkSync,\n writeFileSync,\n} from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport type { ChatMessage } from \"./types.js\";\n\nexport interface SessionInfo {\n name: string;\n path: string;\n size: number;\n messageCount: number;\n mtime: Date;\n}\n\nexport function sessionsDir(): string {\n return join(homedir(), \".reasonix\", \"sessions\");\n}\n\nexport function sessionPath(name: string): string {\n return join(sessionsDir(), `${sanitizeName(name)}.jsonl`);\n}\n\nexport function sanitizeName(name: string): string {\n const cleaned = name.replace(/[^\\w\\-\\u4e00-\\u9fa5]/g, \"_\").slice(0, 64);\n return cleaned || \"default\";\n}\n\nexport function loadSessionMessages(name: string): ChatMessage[] {\n const path = sessionPath(name);\n if (!existsSync(path)) return [];\n try {\n const raw = readFileSync(path, \"utf8\");\n const out: ChatMessage[] = [];\n for (const line of raw.split(/\\r?\\n/)) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n try {\n const msg = JSON.parse(trimmed) as ChatMessage;\n if (msg && typeof msg === \"object\" && \"role\" in msg) out.push(msg);\n } catch {\n /* skip malformed line */\n }\n }\n return out;\n } catch {\n return [];\n }\n}\n\nexport function appendSessionMessage(name: string, message: ChatMessage): void {\n const path = sessionPath(name);\n mkdirSync(dirname(path), { recursive: true });\n appendFileSync(path, `${JSON.stringify(message)}\\n`, \"utf8\");\n try {\n chmodSync(path, 0o600);\n } catch {\n /* chmod not supported on this platform */\n }\n}\n\nexport function listSessions(): SessionInfo[] {\n const dir = sessionsDir();\n if (!existsSync(dir)) return [];\n try {\n const files = readdirSync(dir).filter((f) => f.endsWith(\".jsonl\"));\n return files\n .map((file) => {\n const path = join(dir, file);\n const stat = statSync(path);\n const name = file.replace(/\\.jsonl$/, \"\");\n const messageCount = countLines(path);\n return { name, path, size: stat.size, messageCount, mtime: stat.mtime };\n })\n .sort((a, b) => b.mtime.getTime() - a.mtime.getTime());\n } catch {\n return [];\n }\n}\n\nexport function deleteSession(name: string): boolean {\n const path = sessionPath(name);\n try {\n unlinkSync(path);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Overwrite the session file with a fresh message list. Used by\n * `/compact` so the compacted in-memory log persists across restarts\n * instead of being re-healed from a huge on-disk file every launch.\n * We accept the brief non-atomic window between truncate and write —\n * worst case: a concurrent crash loses the session, which is what\n * `/forget` would have done anyway.\n */\nexport function rewriteSession(name: string, messages: ChatMessage[]): void {\n const path = sessionPath(name);\n mkdirSync(dirname(path), { recursive: true });\n const body = messages.map((m) => JSON.stringify(m)).join(\"\\n\");\n writeFileSync(path, body ? `${body}\\n` : \"\", \"utf8\");\n try {\n chmodSync(path, 0o600);\n } catch {\n /* chmod not supported */\n }\n}\n\nfunction countLines(path: string): number {\n try {\n const raw = readFileSync(path, \"utf8\");\n return raw.split(/\\r?\\n/).filter((l) => l.trim()).length;\n } catch {\n return 0;\n }\n}\n","import type { Usage } from \"./client.js\";\n\n/**\n * USD per 1M tokens. Source of truth is DeepSeek's CNY price sheet at\n * https://api-docs.deepseek.com/zh-cn/quick_start/pricing (as of\n * 2026-04-23): chat and reasoner are unified at ¥0.2 / ¥2 / ¥3 per 1M\n * tokens (cache-hit input / cache-miss input / output). Converted at\n * a fixed 7.2 CNY/USD rate so stats stay stable across the daily FX\n * drift; revisit if the rate moves more than ±5%.\n *\n * Historical note: the pre-unification prices were chat $0.07/$0.27/$1.10\n * and reasoner $0.14/$0.55/$2.19. Sessions logged under those values\n * in `~/.reasonix/usage.jsonl` remain as-is (USD frozen at record time)\n * — we never retroactively rewrite billing history.\n */\nexport const DEEPSEEK_PRICING: Record<\n string,\n { inputCacheHit: number; inputCacheMiss: number; output: number }\n> = {\n \"deepseek-chat\": { inputCacheHit: 0.028, inputCacheMiss: 0.28, output: 0.42 },\n \"deepseek-reasoner\": { inputCacheHit: 0.028, inputCacheMiss: 0.28, output: 0.42 },\n};\n\n/** Reference Claude Sonnet 4.6 pricing (USD per 1M tokens). */\nexport const CLAUDE_SONNET_PRICING = { input: 3.0, output: 15.0 };\n\n/**\n * Maximum prompt-side context window per DeepSeek model, in tokens.\n * Both V3 (`deepseek-chat`) and R1 (`deepseek-reasoner`) currently expose\n * a 131,072-token prompt limit per the OpenAPI spec; completion caps\n * differ but don't affect the prompt budget the StatsPanel shows.\n */\nexport const DEEPSEEK_CONTEXT_TOKENS: Record<string, number> = {\n \"deepseek-chat\": 131_072,\n \"deepseek-reasoner\": 131_072,\n};\n\n/** Fallback when the caller's model id isn't in the table — safe lower bound. */\nexport const DEFAULT_CONTEXT_TOKENS = 131_072;\n\nexport function costUsd(model: string, usage: Usage): number {\n const p = DEEPSEEK_PRICING[model];\n if (!p) return 0;\n return (\n (usage.promptCacheHitTokens * p.inputCacheHit +\n usage.promptCacheMissTokens * p.inputCacheMiss +\n usage.completionTokens * p.output) /\n 1_000_000\n );\n}\n\n/** Input-side cost only (prompt, cache hit + miss). Used for the panel breakdown. */\nexport function inputCostUsd(model: string, usage: Usage): number {\n const p = DEEPSEEK_PRICING[model];\n if (!p) return 0;\n return (\n (usage.promptCacheHitTokens * p.inputCacheHit +\n usage.promptCacheMissTokens * p.inputCacheMiss) /\n 1_000_000\n );\n}\n\n/** Output-side cost only (completion tokens). Used for the panel breakdown. */\nexport function outputCostUsd(model: string, usage: Usage): number {\n const p = DEEPSEEK_PRICING[model];\n if (!p) return 0;\n return (usage.completionTokens * p.output) / 1_000_000;\n}\n\nexport function claudeEquivalentCost(usage: Usage): number {\n return (\n (usage.promptTokens * CLAUDE_SONNET_PRICING.input +\n usage.completionTokens * CLAUDE_SONNET_PRICING.output) /\n 1_000_000\n );\n}\n\nexport interface TurnStats {\n turn: number;\n model: string;\n usage: Usage;\n cost: number;\n cacheHitRatio: number;\n}\n\nexport interface SessionSummary {\n turns: number;\n totalCostUsd: number;\n /**\n * Input-side (prompt) cost aggregated across the session. Split\n * from totalCostUsd so the panel can render \"cost $X (in $Y · out\n * $Z)\" — users asked for visibility into where the spend lands.\n */\n totalInputCostUsd: number;\n /** Output-side (completion) cost aggregated across the session. */\n totalOutputCostUsd: number;\n /** @deprecated Claude reference; kept for benchmarks + replay compat, no longer surfaced in the TUI. */\n claudeEquivalentUsd: number;\n /** @deprecated. Same as claudeEquivalentUsd — synthetic ratio, not a real measurement. */\n savingsVsClaudePct: number;\n cacheHitRatio: number;\n /**\n * Most recent turn's prompt-token count. Used by the TUI's context\n * gauge: we can't know the next call's cost without making it, but\n * the last turn's prompt tokens is the floor (next call is last\n * prompt + user delta + any new tool outputs).\n */\n lastPromptTokens: number;\n}\n\nexport class SessionStats {\n readonly turns: TurnStats[] = [];\n\n record(turn: number, model: string, usage: Usage): TurnStats {\n const cost = costUsd(model, usage);\n const stats: TurnStats = {\n turn,\n model,\n usage,\n cost,\n cacheHitRatio: usage.cacheHitRatio,\n };\n this.turns.push(stats);\n return stats;\n }\n\n get totalCost(): number {\n return this.turns.reduce((sum, t) => sum + t.cost, 0);\n }\n\n get totalClaudeEquivalent(): number {\n return this.turns.reduce((sum, t) => sum + claudeEquivalentCost(t.usage), 0);\n }\n\n get savingsVsClaude(): number {\n const c = this.totalClaudeEquivalent;\n return c > 0 ? 1 - this.totalCost / c : 0;\n }\n\n get totalInputCost(): number {\n return this.turns.reduce((sum, t) => sum + inputCostUsd(t.model, t.usage), 0);\n }\n\n get totalOutputCost(): number {\n return this.turns.reduce((sum, t) => sum + outputCostUsd(t.model, t.usage), 0);\n }\n\n get aggregateCacheHitRatio(): number {\n let hit = 0;\n let miss = 0;\n for (const t of this.turns) {\n hit += t.usage.promptCacheHitTokens;\n miss += t.usage.promptCacheMissTokens;\n }\n const denom = hit + miss;\n return denom > 0 ? hit / denom : 0;\n }\n\n summary(): SessionSummary {\n const last = this.turns[this.turns.length - 1];\n return {\n turns: this.turns.length,\n totalCostUsd: round(this.totalCost, 6),\n totalInputCostUsd: round(this.totalInputCost, 6),\n totalOutputCostUsd: round(this.totalOutputCost, 6),\n claudeEquivalentUsd: round(this.totalClaudeEquivalent, 6),\n savingsVsClaudePct: round(this.savingsVsClaude * 100, 2),\n cacheHitRatio: round(this.aggregateCacheHitRatio, 4),\n lastPromptTokens: last?.usage.promptTokens ?? 0,\n };\n }\n}\n\nfunction round(n: number, digits: number): number {\n const f = 10 ** digits;\n return Math.round(n * f) / f;\n}\n","import { type DeepSeekClient, Usage } from \"./client.js\";\nimport {\n type BranchOptions,\n type BranchSample,\n aggregateBranchUsage,\n runBranches,\n} from \"./consistency.js\";\nimport { type HarvestOptions, type TypedPlanState, emptyPlanState, harvest } from \"./harvest.js\";\nimport {\n type HookOutcome,\n type HookPayload,\n type ResolvedHook,\n formatHookOutcomeMessage,\n runHooks,\n} from \"./hooks.js\";\nimport {\n DEFAULT_MAX_RESULT_CHARS,\n DEFAULT_MAX_RESULT_TOKENS,\n truncateForModel,\n truncateForModelByTokens,\n} from \"./mcp/registry.js\";\nimport { AppendOnlyLog, type ImmutablePrefix, VolatileScratch } from \"./memory.js\";\nimport { type RepairReport, ToolCallRepair } from \"./repair/index.js\";\nimport { appendSessionMessage, loadSessionMessages, rewriteSession } from \"./session.js\";\nimport {\n DEEPSEEK_CONTEXT_TOKENS,\n DEFAULT_CONTEXT_TOKENS,\n SessionStats,\n type TurnStats,\n} from \"./telemetry.js\";\nimport { countTokens, estimateRequestTokens } from \"./tokenizer.js\";\nimport { ToolRegistry } from \"./tools.js\";\nimport type { ChatMessage, ToolCall } from \"./types.js\";\n\nexport type EventRole =\n | \"assistant_delta\"\n | \"assistant_final\"\n /**\n * Emitted as `tool_calls[].function.arguments` streams in. A tool\n * call with a large arguments payload produces no `content` or\n * `reasoning_content` bytes — this is the only signal the UI has\n * that the stream is alive during that window.\n */\n | \"tool_call_delta\"\n /**\n * Yielded immediately before a tool is dispatched. Lets the TUI put\n * up a \"▸ tool<X> running…\" spinner while the tool's Promise is\n * pending — otherwise the UI looks frozen whenever a tool call\n * takes more than a few hundred ms (a big `filesystem_edit_file`\n * is a typical trigger).\n */\n | \"tool_start\"\n | \"tool\"\n | \"done\"\n | \"error\"\n | \"warning\"\n /**\n * Transient \"what's happening right now\" indicator. Emitted during\n * silent phases — between a tool result and the next iteration's\n * first streaming byte, and right before harvest — so the TUI can\n * show a spinner with explanatory text instead of looking frozen.\n * The UI clears it on the next primary event (assistant_delta,\n * tool_start, tool, assistant_final, error).\n */\n | \"status\"\n | \"branch_start\"\n | \"branch_progress\"\n | \"branch_done\";\n\nexport interface BranchSummary {\n budget: number;\n chosenIndex: number;\n uncertainties: number[]; // per-sample uncertainty counts\n temperatures: number[];\n}\n\nexport interface BranchProgress {\n completed: number;\n total: number;\n latestIndex: number;\n latestTemperature: number;\n latestUncertainties: number;\n}\n\nexport interface LoopEvent {\n turn: number;\n role: EventRole;\n content: string;\n reasoningDelta?: string;\n toolName?: string;\n /**\n * Raw JSON-string arguments the model sent for a tool call (role === \"tool\").\n * Populated so transcripts can persist *why* a tool was called, not just\n * what it returned. Needed by `reasonix diff` to explain divergences.\n */\n toolArgs?: string;\n /** Cumulative arguments-string length for `role === \"tool_call_delta\"`. */\n toolCallArgsChars?: number;\n stats?: TurnStats;\n planState?: TypedPlanState;\n repair?: RepairReport;\n branch?: BranchSummary;\n branchProgress?: BranchProgress;\n error?: string;\n /**\n * True on `assistant_final` events emitted by the no-tools fallback\n * when the loop hit its budget, was aborted, or tripped the\n * token-context guard. Consumers that act on assistant text (notably\n * the code-mode edit applier) MUST treat these as display-only —\n * the model is \"wrapping up,\" not proposing new work. Applying\n * SEARCH/REPLACE blocks found in a forced summary caused the\n * \"analysis became edits\" bug in v0.4.1 and earlier.\n */\n forcedSummary?: boolean;\n}\n\nexport interface CacheFirstLoopOptions {\n client: DeepSeekClient;\n prefix: ImmutablePrefix;\n tools?: ToolRegistry;\n model?: string;\n maxToolIters?: number;\n stream?: boolean;\n /**\n * Pillar 2 — structured harvesting of R1 reasoning into a typed plan state.\n * Pass `true` for defaults or an options object. Off by default (adds a\n * cheap but non-zero V3 call per turn).\n */\n harvest?: boolean | HarvestOptions;\n /**\n * Self-consistency branching. Pass a number for just a budget (e.g. 3) or\n * a full `BranchOptions` object. Disables streaming for the branched turn\n * because all samples must complete before selection. Auto-enables harvest\n * since the default selector scores samples by plan-state uncertainty.\n */\n branch?: number | BranchOptions;\n /**\n * Session name. When set, the loop pre-loads the session's prior messages\n * into its log on construction, and appends every new log entry to\n * `~/.reasonix/sessions/<name>.jsonl` so the next run can resume.\n */\n session?: string;\n /**\n * Resolved hook list — loaded from `<project>/.reasonix/settings.json`\n * + `~/.reasonix/settings.json` by the CLI before constructing the loop.\n * The loop dispatches `PreToolUse` and `PostToolUse` events itself; the\n * CLI handles `UserPromptSubmit` and `Stop` since they live at the App\n * boundary. Empty / unset → no hooks fire (the runtime cost of an empty\n * filter is one ms). See `src/hooks.ts` for the full contract.\n */\n hooks?: ResolvedHook[];\n /**\n * `cwd` reported to hooks via the stdin payload. Defaults to `process.cwd()`.\n * `reasonix code` overrides this to the sandbox root so a hook that does\n * `cd $REASONIX_CWD` lands in the project, not in the user's shell home.\n */\n hookCwd?: string;\n}\n\n/**\n * Pillar 1 — Cache-First Loop.\n *\n * - prefix is immutable (cache target)\n * - log is append-only (preserves prior-turn prefix)\n * - scratch is per-turn volatile (never sent upstream)\n *\n * Yields a stream of events so a TUI can render progressively.\n */\nexport interface ReconfigurableOptions {\n model?: string;\n harvest?: boolean | HarvestOptions;\n branch?: number | BranchOptions;\n stream?: boolean;\n}\n\nexport class CacheFirstLoop {\n readonly client: DeepSeekClient;\n readonly prefix: ImmutablePrefix;\n readonly tools: ToolRegistry;\n readonly maxToolIters: number;\n readonly log = new AppendOnlyLog();\n readonly scratch = new VolatileScratch();\n readonly stats = new SessionStats();\n readonly repair: ToolCallRepair;\n\n // Mutable via configure() — slash commands in the TUI / library callers tweak\n // these mid-session so users don't have to restart to try harvest or branch.\n model: string;\n stream: boolean;\n harvestEnabled: boolean;\n harvestOptions: HarvestOptions;\n branchEnabled: boolean;\n branchOptions: BranchOptions;\n sessionName: string | null;\n\n /**\n * Hook list, mutable so `/hooks reload` can swap it without\n * reconstructing the loop. Default empty — the filter cost on a\n * tool call is one array length check.\n */\n hooks: ResolvedHook[];\n /** `cwd` reported to hook stdin. Resolved once at construction. */\n readonly hookCwd: string;\n\n /** Number of messages that were pre-loaded from the session file. */\n readonly resumedMessageCount: number;\n\n private _turn = 0;\n private _streamPreference: boolean;\n /**\n * AbortController per active turn. Threaded through the DeepSeek\n * HTTP calls AND every tool dispatch so Esc actually cancels the\n * in-flight network/subprocess work — not \"we'll get to it after\n * the current call finishes.\" Re-created at the start of each\n * `step()` (the prior turn's signal has already fired).\n */\n private _turnAbort: AbortController = new AbortController();\n\n constructor(opts: CacheFirstLoopOptions) {\n this.client = opts.client;\n this.prefix = opts.prefix;\n this.tools = opts.tools ?? new ToolRegistry();\n this.model = opts.model ?? \"deepseek-chat\";\n // Iter cap is a safety net, not the primary stop condition. The\n // primary stop is the token-context guard inside step(): after\n // every model response we check whether the prompt is already past\n // 80% of the model's context window, and if so divert to the\n // forced-summary path. 64 is high enough that exploration almost\n // never exhausts it before the token guard fires first — which\n // is the point: let the real constraint (context window) drive\n // the decision, keep the iter cap as a last-resort backstop for\n // the case where something spins without growing the prompt.\n this.maxToolIters = opts.maxToolIters ?? 64;\n this.hooks = opts.hooks ?? [];\n this.hookCwd = opts.hookCwd ?? process.cwd();\n\n // Resolve branch config first (since it forces harvest on).\n if (typeof opts.branch === \"number\") {\n this.branchOptions = { budget: opts.branch };\n } else if (opts.branch && typeof opts.branch === \"object\") {\n this.branchOptions = opts.branch;\n } else {\n this.branchOptions = {};\n }\n this.branchEnabled = (this.branchOptions.budget ?? 1) > 1;\n\n // Branching requires harvest for its default selector to work.\n const harvestForced = this.branchEnabled;\n this.harvestEnabled =\n harvestForced ||\n opts.harvest === true ||\n (typeof opts.harvest === \"object\" && opts.harvest !== null);\n this.harvestOptions =\n typeof opts.harvest === \"object\" && opts.harvest !== null\n ? opts.harvest\n : (this.branchOptions.harvestOptions ?? {});\n\n // Streaming is incompatible with branching (need all samples to select).\n this._streamPreference = opts.stream ?? true;\n this.stream = this.branchEnabled ? false : this._streamPreference;\n\n const allowedNames = new Set([...this.prefix.toolSpecs.map((s) => s.function.name)]);\n this.repair = new ToolCallRepair({ allowedToolNames: allowedNames });\n\n // Session resume: pre-load prior messages into the log if a session name\n // is provided. New messages appended to the log are also persisted.\n //\n // Heal-on-load: if a previous run (or a pre-alpha.6 client) stored a\n // tool result bigger than the cap, the next API call would blow past\n // DeepSeek's 131k-token limit *before the user even types anything*.\n // Truncating here lets the user pick up their session history without\n // losing the conversational context around the oversized call.\n this.sessionName = opts.session ?? null;\n if (this.sessionName) {\n const prior = loadSessionMessages(this.sessionName);\n const { messages, healedCount, tokensSaved } = healLoadedMessagesByTokens(\n prior,\n DEFAULT_MAX_RESULT_TOKENS,\n );\n for (const msg of messages) this.log.append(msg);\n this.resumedMessageCount = messages.length;\n if (healedCount > 0) {\n // Persist the healed log back to disk so the damage doesn't\n // re-surface on the next session load — otherwise `heal →\n // append → resume → heal → …` would keep noticing the same\n // broken tail every restart. Non-fatal on I/O error: the\n // in-memory log is already healed so this session still works.\n try {\n rewriteSession(this.sessionName, messages);\n } catch {\n /* disk full / perms — skip, in-memory heal still applies */\n }\n process.stderr.write(\n `▸ session \"${this.sessionName}\": healed ${healedCount} entr${healedCount === 1 ? \"y\" : \"ies\"}${tokensSaved > 0 ? ` (shrunk ${tokensSaved.toLocaleString()} tokens of oversized tool output)` : \" (dropped dangling tool_calls tail)\"}. Rewrote session file.\\n`,\n );\n }\n } else {\n this.resumedMessageCount = 0;\n }\n }\n\n /**\n * Shrink the log by re-truncating oversized tool results to a tighter\n * token cap, and persist the result back to disk so the next launch\n * doesn't re-inherit a fat session file. Returns a summary the TUI\n * can display.\n *\n * The cap is in DeepSeek V3 tokens (not chars) — so CJK text gets\n * capped at the same effective context footprint as English instead\n * of slipping past a char cap at 2× the token cost. Default 4000\n * tokens, matching the token-aware dispatch cap from 0.5.2.\n *\n * Only tool-role messages are touched (same rationale as\n * {@link healLoadedMessages}). User and assistant messages carry\n * authored intent we can't mechanically shrink without losing\n * meaning.\n */\n compact(maxTokens = 4000): {\n healedCount: number;\n tokensSaved: number;\n charsSaved: number;\n } {\n const before = this.log.toMessages();\n // Use `shrinkOversizedToolResultsByTokens` (not `healLoadedMessages`)\n // — the full heal would also strip a dangling `assistant.tool_calls`\n // tail, which during an active turn is legitimate state we still\n // need (tools haven't been dispatched yet). Structural healing is\n // only appropriate at session LOAD; mid-session `/compact` is\n // strictly about shrinking oversized tool payloads.\n const { messages, healedCount, tokensSaved, charsSaved } = shrinkOversizedToolResultsByTokens(\n before,\n maxTokens,\n );\n if (healedCount > 0) {\n this.log.compactInPlace(messages);\n if (this.sessionName) {\n try {\n rewriteSession(this.sessionName, messages);\n } catch {\n /* disk full or perms — compaction still applies in-memory */\n }\n }\n }\n return { healedCount, tokensSaved, charsSaved };\n }\n\n private appendAndPersist(message: ChatMessage): void {\n this.log.append(message);\n if (this.sessionName) {\n try {\n appendSessionMessage(this.sessionName, message);\n } catch {\n /* disk full or permission denied shouldn't kill the chat */\n }\n }\n }\n\n /**\n * Start a fresh conversation WITHOUT exiting. Drops every message\n * in the in-memory log AND rewrites the session file to empty so\n * a resume won't re-hydrate the old turns. Unlike `/forget`, which\n * deletes the session entirely, this keeps the session name and\n * config intact — it's the \"new chat\" button.\n *\n * The immutable prefix (system prompt + tool specs) is preserved\n * — that's the cache-first invariant, not part of the conversation.\n * Returns the number of messages dropped so the UI can show it.\n */\n clearLog(): { dropped: number } {\n const dropped = this.log.length;\n this.log.compactInPlace([]);\n if (this.sessionName) {\n try {\n rewriteSession(this.sessionName, []);\n } catch {\n /* disk issue shouldn't block the in-memory clear */\n }\n }\n this.scratch.reset();\n return { dropped };\n }\n\n /**\n * Reconfigure model/harvest/branch/stream mid-session. The loop's log,\n * scratch, and stats are preserved — only the per-turn behavior changes.\n * Used by the TUI's slash commands and by library callers who want to\n * flip a knob between turns.\n */\n configure(opts: ReconfigurableOptions): void {\n if (opts.model !== undefined) this.model = opts.model;\n if (opts.stream !== undefined) this._streamPreference = opts.stream;\n\n if (opts.branch !== undefined) {\n if (typeof opts.branch === \"number\") {\n this.branchOptions = { budget: opts.branch };\n } else if (opts.branch && typeof opts.branch === \"object\") {\n this.branchOptions = opts.branch;\n } else {\n this.branchOptions = {};\n }\n this.branchEnabled = (this.branchOptions.budget ?? 1) > 1;\n }\n\n if (opts.harvest !== undefined) {\n const want =\n opts.harvest === true || (typeof opts.harvest === \"object\" && opts.harvest !== null);\n this.harvestEnabled = want || this.branchEnabled;\n if (typeof opts.harvest === \"object\" && opts.harvest !== null) {\n this.harvestOptions = opts.harvest;\n }\n } else if (this.branchEnabled) {\n // branch turned on without explicit harvest → force it on\n this.harvestEnabled = true;\n }\n\n // Branching always forces non-streaming; otherwise honor preference.\n this.stream = this.branchEnabled ? false : this._streamPreference;\n }\n\n private buildMessages(pendingUser: string | null): ChatMessage[] {\n // Full tool_calls ↔ tool pairing validation. DeepSeek 400s on\n // both sides of this contract — unpaired assistant.tool_calls\n // (\"insufficient tool messages following\") OR stray tool entries\n // (\"tool must be a response to a preceding tool_calls\"). A corrupted\n // session from an earlier build can have either. Rather than\n // applying a bunch of narrow tail-trim heuristics, rebuild the\n // message stream through the same validator used at load time so\n // the payload we hand to the API is well-formed by construction.\n const healed = healLoadedMessages(this.log.toMessages(), DEFAULT_MAX_RESULT_CHARS);\n const msgs: ChatMessage[] = [...this.prefix.toMessages(), ...healed.messages];\n if (pendingUser !== null) msgs.push({ role: \"user\", content: pendingUser });\n return msgs;\n }\n\n /**\n * Signal the currently-running {@link step} to stop **now**. Cancels\n * the in-flight network request (DeepSeek HTTP/SSE) AND any tool call\n * currently dispatching (MCP `notifications/cancelled` + promise\n * reject). The loop itself also sees `signal.aborted` at each\n * iteration boundary and exits quickly instead of looping again.\n * Called by the TUI on Esc.\n */\n abort(): void {\n this._turnAbort.abort();\n }\n\n /**\n * Drop everything in the log after (and including) the most recent\n * user message. Used by `/retry` so the caller can re-send that\n * message with a fresh turn instead of layering another response on\n * top of the prior exchange. Returns the content of the dropped user\n * message, or `null` if there isn't one yet.\n *\n * Persists by rewriting the session file — otherwise the next\n * launch would rehydrate the old exchange and `/retry` would seem\n * to have done nothing.\n */\n retryLastUser(): string | null {\n const entries = this.log.entries;\n let lastUserIdx = -1;\n for (let i = entries.length - 1; i >= 0; i--) {\n if (entries[i]!.role === \"user\") {\n lastUserIdx = i;\n break;\n }\n }\n if (lastUserIdx < 0) return null;\n const raw = entries[lastUserIdx]!.content;\n const userText = typeof raw === \"string\" ? raw : \"\";\n // Keep everything strictly before the user message. The caller\n // will submit the text again through the normal path, which\n // re-appends the user turn on first successful API response.\n const preserved = entries.slice(0, lastUserIdx).map((m) => ({ ...m }));\n this.log.compactInPlace(preserved);\n if (this.sessionName) {\n try {\n rewriteSession(this.sessionName, preserved);\n } catch {\n /* disk-full / perms — in-memory compaction still applies */\n }\n }\n return userText;\n }\n\n async *step(userInput: string): AsyncGenerator<LoopEvent> {\n this._turn++;\n this.scratch.reset();\n // A fresh user turn is a new intent — don't let StormBreaker's\n // old sliding window of (name, args) signatures keep blocking\n // calls that are now legitimately on-task. The window repopulates\n // naturally as this turn's tool calls flow through.\n this.repair.resetStorm();\n // Fresh controller for this turn: the prior step's signal has\n // already fired (or stayed clean); either way we don't want its\n // state to bleed into the new turn.\n this._turnAbort = new AbortController();\n const signal = this._turnAbort.signal;\n let pendingUser: string | null = userInput;\n const toolSpecs = this.prefix.tools();\n // 70% of the iter budget is the \"you're getting close\" threshold. We\n // only warn once per step so the user sees a single signal, not a\n // string of identical yellow lines stacked up.\n const warnAt = Math.max(1, Math.floor(this.maxToolIters * 0.7));\n let warnedForIterBudget = false;\n\n for (let iter = 0; iter < this.maxToolIters; iter++) {\n if (signal.aborted) {\n // Esc means \"stop now\" — not \"stop and force another 30-90s\n // reasoner call to produce a summary I didn't ask for\". The\n // user's mental model of cancel is immediate. We emit a\n // synthetic assistant_final (tagged forcedSummary so the\n // code-mode applier ignores it) with a short stopped\n // message, then done. The prior tool outputs are still in\n // the log if the user wants to continue — asking again\n // will hit a warm cache and be cheap.\n //\n // Budget / context-guard still call forceSummaryAfterIterLimit\n // because there the USER didn't choose to stop — we did —\n // and leaving them staring at nothing is worse than one extra\n // call.\n yield {\n turn: this._turn,\n role: \"warning\",\n content: `aborted at iter ${iter}/${this.maxToolIters} — stopped without producing a summary (press ↑ + Enter or /retry to resume)`,\n };\n const stoppedMsg =\n \"[aborted by user (Esc) — no summary produced. Ask again or /retry when ready; prior tool output is still in the log.]\";\n this.appendAndPersist({ role: \"assistant\", content: stoppedMsg });\n yield {\n turn: this._turn,\n role: \"assistant_final\",\n content: stoppedMsg,\n forcedSummary: true,\n };\n yield { turn: this._turn, role: \"done\", content: stoppedMsg };\n return;\n }\n // Bridge the silence between the PREVIOUS iter's tool result and\n // THIS iter's first streaming byte. R1 can spend 20-90s reasoning\n // about tool output before the first delta lands, and prior to\n // this hint the UI had nothing to render. Only emit on iter > 0\n // because iter 0's \"thinking\" phase is already covered by the\n // streaming row / StreamingAssistant's placeholder.\n //\n // Wording is explicit about the two things happening: the tool\n // result IS being uploaded (it's now part of the next prompt) and\n // the model IS thinking. Users were reading \"thinking about the\n // tool result\" as the model-only phase, but the wait also covers\n // the upload round-trip.\n if (iter > 0) {\n yield {\n turn: this._turn,\n role: \"status\",\n content: \"tool result uploaded · model thinking before next response…\",\n };\n }\n if (!warnedForIterBudget && iter >= warnAt) {\n warnedForIterBudget = true;\n yield {\n turn: this._turn,\n role: \"warning\",\n content: `${iter}/${this.maxToolIters} tool calls used — approaching budget. Press Esc to force a summary now.`,\n };\n }\n let messages = this.buildMessages(pendingUser);\n\n // Preflight context check. Reactive auto-compact at 60%/80%\n // keys off the PREVIOUS turn's server-reported prompt_tokens,\n // so a single new oversized tool result (or a fresh resumed\n // session) can push this turn's request straight past 131,072\n // tokens before we ever see a usage number — DeepSeek 400s with\n // \"maximum context length\". Here we estimate the outgoing\n // payload locally and compact preemptively when it's in the red\n // zone (>95% of the model's context window). One cheap\n // tokenize-pass per iter, only on our side.\n {\n const ctxMax = DEEPSEEK_CONTEXT_TOKENS[this.model] ?? DEFAULT_CONTEXT_TOKENS;\n const estimate = estimateRequestTokens(messages, this.prefix.toolSpecs);\n if (estimate / ctxMax > 0.95) {\n const result = this.compact(1_000);\n if (result.healedCount > 0) {\n yield {\n turn: this._turn,\n role: \"warning\",\n content: `preflight: request ~${estimate.toLocaleString()}/${ctxMax.toLocaleString()} tokens (${Math.round(\n (estimate / ctxMax) * 100,\n )}%) — pre-compacted ${result.healedCount} tool result(s), saved ${result.tokensSaved.toLocaleString()} tokens. Sending.`,\n };\n // Rebuild with the compacted log so we send the smaller payload.\n messages = this.buildMessages(pendingUser);\n } else {\n yield {\n turn: this._turn,\n role: \"warning\",\n content: `preflight: request ~${estimate.toLocaleString()}/${ctxMax.toLocaleString()} tokens (${Math.round(\n (estimate / ctxMax) * 100,\n )}%) and nothing to auto-compact — DeepSeek will likely 400. Run /forget or /clear to start fresh.`,\n };\n }\n }\n }\n\n let assistantContent = \"\";\n let reasoningContent = \"\";\n let toolCalls: ToolCall[] = [];\n let usage: TurnStats[\"usage\"] | null = null;\n\n let branchSummary: BranchSummary | undefined;\n let preHarvestedPlanState: TypedPlanState | undefined;\n\n try {\n if (this.branchEnabled) {\n const budget = this.branchOptions.budget ?? 1;\n yield {\n turn: this._turn,\n role: \"branch_start\",\n content: \"\",\n branchProgress: {\n completed: 0,\n total: budget,\n latestIndex: -1,\n latestTemperature: -1,\n latestUncertainties: -1,\n },\n };\n\n // Queue samples as they complete so we can yield progress events\n // in resolution order (not launch order).\n const queue: BranchSample[] = [];\n let waiter: ((s: BranchSample) => void) | null = null;\n\n const onSampleDone = (sample: BranchSample) => {\n if (waiter) {\n const w = waiter;\n waiter = null;\n w(sample);\n } else {\n queue.push(sample);\n }\n };\n\n const branchPromise = runBranches(\n this.client,\n {\n model: this.model,\n messages,\n tools: toolSpecs.length ? toolSpecs : undefined,\n signal,\n },\n {\n ...this.branchOptions,\n harvestOptions: this.harvestOptions,\n onSampleDone,\n },\n );\n\n for (let k = 0; k < budget; k++) {\n const sample: BranchSample =\n queue.shift() ??\n (await new Promise<BranchSample>((resolve) => {\n waiter = resolve;\n }));\n yield {\n turn: this._turn,\n role: \"branch_progress\",\n content: \"\",\n branchProgress: {\n completed: k + 1,\n total: budget,\n latestIndex: sample.index,\n latestTemperature: sample.temperature,\n latestUncertainties: sample.planState.uncertainties.length,\n },\n };\n }\n\n const result = await branchPromise;\n assistantContent = result.chosen.response.content;\n reasoningContent = result.chosen.response.reasoningContent ?? \"\";\n toolCalls = result.chosen.response.toolCalls;\n\n // Cost accounting: sum usage across ALL samples, not just the winner.\n // (We paid for all three.) Harvest-call tokens are not tracked; they\n // amount to rounding error compared to the main R1 calls.\n const agg = aggregateBranchUsage(result.samples);\n usage = new Usage(\n agg.promptTokens,\n agg.completionTokens,\n agg.totalTokens,\n agg.promptCacheHitTokens,\n agg.promptCacheMissTokens,\n );\n preHarvestedPlanState = result.chosen.planState;\n branchSummary = summarizeBranch(result.chosen, result.samples);\n yield {\n turn: this._turn,\n role: \"branch_done\",\n content: \"\",\n branch: branchSummary,\n };\n } else if (this.stream) {\n const callBuf: Map<number, ToolCall> = new Map();\n for await (const chunk of this.client.stream({\n model: this.model,\n messages,\n tools: toolSpecs.length ? toolSpecs : undefined,\n signal,\n })) {\n if (chunk.contentDelta) {\n assistantContent += chunk.contentDelta;\n yield {\n turn: this._turn,\n role: \"assistant_delta\",\n content: chunk.contentDelta,\n };\n }\n if (chunk.reasoningDelta) {\n reasoningContent += chunk.reasoningDelta;\n yield {\n turn: this._turn,\n role: \"assistant_delta\",\n content: \"\",\n reasoningDelta: chunk.reasoningDelta,\n };\n }\n if (chunk.toolCallDelta) {\n const d = chunk.toolCallDelta;\n const cur = callBuf.get(d.index) ?? {\n id: d.id,\n type: \"function\" as const,\n function: { name: \"\", arguments: \"\" },\n };\n if (d.id) cur.id = d.id;\n if (d.name) cur.function.name = (cur.function.name ?? \"\") + d.name;\n if (d.argumentsDelta)\n cur.function.arguments = (cur.function.arguments ?? \"\") + d.argumentsDelta;\n callBuf.set(d.index, cur);\n // Skip the id-only opener: name is empty until the next chunk.\n if (cur.function.name) {\n yield {\n turn: this._turn,\n role: \"tool_call_delta\",\n content: \"\",\n toolName: cur.function.name,\n toolCallArgsChars: (cur.function.arguments ?? \"\").length,\n };\n }\n }\n if (chunk.usage) usage = chunk.usage;\n }\n toolCalls = [...callBuf.values()];\n } else {\n const resp = await this.client.chat({\n model: this.model,\n messages,\n tools: toolSpecs.length ? toolSpecs : undefined,\n signal,\n });\n assistantContent = resp.content;\n reasoningContent = resp.reasoningContent ?? \"\";\n toolCalls = resp.toolCalls;\n usage = resp.usage;\n }\n } catch (err) {\n // An aborted signal here is almost always our own doing —\n // either Esc, or App.tsx calling `loop.abort()` to switch to a\n // queued synthetic input (ShellConfirm \"always allow\", PlanConfirm\n // approve, etc.). The DeepSeek client's fetch path translates\n // the abort into a generic `AbortError(\"This operation was\n // aborted\")`, which used to bubble up here and render as a\n // scary red \"error\" row even though nothing actually broke.\n // Treat it as a clean early-exit instead: the next turn (queued\n // synthetic OR user re-prompt) starts immediately and gets to\n // produce its own answer.\n if (signal.aborted) {\n yield { turn: this._turn, role: \"done\", content: \"\" };\n return;\n }\n yield {\n turn: this._turn,\n role: \"error\",\n content: \"\",\n error: formatLoopError(err as Error),\n };\n return;\n }\n\n const turnStats = this.stats.record(this._turn, this.model, usage ?? new Usage());\n\n // Commit the user turn to the log only on success of the first round-trip.\n if (pendingUser !== null) {\n this.appendAndPersist({ role: \"user\", content: pendingUser });\n pendingUser = null;\n }\n\n this.scratch.reasoning = reasoningContent || null;\n // Harvest is a second API round-trip (cheap model, but still\n // 1-10s) that was previously silent. Bridge the gap with a\n // status indicator so the TUI shows *something* instead of\n // \"reasoning finished, now staring at the wall.\"\n if (\n !preHarvestedPlanState &&\n this.harvestEnabled &&\n (reasoningContent?.trim().length ?? 0) >= 40\n ) {\n yield {\n turn: this._turn,\n role: \"status\",\n content: \"extracting plan state from reasoning…\",\n };\n }\n const planState = preHarvestedPlanState\n ? preHarvestedPlanState\n : this.harvestEnabled\n ? await harvest(reasoningContent || null, this.client, this.harvestOptions, signal)\n : emptyPlanState();\n\n const { calls: repairedCalls, report } = this.repair.process(\n toolCalls,\n reasoningContent || null,\n assistantContent || null,\n );\n\n this.appendAndPersist(this.assistantMessage(assistantContent, repairedCalls));\n\n yield {\n turn: this._turn,\n role: \"assistant_final\",\n content: assistantContent,\n stats: turnStats,\n planState,\n repair: report,\n branch: branchSummary,\n };\n\n // Loud signal when the storm breaker caught a repeat pattern.\n // The `repair` field on assistant_final already carries the\n // count as a subtext on the assistant row, but a dedicated\n // warning row is far more noticeable — and critical when ALL\n // calls were suppressed, because the turn then ends with no\n // visible explanation of why nothing happened.\n if (report.stormsBroken > 0) {\n const noteTail = report.notes.length ? ` — ${report.notes[report.notes.length - 1]}` : \"\";\n const allSuppressed = repairedCalls.length === 0 && toolCalls.length > 0;\n const phrase = allSuppressed\n ? `stopped the model from calling the same tool with identical args repeatedly (all ${toolCalls.length} call(s) this turn were already in the recent-repeat window). Likely a stuck retry — reword your instruction, rule out the underlying blocker, or try /retry after fixing it`\n : `suppressed ${report.stormsBroken} repeat tool call(s) that had fired 3+ times with identical args in a sliding window`;\n yield {\n turn: this._turn,\n role: \"warning\",\n content: `${phrase}${noteTail}`,\n };\n }\n\n if (repairedCalls.length === 0) {\n yield { turn: this._turn, role: \"done\", content: assistantContent };\n return;\n }\n\n // Token-budget guard — the real stop condition. Iter count is a\n // proxy that misses the actual constraint: how close the prompt\n // already is to DeepSeek's 131k context. If we're over 80%, the\n // NEXT call (with the just-executed tools' results stuffed into\n // history) will be worse, and fairly soon it'll 400 with\n // \"maximum context length\".\n //\n // Strategy, in order:\n // 1. Try auto-compacting the log (shrink oversized tool\n // results). If that gets us back under 80% we keep going —\n // the user doesn't lose their turn to a premature summary.\n // 2. If still over after compact, divert to the forced-summary\n // path. BUT first drop the trailing assistant-with-tool_calls\n // that we just appended — we haven't executed the tools yet,\n // so sending this to the summary call with no matching tool\n // responses would 400 (\"insufficient tool messages following\n // tool_calls\"). The summary is about what was LEARNED so far,\n // not what we intended to do next.\n const ctxMax = DEEPSEEK_CONTEXT_TOKENS[this.model] ?? DEFAULT_CONTEXT_TOKENS;\n // Proactive tier: between 60% and 80%, pre-shrink oversized tool\n // results to a moderate cap (4k tokens) so the next iter doesn't\n // slam straight into the 80% reactive path — which shrinks far\n // more aggressively (1k tokens) and risks losing useful tail\n // info. This catches the slow-growth pattern (lots of medium\n // reads) before it compounds.\n if (usage) {\n const ratio = usage.promptTokens / ctxMax;\n if (ratio > 0.6 && ratio <= 0.8) {\n const before = usage.promptTokens;\n const soft = this.compact(4_000);\n if (soft.healedCount > 0) {\n const after = Math.max(0, before - soft.tokensSaved);\n yield {\n turn: this._turn,\n role: \"warning\",\n content: `context ${before.toLocaleString()}/${ctxMax.toLocaleString()} (${Math.round(\n ratio * 100,\n )}%) — proactively compacted ${soft.healedCount} tool result(s) to 4k tokens, saved ${soft.tokensSaved.toLocaleString()} tokens (now ~${after.toLocaleString()}). Staying ahead of the 80% guard.`,\n };\n }\n }\n }\n if (usage && usage.promptTokens / ctxMax > 0.8) {\n const before = usage.promptTokens;\n const compactResult = this.compact(1_000);\n if (compactResult.healedCount > 0) {\n const after = Math.max(0, before - compactResult.tokensSaved);\n yield {\n turn: this._turn,\n role: \"warning\",\n content: `context ${before.toLocaleString()}/${ctxMax.toLocaleString()} — auto-compacted ${compactResult.healedCount} oversized tool result(s), saved ${compactResult.tokensSaved.toLocaleString()} tokens (now ~${after.toLocaleString()}). Continuing.`,\n };\n // Intentionally don't re-check the threshold here: even if\n // compaction didn't fully clear us under 80%, one more tool\n // call's overhead isn't going to overflow, and the NEXT\n // iter's fresh `usage` from the API will catch real danger.\n } else {\n yield {\n turn: this._turn,\n role: \"warning\",\n content: `context ${before.toLocaleString()}/${ctxMax.toLocaleString()} (${Math.round(\n (before / ctxMax) * 100,\n )}%) — nothing to auto-compact. Forcing summary from what was gathered.`,\n };\n // Drop the trailing assistant-with-tool_calls we just\n // appended. The forced-summary call would otherwise trip\n // DeepSeek's \"insufficient tool messages following tool_calls\"\n // validator, since we bail BEFORE dispatching the tools.\n const tail = this.log.entries[this.log.entries.length - 1];\n if (\n tail &&\n tail.role === \"assistant\" &&\n Array.isArray(tail.tool_calls) &&\n tail.tool_calls.length > 0\n ) {\n const kept = this.log.entries.slice(0, -1);\n this.log.compactInPlace([...kept]);\n if (this.sessionName) {\n try {\n rewriteSession(this.sessionName, kept);\n } catch {\n /* disk issue shouldn't block the summary path */\n }\n }\n }\n yield* this.forceSummaryAfterIterLimit({ reason: \"context-guard\" });\n return;\n }\n }\n\n for (const call of repairedCalls) {\n const name = call.function?.name ?? \"\";\n const args = call.function?.arguments ?? \"{}\";\n // Announce the tool BEFORE awaiting it so the TUI can render a\n // \"running…\" indicator. Without this, the window between\n // assistant_final and the tool-result yield is silent from the\n // UI's perspective — which makes long tool calls feel like the\n // app has hung.\n yield {\n turn: this._turn,\n role: \"tool_start\",\n content: \"\",\n toolName: name,\n toolArgs: args,\n };\n\n // PreToolUse hooks. A `block` decision (exit 2) skips dispatch\n // and surfaces the hook's stderr as the tool result so the model\n // sees a structured refusal instead of a silent omission. Non-\n // block non-zero outcomes are warnings: the loop continues, the\n // UI gets a yellow row.\n const parsedArgs = safeParseToolArgs(args);\n const preReport = await runHooks({\n hooks: this.hooks,\n payload: {\n event: \"PreToolUse\",\n cwd: this.hookCwd,\n toolName: name,\n toolArgs: parsedArgs,\n },\n });\n for (const w of hookWarnings(preReport.outcomes, this._turn)) yield w;\n\n let result: string;\n if (preReport.blocked) {\n const blocking = preReport.outcomes[preReport.outcomes.length - 1];\n const reason = (\n blocking?.stderr ||\n blocking?.stdout ||\n \"blocked by PreToolUse hook\"\n ).trim();\n result = `[hook block] ${blocking?.hook.command ?? \"<unknown>\"}\\n${reason}`;\n } else {\n result = await this.tools.dispatch(name, args, {\n signal,\n maxResultTokens: DEFAULT_MAX_RESULT_TOKENS,\n });\n\n // PostToolUse hooks — block is meaningless after the fact, so\n // every non-pass outcome is a warning. Hooks here are the\n // natural place for \"after every edit, run the formatter.\"\n const postReport = await runHooks({\n hooks: this.hooks,\n payload: {\n event: \"PostToolUse\",\n cwd: this.hookCwd,\n toolName: name,\n toolArgs: parsedArgs,\n toolResult: result,\n },\n });\n for (const w of hookWarnings(postReport.outcomes, this._turn)) yield w;\n }\n\n this.appendAndPersist({\n role: \"tool\",\n tool_call_id: call.id ?? \"\",\n name,\n content: result,\n });\n yield {\n turn: this._turn,\n role: \"tool\",\n content: result,\n toolName: name,\n toolArgs: args,\n };\n }\n }\n\n // We exhausted the tool-call budget while the model still wanted to\n // call more tools. Rather than stopping silently (which leaves the\n // user staring at a blank prompt), force one final no-tools call so\n // the model must produce a text summary from everything it has\n // already seen.\n yield* this.forceSummaryAfterIterLimit({ reason: \"budget\" });\n }\n\n private async *forceSummaryAfterIterLimit(\n opts: { reason: \"budget\" | \"aborted\" | \"context-guard\" } = { reason: \"budget\" },\n ): AsyncGenerator<LoopEvent> {\n try {\n // The summary call is non-streaming (reasoner, 30-60s typical).\n // Without this status the user sees nothing happening after the\n // yellow \"budget reached\" warning until the summary arrives.\n yield {\n turn: this._turn,\n role: \"status\",\n content: \"summarizing what was gathered…\",\n };\n const messages = this.buildMessages(null);\n // Passing `tools: undefined` was supposed to force a text\n // response, but R1 can still hallucinate tool-call markup\n // (e.g. DSML `<|DSML|function_calls>…</|DSML|function_calls>`)\n // in prose when it's been primed by prior tool use. An explicit\n // user-role instruction plus post-hoc stripping of known\n // hallucination shapes keeps the user from seeing raw markup.\n messages.push({\n role: \"user\",\n content:\n \"I'm out of tool-call budget for this turn. Summarize in plain prose what you learned from the tool results above. Do NOT emit any tool calls, function-call markup, DSML invocations, or SEARCH/REPLACE edit blocks — they will be silently discarded. Just plain text.\",\n });\n const resp = await this.client.chat({\n model: this.model,\n messages,\n // no tools → model is forced to answer in text\n signal: this._turnAbort.signal,\n });\n const rawContent = resp.content?.trim() ?? \"\";\n const cleaned = stripHallucinatedToolMarkup(rawContent);\n const summary =\n cleaned ||\n \"(model emitted fake tool-call markup instead of a prose summary — try /retry with a narrower question, or /think to inspect R1's reasoning)\";\n const reasonPrefix = reasonPrefixFor(opts.reason, this.maxToolIters);\n const annotated = `${reasonPrefix}\\n\\n${summary}`;\n const summaryStats = this.stats.record(this._turn, this.model, resp.usage ?? new Usage());\n this.appendAndPersist({ role: \"assistant\", content: summary });\n yield {\n turn: this._turn,\n role: \"assistant_final\",\n content: annotated,\n stats: summaryStats,\n forcedSummary: true,\n };\n yield { turn: this._turn, role: \"done\", content: summary };\n } catch (err) {\n const label = errorLabelFor(opts.reason, this.maxToolIters);\n yield {\n turn: this._turn,\n role: \"error\",\n content: \"\",\n error: `${label} and the fallback summary call failed: ${(err as Error).message}. Run /clear and retry with a narrower question, or raise --max-tool-iters.`,\n };\n yield { turn: this._turn, role: \"done\", content: \"\" };\n }\n }\n\n async run(userInput: string, onEvent?: (ev: LoopEvent) => void): Promise<string> {\n let final = \"\";\n for await (const ev of this.step(userInput)) {\n onEvent?.(ev);\n if (ev.role === \"assistant_final\") final = ev.content;\n if (ev.role === \"done\") break;\n }\n return final;\n }\n\n private assistantMessage(content: string, toolCalls: ToolCall[]): ChatMessage {\n const msg: ChatMessage = { role: \"assistant\", content };\n if (toolCalls.length > 0) msg.tool_calls = toolCalls;\n return msg;\n }\n}\n\n/**\n * R1 occasionally hallucinates tool-call markup as plain text when the\n * real tool channel has been closed — typically our forced-summary\n * path, where `tools: undefined` is supposed to force prose but isn't\n * always respected. The markup isn't parsed by our tool-call path\n * (the API response's structured `tool_calls` field is empty), so\n * it's just noise in the user's view. Strip known envelope shapes.\n *\n * Exported so tests can exercise it against concrete R1 outputs.\n */\nexport function stripHallucinatedToolMarkup(s: string): string {\n let out = s;\n // DeepSeek's DSML envelope (both the full-width \"|\" character and\n // the ASCII-only fallback we've seen — the full-width form is the\n // one R1 emits in practice)\n out = out.replace(/<|DSML|function_calls>[\\s\\S]*?<\\/?|DSML|function_calls>/g, \"\");\n out = out.replace(/<\\|DSML\\|function_calls>[\\s\\S]*?<\\/?\\|DSML\\|function_calls>/g, \"\");\n // Anthropic / generic XML-ish envelope\n out = out.replace(/<function_calls>[\\s\\S]*?<\\/function_calls>/g, \"\");\n // Lone unpaired DSML opener left over after the closer was on a\n // different line (seen when R1 truncates mid-call).\n out = out.replace(/<|DSML|[\\s\\S]*$/g, \"\");\n return out.trim();\n}\n\n/**\n * Try to JSON-decode the model's tool-call arguments so PreToolUse /\n * PostToolUse hooks get a structured object instead of a string.\n * Falls back to the raw string when the model emits malformed JSON\n * (the loop's own dispatch already tolerates that — keep parity).\n */\nfunction safeParseToolArgs(raw: string): unknown {\n try {\n return JSON.parse(raw);\n } catch {\n return raw;\n }\n}\n\n/** Format non-pass hook outcomes as `LoopEvent`s of role `warning`. */\nfunction* hookWarnings(outcomes: HookOutcome[], turn: number): Generator<LoopEvent> {\n for (const o of outcomes) {\n if (o.decision === \"pass\") continue;\n yield { turn, role: \"warning\", content: formatHookOutcomeMessage(o) };\n }\n}\n\nfunction reasonPrefixFor(reason: \"budget\" | \"aborted\" | \"context-guard\", iterCap: number): string {\n if (reason === \"aborted\") return \"[aborted by user (Esc) — summarizing what I found so far]\";\n if (reason === \"context-guard\") {\n return \"[context budget running low — summarizing before the next call would overflow]\";\n }\n return `[tool-call budget (${iterCap}) reached — forcing summary from what I found]`;\n}\n\nfunction errorLabelFor(reason: \"budget\" | \"aborted\" | \"context-guard\", iterCap: number): string {\n if (reason === \"aborted\") return \"aborted by user\";\n if (reason === \"context-guard\") return \"context-guard triggered (prompt > 80% of window)\";\n return `tool-call budget (${iterCap}) reached`;\n}\n\nfunction summarizeBranch(chosen: BranchSample, samples: BranchSample[]): BranchSummary {\n return {\n budget: samples.length,\n chosenIndex: chosen.index,\n uncertainties: samples.map((s) => s.planState.uncertainties.length),\n temperatures: samples.map((s) => s.temperature),\n };\n}\n\n/**\n * Truncate any tool-role message whose content exceeds the cap. User\n * and assistant messages are left alone because (a) they're almost\n * always small, (b) truncating user prompts would corrupt conversational\n * intent in a way the user didn't author. Exported for tests.\n */\n/**\n * Shrink oversized tool results only — the original compact concern.\n * Separated from `healLoadedMessages` so `/compact` (live, mid-session)\n * doesn't accidentally strip structural tail that belongs in the\n * current turn's state.\n */\nexport function shrinkOversizedToolResults(\n messages: ChatMessage[],\n maxChars: number,\n): { messages: ChatMessage[]; healedCount: number; healedFrom: number } {\n let healedCount = 0;\n let healedFrom = 0;\n const out = messages.map((msg) => {\n if (msg.role !== \"tool\") return msg;\n const content = typeof msg.content === \"string\" ? msg.content : \"\";\n if (content.length <= maxChars) return msg;\n healedCount += 1;\n healedFrom += content.length;\n return { ...msg, content: truncateForModel(content, maxChars) };\n });\n return { messages: out, healedCount, healedFrom };\n}\n\n/**\n * Token-aware variant of `shrinkOversizedToolResults`. Used by live\n * `/compact` and auto-compact so the shrink cap bounds the REAL\n * context footprint (CJK at 1 char/token would otherwise survive a\n * char cap at 2× the intended token cost). Session-load heal still\n * uses the char version for backward-compat on stored session files.\n *\n * Per-message token accounting: we tokenize each shrink candidate\n * twice (before + after) so `tokensSaved` is exact. At typical log\n * sizes (≤20 tool results) this is bounded; at pathological sizes\n * the `truncateForModelByTokens` call internally never tokenizes the\n * full input, so worst-case stays bounded too.\n */\nexport function shrinkOversizedToolResultsByTokens(\n messages: ChatMessage[],\n maxTokens: number,\n): {\n messages: ChatMessage[];\n healedCount: number;\n tokensSaved: number;\n charsSaved: number;\n} {\n let healedCount = 0;\n let tokensSaved = 0;\n let charsSaved = 0;\n const out = messages.map((msg) => {\n if (msg.role !== \"tool\") return msg;\n const content = typeof msg.content === \"string\" ? msg.content : \"\";\n // Fast path: length ≤ maxTokens ⇒ tokens ≤ maxTokens (every token\n // is ≥1 char). Skip the per-message tokenize for small results.\n if (content.length <= maxTokens) return msg;\n const beforeTokens = countTokens(content);\n if (beforeTokens <= maxTokens) return msg;\n const truncated = truncateForModelByTokens(content, maxTokens);\n const afterTokens = countTokens(truncated);\n healedCount += 1;\n tokensSaved += Math.max(0, beforeTokens - afterTokens);\n charsSaved += Math.max(0, content.length - truncated.length);\n return { ...msg, content: truncated };\n });\n return { messages: out, healedCount, tokensSaved, charsSaved };\n}\n\n/**\n * Enforce tool_calls ↔ tool pairing across a message log. DeepSeek\n * rejects two shapes at the API boundary:\n * (a) assistant with tool_calls not followed by matching tool\n * responses (\"insufficient tool messages following tool_calls\")\n * (b) tool message without a preceding assistant.tool_calls with\n * the matching tool_call_id (\"must be a response to a preceding\n * message with 'tool_calls'\")\n *\n * Corrupted session files from earlier builds have hit both. This pass\n * rebuilds the message stream so only well-formed (assistant.tool_calls\n * + all matching responses) groups survive. Plain user/assistant/system\n * messages (no tool_calls) always pass through.\n *\n * Exported so both char-based and token-based heal can compose it.\n */\nexport function fixToolCallPairing(messages: ChatMessage[]): {\n messages: ChatMessage[];\n droppedAssistantCalls: number;\n droppedStrayTools: number;\n} {\n const out: ChatMessage[] = [];\n let droppedAssistantCalls = 0;\n let droppedStrayTools = 0;\n for (let i = 0; i < messages.length; i++) {\n const msg = messages[i]!;\n if (msg.role === \"assistant\" && Array.isArray(msg.tool_calls) && msg.tool_calls.length > 0) {\n const needed = new Set<string>();\n for (const call of msg.tool_calls) {\n if (call?.id) needed.add(call.id);\n }\n const candidates: ChatMessage[] = [];\n let j = i + 1;\n while (j < messages.length && needed.size > 0) {\n const nxt = messages[j]!;\n if (nxt.role !== \"tool\") break;\n const id = nxt.tool_call_id ?? \"\";\n if (!needed.has(id)) break;\n needed.delete(id);\n candidates.push(nxt);\n j++;\n }\n if (needed.size === 0) {\n out.push(msg);\n for (const r of candidates) out.push(r);\n i = j - 1;\n } else {\n droppedAssistantCalls += 1;\n droppedStrayTools += candidates.length;\n i = j - 1;\n }\n continue;\n }\n if (msg.role === \"tool\") {\n droppedStrayTools += 1;\n continue;\n }\n out.push(msg);\n }\n return { messages: out, droppedAssistantCalls, droppedStrayTools };\n}\n\nexport function healLoadedMessages(\n messages: ChatMessage[],\n maxChars: number,\n): { messages: ChatMessage[]; healedCount: number; healedFrom: number } {\n const shrunk = shrinkOversizedToolResults(messages, maxChars);\n const paired = fixToolCallPairing(shrunk.messages);\n const healedCount = shrunk.healedCount + paired.droppedAssistantCalls + paired.droppedStrayTools;\n return { messages: paired.messages, healedCount, healedFrom: shrunk.healedFrom };\n}\n\n/**\n * Token-aware counterpart of {@link healLoadedMessages}. Used at\n * session-load time so resumed sessions come back capped at the same\n * token budget (not char budget) as live tool results — CJK text no\n * longer slips past at 2× the intended token cost when re-hydrated.\n *\n * Still does the same structural pass for tool_calls ↔ tool pairing;\n * that logic is orthogonal to the truncation cap.\n */\nexport function healLoadedMessagesByTokens(\n messages: ChatMessage[],\n maxTokens: number,\n): {\n messages: ChatMessage[];\n healedCount: number;\n tokensSaved: number;\n charsSaved: number;\n} {\n const shrunk = shrinkOversizedToolResultsByTokens(messages, maxTokens);\n const paired = fixToolCallPairing(shrunk.messages);\n const healedCount = shrunk.healedCount + paired.droppedAssistantCalls + paired.droppedStrayTools;\n return {\n messages: paired.messages,\n healedCount,\n tokensSaved: shrunk.tokensSaved,\n charsSaved: shrunk.charsSaved,\n };\n}\n\n/**\n * Annotate the `DeepSeek 400: … maximum context length …` error the API\n * returns when a session's history has grown past 131,072 tokens. The\n * raw message is a JSON blob; we surface a short actionable hint on top\n * so the user knows to `/forget` or `/clear` rather than parsing the\n * JSON themselves. Other errors pass through unchanged — the loop's\n * error channel already formats them well enough.\n */\nexport function formatLoopError(err: Error): string {\n const msg = err.message ?? \"\";\n if (msg.includes(\"maximum context length\")) {\n // Pull the \"requested X tokens\" figure out of the JSON for scale.\n const reqMatch = msg.match(/requested\\s+(\\d+)\\s+tokens/);\n const requested = reqMatch\n ? `${Number(reqMatch[1]).toLocaleString()} tokens`\n : \"too many tokens\";\n return `Context overflow (DeepSeek 400): session history is ${requested}, past the 131,072-token limit. Usually this means a single tool call returned a huge payload. v0.3.0-alpha.6+ caps new tool results at 32k chars, AND auto-heals oversized history on session load — restart Reasonix and this session should come back trimmed. If it still overflows, run /forget (delete the session) or /clear (drop the displayed history) to start fresh.`;\n }\n return msg;\n}\n","/**\n * Expand `@path/to/file` mentions in a user prompt to inline file\n * content.\n *\n * Why: most interactive coding sessions start with \"look at X, then\n * change Y\". Typing `@src/loop.ts` reads faster and cheaper than\n * \"look at src/loop.ts (and the model fires read_file, and we pay for\n * the round trip)\" — the model sees the file content from turn 1\n * instead of round-tripping a tool call for it.\n *\n * Shape: the user's text is kept verbatim. Expanded file contents are\n * appended in a \"Referenced files\" block at the end, each wrapped in\n * `<file path=\"...\">...</file>` so the model can cite them back\n * unambiguously.\n *\n * Safety: paths must resolve inside `rootDir` (no `..` escape, no\n * absolute paths), must exist as a regular file, and must be under\n * `maxBytes`. Missing / too-large / escaping paths get a short note\n * appended instead of content so the user sees why it was skipped.\n */\n\nimport { type Dirent, existsSync, readFileSync, readdirSync, statSync } from \"node:fs\";\nimport { isAbsolute, join, relative, resolve } from \"node:path\";\n\n/** Caps match tool-result dispatch truncation (0.5.2). */\nexport const DEFAULT_AT_MENTION_MAX_BYTES = 64 * 1024;\n\n/**\n * Default directory names skipped when listing files for the picker.\n * Matches what most repos gitignore AND keeps the picker off the\n * hottest bloat — `node_modules` alone can be 100k+ entries.\n */\nexport const DEFAULT_PICKER_IGNORE_DIRS: readonly string[] = [\n \"node_modules\",\n \".git\",\n \"dist\",\n \"build\",\n \".next\",\n \"out\",\n \"coverage\",\n \".cache\",\n \".vscode\",\n \".idea\",\n \"target\",\n \".venv\",\n \"venv\",\n \"__pycache__\",\n];\n\nexport interface ListFilesOptions {\n /** Cap the walk once we've collected this many entries. Default 500. */\n maxResults?: number;\n /** Directory names to skip entirely. Defaults to {@link DEFAULT_PICKER_IGNORE_DIRS}. */\n ignoreDirs?: readonly string[];\n}\n\n/**\n * Walk `root` recursively and return relative file paths (forward-slash\n * separator, regardless of platform) for the `@` picker.\n *\n * Synchronous on purpose: this runs once at App mount (and on each turn\n * so newly-created files show up) and blocks the render thread for a\n * predictable ~10-50ms on a moderate repo. An async variant would need\n * to coordinate with the Ink render loop; sync fits the rest of the\n * TUI's single-turn-per-tick model cleanly.\n *\n * Skips:\n * - directories in `ignoreDirs` (default: DEFAULT_PICKER_IGNORE_DIRS)\n * - any directory whose name starts with `.` (covers `.git`,\n * `.vscode`, dotfile vendors). Dotfile REGULAR FILES (`.env`,\n * `.gitignore`, `.prettierrc`) are kept — users reference them.\n * - entries the walker can't read (permission errors, broken links).\n */\nexport function listFilesSync(root: string, opts: ListFilesOptions = {}): string[] {\n const maxResults = Math.max(1, opts.maxResults ?? 500);\n const ignore = new Set(opts.ignoreDirs ?? DEFAULT_PICKER_IGNORE_DIRS);\n const rootAbs = resolve(root);\n const out: string[] = [];\n\n const walk = (dirAbs: string, dirRel: string) => {\n if (out.length >= maxResults) return;\n let entries: Dirent[];\n try {\n entries = readdirSync(dirAbs, { withFileTypes: true });\n } catch {\n return;\n }\n entries.sort((a, b) => a.name.localeCompare(b.name));\n for (const ent of entries) {\n if (out.length >= maxResults) return;\n const relPath = dirRel ? `${dirRel}/${ent.name}` : ent.name;\n if (ent.isDirectory()) {\n // Skip dot-dirs (.git, .vscode, .idea…) and the explicit ignore\n // list. Users who want to @-reference a file inside a dot-dir\n // can type the full path — picker just doesn't surface them.\n if (ent.name.startsWith(\".\") || ignore.has(ent.name)) continue;\n walk(join(dirAbs, ent.name), relPath);\n } else if (ent.isFile()) {\n out.push(relPath);\n }\n }\n };\n\n walk(rootAbs, \"\");\n return out;\n}\n\n/**\n * Prefix pattern used by the `@` picker to detect an IN-PROGRESS\n * mention at the END of the input buffer. Captures the partial path\n * (which may be empty — just `@`) so the picker can use it as a\n * substring filter.\n *\n * Distinct from {@link AT_MENTION_PATTERN} (which finds completed\n * mentions anywhere in the text for expansion-at-submit). This one\n * fires on the trailing token only, anchored at end-of-input.\n */\nexport const AT_PICKER_PREFIX = /(?:^|\\s)@([a-zA-Z0-9_./\\\\-]*)$/;\n\n/**\n * Return the picker state for a given input buffer: the partial query\n * (may be empty string — just `@`) and the buffer offset of the `@`\n * character. `null` when the buffer doesn't end in a mention-in-\n * progress.\n */\nexport function detectAtPicker(input: string): { query: string; atOffset: number } | null {\n const m = AT_PICKER_PREFIX.exec(input);\n if (!m) return null;\n const query = m[1] ?? \"\";\n // `m.index` is the offset of the capture group's SURROUNDING match —\n // which starts at either ^ or the preceding whitespace. The `@`\n // itself is at `end-of-input - query.length - 1`.\n const atOffset = input.length - query.length - 1;\n return { query, atOffset };\n}\n\n/**\n * Filter and rank candidate files against the picker's partial query.\n * Empty query → return the first `limit` candidates as-is (alpha).\n * Non-empty query → case-insensitive substring match, with a modest\n * boost for basename-starts-with matches so `src/l` still puts\n * `loop.ts`-shaped paths near the top.\n */\nexport function rankPickerCandidates(\n files: readonly string[],\n query: string,\n limit = 40,\n): string[] {\n if (!query) return files.slice(0, limit);\n const needle = query.toLowerCase();\n const scored: Array<{ path: string; score: number }> = [];\n for (const f of files) {\n const lower = f.toLowerCase();\n const hit = lower.indexOf(needle);\n if (hit < 0) continue;\n // Rank: basename prefix < path prefix < substring. Lower score = better.\n const slash = lower.lastIndexOf(\"/\");\n const base = slash >= 0 ? lower.slice(slash + 1) : lower;\n let score = 2;\n if (base.startsWith(needle)) score = 0;\n else if (lower.startsWith(needle)) score = 1;\n scored.push({ path: f, score: score * 10_000 + hit });\n }\n scored.sort((a, b) => a.score - b.score);\n return scored.slice(0, limit).map((s) => s.path);\n}\n\n/**\n * Matches `@` at a word boundary (start-of-string or preceded by\n * whitespace) followed by a path-like token. Deliberately rejects `@`\n * embedded in longer words (email addresses, mentions on social sites)\n * by requiring the word boundary.\n *\n * Path charset keeps it to the characters that appear in real repo\n * paths — letters, digits, `_` `-` `.` `/` `\\`. Trailing `.` (e.g.\n * `@foo.ts.`) is stripped before lookup so a sentence-terminating\n * period doesn't break the mention.\n */\nexport const AT_MENTION_PATTERN = /(?<=^|\\s)@([a-zA-Z0-9_./\\\\-]+)/g;\n\nexport interface AtMentionExpansion {\n /** The raw `@path` token as it appeared in the text. */\n token: string;\n /** The relative path, as resolved against rootDir. */\n path: string;\n /** True if the content was inlined. False = skipped (reason in `skip`). */\n ok: boolean;\n /** Bytes read (only for ok=true). */\n bytes?: number;\n /** Why the mention was skipped. Set when ok=false. */\n skip?: \"missing\" | \"not-file\" | \"too-large\" | \"escape\" | \"read-error\";\n}\n\nexport interface AtMentionOptions {\n /** Max file size in bytes before a mention is skipped. */\n maxBytes?: number;\n /**\n * Optional file-system overrides for tests. Real callers omit these;\n * the helper falls through to `node:fs`.\n */\n fs?: {\n exists: (path: string) => boolean;\n isFile: (path: string) => boolean;\n size: (path: string) => number;\n read: (path: string) => string;\n };\n}\n\n/**\n * Expand `@path` mentions in `text`. Returns the (possibly augmented)\n * text plus a per-mention report so the caller can surface expansions\n * in the UI.\n */\nexport function expandAtMentions(\n text: string,\n rootDir: string,\n opts: AtMentionOptions = {},\n): { text: string; expansions: AtMentionExpansion[] } {\n const maxBytes = opts.maxBytes ?? DEFAULT_AT_MENTION_MAX_BYTES;\n const fs = opts.fs ?? defaultFs;\n const root = resolve(rootDir);\n // De-dupe by token so `@file.ts` referenced twice inlines once.\n const seen = new Map<string, AtMentionExpansion>();\n const expansions: AtMentionExpansion[] = [];\n\n for (const match of text.matchAll(AT_MENTION_PATTERN)) {\n const rawPath = match[1] ?? \"\";\n // Strip trailing dot (sentence terminator): `@foo.ts.` → `@foo.ts`.\n // Keep internal dots intact.\n const cleaned = rawPath.replace(/\\.+$/, \"\");\n if (!cleaned) continue;\n const token = `@${cleaned}`;\n if (seen.has(token)) continue;\n\n const expansion = resolveMention(cleaned, root, maxBytes, fs);\n seen.set(token, expansion);\n expansions.push(expansion);\n }\n\n if (expansions.length === 0) return { text, expansions };\n\n // Build the trailing \"Referenced files\" block. Keep successful\n // inlines and skipped ones (with their reason) so the model sees\n // both what's here and what's missing.\n const blocks: string[] = [];\n for (const ex of expansions) {\n if (ex.ok) {\n const content = readSafe(root, ex.path, fs);\n blocks.push(`<file path=\"${ex.path}\">\\n${content}\\n</file>`);\n } else {\n blocks.push(`<file path=\"${ex.path}\" skipped=\"${ex.skip}\" />`);\n }\n }\n const augmented = `${text}\\n\\n[Referenced files]\\n${blocks.join(\"\\n\\n\")}`;\n return { text: augmented, expansions };\n}\n\nfunction resolveMention(\n rawPath: string,\n root: string,\n maxBytes: number,\n fs: NonNullable<AtMentionOptions[\"fs\"]>,\n): AtMentionExpansion {\n // Reject absolute paths — `@/etc/passwd` should not inline.\n if (isAbsolute(rawPath)) {\n return { token: `@${rawPath}`, path: rawPath, ok: false, skip: \"escape\" };\n }\n const resolved = resolve(root, rawPath);\n // Sandbox escape: after resolution the path must still be inside root.\n const rel = relative(root, resolved);\n if (rel.startsWith(\"..\") || isAbsolute(rel)) {\n return { token: `@${rawPath}`, path: rawPath, ok: false, skip: \"escape\" };\n }\n if (!fs.exists(resolved)) {\n return { token: `@${rawPath}`, path: rawPath, ok: false, skip: \"missing\" };\n }\n if (!fs.isFile(resolved)) {\n return { token: `@${rawPath}`, path: rawPath, ok: false, skip: \"not-file\" };\n }\n const size = fs.size(resolved);\n if (size > maxBytes) {\n return { token: `@${rawPath}`, path: rawPath, ok: false, skip: \"too-large\", bytes: size };\n }\n return { token: `@${rawPath}`, path: rawPath, ok: true, bytes: size };\n}\n\nfunction readSafe(root: string, rawPath: string, fs: NonNullable<AtMentionOptions[\"fs\"]>): string {\n const resolved = resolve(root, rawPath);\n try {\n return fs.read(resolved);\n } catch {\n return \"(read failed)\";\n }\n}\n\nconst defaultFs: NonNullable<AtMentionOptions[\"fs\"]> = {\n exists: (p) => existsSync(p),\n isFile: (p) => {\n try {\n return statSync(p).isFile();\n } catch {\n return false;\n }\n },\n size: (p) => {\n try {\n return statSync(p).size;\n } catch {\n return 0;\n }\n },\n read: (p) => readFileSync(p, \"utf8\"),\n};\n","/**\n * Project memory — a user-authored `REASONIX.md` in the project root\n * that gets pinned into the immutable-prefix system prompt.\n *\n * Design notes:\n *\n * - The file lands in `ImmutablePrefix.system`, so the whole memory\n * block is hashed into the cache prefix fingerprint. Editing the\n * file invalidates the prefix; unchanged memory across sessions\n * keeps the DeepSeek prefix cache warm. That matches Pillar 1 —\n * memory is a deliberate, stable prefix, not per-turn drift.\n * - Only one source: the working-root `REASONIX.md`. No parent walk,\n * no `~/.reasonix/REASONIX.md`, no CLAUDE.md fallback. User-global\n * memory can come later; for v1 one file == one mental model.\n * - Truncated at 8 000 chars (≈ 2k tokens). `.gitignore` gets 2 000\n * because it's a constraint dump; memory gets more headroom because\n * it's deliberate instructions.\n * - Opt-out via `REASONIX_MEMORY=off|false|0`. No CLI flag — memory\n * is a file, `rm REASONIX.md` is the other opt-out.\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nexport const PROJECT_MEMORY_FILE = \"REASONIX.md\";\nexport const PROJECT_MEMORY_MAX_CHARS = 8000;\n\nexport interface ProjectMemory {\n /** Absolute path the memory was read from. */\n path: string;\n /** Post-truncation content (may include a \"… (truncated N chars)\" marker). */\n content: string;\n /** Original byte length before truncation. */\n originalChars: number;\n /** True iff `originalChars > PROJECT_MEMORY_MAX_CHARS`. */\n truncated: boolean;\n}\n\n/**\n * Read `REASONIX.md` from `rootDir`. Returns `null` when the file is\n * missing, unreadable, or empty (whitespace-only counts as empty — an\n * empty memory file shouldn't perturb the cache prefix).\n */\nexport function readProjectMemory(rootDir: string): ProjectMemory | null {\n const path = join(rootDir, PROJECT_MEMORY_FILE);\n if (!existsSync(path)) return null;\n let raw: string;\n try {\n raw = readFileSync(path, \"utf8\");\n } catch {\n return null;\n }\n const trimmed = raw.trim();\n if (!trimmed) return null;\n const originalChars = trimmed.length;\n const truncated = originalChars > PROJECT_MEMORY_MAX_CHARS;\n const content = truncated\n ? `${trimmed.slice(0, PROJECT_MEMORY_MAX_CHARS)}\\n… (truncated ${\n originalChars - PROJECT_MEMORY_MAX_CHARS\n } chars)`\n : trimmed;\n return { path, content, originalChars, truncated };\n}\n\n/**\n * Resolve whether project memory should be read. Default: on.\n * `REASONIX_MEMORY=off|false|0` turns it off (CI, reproducing issues,\n * intentional offline runs).\n */\nexport function memoryEnabled(): boolean {\n const env = process.env.REASONIX_MEMORY;\n if (env === \"off\" || env === \"false\" || env === \"0\") return false;\n return true;\n}\n\n/**\n * Return `basePrompt` with the project's `REASONIX.md` appended as a\n * \"Project memory\" section. No-op when the file is absent, empty, or\n * memory is disabled via env.\n *\n * The appended block is deterministic — identical input ⇒ identical\n * output — so every session that opens against the same memory file\n * gets the same prefix hash.\n */\nexport function applyProjectMemory(basePrompt: string, rootDir: string): string {\n if (!memoryEnabled()) return basePrompt;\n const mem = readProjectMemory(rootDir);\n if (!mem) return basePrompt;\n return `${basePrompt}\n\n# Project memory (REASONIX.md)\n\nThe user pinned these notes about this project — treat them as authoritative context for every turn:\n\n\\`\\`\\`\n${mem.content}\n\\`\\`\\`\n`;\n}\n","/**\n * User memory — `~/.reasonix/memory/` markdown notes pinned into the\n * immutable-prefix system prompt across sessions.\n *\n * Two scopes:\n * - `global` → `~/.reasonix/memory/global/` (cross-project)\n * - `project` → `~/.reasonix/memory/<hash>/` (per sandbox root)\n *\n * Each scope has an always-loaded `MEMORY.md` index plus zero-or-more\n * `<name>.md` detail files loaded on demand via `recall_memory`.\n *\n * Distinct from `src/project-memory.ts` (REASONIX.md) in purpose:\n * REASONIX.md is committable, team-shared project memory.\n * ~/.reasonix/memory is user-private memory, never committed.\n */\n\nimport { createHash } from \"node:crypto\";\nimport {\n existsSync,\n mkdirSync,\n readFileSync,\n readdirSync,\n unlinkSync,\n writeFileSync,\n} from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join, resolve } from \"node:path\";\nimport { applyProjectMemory, memoryEnabled } from \"./project-memory.js\";\nimport { applySkillsIndex } from \"./skills.js\";\n\nexport const USER_MEMORY_DIR = \"memory\";\nexport const MEMORY_INDEX_FILE = \"MEMORY.md\";\n/** Cap on the index file content loaded into the prefix, per scope. */\nexport const MEMORY_INDEX_MAX_CHARS = 4000;\n\nexport type MemoryType = \"user\" | \"feedback\" | \"project\" | \"reference\";\nexport type MemoryScope = \"global\" | \"project\";\n\nexport interface MemoryEntry {\n name: string;\n type: MemoryType;\n scope: MemoryScope;\n description: string;\n body: string;\n /** ISO date string (YYYY-MM-DD). */\n createdAt: string;\n}\n\nexport interface MemoryStoreOptions {\n /** Override `~/.reasonix` — tests set this to a tmpdir. */\n homeDir?: string;\n /** Absolute sandbox root. Required to use `scope: \"project\"`. */\n projectRoot?: string;\n}\n\nexport interface WriteInput {\n name: string;\n type: MemoryType;\n scope: MemoryScope;\n description: string;\n body: string;\n}\n\nconst VALID_NAME = /^[a-zA-Z0-9_-][a-zA-Z0-9_.-]{1,38}[a-zA-Z0-9]$/;\n\n/**\n * Throws on filename injection attempts (`../foo`, `foo/bar`, leading\n * dots, etc.). Allowed: 3-40 chars, alnum + `_` + `-` + interior `.`.\n */\nexport function sanitizeMemoryName(raw: string): string {\n const trimmed = String(raw ?? \"\").trim();\n if (!VALID_NAME.test(trimmed)) {\n throw new Error(\n `invalid memory name: ${JSON.stringify(raw)} — must be 3-40 chars, alnum/_/-, no path separators`,\n );\n }\n return trimmed;\n}\n\n/** Stable 16-hex-char hash of an absolute sandbox root path. */\nexport function projectHash(rootDir: string): string {\n const abs = resolve(rootDir);\n return createHash(\"sha1\").update(abs).digest(\"hex\").slice(0, 16);\n}\n\nfunction scopeDir(opts: { homeDir: string; scope: MemoryScope; projectRoot?: string }): string {\n if (opts.scope === \"global\") {\n return join(opts.homeDir, USER_MEMORY_DIR, \"global\");\n }\n if (!opts.projectRoot) {\n throw new Error(\"scope=project requires a projectRoot on MemoryStore\");\n }\n return join(opts.homeDir, USER_MEMORY_DIR, projectHash(opts.projectRoot));\n}\n\nfunction ensureDir(p: string): void {\n if (!existsSync(p)) mkdirSync(p, { recursive: true });\n}\n\n/**\n * Parse a `---` frontmatter block off the top of a markdown string.\n * Tolerates missing frontmatter, returning `{}` for data and the full\n * string as body. Only recognizes the simple `key: value` shape — no\n * quoting, no multi-line, no YAML features. Matches what we emit.\n */\nfunction parseFrontmatter(raw: string): { data: Record<string, string>; body: string } {\n const lines = raw.split(/\\r?\\n/);\n if (lines[0] !== \"---\") return { data: {}, body: raw };\n const end = lines.indexOf(\"---\", 1);\n if (end < 0) return { data: {}, body: raw };\n const data: Record<string, string> = {};\n for (let i = 1; i < end; i++) {\n const line = lines[i];\n if (!line) continue;\n const m = line.match(/^([a-zA-Z_][a-zA-Z0-9_-]*):\\s*(.*)$/);\n if (m?.[1]) data[m[1]] = (m[2] ?? \"\").trim();\n }\n return {\n data,\n body: lines\n .slice(end + 1)\n .join(\"\\n\")\n .replace(/^\\n+/, \"\"),\n };\n}\n\nfunction formatFrontmatter(e: WriteInput & { createdAt: string }): string {\n return [\n \"---\",\n `name: ${e.name}`,\n `description: ${e.description.replace(/\\n/g, \" \")}`,\n `type: ${e.type}`,\n `scope: ${e.scope}`,\n `created: ${e.createdAt}`,\n \"---\",\n \"\",\n ].join(\"\\n\");\n}\n\nfunction todayIso(): string {\n const d = new Date();\n return d.toISOString().slice(0, 10);\n}\n\n/**\n * A `MEMORY.md` index line for one entry. One-liner, under ~150 chars.\n * `description` is truncated if it would push past the soft limit.\n */\nfunction indexLine(e: Pick<MemoryEntry, \"name\" | \"description\">): string {\n const safeDesc = e.description.replace(/\\n/g, \" \").trim();\n const max = 130 - e.name.length;\n const clipped = safeDesc.length > max ? `${safeDesc.slice(0, Math.max(1, max - 1))}…` : safeDesc;\n return `- [${e.name}](${e.name}.md) — ${clipped}`;\n}\n\nexport class MemoryStore {\n private readonly homeDir: string;\n private readonly projectRoot: string | undefined;\n\n constructor(opts: MemoryStoreOptions = {}) {\n this.homeDir = opts.homeDir ?? join(homedir(), \".reasonix\");\n this.projectRoot = opts.projectRoot ? resolve(opts.projectRoot) : undefined;\n }\n\n /** Directory this store writes `scope` files into, creating it if needed. */\n dir(scope: MemoryScope): string {\n const d = scopeDir({ homeDir: this.homeDir, scope, projectRoot: this.projectRoot });\n ensureDir(d);\n return d;\n }\n\n /** Absolute path to a memory file (no existence check). */\n pathFor(scope: MemoryScope, name: string): string {\n return join(this.dir(scope), `${sanitizeMemoryName(name)}.md`);\n }\n\n /** True iff this store is configured with a project scope available. */\n hasProjectScope(): boolean {\n return this.projectRoot !== undefined;\n }\n\n /**\n * Read the `MEMORY.md` index for a scope. Returns post-cap content\n * (with a truncation marker if clipped), or `null` when absent / empty.\n */\n loadIndex(\n scope: MemoryScope,\n ): { content: string; originalChars: number; truncated: boolean } | null {\n if (scope === \"project\" && !this.projectRoot) return null;\n const file = join(\n scopeDir({ homeDir: this.homeDir, scope, projectRoot: this.projectRoot }),\n MEMORY_INDEX_FILE,\n );\n if (!existsSync(file)) return null;\n let raw: string;\n try {\n raw = readFileSync(file, \"utf8\");\n } catch {\n return null;\n }\n const trimmed = raw.trim();\n if (!trimmed) return null;\n const originalChars = trimmed.length;\n const truncated = originalChars > MEMORY_INDEX_MAX_CHARS;\n const content = truncated\n ? `${trimmed.slice(0, MEMORY_INDEX_MAX_CHARS)}\\n… (truncated ${originalChars - MEMORY_INDEX_MAX_CHARS} chars)`\n : trimmed;\n return { content, originalChars, truncated };\n }\n\n /** Read one memory file's body (frontmatter stripped). Throws if missing. */\n read(scope: MemoryScope, name: string): MemoryEntry {\n const file = this.pathFor(scope, name);\n if (!existsSync(file)) {\n throw new Error(`memory not found: scope=${scope} name=${name}`);\n }\n const raw = readFileSync(file, \"utf8\");\n const { data, body } = parseFrontmatter(raw);\n return {\n name: data.name ?? name,\n type: (data.type as MemoryType) ?? \"project\",\n scope: (data.scope as MemoryScope) ?? scope,\n description: data.description ?? \"\",\n body: body.trim(),\n createdAt: data.created ?? \"\",\n };\n }\n\n /**\n * List every memory in this store. Scans both scopes (skips project\n * scope if unconfigured). Silently skips malformed files; the index\n * must stay queryable even if one file is hand-edited into nonsense.\n */\n list(): MemoryEntry[] {\n const out: MemoryEntry[] = [];\n const scopes: MemoryScope[] = this.projectRoot ? [\"global\", \"project\"] : [\"global\"];\n for (const scope of scopes) {\n const dir = scopeDir({ homeDir: this.homeDir, scope, projectRoot: this.projectRoot });\n if (!existsSync(dir)) continue;\n let entries: string[];\n try {\n entries = readdirSync(dir);\n } catch {\n continue;\n }\n for (const entry of entries) {\n if (entry === MEMORY_INDEX_FILE) continue;\n if (!entry.endsWith(\".md\")) continue;\n const name = entry.slice(0, -3);\n try {\n out.push(this.read(scope, name));\n } catch {\n // malformed file — skip rather than fail the whole list\n }\n }\n }\n return out;\n }\n\n /**\n * Write a new memory (or overwrite existing). Creates the scope dir,\n * writes the `.md` file, and regenerates `MEMORY.md`. Returns the\n * absolute path written to.\n */\n write(input: WriteInput): string {\n if (input.scope === \"project\" && !this.projectRoot) {\n throw new Error(\"cannot write project-scoped memory: no projectRoot configured\");\n }\n const name = sanitizeMemoryName(input.name);\n const desc = String(input.description ?? \"\").trim();\n if (!desc) throw new Error(\"memory description cannot be empty\");\n const body = String(input.body ?? \"\").trim();\n if (!body) throw new Error(\"memory body cannot be empty\");\n const entry: WriteInput & { createdAt: string } = {\n ...input,\n name,\n description: desc,\n body,\n createdAt: todayIso(),\n };\n const dir = this.dir(input.scope);\n const file = join(dir, `${name}.md`);\n const content = `${formatFrontmatter(entry)}${body}\\n`;\n writeFileSync(file, content, \"utf8\");\n this.regenerateIndex(input.scope);\n return file;\n }\n\n /** Delete one memory + its index line. No-op if the file is already gone. */\n delete(scope: MemoryScope, rawName: string): boolean {\n if (scope === \"project\" && !this.projectRoot) {\n throw new Error(\"cannot delete project-scoped memory: no projectRoot configured\");\n }\n const file = this.pathFor(scope, rawName);\n if (!existsSync(file)) return false;\n unlinkSync(file);\n this.regenerateIndex(scope);\n return true;\n }\n\n /**\n * Rebuild `MEMORY.md` from the `.md` files currently in the scope dir.\n * Called after every write/delete. Sorted by name for stable prefix\n * hashing — two stores with the same set of files produce byte-identical\n * MEMORY.md content, keeping the cache prefix reproducible.\n */\n private regenerateIndex(scope: MemoryScope): void {\n const dir = scopeDir({ homeDir: this.homeDir, scope, projectRoot: this.projectRoot });\n if (!existsSync(dir)) return;\n let files: string[];\n try {\n files = readdirSync(dir);\n } catch {\n return;\n }\n const mdFiles = files\n .filter((f) => f !== MEMORY_INDEX_FILE && f.endsWith(\".md\"))\n .sort((a, b) => a.localeCompare(b));\n const indexPath = join(dir, MEMORY_INDEX_FILE);\n if (mdFiles.length === 0) {\n if (existsSync(indexPath)) unlinkSync(indexPath);\n return;\n }\n const lines: string[] = [];\n for (const f of mdFiles) {\n const name = f.slice(0, -3);\n try {\n const entry = this.read(scope, name);\n lines.push(indexLine({ name: entry.name || name, description: entry.description }));\n } catch {\n // Malformed: still surface it in the index so the user notices.\n lines.push(`- [${name}](${name}.md) — (malformed, check frontmatter)`);\n }\n }\n writeFileSync(indexPath, `${lines.join(\"\\n\")}\\n`, \"utf8\");\n }\n}\n\n/**\n * Append `MEMORY_GLOBAL` and (optionally) `MEMORY_PROJECT` blocks to\n * `basePrompt`. Omits a block entirely when its index is absent — an\n * empty tag would add bytes to the prefix hash without content.\n * Respects `REASONIX_MEMORY=off` via `memoryEnabled()` from\n * `project-memory.ts`.\n */\nexport function applyUserMemory(\n basePrompt: string,\n opts: { homeDir?: string; projectRoot?: string } = {},\n): string {\n if (!memoryEnabled()) return basePrompt;\n const store = new MemoryStore(opts);\n const global = store.loadIndex(\"global\");\n const project = store.hasProjectScope() ? store.loadIndex(\"project\") : null;\n if (!global && !project) return basePrompt;\n const parts: string[] = [basePrompt];\n if (global) {\n parts.push(\n \"\",\n \"# User memory — global (~/.reasonix/memory/global/MEMORY.md)\",\n \"\",\n \"Cross-project facts and preferences the user has told you in prior sessions. TREAT AS AUTHORITATIVE — don't re-verify via filesystem or web. One-liners index detail files; call `recall_memory` for full bodies only when the one-liner isn't enough.\",\n \"\",\n \"```\",\n global.content,\n \"```\",\n );\n }\n if (project) {\n parts.push(\n \"\",\n \"# User memory — this project\",\n \"\",\n \"Per-project facts the user established in prior sessions (not committed to the repo). TREAT AS AUTHORITATIVE. Same recall pattern as global memory.\",\n \"\",\n \"```\",\n project.content,\n \"```\",\n );\n }\n return parts.join(\"\\n\");\n}\n\n/**\n * Compose every lazy-loaded prefix block in one call: REASONIX.md,\n * user memory (global + project), and the skills index. Drop-in\n * replacement for `applyProjectMemory` at CLI entry points. Stacking\n * order is stable — the prefix hash only changes when block *content*\n * changes, not when this helper is called a second time with the same\n * filesystem state.\n */\nexport function applyMemoryStack(basePrompt: string, rootDir: string): string {\n const withProject = applyProjectMemory(basePrompt, rootDir);\n const withMemory = applyUserMemory(withProject, { projectRoot: rootDir });\n return applySkillsIndex(withMemory, { projectRoot: rootDir });\n}\n","/**\n * Skills — user-defined prompt packs pinned (by name) into the\n * immutable prefix and loaded (by body) on demand.\n *\n * Two scopes mirror the user-memory layout:\n * - `project` → `<projectRoot>/.reasonix/skills/` (this repo only)\n * - `global` → `~/.reasonix/skills/` (every session)\n *\n * Project scope wins on a name collision. Deliberately NOT tied to\n * any specific client's directory convention (`.claude/`, `.glm/`,\n * etc.) — Reasonix is model-agnostic at the conversation layer, so\n * coupling the skill filesystem to one vendor would break any user\n * running a different backend.\n *\n * Accepted file layouts (both emit the same `Skill`):\n * - `{dir}/<name>/SKILL.md` (preferred — lets a skill bundle\n * additional assets alongside)\n * - `{dir}/<name>.md` (flat, one-file shorthand)\n *\n * Frontmatter keys we read:\n * - `name` — optional, defaults to the file / dir name\n * - `description` — one-line index description (REQUIRED for listing)\n * - `allowed-tools` — parsed but UNUSED in v1 (see tools/skills.ts)\n *\n * Cache-First contract (Pillar 1):\n * - The PREFIX sees only names + descriptions (one line each).\n * - Bodies enter the APPEND-ONLY LOG lazily, via `run_skill` or\n * `/skill <name>` — never the prefix. That keeps the prefix hash\n * stable across skill additions to the body store.\n */\n\nimport { existsSync, readFileSync, readdirSync, statSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join, resolve } from \"node:path\";\n\nexport const SKILLS_DIRNAME = \"skills\";\nexport const SKILL_FILE = \"SKILL.md\";\n/** Cap on the pinned skills-index block, mirrors memory-index cap. */\nexport const SKILLS_INDEX_MAX_CHARS = 4000;\n/** Skill identifier shape — alnum + `_` + `-` + interior `.`, 1-64 chars. */\nconst VALID_SKILL_NAME = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/;\n\nexport type SkillScope = \"project\" | \"global\" | \"builtin\";\n\n/**\n * Execution mode for a skill. `inline` (default) returns the body as a\n * tool result so the body enters the parent's append-only log — the\n * model continues the loop using the loaded instructions. `subagent`\n * spawns an isolated child loop with the body as the system prompt and\n * the user-supplied `arguments` as the task; only the child's final\n * answer comes back. Use `subagent` for big-context exploration / research\n * playbooks where the parent doesn't need to see the trail.\n */\nexport type SkillRunAs = \"inline\" | \"subagent\";\n\nexport interface Skill {\n /** Canonical name — sanitized, matches the directory / filename stem. */\n name: string;\n /** One-line description shown in the pinned index. */\n description: string;\n /** Full markdown body (post-frontmatter). Loaded on demand. */\n body: string;\n /** Which scope this skill was loaded from. */\n scope: SkillScope;\n /** Absolute path to the SKILL.md (or {name}.md) file, or \"(builtin)\" for shipped defaults. */\n path: string;\n /** Raw `allowed-tools` field from frontmatter, if any. Unused in v1. */\n allowedTools?: string;\n /**\n * Execution mode (frontmatter `runAs`). Defaults to `inline` for\n * backwards compatibility with skills written before this field\n * existed.\n */\n runAs: SkillRunAs;\n /**\n * Frontmatter `model` — when set, overrides the default model the\n * subagent runs on. Only meaningful when `runAs === \"subagent\"`.\n * Accept any DeepSeek model id; the subagent layer falls back to its\n * own default if this is missing or invalid.\n */\n model?: string;\n}\n\nexport interface SkillStoreOptions {\n /** Override `$HOME` — tests point this at a tmpdir. */\n homeDir?: string;\n /**\n * Absolute project root. Required to surface project-scope skills;\n * omit (e.g. in `reasonix chat` without `code`) and the store only\n * reads the global scope.\n */\n projectRoot?: string;\n /**\n * Suppress the bundled built-in skills (`explore`, `research`).\n * Used by unit tests that want to assert exact list contents\n * without the +2 builtins distorting counts. Production callers\n * leave this off so users always get the bundled defaults.\n */\n disableBuiltins?: boolean;\n}\n\n/**\n * Parse a `---` frontmatter block. Same minimal shape as user-memory:\n * `key: value` lines, no quoting, no nesting. Returns `{}` data and the\n * full input as body when no frontmatter fence is present — so hand-\n * written files without frontmatter still surface (with empty desc).\n */\nfunction parseFrontmatter(raw: string): { data: Record<string, string>; body: string } {\n const lines = raw.split(/\\r?\\n/);\n if (lines[0] !== \"---\") return { data: {}, body: raw };\n const end = lines.indexOf(\"---\", 1);\n if (end < 0) return { data: {}, body: raw };\n const data: Record<string, string> = {};\n for (let i = 1; i < end; i++) {\n const line = lines[i];\n if (!line) continue;\n const m = line.match(/^([a-zA-Z_][a-zA-Z0-9_-]*):\\s*(.*)$/);\n if (m?.[1]) data[m[1]] = (m[2] ?? \"\").trim();\n }\n return {\n data,\n body: lines\n .slice(end + 1)\n .join(\"\\n\")\n .replace(/^\\n+/, \"\"),\n };\n}\n\nfunction isValidSkillName(name: string): boolean {\n return VALID_SKILL_NAME.test(name);\n}\n\nexport class SkillStore {\n private readonly homeDir: string;\n private readonly projectRoot: string | undefined;\n private readonly disableBuiltins: boolean;\n\n constructor(opts: SkillStoreOptions = {}) {\n this.homeDir = opts.homeDir ?? homedir();\n this.projectRoot = opts.projectRoot ? resolve(opts.projectRoot) : undefined;\n this.disableBuiltins = opts.disableBuiltins === true;\n }\n\n /** True iff this store was configured with a project root. */\n hasProjectScope(): boolean {\n return this.projectRoot !== undefined;\n }\n\n /**\n * Root directories scanned, in priority order. Project scope first\n * so a per-repo skill overrides a global one with the same name —\n * users expect the local copy to win when both exist.\n */\n roots(): Array<{ dir: string; scope: SkillScope }> {\n const out: Array<{ dir: string; scope: SkillScope }> = [];\n if (this.projectRoot) {\n out.push({\n dir: join(this.projectRoot, \".reasonix\", SKILLS_DIRNAME),\n scope: \"project\",\n });\n }\n out.push({ dir: join(this.homeDir, \".reasonix\", SKILLS_DIRNAME), scope: \"global\" });\n return out;\n }\n\n /**\n * List every skill visible to this store. On name collisions the\n * higher-priority root (project over global over builtin) wins.\n * Sorted by name for stable prefix hashing.\n */\n list(): Skill[] {\n const byName = new Map<string, Skill>();\n for (const { dir, scope } of this.roots()) {\n if (!existsSync(dir)) continue;\n let entries: import(\"node:fs\").Dirent[];\n try {\n entries = readdirSync(dir, { withFileTypes: true });\n } catch {\n continue;\n }\n for (const entry of entries) {\n const skill = this.readEntry(dir, scope, entry);\n if (!skill) continue;\n if (!byName.has(skill.name)) byName.set(skill.name, skill);\n }\n }\n // Builtins are appended last so user/project files take precedence\n // when names collide. The same priority you'd expect: my-project's\n // \"explore\" overrides the shipped one without forcing a different\n // name.\n if (!this.disableBuiltins) {\n for (const skill of BUILTIN_SKILLS) {\n if (!byName.has(skill.name)) byName.set(skill.name, skill);\n }\n }\n return [...byName.values()].sort((a, b) => a.name.localeCompare(b.name));\n }\n\n /** Resolve one skill by name. Returns `null` if not found or malformed. */\n read(name: string): Skill | null {\n if (!isValidSkillName(name)) return null;\n for (const { dir, scope } of this.roots()) {\n if (!existsSync(dir)) continue;\n const dirCandidate = join(dir, name, SKILL_FILE);\n if (existsSync(dirCandidate) && statSync(dirCandidate).isFile()) {\n return this.parse(dirCandidate, name, scope);\n }\n const flatCandidate = join(dir, `${name}.md`);\n if (existsSync(flatCandidate) && statSync(flatCandidate).isFile()) {\n return this.parse(flatCandidate, name, scope);\n }\n }\n // Fall back to builtins. Same precedence as `list()` — user-authored\n // wins, builtins are the floor.\n if (!this.disableBuiltins) {\n for (const skill of BUILTIN_SKILLS) {\n if (skill.name === name) return skill;\n }\n }\n return null;\n }\n\n private readEntry(dir: string, scope: SkillScope, entry: import(\"node:fs\").Dirent): Skill | null {\n if (entry.isDirectory()) {\n if (!isValidSkillName(entry.name)) return null;\n const file = join(dir, entry.name, SKILL_FILE);\n if (!existsSync(file)) return null;\n return this.parse(file, entry.name, scope);\n }\n if (entry.isFile() && entry.name.endsWith(\".md\")) {\n const stem = entry.name.slice(0, -3);\n if (!isValidSkillName(stem)) return null;\n return this.parse(join(dir, entry.name), stem, scope);\n }\n return null;\n }\n\n private parse(path: string, stem: string, scope: SkillScope): Skill | null {\n let raw: string;\n try {\n raw = readFileSync(path, \"utf8\");\n } catch {\n return null;\n }\n const { data, body } = parseFrontmatter(raw);\n const name = data.name && isValidSkillName(data.name) ? data.name : stem;\n return {\n name,\n description: (data.description ?? \"\").trim(),\n body: body.trim(),\n scope,\n path,\n allowedTools: data[\"allowed-tools\"],\n runAs: parseRunAs(data.runAs),\n model: data.model?.startsWith(\"deepseek-\") ? data.model : undefined,\n };\n }\n}\n\n/**\n * Coerce a frontmatter `runAs` string to the discriminated union. Any\n * value other than the literal \"subagent\" is treated as inline — typos\n * and unknown values default to the safe (non-spawning) mode rather\n * than failing the load.\n */\nfunction parseRunAs(raw: string | undefined): SkillRunAs {\n return raw?.trim() === \"subagent\" ? \"subagent\" : \"inline\";\n}\n\n/**\n * Build a single index line for one skill. Shape mirrors memory's\n * `indexLine` — a bullet suitable for a markdown fenced block in the\n * system prompt. Description is truncated to keep the full line under\n * ~150 chars. Subagent-runAs skills carry a 🧬 marker so the model\n * sees at a glance which skills will spawn an isolated child loop.\n */\nfunction skillIndexLine(s: Pick<Skill, \"name\" | \"description\" | \"runAs\">): string {\n const safeDesc = s.description.replace(/\\n/g, \" \").trim();\n const marker = s.runAs === \"subagent\" ? \"🧬 \" : \"\";\n const max = 130 - s.name.length - marker.length;\n const clipped = safeDesc.length > max ? `${safeDesc.slice(0, Math.max(1, max - 1))}…` : safeDesc;\n return clipped ? `- ${marker}${s.name} — ${clipped}` : `- ${marker}${s.name}`;\n}\n\n/**\n * Append a `# Skills` block to `basePrompt` listing every discovered\n * skill (name + description only). Bodies are NOT inlined — that's the\n * whole point: the prefix stays short and cacheable; full content loads\n * on demand via `run_skill` or `/skill <name>`.\n *\n * Emits nothing when no skills are discovered — keeps the prefix hash\n * stable for users who don't use skills at all.\n */\nexport function applySkillsIndex(basePrompt: string, opts: SkillStoreOptions = {}): string {\n const store = new SkillStore(opts);\n const skills = store.list().filter((s) => s.description);\n if (skills.length === 0) return basePrompt;\n const lines = skills.map(skillIndexLine);\n const joined = lines.join(\"\\n\");\n const truncated =\n joined.length > SKILLS_INDEX_MAX_CHARS\n ? `${joined.slice(0, SKILLS_INDEX_MAX_CHARS)}\\n… (truncated ${\n joined.length - SKILLS_INDEX_MAX_CHARS\n } chars)`\n : joined;\n return [\n basePrompt,\n \"\",\n \"# Skills — playbooks you can invoke\",\n \"\",\n 'One-liner index. Each entry is either a built-in or a user-authored playbook. Call `run_skill({ name: \"<skill-name>\", arguments: \"<task>\" })` to invoke one. Skills marked with 🧬 spawn an **isolated subagent** — its tool calls and reasoning never enter your context, only its final answer does. Use 🧬 skills for tasks that would otherwise flood your context (deep exploration, multi-step research, anything where you only need the conclusion). Plain skills are inlined: their body becomes a tool result you read and act on directly. The user can also invoke a skill via `/skill <name>`.',\n \"\",\n \"```\",\n truncated,\n \"```\",\n ].join(\"\\n\");\n}\n\n/**\n * Built-in skills shipped with Reasonix. These are always available\n * (no install step) and live as constants rather than files because:\n * - Zero filesystem coupling — no copy-on-first-run dance, nothing\n * to migrate when we update them.\n * - They participate in the same `byName` priority as user/project\n * skills: write `~/.reasonix/skills/explore.md` to override.\n *\n * Keep this list small and high-leverage. The bar for adding one: it\n * demonstrates a pattern users would otherwise have to invent\n * themselves, and the body fits in a screen.\n */\nconst BUILTIN_EXPLORE_BODY = `You are running as an exploration subagent. Your job is to investigate the codebase the parent agent pointed you at, then return one focused, distilled answer.\n\nHow to operate:\n- Use read_file, search_files, search_content, directory_tree, list_directory, get_file_info as your primary tools. Stay read-only.\n- For \"find all places that call / reference / use X\" questions, use \\`search_content\\` (content grep) — NOT \\`search_files\\` (which only matches file names). This is the most common subagent mistake; using the wrong tool gives empty results and you waste your iter budget chasing a phantom.\n- Cast a wide net first (search_content for symbol references, directory_tree for structure) to map the territory; then read the 3-10 most relevant files in full.\n- Don't read every file — be selective. Aim for breadth on the first pass, depth only where the question demands it.\n- Stop exploring as soon as you can answer the question. The parent doesn't see your tool calls, so over-exploration is pure waste.\n\nYour final answer:\n- One paragraph (or a few short bullets). Lead with the conclusion.\n- Cite specific file paths + line ranges when they support the answer.\n- If the question can't be answered from what you found, say so plainly and suggest where to look next.\n- No follow-up offers, no \"let me know if you need more.\" The parent will ask again if they need more.\n\nFormatting (rendered in a TUI):\n- Tabular data → GitHub-Flavored Markdown tables with ASCII pipes (\\`| col | col |\\` + \\`| --- | --- |\\`). Never use Unicode box-drawing characters (│ ─ ┼) — they break word-wrap.\n- Keep table cells short; if a cell needs a paragraph, use bullets below the table instead.\n- Code, file paths with line ranges, and shell commands → fenced code blocks (\\`\\`\\`).\n- NEVER draw decorative frames around code or text with \\`┌──┐ │ └──┘\\` box-drawing characters. Use plain code blocks; the renderer adds its own border.\n- For flow charts: use a bullet list with \\`→\\` or \\`↓\\` between steps, not ASCII boxes-and-arrows.\n\nThe 'task' the parent gave you is the question you must answer. Treat any other reading of it as scope creep.`;\n\nconst BUILTIN_RESEARCH_BODY = `You are running as a research subagent. Your job is to gather information from code AND the web, synthesize it, and return one focused conclusion.\n\nHow to operate:\n- Combine code reading (read_file, search_files) with web tools (web_search, web_fetch) as appropriate to the question.\n- For \"how does X work\" / \"is Y supported\" questions: web first to find the canonical reference, then verify against the local code.\n- For \"what's our policy on Z\" / \"where do we use Q\": local code first, web only if you need to compare against external standards.\n- Cap yourself at ~10 tool calls. If you can't converge in 10, return what you have plus a note about what's missing.\n\nYour final answer:\n- One paragraph (or short bullets). Lead with the conclusion.\n- Cite both code (file:line) AND web sources (URL) when they back the answer.\n- Distinguish \"I verified this in code\" from \"I read this on a docs page\" — the parent will trust the former more.\n- If the answer is uncertain, say so. Don't invent confidence.\n\nFormatting (rendered in a TUI):\n- Tabular data → GitHub-Flavored Markdown tables with ASCII pipes (\\`| col | col |\\` + \\`| --- | --- |\\`). Never use Unicode box-drawing characters (│ ─ ┼) — they break word-wrap.\n- Keep table cells short; if a cell needs a paragraph, use bullets below the table instead.\n- Code, file paths with line ranges, and shell commands → fenced code blocks (\\`\\`\\`).\n- NEVER draw decorative frames around code or text with \\`┌──┐ │ └──┘\\` box-drawing characters. Use plain code blocks; the renderer adds its own border.\n- For flow charts: use a bullet list with \\`→\\` or \\`↓\\` between steps, not ASCII boxes-and-arrows.\n\nThe 'task' the parent gave you is the research question. Stay on it.`;\n\nconst BUILTIN_SKILLS: readonly Skill[] = Object.freeze([\n Object.freeze<Skill>({\n name: \"explore\",\n description:\n \"Explore the codebase in an isolated subagent — wide-net read-only investigation that returns one distilled answer. Best for: 'find all places that...', 'how does X work across the project', 'survey the code for Y'.\",\n body: BUILTIN_EXPLORE_BODY,\n scope: \"builtin\",\n path: \"(builtin)\",\n runAs: \"subagent\",\n }),\n Object.freeze<Skill>({\n name: \"research\",\n description:\n \"Research a question by combining web search + code reading in an isolated subagent. Best for: 'is X feature supported by lib Y', 'what's the canonical way to do Z', 'compare our impl against the spec'.\",\n body: BUILTIN_RESEARCH_BODY,\n scope: \"builtin\",\n path: \"(builtin)\",\n runAs: \"subagent\",\n }),\n]);\n","/**\n * Built-in filesystem tools for `reasonix code`.\n *\n * Why native instead of the official `@modelcontextprotocol/server-filesystem`:\n * - No subprocess overhead — every call is 50-200 ms cheaper.\n * - Schema shapes tuned for R1: `edit_file` takes a single\n * SEARCH/REPLACE string instead of `string=\"false\"`-encoded\n * JSON arrays, which was the biggest single source of DSML\n * hallucinations in 0.4.x.\n * - Sandbox enforcement lives here so Reasonix can reason about\n * it (tests cover path-traversal, symlink-escape, and the\n * cwd-outside-root case) rather than trusting an external server.\n * - No `npx install` / network dependency in `reasonix code`.\n *\n * Tool names + argument shapes intentionally mirror the official\n * filesystem server so R1's muscle memory carries over. The only\n * intentional divergence is `edit_file`, noted above.\n */\n\nimport { promises as fs } from \"node:fs\";\nimport * as pathMod from \"node:path\";\nimport type { ToolRegistry } from \"../tools.js\";\n\nexport interface FilesystemToolsOptions {\n /** Absolute directory the tools may read/write. Paths outside this are refused. */\n rootDir: string;\n /**\n * When `false`, register only read-side tools (read_file, list_directory,\n * search_files, get_file_info, directory_tree). Useful for read-only\n * workflows where the model should never mutate the tree. Default: true.\n */\n allowWriting?: boolean;\n /**\n * Cap for a single file read, in bytes. Prevents a stray `read_file`\n * on a multi-GB blob from OOM'ing Node. 2 MB is enough for any realistic\n * source file (the biggest single-file TypeScript project checked in to\n * GitHub is ~500 KB); pass higher when working with data files.\n */\n maxReadBytes?: number;\n /**\n * Cap for total bytes returned from search_files / directory_tree /\n * grep, so the model can't accidentally pull down the whole tree as\n * one giant string. 256 KB by default.\n */\n maxListBytes?: number;\n}\n\nconst DEFAULT_MAX_READ_BYTES = 2 * 1024 * 1024;\nconst DEFAULT_MAX_LIST_BYTES = 256 * 1024;\n\n/**\n * Directory names skipped by `search_content` unless `include_deps:true`\n * is passed. The intent is \"user is asking about THEIR code, not the\n * libraries they depend on\" — vendored / generated trees would otherwise\n * dominate every match list. Pass include_deps when you genuinely need\n * to grep a dependency.\n */\nconst SKIP_DIR_NAMES: ReadonlySet<string> = new Set([\n \"node_modules\",\n \".git\",\n \".hg\",\n \".svn\",\n \"dist\",\n \"build\",\n \"out\",\n \".next\",\n \".nuxt\",\n \"target\", // Rust / Java\n \".venv\",\n \"venv\",\n \"__pycache__\",\n \".pytest_cache\",\n \".mypy_cache\",\n \".cache\",\n \"coverage\",\n]);\n\n/**\n * Cheap binary-by-extension check for `search_content`. We err on the\n * side of skipping so a NUL-byte content sniff is the second line of\n * defense (handles e.g. a `.txt` that's actually a binary dump).\n */\nconst BINARY_EXTENSIONS: ReadonlySet<string> = new Set([\n \".png\",\n \".jpg\",\n \".jpeg\",\n \".gif\",\n \".bmp\",\n \".ico\",\n \".webp\",\n \".tiff\",\n \".pdf\",\n \".zip\",\n \".tar\",\n \".gz\",\n \".bz2\",\n \".xz\",\n \".7z\",\n \".rar\",\n \".exe\",\n \".dll\",\n \".so\",\n \".dylib\",\n \".bin\",\n \".class\",\n \".jar\",\n \".war\",\n \".o\",\n \".obj\",\n \".lib\",\n \".a\",\n \".woff\",\n \".woff2\",\n \".ttf\",\n \".otf\",\n \".eot\",\n \".mp3\",\n \".mp4\",\n \".mov\",\n \".avi\",\n \".webm\",\n \".wasm\",\n \".pyc\",\n \".pyo\",\n]);\n\nfunction isLikelyBinaryByName(name: string): boolean {\n const dot = name.lastIndexOf(\".\");\n if (dot < 0) return false;\n return BINARY_EXTENSIONS.has(name.slice(dot).toLowerCase());\n}\n\nexport function registerFilesystemTools(\n registry: ToolRegistry,\n opts: FilesystemToolsOptions,\n): ToolRegistry {\n const rootDir = pathMod.resolve(opts.rootDir);\n const allowWriting = opts.allowWriting !== false;\n const maxReadBytes = opts.maxReadBytes ?? DEFAULT_MAX_READ_BYTES;\n const maxListBytes = opts.maxListBytes ?? DEFAULT_MAX_LIST_BYTES;\n\n /** Resolve path, enforce it's under rootDir, return absolute. */\n const safePath = (raw: unknown): string => {\n if (typeof raw !== \"string\" || raw.length === 0) {\n throw new Error(\"path must be a non-empty string\");\n }\n // Sandbox-root semantics: a leading POSIX-style `/` (or `\\` on\n // Windows) means \"from the project root\", not \"from the filesystem\n // root\". Models routinely write `path: \"/\"` or `path: \"/src/foo.ts\"`\n // intending the sandbox root — without this normalization,\n // path.resolve interprets `/` as the actual drive root (`F:\\` on\n // Windows, `/` on POSIX) and the escape check rightly rejects it,\n // confusing the model. Strip leading separators so the rest of the\n // resolution treats the input as relative to rootDir. Drive-letter\n // absolutes (`C:\\foo`) and Unix absolutes outside rootDir still\n // get caught by the relative-escape check below.\n let normalized = raw;\n while (normalized.startsWith(\"/\") || normalized.startsWith(\"\\\\\")) {\n normalized = normalized.slice(1);\n }\n if (normalized.length === 0) normalized = \".\";\n const resolved = pathMod.resolve(rootDir, normalized);\n const normRoot = pathMod.resolve(rootDir);\n // Use relative() to catch any `..` segments that escape.\n const rel = pathMod.relative(normRoot, resolved);\n if (rel.startsWith(\"..\") || pathMod.isAbsolute(rel)) {\n throw new Error(`path escapes sandbox root (${normRoot}): ${raw}`);\n }\n return resolved;\n };\n\n registry.register({\n name: \"read_file\",\n description:\n \"Read a file under the sandbox root. Returns the full contents (truncated with a notice if larger than the per-call cap). Paths may be relative to the root or absolute-under-root.\",\n readOnly: true,\n parameters: {\n type: \"object\",\n properties: {\n path: { type: \"string\", description: \"Path to read (relative to rootDir or absolute).\" },\n head: { type: \"integer\", description: \"If set, return only the first N lines.\" },\n tail: { type: \"integer\", description: \"If set, return only the last N lines.\" },\n },\n required: [\"path\"],\n },\n fn: async (args: { path: string; head?: number; tail?: number }) => {\n const abs = safePath(args.path);\n const stat = await fs.stat(abs);\n if (stat.isDirectory()) {\n throw new Error(`not a file: ${args.path} (it's a directory)`);\n }\n const raw = await fs.readFile(abs);\n if (raw.length > maxReadBytes) {\n const head = raw.slice(0, maxReadBytes).toString(\"utf8\");\n return `${head}\\n\\n[…truncated ${raw.length - maxReadBytes} bytes — file is ${raw.length} B, cap ${maxReadBytes} B. Retry with head/tail for targeted view.]`;\n }\n const text = raw.toString(\"utf8\");\n if (typeof args.head === \"number\" && args.head > 0) {\n return text.split(/\\r?\\n/).slice(0, args.head).join(\"\\n\");\n }\n if (typeof args.tail === \"number\" && args.tail > 0) {\n let lines = text.split(/\\r?\\n/);\n // Most files end with a final '\\n', which splits into an empty\n // trailing string. Drop it before slicing so tail=2 returns the\n // last two *real* lines, not \"last line + empty\".\n if (lines.length > 0 && lines[lines.length - 1] === \"\") lines = lines.slice(0, -1);\n return lines.slice(Math.max(0, lines.length - args.tail)).join(\"\\n\");\n }\n return text;\n },\n });\n\n registry.register({\n name: \"list_directory\",\n description:\n \"List entries in a directory under the sandbox root. Returns one line per entry, marking directories with a trailing slash. Not recursive — use directory_tree for that.\",\n readOnly: true,\n parameters: {\n type: \"object\",\n properties: {\n path: { type: \"string\", description: \"Directory to list (default: root).\" },\n },\n },\n fn: async (args: { path?: string }) => {\n const abs = safePath(args.path ?? \".\");\n const entries = await fs.readdir(abs, { withFileTypes: true });\n const lines: string[] = [];\n for (const e of entries.sort((a, b) => a.name.localeCompare(b.name))) {\n lines.push(e.isDirectory() ? `${e.name}/` : e.name);\n }\n return lines.join(\"\\n\") || \"(empty directory)\";\n },\n });\n\n registry.register({\n name: \"directory_tree\",\n description:\n \"Recursively list entries in a directory. Shows indented tree structure with directories marked '/'. Caps output so a huge tree doesn't drown the context.\",\n readOnly: true,\n parameters: {\n type: \"object\",\n properties: {\n path: { type: \"string\", description: \"Root of the tree (default: sandbox root).\" },\n maxDepth: { type: \"integer\", description: \"Max recursion depth (default 4).\" },\n },\n },\n fn: async (args: { path?: string; maxDepth?: number }) => {\n const startAbs = safePath(args.path ?? \".\");\n const maxDepth = typeof args.maxDepth === \"number\" ? args.maxDepth : 4;\n const lines: string[] = [];\n let totalBytes = 0;\n let truncated = false;\n const walk = async (dir: string, depth: number): Promise<void> => {\n if (truncated) return;\n if (depth > maxDepth) return;\n let entries: import(\"node:fs\").Dirent[];\n try {\n entries = await fs.readdir(dir, { withFileTypes: true });\n } catch {\n return;\n }\n entries.sort((a, b) => a.name.localeCompare(b.name));\n for (const e of entries) {\n if (truncated) return;\n const indent = \" \".repeat(depth);\n const line = e.isDirectory() ? `${indent}${e.name}/` : `${indent}${e.name}`;\n totalBytes += line.length + 1;\n if (totalBytes > maxListBytes) {\n lines.push(` [… tree truncated at ${maxListBytes} bytes …]`);\n truncated = true;\n return;\n }\n lines.push(line);\n if (e.isDirectory()) {\n await walk(pathMod.join(dir, e.name), depth + 1);\n }\n }\n };\n await walk(startAbs, 0);\n return lines.join(\"\\n\") || \"(empty tree)\";\n },\n });\n\n registry.register({\n name: \"search_files\",\n description:\n \"Find files whose NAME matches a substring or regex. Case-insensitive. Walks the directory recursively under the sandbox root. Returns one path per line.\",\n readOnly: true,\n parameters: {\n type: \"object\",\n properties: {\n path: { type: \"string\", description: \"Directory to start the search at (default: root).\" },\n pattern: {\n type: \"string\",\n description: \"Substring (or regex) to match against filenames.\",\n },\n },\n required: [\"pattern\"],\n },\n fn: async (args: { path?: string; pattern: string }) => {\n const startAbs = safePath(args.path ?? \".\");\n const needle = args.pattern.toLowerCase();\n // Try as regex first (permits users who want patterns); fall\n // back to plain substring when it's not a valid regex. Flag `i`\n // so matching is case-insensitive regardless of path.\n let re: RegExp | null = null;\n try {\n re = new RegExp(args.pattern, \"i\");\n } catch {\n re = null;\n }\n const matches: string[] = [];\n let totalBytes = 0;\n const walk = async (dir: string): Promise<void> => {\n let entries: import(\"node:fs\").Dirent[];\n try {\n entries = await fs.readdir(dir, { withFileTypes: true });\n } catch {\n return;\n }\n for (const e of entries) {\n const full = pathMod.join(dir, e.name);\n const lower = e.name.toLowerCase();\n const hit = re ? re.test(e.name) : lower.includes(needle);\n if (hit) {\n const rel = pathMod.relative(rootDir, full);\n if (totalBytes + rel.length + 1 > maxListBytes) {\n matches.push(\"[… search truncated — refine pattern …]\");\n return;\n }\n matches.push(rel);\n totalBytes += rel.length + 1;\n }\n if (e.isDirectory()) await walk(full);\n }\n };\n await walk(startAbs);\n return matches.length === 0 ? \"(no matches)\" : matches.join(\"\\n\");\n },\n });\n\n registry.register({\n name: \"search_content\",\n description:\n \"Recursively grep file CONTENTS for a substring or regex. This is the right tool for 'find all places that call X', 'where is Y referenced', 'what files contain Z'. Different from search_files (which matches FILE NAMES). Returns one match per line in 'path:line: text' format. Skips dependency / VCS / build directories (node_modules, .git, dist, build, .next, target, .venv) and binary files by default.\",\n readOnly: true,\n parameters: {\n type: \"object\",\n properties: {\n pattern: {\n type: \"string\",\n description: \"Substring (or regex) to search file contents for.\",\n },\n path: {\n type: \"string\",\n description: \"Directory to start the search at (default: sandbox root).\",\n },\n glob: {\n type: \"string\",\n description:\n \"Optional file-name suffix or substring filter. Examples: '.ts' (only TypeScript), 'test' (any file with 'test' in the name). Reduces noise when you know the file shape.\",\n },\n case_sensitive: {\n type: \"boolean\",\n description: \"When true, match case exactly. Default false (case-insensitive).\",\n },\n include_deps: {\n type: \"boolean\",\n description:\n \"When true, also search inside node_modules / .git / dist / build / etc. Off by default — most exploration questions are about the user's own code.\",\n },\n },\n required: [\"pattern\"],\n },\n fn: async (args: {\n pattern: string;\n path?: string;\n glob?: string;\n case_sensitive?: boolean;\n include_deps?: boolean;\n }) => {\n const startAbs = safePath(args.path ?? \".\");\n const caseSensitive = args.case_sensitive === true;\n const includeDeps = args.include_deps === true;\n const nameFilter = typeof args.glob === \"string\" ? args.glob.toLowerCase() : null;\n // Try the pattern as a regex first (lets the model say `\\bdispatch\\(`\n // for a word-bounded match); fall back to literal substring on\n // invalid regex. No `g` flag — we test once per line, so global\n // statefulness (lastIndex tracking) would just be noise.\n let re: RegExp | null = null;\n try {\n re = new RegExp(args.pattern, caseSensitive ? \"\" : \"i\");\n } catch {\n re = null;\n }\n const needle = caseSensitive ? args.pattern : args.pattern.toLowerCase();\n const matches: string[] = [];\n let totalBytes = 0;\n let scanned = 0;\n let truncated = false;\n\n const walk = async (dir: string): Promise<void> => {\n if (truncated) return;\n let entries: import(\"node:fs\").Dirent[];\n try {\n entries = await fs.readdir(dir, { withFileTypes: true });\n } catch {\n return;\n }\n for (const e of entries) {\n if (truncated) return;\n if (e.isDirectory()) {\n if (!includeDeps && SKIP_DIR_NAMES.has(e.name)) continue;\n await walk(pathMod.join(dir, e.name));\n continue;\n }\n if (!e.isFile()) continue;\n if (nameFilter && !e.name.toLowerCase().includes(nameFilter)) continue;\n if (isLikelyBinaryByName(e.name)) continue;\n const full = pathMod.join(dir, e.name);\n let stat: import(\"node:fs\").Stats;\n try {\n stat = await fs.stat(full);\n } catch {\n continue;\n }\n // Per-file size cap so a 50MB log doesn't dominate the search.\n // Anything legitimately interesting fits in 2 MB; bigger files\n // are usually data dumps or generated bundles.\n if (stat.size > 2 * 1024 * 1024) continue;\n let raw: Buffer;\n try {\n raw = await fs.readFile(full);\n } catch {\n continue;\n }\n // Content-based binary sniff: a NUL byte in the first 8KB is\n // a strong indicator. Catches binaries with .json or .txt\n // extensions (yes, this happens).\n const firstNul = raw.indexOf(0);\n if (firstNul !== -1 && firstNul < 8 * 1024) continue;\n const text = raw.toString(\"utf8\");\n const rel = pathMod.relative(rootDir, full);\n const lines = text.split(/\\r?\\n/);\n for (let li = 0; li < lines.length; li++) {\n const line = lines[li]!;\n const lineForCheck = caseSensitive ? line : line.toLowerCase();\n const hit = re ? re.test(line) : lineForCheck.includes(needle);\n if (!hit) continue;\n // Truncate very long lines so one giant minified file\n // doesn't blow the budget on a single match.\n const display = line.length > 200 ? `${line.slice(0, 200)}…` : line;\n const out = `${rel}:${li + 1}: ${display}`;\n if (totalBytes + out.length + 1 > maxListBytes) {\n matches.push(`[… truncated at ${maxListBytes} bytes — refine pattern or path …]`);\n truncated = true;\n return;\n }\n matches.push(out);\n totalBytes += out.length + 1;\n }\n scanned++;\n }\n };\n await walk(startAbs);\n if (matches.length === 0) {\n return scanned === 0\n ? \"(no files scanned — path empty or all files filtered out)\"\n : `(no matches across ${scanned} file${scanned === 1 ? \"\" : \"s\"})`;\n }\n return matches.join(\"\\n\");\n },\n });\n\n registry.register({\n name: \"get_file_info\",\n description:\n \"Stat a path under the sandbox root. Returns type (file|directory|symlink), size in bytes, mtime in ISO-8601.\",\n readOnly: true,\n parameters: {\n type: \"object\",\n properties: {\n path: { type: \"string\" },\n },\n required: [\"path\"],\n },\n fn: async (args: { path: string }) => {\n const abs = safePath(args.path);\n const st = await fs.lstat(abs);\n const type = st.isDirectory() ? \"directory\" : st.isSymbolicLink() ? \"symlink\" : \"file\";\n return JSON.stringify({\n type,\n size: st.size,\n mtime: st.mtime.toISOString(),\n });\n },\n });\n\n if (!allowWriting) return registry;\n\n registry.register({\n name: \"write_file\",\n description:\n \"Create or overwrite a file under the sandbox root with the given content. Parent directories are created as needed.\",\n parameters: {\n type: \"object\",\n properties: {\n path: { type: \"string\" },\n content: { type: \"string\" },\n },\n required: [\"path\", \"content\"],\n },\n fn: async (args: { path: string; content: string }) => {\n const abs = safePath(args.path);\n await fs.mkdir(pathMod.dirname(abs), { recursive: true });\n await fs.writeFile(abs, args.content, \"utf8\");\n return `wrote ${args.content.length} chars to ${pathMod.relative(rootDir, abs)}`;\n },\n });\n\n registry.register({\n name: \"edit_file\",\n description:\n \"Apply a SEARCH/REPLACE edit to an existing file. `search` must match exactly (whitespace sensitive) — no regex. The match must be unique in the file; otherwise the edit is refused to avoid surprise rewrites.\",\n parameters: {\n type: \"object\",\n properties: {\n path: { type: \"string\" },\n search: { type: \"string\", description: \"Exact text to find (must be unique).\" },\n replace: { type: \"string\", description: \"Text to substitute in place of `search`.\" },\n },\n required: [\"path\", \"search\", \"replace\"],\n },\n fn: async (args: { path: string; search: string; replace: string }) => {\n const abs = safePath(args.path);\n const before = await fs.readFile(abs, \"utf8\");\n if (args.search.length === 0) {\n throw new Error(\"edit_file: search cannot be empty\");\n }\n const firstIdx = before.indexOf(args.search);\n if (firstIdx < 0) {\n throw new Error(`edit_file: search text not found in ${pathMod.relative(rootDir, abs)}`);\n }\n const nextIdx = before.indexOf(args.search, firstIdx + 1);\n if (nextIdx >= 0) {\n throw new Error(\n `edit_file: search text appears multiple times in ${pathMod.relative(rootDir, abs)} — include more context to disambiguate`,\n );\n }\n const after =\n before.slice(0, firstIdx) + args.replace + before.slice(firstIdx + args.search.length);\n await fs.writeFile(abs, after, \"utf8\");\n const rel = pathMod.relative(rootDir, abs);\n const header = `edited ${rel} (${args.search.length}→${args.replace.length} chars)`;\n // Starting line number of the search block in the original\n // file. `split/length` on the prefix gives a 1-based line\n // count where the match begins, matching git-diff's @@ -N,M\n // +N,M @@ header convention.\n const startLine = before.slice(0, firstIdx).split(/\\r?\\n/).length;\n const diff = renderEditDiff(args.search, args.replace, startLine);\n return `${header}\\n${diff}`;\n },\n });\n\n registry.register({\n name: \"create_directory\",\n description: \"Create a directory (and any missing parents) under the sandbox root.\",\n parameters: {\n type: \"object\",\n properties: { path: { type: \"string\" } },\n required: [\"path\"],\n },\n fn: async (args: { path: string }) => {\n const abs = safePath(args.path);\n await fs.mkdir(abs, { recursive: true });\n return `created ${pathMod.relative(rootDir, abs)}/`;\n },\n });\n\n registry.register({\n name: \"move_file\",\n description: \"Rename/move a file or directory under the sandbox root.\",\n parameters: {\n type: \"object\",\n properties: {\n source: { type: \"string\" },\n destination: { type: \"string\" },\n },\n required: [\"source\", \"destination\"],\n },\n fn: async (args: { source: string; destination: string }) => {\n const src = safePath(args.source);\n const dst = safePath(args.destination);\n await fs.mkdir(pathMod.dirname(dst), { recursive: true });\n await fs.rename(src, dst);\n return `moved ${pathMod.relative(rootDir, src)} → ${pathMod.relative(rootDir, dst)}`;\n },\n });\n\n return registry;\n}\n\n/**\n * Format an edit_file change as a proper line-level diff, styled\n * like `git diff`. Starts with a unified-diff hunk header —\n * `@@ -startLine,oldCount +startLine,newCount @@` — so the user\n * can tell where in the file the change lands. Body uses LCS\n * (longest common subsequence) to mark lines as removed (`-`),\n * added (`+`), or unchanged context (` `). Users were getting\n * hundreds of `-` followed by hundreds of `+` for tiny changes\n * because the naive \"dump both sides\" format can't tell what\n * actually moved vs. stayed — this fixes that and adds line-\n * number context on top.\n */\nfunction renderEditDiff(search: string, replace: string, startLine: number): string {\n const a = search.split(/\\r?\\n/);\n const b = replace.split(/\\r?\\n/);\n const diff = lineDiff(a, b);\n const hunk = `@@ -${startLine},${a.length} +${startLine},${b.length} @@`;\n const body = diff.map((d) => `${d.op === \" \" ? \" \" : d.op} ${d.line}`).join(\"\\n\");\n return `${hunk}\\n${body}`;\n}\n\n/**\n * Compute a line-level diff via classic LCS dynamic programming.\n * Good enough for SEARCH/REPLACE blocks where both sides are\n * typically under a few hundred lines — O(n*m) space + time. For\n * huge blocks we'd want Myers' algorithm, but the caller already\n * caps the inline-display size and `/tool N` shows the full result,\n * so quadratic is fine in practice.\n *\n * Exported so tests can exercise the diff logic without spinning\n * up the full tool dispatch path.\n */\nexport function lineDiff(\n a: readonly string[],\n b: readonly string[],\n): Array<{ op: \"-\" | \"+\" | \" \"; line: string }> {\n const n = a.length;\n const m = b.length;\n // dp[i][j] = LCS length of a[0..i) and b[0..j).\n const dp: number[][] = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(0));\n for (let i = 1; i <= n; i++) {\n for (let j = 1; j <= m; j++) {\n if (a[i - 1] === b[j - 1]) dp[i]![j] = dp[i - 1]![j - 1]! + 1;\n else dp[i]![j] = Math.max(dp[i - 1]![j]!, dp[i]![j - 1]!);\n }\n }\n // Backtrack to recover the op sequence.\n const out: Array<{ op: \"-\" | \"+\" | \" \"; line: string }> = [];\n let i = n;\n let j = m;\n while (i > 0 && j > 0) {\n if (a[i - 1] === b[j - 1]) {\n out.unshift({ op: \" \", line: a[i - 1]! });\n i--;\n j--;\n } else if ((dp[i - 1]![j] ?? 0) > (dp[i]![j - 1] ?? 0)) {\n out.unshift({ op: \"-\", line: a[i - 1]! });\n i--;\n } else {\n // Tie-break goes here (strictly less or equal): take the\n // insertion first during backtrack so the final forward order\n // renders removals BEFORE additions for a substitution —\n // matches git-diff convention of `- old / + new`.\n out.unshift({ op: \"+\", line: b[j - 1]! });\n j--;\n }\n }\n while (i > 0) {\n out.unshift({ op: \"-\", line: a[i - 1]! });\n i--;\n }\n while (j > 0) {\n out.unshift({ op: \"+\", line: b[j - 1]! });\n j--;\n }\n return out;\n}\n","/**\n * `remember` / `forget` / `recall_memory` — tools that let the model\n * read and write the user-memory store across sessions.\n *\n * Scope rules:\n * - `global` — always available (no sandbox needed).\n * - `project` — requires a `projectRoot` on MemoryStore. In chat mode\n * (no sandbox), the tools still register but a `scope=project` call\n * returns a structured refusal so the model can try `global` instead.\n *\n * Memory changes are written eagerly but NOT re-loaded into the prefix\n * mid-session (cache invariant). The user notices at `/new` or the next\n * launch — or they can read fresh content via `recall_memory` which\n * always hits disk.\n */\n\nimport type { ToolRegistry } from \"../tools.js\";\nimport {\n type MemoryScope,\n MemoryStore,\n type MemoryType,\n sanitizeMemoryName,\n} from \"../user-memory.js\";\n\nexport interface MemoryToolsOptions {\n /** Sandbox root for the `project` scope. Omit for chat mode. */\n projectRoot?: string;\n /** Override `~/.reasonix` (tests). */\n homeDir?: string;\n}\n\nexport function registerMemoryTools(\n registry: ToolRegistry,\n opts: MemoryToolsOptions = {},\n): ToolRegistry {\n const store = new MemoryStore({ homeDir: opts.homeDir, projectRoot: opts.projectRoot });\n const hasProject = store.hasProjectScope();\n\n registry.register({\n name: \"remember\",\n description:\n \"Save a memory for future sessions. Use when the user states a preference, corrects your approach, shares a non-obvious fact about this project, or explicitly asks you to remember something. Don't remember transient task state — only things worth recalling next session. The memory is written now but won't re-load into the system prompt until the next `/new` or launch.\",\n parameters: {\n type: \"object\",\n properties: {\n type: {\n type: \"string\",\n enum: [\"user\", \"feedback\", \"project\", \"reference\"],\n description:\n \"'user' = role/skills/prefs; 'feedback' = corrections or confirmed approaches; 'project' = facts/decisions about the current work; 'reference' = pointers to external systems the user uses.\",\n },\n scope: {\n type: \"string\",\n enum: [\"global\", \"project\"],\n description:\n \"'global' = applies across every project (preferences, tooling); 'project' = scoped to the current sandbox (decisions, local facts). Only available in `reasonix code`.\",\n },\n name: {\n type: \"string\",\n description:\n \"filename-safe identifier, 3-40 chars, alnum + _ - . (no path separators, no leading dot).\",\n },\n description: {\n type: \"string\",\n description: \"One-line summary shown in MEMORY.md (under ~150 chars).\",\n },\n content: {\n type: \"string\",\n description:\n \"Full memory body in markdown. For feedback/project types, structure as: rule/fact, then **Why:** line, then **How to apply:** line.\",\n },\n },\n required: [\"type\", \"scope\", \"name\", \"description\", \"content\"],\n },\n fn: async (args: {\n type: MemoryType;\n scope: MemoryScope;\n name: string;\n description: string;\n content: string;\n }) => {\n if (args.scope === \"project\" && !hasProject) {\n return JSON.stringify({\n error:\n \"scope='project' is unavailable in this session (no sandbox root). Retry with scope='global', or ask the user to switch to `reasonix code` for project-scoped memory.\",\n });\n }\n try {\n const path = store.write({\n name: args.name,\n type: args.type,\n scope: args.scope,\n description: args.description,\n body: args.content,\n });\n const key = sanitizeMemoryName(args.name);\n // The return text is load-bearing: it's the ONLY thing keeping\n // the fact visible within the current session, because the\n // prefix isn't re-hashed mid-session (Pillar 1). R1 reads this\n // on its next turn — the wording is deliberately imperative so\n // it doesn't get ignored in favor of explore-first behavior.\n return [\n `✓ REMEMBERED (${args.scope}/${key}): ${args.description}`,\n \"\",\n \"TREAT THIS AS ESTABLISHED FACT for the rest of this session.\",\n \"The user just told you — don't re-explore the filesystem to re-derive it.\",\n `(Saved to ${path}; pins into the system prompt on next /new or launch.)`,\n ].join(\"\\n\");\n } catch (err) {\n return JSON.stringify({ error: `remember failed: ${(err as Error).message}` });\n }\n },\n });\n\n registry.register({\n name: \"forget\",\n description:\n \"Delete a memory file and remove it from MEMORY.md. Use when the user explicitly asks to forget something, or when a previously-remembered fact has become wrong. Irreversible — no tombstone.\",\n parameters: {\n type: \"object\",\n properties: {\n name: { type: \"string\", description: \"Memory name (the identifier used in `remember`).\" },\n scope: { type: \"string\", enum: [\"global\", \"project\"] },\n },\n required: [\"name\", \"scope\"],\n },\n fn: async (args: { name: string; scope: MemoryScope }) => {\n if (args.scope === \"project\" && !hasProject) {\n return JSON.stringify({\n error: \"scope='project' is unavailable in this session (no sandbox root).\",\n });\n }\n try {\n const existed = store.delete(args.scope, args.name);\n return existed\n ? `forgot (${args.scope}/${sanitizeMemoryName(args.name)}). Re-load on next /new or launch.`\n : `no such memory: ${args.scope}/${args.name} (nothing to forget).`;\n } catch (err) {\n return JSON.stringify({ error: `forget failed: ${(err as Error).message}` });\n }\n },\n });\n\n registry.register({\n name: \"recall_memory\",\n description:\n \"Read the full body of a memory file when its MEMORY.md one-liner (already in the system prompt) isn't enough detail. Most of the time the index suffices — only call this when the user's question genuinely requires the full context.\",\n readOnly: true,\n parameters: {\n type: \"object\",\n properties: {\n name: { type: \"string\" },\n scope: { type: \"string\", enum: [\"global\", \"project\"] },\n },\n required: [\"name\", \"scope\"],\n },\n fn: async (args: { name: string; scope: MemoryScope }) => {\n if (args.scope === \"project\" && !hasProject) {\n return JSON.stringify({\n error: \"scope='project' is unavailable in this session (no sandbox root).\",\n });\n }\n try {\n const entry = store.read(args.scope, args.name);\n return [\n `# ${entry.name} (${entry.scope}/${entry.type}, created ${entry.createdAt || \"?\"})`,\n entry.description ? `> ${entry.description}` : \"\",\n \"\",\n entry.body,\n ]\n .filter(Boolean)\n .join(\"\\n\");\n } catch (err) {\n return JSON.stringify({ error: `recall failed: ${(err as Error).message}` });\n }\n },\n });\n\n return registry;\n}\n","/**\n * Plan Mode — read-only exploration phase for `reasonix code`.\n *\n * Shape (mirrors claude-code's plan/act split, adapted for Reasonix):\n *\n * 1. User types `/plan` → registry switches to plan-mode enforcement\n * (write tools refused at dispatch; reads + allowlisted shell\n * still work).\n * 2. Model explores, then calls `submit_plan` with a markdown plan.\n * 3. `submit_plan` throws `PlanProposedError`, which the TUI renders\n * as a picker: Approve / Refine / Cancel.\n * 4. Approve → registry leaves plan mode, a synthetic user message\n * \"The plan has been approved. Implement it now.\" is pushed into\n * the loop so the next turn executes.\n *\n * The read-only enforcement lives in `ToolRegistry.dispatch` via\n * `readOnly` / `readOnlyCheck`; this file only ships the `submit_plan`\n * escape hatch and the error type that carries the plan out of the\n * registry without stuffing it into the message.\n *\n * We do not change `ImmutablePrefix.toolSpecs` when plan mode toggles —\n * that would break Pillar 1's prefix cache. Instead the same full spec\n * list stays pinned, and the registry enforces mode at dispatch time.\n * The refusal string teaches the model the rule; cache hits stay\n * intact.\n */\n\nimport type { ToolRegistry } from \"../tools.js\";\n\n/**\n * Thrown by `submit_plan` when plan mode is active, carrying the plan\n * text the TUI will render for the user's approval.\n *\n * Implements the `toToolResult` protocol so `ToolRegistry.dispatch`\n * serializes the full plan into the tool-result JSON (not just the\n * error message). The TUI parses `{ error, plan }` from the tool event\n * and mounts the `PlanConfirm` picker.\n */\nexport class PlanProposedError extends Error {\n readonly plan: string;\n constructor(plan: string) {\n super(\n \"PlanProposedError: plan submitted. STOP calling tools now — the TUI has shown the plan to the user. Wait for their next message; it will either approve (you'll then implement the plan), request a refinement (you should explore more and submit an updated plan), or cancel (drop the plan and ask what they want instead). Don't call any tools in the meantime.\",\n );\n this.name = \"PlanProposedError\";\n this.plan = plan;\n }\n\n /**\n * Structured tool-result shape. Consumed by the TUI to extract the\n * plan without regex-scraping the error message.\n */\n toToolResult(): { error: string; plan: string } {\n return { error: `${this.name}: ${this.message}`, plan: this.plan };\n }\n}\n\nexport interface PlanToolOptions {\n /**\n * Optional side-channel callback fired when the model submits a plan.\n * The TUI uses this to preview the plan in real time (the tool-result\n * event is also emitted; this is just earlier and friendlier to\n * test harnesses that don't want to parse JSON).\n */\n onPlanSubmitted?: (plan: string) => void;\n}\n\nexport function registerPlanTool(registry: ToolRegistry, opts: PlanToolOptions = {}): ToolRegistry {\n registry.register({\n name: \"submit_plan\",\n description:\n \"Submit a concrete plan to the user for review before executing. Use this for tasks that warrant a review gate — multi-file refactors, architecture changes, anything that would be expensive or confusing to undo. Skip it for small fixes (one-line typo, obvious bug with a clear fix) — just make the change. The user will either approve (you then implement it), ask for refinement, or cancel. If the user has already enabled /plan mode, writes are blocked at dispatch and you MUST use this. Write the plan as markdown with a one-line summary, a bulleted list of files to touch and what will change, and any risks or open questions.\",\n readOnly: true,\n parameters: {\n type: \"object\",\n properties: {\n plan: {\n type: \"string\",\n description:\n \"Markdown-formatted plan. Lead with a one-sentence summary. Then a file-by-file breakdown of what you'll change and why. Flag any risks or open questions at the end so the user can weigh in before you start.\",\n },\n },\n required: [\"plan\"],\n },\n fn: async (args: { plan: string }) => {\n const plan = (args?.plan ?? \"\").trim();\n if (!plan) {\n throw new Error(\"submit_plan: empty plan — write a markdown plan and try again.\");\n }\n // Always fire the picker, not just inside plan mode. Plan mode's\n // role is the *stronger* constraint — it forces you into read-only\n // until you submit. Outside plan mode, submit_plan is your own\n // call: use it when the task is large enough to deserve a review\n // gate (multi-file refactors, architecture changes, anything\n // that would be expensive to undo), skip it for small fixes.\n opts.onPlanSubmitted?.(plan);\n throw new PlanProposedError(plan);\n },\n });\n return registry;\n}\n","/**\n * Subagent runtime — isolated child loops for offloading exploration or\n * self-contained subtasks.\n *\n * Two surfaces sit on top of the same `spawnSubagent` core:\n *\n * 1. `registerSubagentTool` — exposes a low-level `spawn_subagent`\n * function-call tool. Library API. NOT registered into the model\n * tool list by `reasonix code` since 0.4.26 — Skills (with\n * `runAs: subagent` frontmatter) became the user-facing surface.\n * Kept exported because library callers and tests still want\n * direct access to the primitive.\n *\n * 2. `run_skill` (in src/tools/skills.ts) — when the resolved skill\n * has `runAs: subagent`, it calls `spawnSubagent` with the skill\n * body as the system prompt and the user's `arguments` as the\n * task. Subagent skills are listed in the pinned Skills index\n * with a 🧬 marker, which gives the model a clear pattern-match\n * trigger without forcing it to reason about \"is this task big\n * enough to delegate.\"\n *\n * Why R1 specifically benefits:\n * - R1 reasoning tokens are expensive AND inflate the parent context.\n * A subagent runs its own private loop, then surfaces only the\n * distilled final answer back to the parent — the main session\n * never sees the reasoning trail.\n *\n * Invariants common to both surfaces:\n * - Serial only — no parallel spawn (MVP).\n * - Inherits parent's tool registry MINUS `spawn_subagent` itself\n * (no recursion via the tool API) and MINUS `submit_plan`\n * (subagents don't propose plans to the user).\n * - No hooks, no session — runs are ephemeral.\n * - Lower default `maxToolIters` than the parent (16 vs 64).\n * - Independent prefix cache (subagent's prefix has its own\n * fingerprint).\n * - Parent registry's plan-mode state propagates: subagents can't\n * escape `/plan`.\n * - Non-streaming child loop — the parent isn't watching deltas, so\n * streaming would only add an SSE parser to the critical path.\n * Cancellation still works via the AbortSignal.\n */\n\nimport type { DeepSeekClient } from \"../client.js\";\nimport { CacheFirstLoop } from \"../loop.js\";\nimport { ImmutablePrefix } from \"../memory.js\";\nimport { applyProjectMemory } from \"../project-memory.js\";\nimport { ToolRegistry } from \"../tools.js\";\n\n/**\n * Live event emitted by a running subagent. Surfaced via the optional\n * `sink` ref the TUI attaches its handler to. Side-channel only — these\n * events do NOT pass through the parent loop's `LoopEvent` stream\n * because subagents run inside a tool-dispatch frame, after the parent's\n * `step()` has already yielded `tool_start` and is awaiting the result.\n */\nexport interface SubagentEvent {\n kind: \"start\" | \"progress\" | \"end\";\n /** First ~30 chars of the task prompt — used for the TUI status row. */\n task: string;\n /** Iteration count inside the child loop (number of tool results so far). */\n iter?: number;\n /** Wall-clock ms since the subagent started. */\n elapsedMs?: number;\n /** First ~120 chars of the final assistant message. Set on `end`. */\n summary?: string;\n /** Error message if the subagent failed. Set on `end`. */\n error?: string;\n /** Total turns the subagent took. Set on `end`. */\n turns?: number;\n}\n\n/**\n * Mutable ref the registration writes through. The TUI sets `.current`\n * to its own handler on mount; nothing receives events before that\n * happens (and headless callers leave `.current = null`, which is the\n * library-mode default — they read the final result from the helper's\n * return value instead).\n */\nexport interface SubagentSink {\n current: ((ev: SubagentEvent) => void) | null;\n}\n\n/**\n * Per-spawn options for {@link spawnSubagent}. All but `parentRegistry`\n * + `client` + `system` + `task` are tunables with sensible defaults.\n */\nexport interface SpawnSubagentOptions {\n /** Shared DeepSeek client. The subagent reuses it (same auth, same retries). */\n client: DeepSeekClient;\n /**\n * Parent registry — the subagent inherits a copy of its tools (minus\n * the never-inherited set: `spawn_subagent`, `submit_plan`).\n */\n parentRegistry: ToolRegistry;\n /**\n * System prompt for the child loop. Skills' subagent path passes\n * the skill body here; the spawn_subagent tool passes its default\n * (or the model's `system` argument override).\n */\n system: string;\n /** The task / question / instruction the subagent must address. */\n task: string;\n /** Model id for the child loop. Defaults to `deepseek-chat`. */\n model?: string;\n /** Iteration ceiling for the child loop. Defaults to 16. */\n maxToolIters?: number;\n /**\n * Maximum chars of the final assistant message returned. Long answers\n * are truncated with a notice — the parent's prompt budget shouldn't\n * be blown out by an over-eager subagent.\n */\n maxResultChars?: number;\n /** Optional sink for TUI live updates. */\n sink?: SubagentSink;\n /**\n * Parent's per-tool-dispatch AbortSignal. When the parent aborts (Esc),\n * we forward the cancel into the child loop. Omit for headless callers\n * that don't care about cancellation.\n */\n parentSignal?: AbortSignal;\n}\n\n/**\n * Structured result of a subagent run. The two convenience JSON wrappers\n * (`spawn_subagent` tool, `run_skill` subagent path) serialize this for\n * the model; library callers can read the typed object directly.\n */\nexport interface SubagentResult {\n success: boolean;\n /** Final assistant message (possibly truncated). Empty on error. */\n output: string;\n /** Set when the run failed (network, child-loop error, etc.). */\n error?: string;\n /** Turns the child loop took. */\n turns: number;\n /** Tool calls dispatched inside the child loop. */\n toolIters: number;\n /** Wall-clock ms. */\n elapsedMs: number;\n /** USD spent in the child loop, summed across its turns. */\n costUsd: number;\n}\n\nexport interface SubagentToolOptions {\n /** Shared DeepSeek client. */\n client: DeepSeekClient;\n /**\n * Default system prompt used when the model doesn't pass one. Project\n * memory (REASONIX.md) is appended automatically when `projectRoot` is\n * set.\n */\n defaultSystem?: string;\n /** Project root for `applyProjectMemory` lookup. Omit in chat mode. */\n projectRoot?: string;\n /** Default model. `deepseek-chat` (V3) by default. */\n defaultModel?: string;\n /** Iteration ceiling. Lower than the parent (16 by default). */\n maxToolIters?: number;\n /** Maximum chars returned in the tool result. */\n maxResultChars?: number;\n /** Optional sink the TUI attaches its handler to for live updates. */\n sink?: SubagentSink;\n}\n\nconst DEFAULT_SUBAGENT_SYSTEM = `You are a Reasonix subagent. The parent agent spawned you to handle one focused subtask, then return.\n\nRules:\n- Stay on the task you were given. Do not expand scope.\n- Use tools as needed. You share the parent's sandbox + safety rules.\n- When you're done, your final assistant message is the only thing the parent will see — make it complete and self-contained. No follow-up offers, no questions, no \"let me know if you need more.\"\n- Prefer one clear, distilled answer over a long log of what you tried.\n\nFormatting rules (the parent renders your reply in a TUI with a real markdown renderer):\n- For tabular data use GitHub-Flavored Markdown tables with ASCII pipes: \\`| col | col |\\` headers, \\`| --- | --- |\\` separator. NEVER draw tables with Unicode box-drawing characters (│ ─ ┼ ┌ ┐ └ ┘ ├ ┤). They look intentional but break terminal word-wrap and produce garbled output.\n- Keep table cells short — one short phrase per cell, not multi-line paragraphs. If a description doesn't fit in ~40 chars, use bullets below the table instead.\n- Use fenced code blocks (\\`\\`\\`) for any code, file paths with line ranges, or shell commands.\n- NEVER draw decorative frames around content with \\`┌──┐ │ └──┘\\` box-drawing characters. The renderer handles code blocks and headings on its own — extra ASCII art adds noise without value and breaks at narrow terminal widths.\n- For flow charts and diagrams: use a markdown bullet list with \\`→\\` or \\`↓\\` between steps. Don't try to draw boxes-and-arrows in ASCII; it never survives word-wrap.`;\n\nconst DEFAULT_MAX_RESULT_CHARS = 8000;\nconst DEFAULT_MAX_ITERS = 16;\nconst DEFAULT_SUBAGENT_MODEL = \"deepseek-chat\";\n\nconst SUBAGENT_TOOL_NAME = \"spawn_subagent\";\n/**\n * Tools the subagent never inherits from the parent registry:\n * - spawn_subagent itself: would allow unbounded recursion via the\n * tool API. Depth=1 hard cap by construction.\n * - submit_plan: only the parent talks to the user about plan\n * approval; a subagent submitting a plan would surface a picker\n * midway through the parent's turn, which the user did not ask for.\n */\nconst NEVER_INHERITED_TOOLS = new Set<string>([SUBAGENT_TOOL_NAME, \"submit_plan\"]);\n\n/**\n * Run one subagent to completion. The unified primitive both\n * `spawn_subagent` (function-call tool) and `run_skill` (subagent\n * skills) call into.\n *\n * Headless: returns a `SubagentResult` regardless of success/failure.\n * Errors are captured in the structured shape, never thrown — the\n * caller decides how to surface them (tool result JSON, log line, etc.).\n */\nexport async function spawnSubagent(opts: SpawnSubagentOptions): Promise<SubagentResult> {\n const model = opts.model ?? DEFAULT_SUBAGENT_MODEL;\n const maxToolIters = opts.maxToolIters ?? DEFAULT_MAX_ITERS;\n const maxResultChars = opts.maxResultChars ?? DEFAULT_MAX_RESULT_CHARS;\n const sink = opts.sink;\n\n const startedAt = Date.now();\n const taskPreview = opts.task.length > 30 ? `${opts.task.slice(0, 30)}…` : opts.task;\n sink?.current?.({\n kind: \"start\",\n task: taskPreview,\n iter: 0,\n elapsedMs: 0,\n });\n\n const childTools = forkRegistryExcluding(opts.parentRegistry, NEVER_INHERITED_TOOLS);\n const childPrefix = new ImmutablePrefix({\n system: opts.system,\n toolSpecs: childTools.specs(),\n });\n const childLoop = new CacheFirstLoop({\n client: opts.client,\n prefix: childPrefix,\n tools: childTools,\n model,\n maxToolIters,\n hooks: [],\n stream: false,\n });\n\n const onParentAbort = () => childLoop.abort();\n opts.parentSignal?.addEventListener(\"abort\", onParentAbort, { once: true });\n\n let final = \"\";\n let errorMessage: string | undefined;\n let toolIter = 0;\n try {\n for await (const ev of childLoop.step(opts.task)) {\n if (ev.role === \"tool\") {\n toolIter++;\n sink?.current?.({\n kind: \"progress\",\n task: taskPreview,\n iter: toolIter,\n elapsedMs: Date.now() - startedAt,\n });\n }\n if (ev.role === \"assistant_final\") {\n final = ev.content ?? \"\";\n }\n if (ev.role === \"error\") {\n errorMessage = ev.error ?? \"subagent error\";\n }\n }\n } catch (err) {\n errorMessage = (err as Error).message;\n } finally {\n opts.parentSignal?.removeEventListener(\"abort\", onParentAbort);\n }\n // The loop yields `done` without an `error` event when its API call\n // is aborted mid-flight (intentional UX — see the matching catch in\n // CacheFirstLoop.step). From a SUBAGENT consumer's perspective that\n // still counts as a failure: no answer came back, the parent has\n // nothing to render. Synthesize an error so `success: false` and the\n // UI surfaces the abort instead of returning empty output.\n if (!errorMessage && !final) {\n errorMessage = opts.parentSignal?.aborted\n ? \"subagent aborted before producing an answer\"\n : \"subagent ended without producing an answer\";\n }\n\n const elapsedMs = Date.now() - startedAt;\n const turns = childLoop.stats.turns.length;\n const costUsd = childLoop.stats.totalCost;\n\n const truncated =\n final.length > maxResultChars\n ? `${final.slice(0, maxResultChars)}\\n\\n[…truncated ${final.length - maxResultChars} chars; ask the subagent for a tighter summary if you need more.]`\n : final;\n\n sink?.current?.({\n kind: \"end\",\n task: taskPreview,\n iter: toolIter,\n elapsedMs,\n summary: errorMessage ? undefined : truncated.slice(0, 120),\n error: errorMessage,\n turns,\n });\n\n return {\n success: !errorMessage,\n output: errorMessage ? \"\" : truncated,\n error: errorMessage,\n turns,\n toolIters: toolIter,\n elapsedMs,\n costUsd,\n };\n}\n\n/**\n * Serialize a {@link SubagentResult} into the JSON tool-result shape\n * the model consumes. Both the spawn_subagent tool and the run_skill\n * subagent path return this string verbatim, so the schema stays\n * stable across both surfaces.\n */\nexport function formatSubagentResult(r: SubagentResult): string {\n if (!r.success) {\n return JSON.stringify({\n success: false,\n error: r.error ?? \"unknown subagent error\",\n turns: r.turns,\n tool_iters: r.toolIters,\n elapsed_ms: r.elapsedMs,\n });\n }\n return JSON.stringify({\n success: true,\n output: r.output,\n turns: r.turns,\n tool_iters: r.toolIters,\n elapsed_ms: r.elapsedMs,\n cost_usd: r.costUsd,\n });\n}\n\n/**\n * Register the spawn_subagent tool into the parent registry. Library\n * surface — `reasonix code` does NOT call this since 0.4.26 (Skills\n * with `runAs: subagent` are the user-facing surface), but library\n * consumers who want the low-level tool can opt in.\n */\nexport function registerSubagentTool(\n parentRegistry: ToolRegistry,\n opts: SubagentToolOptions,\n): ToolRegistry {\n const baseSystem = opts.defaultSystem ?? DEFAULT_SUBAGENT_SYSTEM;\n // Bake project memory into the default once — re-reading on every\n // spawn would (a) make the child prefix unstable when REASONIX.md\n // changes mid-session, defeating cache reuse across multiple\n // subagent calls, and (b) cost a stat() per call. The parent itself\n // also reads memory once at startup; matching that semantics keeps\n // subagent and parent on the same page.\n const defaultSystem = opts.projectRoot\n ? applyProjectMemory(baseSystem, opts.projectRoot)\n : baseSystem;\n const defaultModel = opts.defaultModel ?? DEFAULT_SUBAGENT_MODEL;\n const maxToolIters = opts.maxToolIters ?? DEFAULT_MAX_ITERS;\n const maxResultChars = opts.maxResultChars ?? DEFAULT_MAX_RESULT_CHARS;\n const sink = opts.sink;\n\n parentRegistry.register({\n name: SUBAGENT_TOOL_NAME,\n description:\n \"Spawn an isolated subagent to handle a self-contained subtask in a fresh context, returning only its final answer. Use for: deep codebase exploration that would flood the main context, multi-step research where you only need the conclusion, or any focused subtask whose intermediate reasoning the user does not need to see. The subagent inherits all your tools (filesystem, shell, web, MCP, etc.) but runs in its own isolated message log — its tool calls and reasoning never enter your context. Only the final assistant message comes back as this tool's result. Keep tasks focused; the subagent has a stricter iter budget than you do.\",\n parameters: {\n type: \"object\",\n properties: {\n task: {\n type: \"string\",\n description:\n \"The subtask the subagent should perform. Be specific and self-contained — the subagent has none of your conversation context, only what you write here.\",\n },\n system: {\n type: \"string\",\n description:\n \"Optional override for the subagent's system prompt. The default tells it to stay focused and return a concise answer; override only when the subtask needs a specialized persona.\",\n },\n model: {\n type: \"string\",\n enum: [\"deepseek-chat\", \"deepseek-reasoner\"],\n description:\n \"Which DeepSeek model the subagent runs on. 'deepseek-chat' (V3) is the default — fast and cheap. Use 'deepseek-reasoner' (R1) only when the subtask genuinely needs planning or multi-step reasoning; it is roughly 5-10x more expensive.\",\n },\n },\n required: [\"task\"],\n },\n fn: async (args: { task?: unknown; system?: unknown; model?: unknown }, ctx) => {\n const task = typeof args.task === \"string\" ? args.task.trim() : \"\";\n if (!task) {\n return JSON.stringify({\n error: \"spawn_subagent requires a non-empty 'task' argument.\",\n });\n }\n const system =\n typeof args.system === \"string\" && args.system.trim().length > 0\n ? args.system.trim()\n : defaultSystem;\n const model =\n typeof args.model === \"string\" && args.model.startsWith(\"deepseek-\")\n ? args.model\n : defaultModel;\n const result = await spawnSubagent({\n client: opts.client,\n parentRegistry,\n system,\n task,\n model,\n maxToolIters,\n maxResultChars,\n sink,\n parentSignal: ctx?.signal,\n });\n return formatSubagentResult(result);\n },\n });\n\n return parentRegistry;\n}\n\n/**\n * Build a child ToolRegistry that copies every tool from `parent` except\n * those whose names are in `exclude`. Plan-mode state propagates so a\n * subagent spawned while the parent is under `/plan` cannot escape it.\n *\n * Exported for tests + library callers who want the same fork behavior\n * for their own nested-loop patterns.\n */\nexport function forkRegistryExcluding(\n parent: ToolRegistry,\n exclude: ReadonlySet<string>,\n): ToolRegistry {\n const child = new ToolRegistry();\n for (const spec of parent.specs()) {\n const name = spec.function.name;\n if (exclude.has(name)) continue;\n const def = parent.get(name);\n if (!def) continue;\n // Re-register copies the public ToolDefinition fields. The child\n // re-runs auto-flatten analysis on its own, which produces an\n // identical flatSchema for the same input — no surprise.\n child.register(def);\n }\n if (parent.planMode) child.setPlanMode(true);\n return child;\n}\n","/**\n * Native shell tool — lets the model run commands inside the sandbox\n * root so it can actually verify its own work (run tests, check git\n * status, inspect a lockfile, etc.). Without this the coding-mode\n * loop is \"write code, hope it works, ask the user to run it\" —\n * defeats the purpose.\n *\n * Safety model:\n * - Commands run with `cwd` pinned to the registered root. No\n * path traversal via the command itself is enforced (users can\n * `cat ../outside.txt`); the trust boundary is the directory\n * you opened Reasonix from.\n * - Commands are matched against a read-only / testing allowlist.\n * Allowlisted commands execute immediately and return stdout +\n * stderr merged. Everything else throws with a clear message —\n * the UI translates that into an `/apply`-style confirm gate so\n * the user sees the exact command before it runs.\n * - Default timeout: 60s. Output cap: matches tool-result budget.\n * - Every command that DOES run is spawned with `shell: false` and\n * a tokenized argv — no string-to-shell interpolation, so the\n * model can't accidentally construct a chained `rm` via quoting.\n *\n * This is intentionally narrower than what Claude Code / Aider ship:\n * we gate more commands behind confirmation by default. Users who\n * trust the model can widen the allowlist by instantiating their\n * own tool registry.\n */\n\nimport { type SpawnOptions, spawn } from \"node:child_process\";\nimport { existsSync, statSync } from \"node:fs\";\nimport * as pathMod from \"node:path\";\nimport type { ToolRegistry } from \"../tools.js\";\n\nexport interface ShellToolsOptions {\n /** Directory to run commands in. Must be an absolute path. */\n rootDir: string;\n /** Seconds before an individual command is killed. Default: 60. */\n timeoutSec?: number;\n /**\n * Per-command stdout+stderr cap in characters. Default: 32_000 to\n * match the tool-result budget.\n */\n maxOutputChars?: number;\n /**\n * Extra command-name prefixes the user explicitly trusts. Added on\n * top of the built-in allowlist. Examples: `[\"my-ci-script\", \"lint\"]`.\n *\n * Accepts either a fixed array (captured once at registration) or a\n * getter called on every dispatch. The getter form is load-bearing:\n * when the TUI's `ShellConfirm` writes a new prefix to config mid-\n * session, the running `run_command` must pick it up immediately —\n * otherwise the same command gets re-prompted until the next launch.\n */\n extraAllowed?: readonly string[] | (() => readonly string[]);\n /**\n * When true, skip the allowlist entirely and auto-run every command.\n * Off by default — this is an escape hatch for non-interactive use\n * (CI, benchmarks) where a human can't be in the loop to confirm.\n */\n allowAll?: boolean;\n}\n\nconst DEFAULT_TIMEOUT_SEC = 60;\nconst DEFAULT_MAX_OUTPUT_CHARS = 32_000;\n\n/**\n * Command prefixes we consider safe to run without asking the user.\n * Rule of thumb: read-only reports, or test runners whose failure mode\n * is \"exit 1 with output.\" Nothing that can rewrite state, escalate,\n * or touch the network.\n */\nconst BUILTIN_ALLOWLIST: ReadonlyArray<string> = [\n // Repo inspection\n \"git status\",\n \"git diff\",\n \"git log\",\n \"git show\",\n \"git blame\",\n \"git branch\",\n \"git remote\",\n \"git rev-parse\",\n \"git config --get\",\n // Filesystem inspection\n \"ls\",\n \"pwd\",\n \"cat\",\n \"head\",\n \"tail\",\n \"wc\",\n \"file\",\n \"tree\",\n \"find\",\n \"grep\",\n \"rg\",\n // Language version probes\n \"node --version\",\n \"node -v\",\n \"npm --version\",\n \"npx --version\",\n \"python --version\",\n \"python3 --version\",\n \"cargo --version\",\n \"go version\",\n \"rustc --version\",\n \"deno --version\",\n \"bun --version\",\n // Test runners (non-destructive by convention)\n \"npm test\",\n \"npm run test\",\n \"npx vitest run\",\n \"npx vitest\",\n \"npx jest\",\n \"pytest\",\n \"python -m pytest\",\n \"cargo test\",\n \"cargo check\",\n \"cargo clippy\",\n \"go test\",\n \"go vet\",\n \"deno test\",\n \"bun test\",\n // Linters / typecheckers (read-only by convention)\n \"npm run lint\",\n \"npm run typecheck\",\n \"npx tsc --noEmit\",\n \"npx biome check\",\n \"npx eslint\",\n \"npx prettier --check\",\n \"ruff\",\n \"mypy\",\n];\n\n/**\n * Tokenize a shell-ish command string into argv. Handles single/double\n * quoting; rejects unclosed quotes. Does NOT expand env vars, globs,\n * backticks, or `$(…)` — the goal is to prevent the model from\n * accidentally (or not) sneaking arbitrary shells past the allowlist\n * via concatenation. Exported for testing.\n */\nexport function tokenizeCommand(cmd: string): string[] {\n const out: string[] = [];\n let cur = \"\";\n let quote: '\"' | \"'\" | null = null;\n for (let i = 0; i < cmd.length; i++) {\n const ch = cmd[i]!;\n if (quote) {\n if (ch === quote) {\n quote = null;\n } else if (ch === \"\\\\\" && quote === '\"' && i + 1 < cmd.length) {\n cur += cmd[++i];\n } else {\n cur += ch;\n }\n continue;\n }\n if (ch === '\"' || ch === \"'\") {\n quote = ch;\n continue;\n }\n if (ch === \" \" || ch === \"\\t\") {\n if (cur.length > 0) {\n out.push(cur);\n cur = \"\";\n }\n continue;\n }\n cur += ch;\n }\n if (quote) throw new Error(`unclosed ${quote} in command`);\n if (cur.length > 0) out.push(cur);\n return out;\n}\n\n/**\n * Scan `cmd` for a shell operator (`|`, `||`, `>`, `>>`, `<`, `<<`,\n * `&`, `&&`, `2>`, `2>>`, `2>&1`, `&>`) that appears unquoted at a\n * token boundary. Returns the operator string, or null if none.\n *\n * Why this exists: `run_command` documents \"no shell expansion, no\n * pipes, no redirects\" (the tool spawns argv directly, not through a\n * shell), but when the model writes `dir | findstr foo` the `|`\n * survives tokenization as a standalone token and gets quoted as the\n * literal string `\"|\"` by `quoteForCmdExe` — cmd.exe sees it as an\n * argument, not an operator, so the pipe silently fails. Detecting\n * operators up front lets us throw a clear error (\"split into separate\n * calls\") instead of letting the command run with surprising results.\n *\n * Quoted operators (`grep \"a|b\"`) and operator characters embedded in\n * larger tokens (`--flag=1&2`) are NOT flagged — those are literal\n * argv bytes and are safe to pass through.\n *\n * Exported for testing.\n */\nexport function detectShellOperator(cmd: string): string | null {\n const opPrefix = /^(?:2>&1|&>|\\|{1,2}|&{1,2}|2>{1,2}|>{1,2}|<{1,2})/;\n let cur = \"\";\n let curQuoted = false;\n let quote: '\"' | \"'\" | null = null;\n const check = (): string | null => {\n if (cur.length === 0 && !curQuoted) return null;\n if (!curQuoted) {\n const m = opPrefix.exec(cur);\n if (m) return m[0] ?? null;\n }\n return null;\n };\n for (let i = 0; i < cmd.length; i++) {\n const ch = cmd[i]!;\n if (quote) {\n if (ch === quote) {\n quote = null;\n } else if (ch === \"\\\\\" && quote === '\"' && i + 1 < cmd.length) {\n cur += cmd[++i];\n curQuoted = true;\n } else {\n cur += ch;\n curQuoted = true;\n }\n continue;\n }\n if (ch === '\"' || ch === \"'\") {\n quote = ch;\n curQuoted = true;\n continue;\n }\n if (ch === \" \" || ch === \"\\t\") {\n const op = check();\n if (op) return op;\n cur = \"\";\n curQuoted = false;\n continue;\n }\n cur += ch;\n }\n if (quote) return null; // let tokenizeCommand throw the unclosed-quote error\n return check();\n}\n\n/**\n * Return true when `cmd` matches an allowlisted prefix. Exported for\n * testing. Match is on the space-normalized leading tokens so\n * `git status -s ` and `git status` both match `git status`.\n */\nexport function isAllowed(cmd: string, extra: readonly string[] = []): boolean {\n const normalized = cmd.trim().replace(/\\s+/g, \" \");\n const allowlist = [...BUILTIN_ALLOWLIST, ...extra];\n for (const prefix of allowlist) {\n if (normalized === prefix) return true;\n if (normalized.startsWith(`${prefix} `)) return true;\n }\n return false;\n}\n\nexport interface RunCommandResult {\n exitCode: number | null;\n /** Combined stdout+stderr, truncated to `maxOutputChars` with a marker. */\n output: string;\n /** True when the process was killed for exceeding `timeoutSec`. */\n timedOut: boolean;\n}\n\nexport async function runCommand(\n cmd: string,\n opts: {\n cwd: string;\n timeoutSec?: number;\n maxOutputChars?: number;\n signal?: AbortSignal;\n },\n): Promise<RunCommandResult> {\n const argv = tokenizeCommand(cmd);\n if (argv.length === 0) throw new Error(\"run_command: empty command\");\n const operator = detectShellOperator(cmd);\n if (operator !== null) {\n throw new Error(\n `run_command: shell operator \"${operator}\" is not supported — this tool spawns one process, no shell expansion. Split into separate run_command calls and combine the output in your reasoning (e.g. instead of \\`grep foo *.ts | wc -l\\`, call \\`grep -c foo *.ts\\` or two separate commands). To pass \"${operator}\" as a literal argument, wrap it in quotes.`,\n );\n }\n const timeoutMs = (opts.timeoutSec ?? DEFAULT_TIMEOUT_SEC) * 1000;\n const maxChars = opts.maxOutputChars ?? DEFAULT_MAX_OUTPUT_CHARS;\n\n const spawnOpts: SpawnOptions = {\n cwd: opts.cwd,\n shell: false, // no shell-expansion — see header comment\n windowsHide: true,\n env: process.env,\n };\n\n // Windows: two layered fixes on top of shell:false —\n // 1. Resolve bare command names via PATH × PATHEXT (CreateProcess\n // ignores PATHEXT, so `npm` alone misses `npm.cmd`).\n // 2. Node 21.7.3+ (CVE-2024-27980) refuses to spawn `.cmd`/`.bat`\n // directly even with shell:false and safe args — throws\n // EINVAL at invocation time. Wrap those via `cmd.exe /d /s /c`\n // with verbatim args + manual quoting, so shell metacharacters\n // in arguments stay literal.\n // Unix path is unchanged.\n const { bin, args, spawnOverrides } = prepareSpawn(argv);\n const effectiveSpawnOpts = { ...spawnOpts, ...spawnOverrides };\n\n return await new Promise<RunCommandResult>((resolve, reject) => {\n let child: import(\"node:child_process\").ChildProcess;\n try {\n child = spawn(bin, args, effectiveSpawnOpts);\n } catch (err) {\n reject(err);\n return;\n }\n let buf = \"\";\n let timedOut = false;\n const killTimer = setTimeout(() => {\n timedOut = true;\n child.kill(\"SIGKILL\");\n }, timeoutMs);\n const onAbort = () => child.kill(\"SIGKILL\");\n opts.signal?.addEventListener(\"abort\", onAbort, { once: true });\n\n const onData = (chunk: Buffer | string) => {\n buf += chunk.toString();\n // Soft cap: we let the process keep running (killing early could\n // hide a real failure), but we stop growing the buffer past 2×\n // the cap so a chatty test can't OOM us.\n if (buf.length > maxChars * 2) buf = `${buf.slice(0, maxChars * 2)}`;\n };\n child.stdout?.on(\"data\", onData);\n child.stderr?.on(\"data\", onData);\n child.on(\"error\", (err) => {\n clearTimeout(killTimer);\n opts.signal?.removeEventListener(\"abort\", onAbort);\n reject(err);\n });\n child.on(\"close\", (code) => {\n clearTimeout(killTimer);\n opts.signal?.removeEventListener(\"abort\", onAbort);\n const output =\n buf.length > maxChars\n ? `${buf.slice(0, maxChars)}\\n\\n[… truncated ${buf.length - maxChars} chars …]`\n : buf;\n resolve({ exitCode: code, output, timedOut });\n });\n });\n}\n\n/**\n * Test/override hooks for {@link resolveExecutable}. Omitting any field\n * falls through to the real process globals — the runtime call path\n * uses defaults; tests inject `platform` + `env` + `isFile` to exercise\n * Windows-specific lookup from a Linux CI runner without touching\n * actual fs.\n */\nexport interface ResolveExecutableOptions {\n platform?: NodeJS.Platform;\n env?: { PATH?: string; PATHEXT?: string };\n /** Predicate swapped in by tests to avoid creating real files. */\n isFile?: (path: string) => boolean;\n /** Path.join used for the lookup. Defaults to Windows semantics on Windows. */\n pathDelimiter?: string;\n}\n\n/**\n * Resolve a bare command name (e.g. `npm`) to its on-disk path via\n * PATH × PATHEXT on Windows. Returns the input unchanged on non-Windows\n * platforms, when the input is already a path (contains `/`, `\\`, or is\n * absolute), or when no match is found in PATH × PATHEXT (caller gets a\n * natural ENOENT from spawn, which surfaces cleanly).\n *\n * Why this exists: `child_process.spawn` with `shell: false` invokes\n * Windows `CreateProcess`, which does not honor `PATHEXT` and does not\n * search for `.cmd` / `.bat` wrappers. Node-ecosystem tools ship as\n * `npm.cmd`, `npx.cmd`, `yarn.cmd`, etc., so a bare `npm` fails with\n * ENOENT under `shell: false`. Flipping to `shell: true` would work\n * but reintroduces shell-expansion (pipes, redirects, chained cmds)\n * that the tool was explicitly designed to forbid. This resolver\n * threads the needle.\n */\nexport function resolveExecutable(cmd: string, opts: ResolveExecutableOptions = {}): string {\n const platform = opts.platform ?? process.platform;\n if (platform !== \"win32\") return cmd;\n if (!cmd) return cmd;\n // Already a path fragment — spawn handles these natively.\n if (cmd.includes(\"/\") || cmd.includes(\"\\\\\") || pathMod.isAbsolute(cmd)) return cmd;\n // If the model wrote `npm.cmd` explicitly, respect that verbatim.\n if (pathMod.extname(cmd)) return cmd;\n\n const env = opts.env ?? process.env;\n const pathExt = (env.PATHEXT ?? \".COM;.EXE;.BAT;.CMD\")\n .split(\";\")\n .map((e) => e.trim())\n .filter(Boolean);\n const delimiter = opts.pathDelimiter ?? (platform === \"win32\" ? \";\" : pathMod.delimiter);\n const pathDirs = (env.PATH ?? \"\").split(delimiter).filter(Boolean);\n const isFile = opts.isFile ?? defaultIsFile;\n\n for (const dir of pathDirs) {\n for (const ext of pathExt) {\n // Force win32 join so CI tests that pass `platform: \"win32\"`\n // from a Linux runner get backslash-joined paths; the real-\n // Windows runtime path lands here too and gets the correct\n // separator regardless of where pathMod defaults.\n const full = pathMod.win32.join(dir, cmd + ext);\n if (isFile(full)) return full;\n }\n }\n return cmd;\n}\n\nfunction defaultIsFile(full: string): boolean {\n try {\n return existsSync(full) && statSync(full).isFile();\n } catch {\n return false;\n }\n}\n\n/**\n * Prepare `(bin, args, spawnOpts)` for the runCommand spawn call,\n * applying Windows-specific workarounds for (a) PATHEXT lookup and\n * (b) the CVE-2024-27980 prohibition on direct `.cmd`/`.bat` spawns.\n *\n * Exported so tests can assert the transformation without booting an\n * actual child process.\n */\nexport function prepareSpawn(\n argv: readonly string[],\n opts: ResolveExecutableOptions = {},\n): { bin: string; args: string[]; spawnOverrides: SpawnOptions } {\n const head = argv[0] ?? \"\";\n const tail = argv.slice(1);\n const platform = opts.platform ?? process.platform;\n const resolved = resolveExecutable(head, opts);\n\n if (platform !== \"win32\") {\n return { bin: resolved, args: [...tail], spawnOverrides: {} };\n }\n\n // `.cmd` / `.bat` wrappers require cmd.exe on post-CVE Node.\n if (/\\.(cmd|bat)$/i.test(resolved)) {\n const cmdline = [resolved, ...tail].map(quoteForCmdExe).join(\" \");\n return {\n bin: \"cmd.exe\",\n args: [\"/d\", \"/s\", \"/c\", withUtf8Codepage(cmdline)],\n // windowsVerbatimArguments prevents Node from re-quoting the /c\n // payload — we've already composed an exact cmd.exe command\n // line. Without this Node wraps our already-quoted string in\n // another round of quotes and cmd.exe can't parse it.\n spawnOverrides: { windowsVerbatimArguments: true },\n };\n }\n\n // Bare command names that PATH × PATHEXT couldn't resolve to an\n // on-disk file — these are almost always cmd.exe built-ins (`dir`,\n // `echo`, `type`, `ver`, `vol`, `where`, `help`, …) which don't\n // exist as standalone executables. Direct spawn crashes with ENOENT;\n // routing through cmd.exe lets the built-in resolve, and if it's\n // genuinely unknown the user gets the standard \"'foo' is not\n // recognized\" message instead of a raw spawn failure.\n if (isBareWindowsName(resolved) && resolved === head) {\n const cmdline = [head, ...tail].map(quoteForCmdExe).join(\" \");\n return {\n bin: \"cmd.exe\",\n args: [\"/d\", \"/s\", \"/c\", withUtf8Codepage(cmdline)],\n spawnOverrides: { windowsVerbatimArguments: true },\n };\n }\n\n // PowerShell variants: chcp 65001 doesn't help here because PowerShell\n // sets its own [Console]::OutputEncoding at startup — usually system\n // codepage (CP936/CP932/CP949 on CJK Windows) or UTF-16. The result\n // is mojibake when our `chunk.toString()` UTF-8-decodes its stdout.\n // Inject a UTF-8 setup prelude into the `-Command` (or `-c`) arg so\n // any output produced thereafter is UTF-8.\n if (isPowerShellExe(resolved)) {\n const patched = injectPowerShellUtf8(tail);\n if (patched) {\n return { bin: resolved, args: patched, spawnOverrides: {} };\n }\n }\n\n return { bin: resolved, args: [...tail], spawnOverrides: {} };\n}\n\n/** Resolved bin path looks like Windows PowerShell or PowerShell Core. */\nfunction isPowerShellExe(resolved: string): boolean {\n return /(?:^|[\\\\/])(?:powershell|pwsh)(?:\\.exe)?$/i.test(resolved);\n}\n\n/**\n * Locate `-Command` / `-c` in `args` and prepend the UTF-8 setup prelude\n * to its value. Returns the patched args, or `null` when no `-Command`\n * arg is present (in which case we leave the invocation untouched —\n * inline-expression and script-file modes have their own conventions\n * we don't want to silently rewrite).\n *\n * Why not always wrap: PowerShell's quoting semantics are finicky enough\n * that adding a prelude to a script file invocation could break it.\n * `-Command` is the case the model actually uses, and where mojibake\n * matters; targeting just it keeps the blast radius small.\n *\n * Exported for tests.\n */\nexport function injectPowerShellUtf8(args: readonly string[]): string[] | null {\n const prelude =\n \"[Console]::OutputEncoding=[System.Text.Encoding]::UTF8;$OutputEncoding=[System.Text.Encoding]::UTF8;\";\n for (let i = 0; i < args.length; i++) {\n const a = args[i] ?? \"\";\n if (/^-(?:Command|c)$/i.test(a) && i + 1 < args.length) {\n const out = [...args];\n out[i + 1] = `${prelude}${args[i + 1] ?? \"\"}`;\n return out;\n }\n }\n return null;\n}\n\n/**\n * Prefix a cmd.exe command line with `chcp 65001 >nul &` so output\n * (from cmd.exe and any child it spawns) is UTF-8-encoded. Without\n * this, on Chinese / Japanese / Korean Windows, `dir`, `findstr`,\n * `where`, etc. emit text in the system codepage (CP936, CP932,\n * CP949, …) and `chunk.toString()` — which decodes as UTF-8 — produces\n * garbled mojibake the model then sees as poisoned input on the next\n * turn.\n *\n * Scope: chcp affects ONLY this cmd.exe instance, which exits after\n * `/c`. No global console state changes. Single `&` (not `&&`) so the\n * command still runs even on the rare Windows builds where chcp\n * itself returns a non-zero exit (Win7 quirks; harmless on Win10+).\n *\n * Exported so tests can verify the wrapping shape.\n */\nexport function withUtf8Codepage(cmdline: string): string {\n return `chcp 65001 >nul & ${cmdline}`;\n}\n\n/**\n * True when `s` looks like a bare executable name — no path separator,\n * no drive letter, no extension. Such names on Windows, when absent\n * from PATH × PATHEXT, are almost always cmd.exe built-ins.\n */\nfunction isBareWindowsName(s: string): boolean {\n if (!s) return false;\n if (s.includes(\"/\") || s.includes(\"\\\\\")) return false;\n if (pathMod.isAbsolute(s)) return false;\n if (pathMod.extname(s)) return false;\n return true;\n}\n\n/**\n * Quote an argument so cmd.exe parses it back as a single token. We\n * always wrap in double quotes when the arg contains whitespace or\n * any cmd.exe metacharacter, doubling embedded quotes per cmd.exe's\n * `\"\"` escape rule. Bare alphanumeric args pass through unquoted for\n * readability in logs.\n *\n * Exported for test coverage of the quoting semantics.\n */\nexport function quoteForCmdExe(arg: string): string {\n if (arg === \"\") return '\"\"';\n if (!/[\\s\"&|<>^%(),;!]/.test(arg)) return arg;\n return `\"${arg.replace(/\"/g, '\"\"')}\"`;\n}\n\n/** Error thrown by `run_command` when the command isn't allowlisted. */\nexport class NeedsConfirmationError extends Error {\n readonly command: string;\n constructor(command: string) {\n super(\n `run_command: \"${command}\" needs the user's approval before it runs. STOP calling tools now — the TUI has already prompted the user to press y (run) or n (deny). Wait for their next message; it will either be the command's output (if they approved) or an instruction to continue without it (if they denied). Don't retry the command or call other shell commands in the meantime.`,\n );\n this.name = \"NeedsConfirmationError\";\n this.command = command;\n }\n}\n\nexport function registerShellTools(registry: ToolRegistry, opts: ShellToolsOptions): ToolRegistry {\n const rootDir = pathMod.resolve(opts.rootDir);\n const timeoutSec = opts.timeoutSec ?? DEFAULT_TIMEOUT_SEC;\n const maxOutputChars = opts.maxOutputChars ?? DEFAULT_MAX_OUTPUT_CHARS;\n // Resolved on every dispatch so newly-persisted \"always allow\"\n // prefixes take effect inside the session that added them, not just\n // on the next launch. Static arrays are wrapped into a constant\n // getter so the call site below is uniform.\n const getExtraAllowed: () => readonly string[] =\n typeof opts.extraAllowed === \"function\"\n ? opts.extraAllowed\n : (() => {\n const snapshot = opts.extraAllowed ?? [];\n return () => snapshot;\n })();\n const allowAll = opts.allowAll ?? false;\n\n registry.register({\n name: \"run_command\",\n description:\n \"Run a shell command in the project root and return its combined stdout+stderr. Common read-only inspection and test/lint/typecheck commands run immediately; anything that could mutate state, install dependencies, or touch the network is refused until the user confirms it in the TUI. Prefer this over asking the user to run a command manually — after edits, run the project's tests to verify.\",\n // Plan-mode gate: allow allowlisted commands through (git status,\n // cargo check, ls, grep …) so the model can actually investigate\n // during planning. Anything that would otherwise trigger a\n // confirmation prompt is treated as \"not read-only\" and bounced.\n readOnlyCheck: (args: { command?: unknown }) => {\n if (allowAll) return true;\n const cmd = typeof args?.command === \"string\" ? args.command.trim() : \"\";\n if (!cmd) return false;\n return isAllowed(cmd, getExtraAllowed());\n },\n parameters: {\n type: \"object\",\n properties: {\n command: {\n type: \"string\",\n description:\n 'Full command line. Tokenized with POSIX-ish quoting; no shell expansion. Pipes (`|`), redirects (`>`, `<`, `2>`), and `&&`/`||` chaining are rejected with an error — split into separate calls instead. To pass an operator character as a literal argument (e.g. a regex), wrap it in quotes: `grep \"a|b\" file.txt`.',\n },\n timeoutSec: {\n type: \"integer\",\n description: `Override the default ${timeoutSec}s timeout for a single command.`,\n },\n },\n required: [\"command\"],\n },\n fn: async (args: { command: string; timeoutSec?: number }, ctx) => {\n const cmd = args.command.trim();\n if (!cmd) throw new Error(\"run_command: empty command\");\n if (!allowAll && !isAllowed(cmd, getExtraAllowed())) {\n throw new NeedsConfirmationError(cmd);\n }\n const effectiveTimeout = Math.max(1, Math.min(600, args.timeoutSec ?? timeoutSec));\n const result = await runCommand(cmd, {\n cwd: rootDir,\n timeoutSec: effectiveTimeout,\n maxOutputChars,\n signal: ctx?.signal,\n });\n return formatCommandResult(cmd, result);\n },\n });\n\n return registry;\n}\n\nexport function formatCommandResult(cmd: string, r: RunCommandResult): string {\n const header = r.timedOut\n ? `$ ${cmd}\\n[killed after timeout]`\n : `$ ${cmd}\\n[exit ${r.exitCode ?? \"?\"}]`;\n return r.output ? `${header}\\n${r.output}` : header;\n}\n","/**\n * Built-in web search + fetch tools.\n *\n * - `web_search(query, topK?)` — Mojeek's public search page. No API\n * key, no signup. We originally shipped this backed by DuckDuckGo's\n * HTML endpoint, but DDG started serving anti-bot interstitials\n * (HTTP 202 with a challenge page) for every unauthenticated POST.\n * Mojeek runs its own independent index, is bot-friendly, and\n * returns parseable HTML.\n * - `web_fetch(url)` — HTTP GET + naïve HTML-to-text extraction.\n *\n * Both are registered by default on `reasonix chat` / `reasonix code`;\n * set `search: false` in config (or `REASONIX_SEARCH=off`) to turn\n * them off. The model decides when to call them based on the query —\n * no slash command required.\n */\n\nimport type { ToolRegistry } from \"../tools.js\";\n\nexport interface SearchResult {\n title: string;\n url: string;\n snippet: string;\n}\n\nexport interface PageContent {\n url: string;\n title?: string;\n text: string;\n /** True when the extracted text was clipped to fit the cap. */\n truncated: boolean;\n}\n\nexport interface WebFetchOptions {\n /** Max bytes of extracted text. Defaults to 32_000 to match tool-result cap. */\n maxChars?: number;\n /** Timeout in ms. Defaults to 15_000. */\n timeoutMs?: number;\n signal?: AbortSignal;\n}\n\nexport interface WebSearchOptions {\n topK?: number;\n signal?: AbortSignal;\n}\n\nconst DEFAULT_FETCH_MAX_CHARS = 32_000;\nconst DEFAULT_FETCH_TIMEOUT_MS = 15_000;\nconst DEFAULT_TOPK = 5;\n// Real-browser UA. Servers like Mojeek are bot-friendly but still gate\n// obvious scraper UAs; a stock Chrome string avoids the fast-path block.\nconst USER_AGENT =\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36\";\nconst MOJEEK_ENDPOINT = \"https://www.mojeek.com/search\";\n\n/**\n * Search the public web via Mojeek. Returns up to `topK` ranked\n * results with title, url, snippet.\n *\n * Mojeek is an independent index (not a Google/Bing front-end) which\n * means coverage on niche or very recent topics can be thinner, but\n * it's reliable from scripts and doesn't gate on cookies or sessions.\n * If the response has 0 results we distinguish \"truly empty\" from\n * \"layout changed or blocked\" so the caller isn't left guessing.\n */\nexport async function webSearch(\n query: string,\n opts: WebSearchOptions = {},\n): Promise<SearchResult[]> {\n const topK = Math.max(1, Math.min(10, opts.topK ?? DEFAULT_TOPK));\n const resp = await fetch(`${MOJEEK_ENDPOINT}?q=${encodeURIComponent(query)}`, {\n headers: {\n \"User-Agent\": USER_AGENT,\n Accept: \"text/html,application/xhtml+xml,application/xml;q=0.9\",\n \"Accept-Language\": \"en-US,en;q=0.9\",\n },\n signal: opts.signal,\n redirect: \"follow\",\n });\n if (!resp.ok) throw new Error(`web_search ${resp.status}`);\n const html = await resp.text();\n const results = parseMojeekResults(html).slice(0, topK);\n if (results.length === 0) {\n if (/no results found|did not match any documents/i.test(html)) return [];\n if (/captcha|verify you are human|access denied|forbidden/i.test(html)) {\n throw new Error(\"web_search: Mojeek anti-bot page — rate-limited or blocked\");\n }\n throw new Error(\n `web_search: 0 results but response doesn't look like a real empty page (${html.length} chars, first 120: ${html.slice(0, 120).replace(/\\s+/g, \" \")})`,\n );\n }\n return results;\n}\n\n/**\n * Extract results from a Mojeek search page.\n *\n * Mojeek's stable shape (as of April 2026):\n * <a … class=\"ob\" href=\"URL\"> … breadcrumb … </a>\n * <h2><a class=\"title\" href=\"URL\">Title</a></h2>\n * <p class=\"s\">snippet text …</p>\n *\n * We do two tolerant passes — title anchors, then snippet paragraphs —\n * and pair them positionally. Attribute order inside a tag varies\n * between versions, so each pass captures the whole element and we\n * re-extract href / inner text with a second regex. Exported for\n * unit testing against a fixture.\n */\nexport function parseMojeekResults(html: string): SearchResult[] {\n const titles: string[] = [];\n const titleAnchorRe = /<a\\b[^>]*\\bclass=\"title\"[^>]*>[\\s\\S]*?<\\/a>/g;\n let m: RegExpExecArray | null;\n while (true) {\n m = titleAnchorRe.exec(html);\n if (m === null) break;\n titles.push(m[0]);\n }\n\n const snippets: string[] = [];\n const snippetRe = /<p\\b[^>]*\\bclass=\"s\"[^>]*>([\\s\\S]*?)<\\/p>/g;\n while (true) {\n m = snippetRe.exec(html);\n if (m === null) break;\n snippets.push(m[1] ?? \"\");\n }\n\n const hrefRe = /href=\"([^\"]+)\"/;\n const innerRe = /<a\\b[^>]*>([\\s\\S]*?)<\\/a>/;\n const results: SearchResult[] = [];\n for (let i = 0; i < titles.length; i++) {\n const anchor = titles[i]!;\n const hrefMatch = anchor.match(hrefRe);\n const innerMatch = anchor.match(innerRe);\n if (!hrefMatch?.[1]) continue;\n results.push({\n title: decodeHtmlEntities(stripHtml(innerMatch?.[1] ?? \"\")).trim(),\n url: hrefMatch[1],\n snippet: decodeHtmlEntities(stripHtml(snippets[i] ?? \"\"))\n .replace(/\\s+/g, \" \")\n .trim(),\n });\n }\n return results;\n}\n\n/**\n * Download a URL, strip HTML down to readable text, return it. Times\n * out at 15s, caps extracted text at 32k chars to fit the tool-result\n * budget.\n */\nexport async function webFetch(url: string, opts: WebFetchOptions = {}): Promise<PageContent> {\n const maxChars = opts.maxChars ?? DEFAULT_FETCH_MAX_CHARS;\n const timeoutMs = opts.timeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS;\n const ctl = new AbortController();\n const timer = setTimeout(() => ctl.abort(), timeoutMs);\n // Forward the caller's abort too so an Esc during a long fetch is respected.\n const cancel = () => ctl.abort();\n opts.signal?.addEventListener(\"abort\", cancel, { once: true });\n let resp: Response;\n try {\n resp = await fetch(url, {\n headers: { \"User-Agent\": USER_AGENT, Accept: \"text/html,text/plain,*/*\" },\n signal: ctl.signal,\n redirect: \"follow\",\n });\n } finally {\n clearTimeout(timer);\n opts.signal?.removeEventListener(\"abort\", cancel);\n }\n if (!resp.ok) throw new Error(`web_fetch ${resp.status} for ${url}`);\n const contentType = resp.headers.get(\"content-type\") ?? \"\";\n const raw = await resp.text();\n const title = extractTitle(raw);\n const text = contentType.includes(\"text/html\") ? htmlToText(raw) : raw;\n const truncated = text.length > maxChars;\n const finalText = truncated\n ? `${text.slice(0, maxChars)}\\n\\n[… truncated ${text.length - maxChars} chars …]`\n : text;\n return { url, title, text: finalText, truncated };\n}\n\n/**\n * Strip HTML to readable text. Removes scripts/styles/nav/footer/aside\n * blocks first, then tags, then collapses whitespace. Not a Readability\n * clone — purpose-built to keep the extracted text small enough for the\n * tool-result budget while preserving paragraph breaks.\n */\nexport function htmlToText(html: string): string {\n let s = html;\n s = s.replace(/<script[\\s\\S]*?<\\/script>/gi, \"\");\n s = s.replace(/<style[\\s\\S]*?<\\/style>/gi, \"\");\n s = s.replace(/<noscript[\\s\\S]*?<\\/noscript>/gi, \"\");\n s = s.replace(/<nav[\\s\\S]*?<\\/nav>/gi, \"\");\n s = s.replace(/<footer[\\s\\S]*?<\\/footer>/gi, \"\");\n s = s.replace(/<aside[\\s\\S]*?<\\/aside>/gi, \"\");\n s = s.replace(/<svg[\\s\\S]*?<\\/svg>/gi, \"\");\n // Preserve paragraph breaks by turning common block tags into newlines.\n s = s.replace(/<\\/?(p|div|br|h[1-6]|li|tr|section|article)\\b[^>]*>/gi, \"\\n\");\n s = s.replace(/<[^>]+>/g, \"\");\n s = decodeHtmlEntities(s);\n s = s.replace(/[ \\t]+/g, \" \");\n s = s.replace(/\\n[ \\t]+/g, \"\\n\");\n s = s.replace(/\\n{3,}/g, \"\\n\\n\");\n return s.trim();\n}\n\nfunction stripHtml(s: string): string {\n return s.replace(/<[^>]+>/g, \"\");\n}\n\nfunction decodeHtmlEntities(s: string): string {\n return s\n .replace(/&nbsp;/g, \" \")\n .replace(/&amp;/g, \"&\")\n .replace(/&lt;/g, \"<\")\n .replace(/&gt;/g, \">\")\n .replace(/&quot;/g, '\"')\n .replace(/&#39;/g, \"'\");\n}\n\nfunction extractTitle(html: string): string | undefined {\n const m = html.match(/<title[^>]*>([\\s\\S]*?)<\\/title>/i);\n if (!m?.[1]) return undefined;\n return m[1].replace(/\\s+/g, \" \").trim() || undefined;\n}\n\nexport interface WebToolsOptions {\n /** Default top-K for `web_search` when the model doesn't specify. */\n defaultTopK?: number;\n /** Byte cap for `web_fetch` extracted text. */\n maxFetchChars?: number;\n}\n\n/**\n * Register `web_search` + `web_fetch` on a ToolRegistry. The model\n * invokes them automatically when a question needs current info —\n * no slash command from the user is required.\n */\nexport function registerWebTools(registry: ToolRegistry, opts: WebToolsOptions = {}): ToolRegistry {\n const defaultTopK = opts.defaultTopK ?? DEFAULT_TOPK;\n const maxFetchChars = opts.maxFetchChars ?? DEFAULT_FETCH_MAX_CHARS;\n\n registry.register({\n name: \"web_search\",\n description:\n \"Search the public web. Returns ranked results with title, url, and snippet. Use this when the question needs information more current than your training data, when you're unsure of a factual detail, or when the user asks about a specific webpage/library/release you haven't seen.\",\n readOnly: true,\n parameters: {\n type: \"object\",\n properties: {\n query: { type: \"string\", description: \"Natural-language search query.\" },\n topK: {\n type: \"integer\",\n description: `Number of results to return (1..10). Default ${defaultTopK}.`,\n },\n },\n required: [\"query\"],\n },\n fn: async (args: { query: string; topK?: number }, ctx) => {\n const results = await webSearch(args.query, {\n topK: args.topK ?? defaultTopK,\n signal: ctx?.signal,\n });\n return formatSearchResults(args.query, results);\n },\n });\n\n registry.register({\n name: \"web_fetch\",\n description:\n \"Download a URL and return its visible text content (HTML pages get scripts/styles/nav stripped). Truncated at the tool-result cap. Use after web_search when a snippet isn't enough.\",\n readOnly: true,\n parameters: {\n type: \"object\",\n properties: {\n url: { type: \"string\", description: \"Absolute http:// or https:// URL.\" },\n },\n required: [\"url\"],\n },\n fn: async (args: { url: string }, ctx) => {\n if (!/^https?:\\/\\//i.test(args.url)) {\n throw new Error(\"web_fetch: url must start with http:// or https://\");\n }\n const page = await webFetch(args.url, { maxChars: maxFetchChars, signal: ctx?.signal });\n const header = page.title ? `${page.title}\\n${page.url}` : page.url;\n return `${header}\\n\\n${page.text}`;\n },\n });\n\n return registry;\n}\n\nexport function formatSearchResults(query: string, results: SearchResult[]): string {\n const lines: string[] = [`query: ${query}`, `\\nresults (${results.length}):`];\n results.forEach((r, i) => {\n lines.push(`\\n${i + 1}. ${r.title}`);\n lines.push(` ${r.url}`);\n if (r.snippet) lines.push(` ${r.snippet}`);\n });\n return lines.join(\"\\n\");\n}\n","import { readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\n\n/**\n * Minimal `.env` loader; no dependency on dotenv.\n *\n * Reads KEY=VALUE lines and populates `process.env` for keys not already set.\n * Silently no-ops if the file is missing. Safe to call from library entry\n * points, CLI commands, examples, and benchmark runners.\n */\nexport function loadDotenv(path = \".env\"): void {\n let raw: string;\n try {\n raw = readFileSync(resolve(process.cwd(), path), \"utf8\");\n } catch {\n return;\n }\n for (const line of raw.split(/\\r?\\n/)) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith(\"#\")) continue;\n const eq = trimmed.indexOf(\"=\");\n if (eq === -1) continue;\n const key = trimmed.slice(0, eq).trim();\n let value = trimmed.slice(eq + 1).trim();\n if (\n (value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))\n ) {\n value = value.slice(1, -1);\n }\n if (process.env[key] === undefined) process.env[key] = value;\n }\n}\n","/**\n * Transcript format — the canonical \"audit log\" of a Reasonix session.\n *\n * Design split:\n * - Session file (`~/.reasonix/sessions/<name>.jsonl`) stores only the\n * `ChatMessage`s the model needs to resume. See session.ts.\n * - Transcript file (this module) stores every LoopEvent with usage, cost,\n * model, and prefix fingerprint attached where available — enough for\n * replay and diff to reconstruct economics.\n *\n * The two are different contracts: sessions are the user's *memory*;\n * transcripts are the *receipts*. Don't conflate them.\n *\n * Backward compatibility: all fields beyond {ts, turn, role, content} are\n * optional on read. A v0.1 transcript (pre-usage) still parses and renders\n * — it just shows cost/cache as n/a.\n */\n\nimport { type WriteStream, createWriteStream, readFileSync } from \"node:fs\";\nimport type { TypedPlanState } from \"./harvest.js\";\nimport type { LoopEvent } from \"./loop.js\";\nimport type { RawUsage } from \"./types.js\";\n\nexport interface TranscriptRecord {\n /** ISO-8601 timestamp at emit time. */\n ts: string;\n /** 1-based turn number within the session. */\n turn: number;\n /** LoopEvent role — \"assistant_delta\" | \"assistant_final\" | \"tool\" | \"done\" | ... */\n role: string;\n /** For assistant events, the final (or delta) text; for tool events, the tool result. */\n content: string;\n /** Tool name (role === \"tool\"). */\n tool?: string;\n /** JSON-string args the model sent for a tool call (role === \"tool\"). Persisted so diff can explain *why* two runs made different calls. */\n args?: string;\n /** DeepSeek token-usage snapshot (role === \"assistant_final\"). */\n usage?: RawUsage;\n /** USD cost of this turn (role === \"assistant_final\"). */\n cost?: number;\n /** Model id that produced this turn. */\n model?: string;\n /**\n * The ImmutablePrefix fingerprint at this turn. Lets diff prove two runs\n * share a prefix — i.e. any cache-hit delta is attributable to log\n * stability, not to a different system prompt.\n */\n prefixHash?: string;\n /**\n * Structured plan state extracted by the Pillar 2 harvester. Present on\n * assistant_final records when harvest was enabled and produced non-empty\n * state. Omitted entirely when harvest is off or produced nothing —\n * absence means \"no data\", not \"empty plan\".\n */\n planState?: TypedPlanState;\n /** Optional error message (role === \"error\"). */\n error?: string;\n}\n\nexport interface TranscriptMeta {\n /**\n * Optional metadata written as the first line of a transcript. Lets\n * downstream tooling know what it's reading without guessing.\n * Recognized by a special role \"_meta\".\n */\n version: 1;\n source: string; // e.g. \"reasonix chat\", \"bench/baseline\", \"bench/reasonix\"\n model?: string;\n task?: string;\n mode?: string;\n repeat?: number;\n startedAt: string;\n}\n\ninterface MetaLine {\n role: \"_meta\";\n meta: TranscriptMeta;\n}\n\nexport interface ReadTranscriptResult {\n meta: TranscriptMeta | null;\n records: TranscriptRecord[];\n}\n\n/**\n * Build a TranscriptRecord from a LoopEvent. Extra fields (model,\n * prefixHash) that the LoopEvent doesn't carry are passed in separately\n * because they're session-level, not event-level.\n */\nexport function recordFromLoopEvent(\n ev: LoopEvent,\n extra: { model: string; prefixHash: string },\n): TranscriptRecord {\n const rec: TranscriptRecord = {\n ts: new Date().toISOString(),\n turn: ev.turn,\n role: ev.role,\n content: ev.content,\n };\n if (ev.toolName !== undefined) rec.tool = ev.toolName;\n if (ev.toolArgs !== undefined) rec.args = ev.toolArgs;\n if (ev.error !== undefined) rec.error = ev.error;\n // Only persist non-empty plan state — empty harvest output is indistinguishable\n // from \"harvest was off\" for replay purposes, and saves transcript bytes.\n if (ev.planState && !isPlanStateEmptyShape(ev.planState)) {\n rec.planState = {\n subgoals: [...ev.planState.subgoals],\n hypotheses: [...ev.planState.hypotheses],\n uncertainties: [...ev.planState.uncertainties],\n rejectedPaths: [...ev.planState.rejectedPaths],\n };\n }\n if (ev.stats) {\n rec.usage = {\n prompt_tokens: ev.stats.usage.promptTokens,\n completion_tokens: ev.stats.usage.completionTokens,\n total_tokens: ev.stats.usage.totalTokens,\n prompt_cache_hit_tokens: ev.stats.usage.promptCacheHitTokens,\n prompt_cache_miss_tokens: ev.stats.usage.promptCacheMissTokens,\n };\n rec.cost = ev.stats.cost;\n rec.model = ev.stats.model;\n rec.prefixHash = extra.prefixHash;\n } else if (ev.role === \"assistant_final\") {\n // assistant_final without stats (shouldn't happen in the live loop but\n // might in test fixtures) — still persist model + prefix for continuity.\n rec.model = extra.model;\n rec.prefixHash = extra.prefixHash;\n }\n return rec;\n}\n\n/**\n * Append a record to an open write stream. Caller owns the stream lifecycle.\n */\nexport function writeRecord(stream: WriteStream, record: TranscriptRecord): void {\n stream.write(`${JSON.stringify(record)}\\n`);\n}\n\n/**\n * Write a _meta line to an open write stream. Call exactly once, at the top.\n */\nexport function writeMeta(stream: WriteStream, meta: TranscriptMeta): void {\n const line: MetaLine = { role: \"_meta\", meta };\n stream.write(`${JSON.stringify(line)}\\n`);\n}\n\n/**\n * Convenience: open a stream, write meta, return stream.\n */\nexport function openTranscriptFile(path: string, meta: TranscriptMeta): WriteStream {\n const stream = createWriteStream(path, { flags: \"a\" });\n writeMeta(stream, meta);\n return stream;\n}\n\n/**\n * Parse a transcript file. Returns meta (if the first line is a _meta record)\n * and the full record list.\n *\n * Robustness contract:\n * - Empty lines are skipped.\n * - Malformed JSON lines are skipped silently (do not crash on partial\n * files — live chats may be mid-write).\n * - Records missing optional fields still parse — they're just rendered\n * with n/a where the optional value would go.\n */\nexport function readTranscript(path: string): ReadTranscriptResult {\n const raw = readFileSync(path, \"utf8\");\n return parseTranscript(raw);\n}\n\nfunction isPlanStateEmptyShape(s: TypedPlanState): boolean {\n return (\n s.subgoals.length === 0 &&\n s.hypotheses.length === 0 &&\n s.uncertainties.length === 0 &&\n s.rejectedPaths.length === 0\n );\n}\n\nexport function parseTranscript(raw: string): ReadTranscriptResult {\n const out: ReadTranscriptResult = { meta: null, records: [] };\n for (const line of raw.split(/\\r?\\n/)) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n let obj: unknown;\n try {\n obj = JSON.parse(trimmed);\n } catch {\n continue;\n }\n if (!obj || typeof obj !== \"object\") continue;\n const rec = obj as Record<string, unknown>;\n if (rec.role === \"_meta\" && rec.meta && typeof rec.meta === \"object\") {\n out.meta = rec.meta as TranscriptMeta;\n continue;\n }\n if (\n typeof rec.ts === \"string\" &&\n typeof rec.turn === \"number\" &&\n typeof rec.role === \"string\" &&\n typeof rec.content === \"string\"\n ) {\n out.records.push(rec as unknown as TranscriptRecord);\n }\n }\n return out;\n}\n","/**\n * Replay — reconstruct session economics from a transcript file.\n *\n * Given a transcript written by App.tsx or the bench runner, rebuild a\n * SessionSummary-compatible aggregate (turn count, total cost, cache-hit\n * ratio, vs-Claude estimate) without replaying the LLM calls.\n *\n * The whole point is offline auditing: a reader should be able to reproduce\n * the headline numbers from a transcript alone, without an API key.\n */\n\nimport { Usage } from \"./client.js\";\nimport {\n type SessionSummary,\n type TurnStats,\n claudeEquivalentCost,\n costUsd,\n inputCostUsd,\n outputCostUsd,\n} from \"./telemetry.js\";\nimport { type ReadTranscriptResult, type TranscriptRecord, readTranscript } from \"./transcript.js\";\n\n/**\n * A single turn's worth of records — the unit of navigation in replay TUI.\n * Records are grouped by their `turn` field, preserving file order within\n * each group (so tool events interleave with assistant_final events the\n * way they were actually emitted).\n */\nexport interface TurnPage {\n turn: number;\n records: TranscriptRecord[];\n}\n\n/**\n * Group transcript records into turn-pages. Pages are returned in ascending\n * turn order. Records without a numeric turn (meta lines, malformed) are\n * already filtered by the transcript reader, so this sees clean input.\n */\nexport function groupRecordsByTurn(records: TranscriptRecord[]): TurnPage[] {\n const byTurn = new Map<number, TranscriptRecord[]>();\n for (const rec of records) {\n const list = byTurn.get(rec.turn);\n if (list) list.push(rec);\n else byTurn.set(rec.turn, [rec]);\n }\n return [...byTurn.entries()]\n .sort(([a], [b]) => a - b)\n .map(([turn, records]) => ({ turn, records }));\n}\n\n/**\n * Cumulative replay stats up to and including pages[0..upToIdx]. Returns\n * empty stats if upToIdx < 0. Used by replay TUI's sidebar to show \"stats\n * so far\" as the user scrolls through a transcript.\n */\nexport function computeCumulativeStats(pages: TurnPage[], upToIdx: number): ReplayStats {\n if (upToIdx < 0) return computeReplayStats([]);\n const flat: TranscriptRecord[] = [];\n for (let i = 0; i <= upToIdx && i < pages.length; i++) {\n const records = pages[i]?.records;\n if (records) flat.push(...records);\n }\n return computeReplayStats(flat);\n}\n\nexport interface ReplayStats extends SessionSummary {\n /** Per-turn stats, in turn order. Only assistant_final records contribute. */\n perTurn: TurnStats[];\n /** Unique models that appeared in the transcript's assistant_final records. */\n models: string[];\n /** Unique prefix hashes that appeared. Length > 1 means the prefix churned (cache-hostile). */\n prefixHashes: string[];\n /** Count of user-role records (user turns issued). */\n userTurns: number;\n /** Count of tool-role records (tool calls executed). */\n toolCalls: number;\n /** Count of assistant_final records that carry a non-empty planState (harvest signal). */\n harvestedTurns: number;\n /** Sum of uncertainties across all harvested turns — a proxy for \"how much did R1 hedge?\" */\n totalUncertainties: number;\n /** Sum of subgoals across all harvested turns. */\n totalSubgoals: number;\n}\n\n/**\n * Parse a transcript file and compute replay stats. Throws only on I/O\n * errors; malformed lines inside the file are skipped silently.\n */\nexport function replayFromFile(path: string): { parsed: ReadTranscriptResult; stats: ReplayStats } {\n const parsed = readTranscript(path);\n return { parsed, stats: computeReplayStats(parsed.records) };\n}\n\nexport function computeReplayStats(records: TranscriptRecord[]): ReplayStats {\n const turns: TurnStats[] = [];\n const models = new Set<string>();\n const prefixHashes = new Set<string>();\n let userTurns = 0;\n let toolCalls = 0;\n let harvestedTurns = 0;\n let totalUncertainties = 0;\n let totalSubgoals = 0;\n\n for (const rec of records) {\n if (rec.role === \"user\") userTurns++;\n else if (rec.role === \"tool\") toolCalls++;\n else if (rec.role === \"assistant_final\") {\n if (rec.model) models.add(rec.model);\n if (rec.prefixHash) prefixHashes.add(rec.prefixHash);\n if (rec.planState) {\n harvestedTurns++;\n totalUncertainties += rec.planState.uncertainties.length;\n totalSubgoals += rec.planState.subgoals.length;\n }\n if (rec.usage && rec.model) {\n const u = new Usage(\n rec.usage.prompt_tokens ?? 0,\n rec.usage.completion_tokens ?? 0,\n rec.usage.total_tokens ?? 0,\n rec.usage.prompt_cache_hit_tokens ?? 0,\n rec.usage.prompt_cache_miss_tokens ?? 0,\n );\n turns.push({\n turn: rec.turn,\n model: rec.model,\n usage: u,\n // `rec.cost` wins when present — honors whatever the writer computed\n // even if pricing tables have since changed. Only recompute when\n // the transcript didn't record it (old format).\n cost: rec.cost ?? costUsd(rec.model, u),\n cacheHitRatio: u.cacheHitRatio,\n });\n }\n }\n }\n\n return {\n perTurn: turns,\n models: [...models],\n prefixHashes: [...prefixHashes],\n userTurns,\n toolCalls,\n harvestedTurns,\n totalUncertainties,\n totalSubgoals,\n ...summarizeTurns(turns),\n };\n}\n\nfunction summarizeTurns(turns: TurnStats[]): SessionSummary {\n const totalCost = turns.reduce((s, t) => s + t.cost, 0);\n const totalInput = turns.reduce((s, t) => s + inputCostUsd(t.model, t.usage), 0);\n const totalOutput = turns.reduce((s, t) => s + outputCostUsd(t.model, t.usage), 0);\n const totalClaude = turns.reduce((s, t) => s + claudeEquivalentCost(t.usage), 0);\n let hit = 0;\n let miss = 0;\n for (const t of turns) {\n hit += t.usage.promptCacheHitTokens;\n miss += t.usage.promptCacheMissTokens;\n }\n const cacheHitRatio = hit + miss > 0 ? hit / (hit + miss) : 0;\n const savingsVsClaude = totalClaude > 0 ? 1 - totalCost / totalClaude : 0;\n const lastTurn = turns[turns.length - 1];\n return {\n turns: turns.length,\n totalCostUsd: round(totalCost, 6),\n totalInputCostUsd: round(totalInput, 6),\n totalOutputCostUsd: round(totalOutput, 6),\n claudeEquivalentUsd: round(totalClaude, 6),\n savingsVsClaudePct: round(savingsVsClaude * 100, 2),\n cacheHitRatio: round(cacheHitRatio, 4),\n lastPromptTokens: lastTurn?.usage.promptTokens ?? 0,\n };\n}\n\nfunction round(n: number, digits: number): number {\n const f = 10 ** digits;\n return Math.round(n * f) / f;\n}\n","/**\n * Diff — compare two transcripts and produce a summary + divergence report.\n *\n * Two transcripts are \"comparable\" when they stem from the same task (or\n * the same user prompt). Alignment is by turn number: assistant_final #N\n * in A pairs with assistant_final #N in B. If one side ran more turns, the\n * extras are labeled \"only in A\" / \"only in B\".\n *\n * What we compute:\n * - Aggregate deltas: turns, tool calls, cache hit, cost, token counts\n * - First divergence: the lowest turn where A and B's tool calls or\n * assistant text differ meaningfully\n * - Prefix-stability story: how many unique prefix hashes each side used\n *\n * Non-goals (deliberately):\n * - LLM-judge quality comparison\n * - Per-token delta rendering — not useful at the fidelity we're at\n * - Embedding similarity — Levenshtein ratio is cheap and good enough\n */\n\nimport { type ReplayStats, computeReplayStats } from \"./replay.js\";\nimport type { ReadTranscriptResult, TranscriptRecord } from \"./transcript.js\";\n\nexport interface DiffSide {\n label: string;\n meta: ReadTranscriptResult[\"meta\"];\n records: TranscriptRecord[];\n stats: ReplayStats;\n}\n\nexport interface TurnPair {\n turn: number;\n aAssistant?: TranscriptRecord;\n bAssistant?: TranscriptRecord;\n aTools: TranscriptRecord[];\n bTools: TranscriptRecord[];\n /**\n * Classification of the pair:\n * \"match\" — both sides present, text & tool calls within threshold\n * \"diverge\" — both sides present, but text or tool calls differ\n * \"only_in_a\" — assistant_final in A but not B\n * \"only_in_b\" — assistant_final in B but not A\n */\n kind: \"match\" | \"diverge\" | \"only_in_a\" | \"only_in_b\";\n /** When kind === \"diverge\", a short one-liner pointing at what differs. */\n divergenceNote?: string;\n}\n\nexport interface DiffReport {\n a: DiffSide;\n b: DiffSide;\n pairs: TurnPair[];\n firstDivergenceTurn: number | null;\n}\n\n// ---------- navigation helpers (used by the Ink diff TUI) ----------\n\n/**\n * Find the next pair (strictly after `fromIdx`) whose kind is not \"match\".\n * Returns -1 when no later divergence exists. Used by DiffApp's `n` key.\n */\nexport function findNextDivergence(pairs: TurnPair[], fromIdx: number): number {\n for (let i = fromIdx + 1; i < pairs.length; i++) {\n if (pairs[i]!.kind !== \"match\") return i;\n }\n return -1;\n}\n\n/**\n * Find the previous pair (strictly before `fromIdx`) whose kind is not\n * \"match\". Returns -1 when no earlier divergence exists. Used by\n * DiffApp's `N` / `p` key.\n */\nexport function findPrevDivergence(pairs: TurnPair[], fromIdx: number): number {\n const start = Math.min(fromIdx - 1, pairs.length - 1);\n for (let i = start; i >= 0; i--) {\n if (pairs[i]!.kind !== \"match\") return i;\n }\n return -1;\n}\n\nexport function diffTranscripts(\n a: { label: string; parsed: ReadTranscriptResult },\n b: { label: string; parsed: ReadTranscriptResult },\n): DiffReport {\n const aSide: DiffSide = {\n label: a.label,\n meta: a.parsed.meta,\n records: a.parsed.records,\n stats: computeReplayStats(a.parsed.records),\n };\n const bSide: DiffSide = {\n label: b.label,\n meta: b.parsed.meta,\n records: b.parsed.records,\n stats: computeReplayStats(b.parsed.records),\n };\n\n const aByTurn = groupByTurn(a.parsed.records);\n const bByTurn = groupByTurn(b.parsed.records);\n const turns = [...new Set([...aByTurn.keys(), ...bByTurn.keys()])].sort((x, y) => x - y);\n\n const pairs: TurnPair[] = [];\n let firstDivergenceTurn: number | null = null;\n for (const turn of turns) {\n const aGroup = aByTurn.get(turn) ?? { assistant: undefined, tools: [] };\n const bGroup = bByTurn.get(turn) ?? { assistant: undefined, tools: [] };\n const aAssistant = aGroup.assistant;\n const bAssistant = bGroup.assistant;\n const aTools = aGroup.tools;\n const bTools = bGroup.tools;\n\n let kind: TurnPair[\"kind\"];\n let divergenceNote: string | undefined;\n if (!aAssistant && bAssistant) kind = \"only_in_b\";\n else if (aAssistant && !bAssistant) kind = \"only_in_a\";\n else if (!aAssistant && !bAssistant)\n kind = \"diverge\"; // tool-only turn (rare)\n else {\n divergenceNote = classifyDivergence(aAssistant!, bAssistant!, aTools, bTools);\n kind = divergenceNote ? \"diverge\" : \"match\";\n }\n\n if (kind !== \"match\" && firstDivergenceTurn === null) firstDivergenceTurn = turn;\n pairs.push({ turn, aAssistant, bAssistant, aTools, bTools, kind, divergenceNote });\n }\n\n return { a: aSide, b: bSide, pairs, firstDivergenceTurn };\n}\n\n// ---------- divergence classification ----------\n\n/**\n * Return a short reason string if two sides meaningfully disagree, or\n * undefined if they're close enough to call a match.\n *\n * Ranking of divergence signals (cheapest first):\n * 1. Different set of tool names → clearest diff\n * 2. Different tool args for the same tool → second-clearest\n * 3. Text similarity below threshold → fuzziest\n */\nfunction classifyDivergence(\n a: TranscriptRecord,\n b: TranscriptRecord,\n aTools: TranscriptRecord[],\n bTools: TranscriptRecord[],\n): string | undefined {\n const aNames = aTools.map((t) => t.tool ?? \"\").sort();\n const bNames = bTools.map((t) => t.tool ?? \"\").sort();\n if (aNames.join(\",\") !== bNames.join(\",\")) {\n return `tool calls differ: A=[${aNames.join(\",\") || \"—\"}] B=[${bNames.join(\",\") || \"—\"}]`;\n }\n // Same tool names — did they pass different args?\n for (let i = 0; i < aTools.length; i++) {\n const at = aTools[i]!;\n const bt = bTools[i]!;\n if (at.tool !== bt.tool) continue;\n if ((at.args ?? \"\") !== (bt.args ?? \"\")) {\n return `\"${at.tool}\" args differ`;\n }\n }\n const simRatio = similarity(a.content, b.content);\n if (simRatio < 0.75) return `text similarity ${(simRatio * 100).toFixed(0)}%`;\n return undefined;\n}\n\n/**\n * Normalized Levenshtein similarity ratio in [0, 1]. 1 = identical.\n * Early-exits for long strings (> 2000 chars) with a cheap token-overlap\n * estimate to keep diff fast on chatty transcripts.\n */\nexport function similarity(a: string, b: string): number {\n if (a === b) return 1;\n if (!a && !b) return 1;\n if (!a || !b) return 0;\n const maxLen = Math.max(a.length, b.length);\n if (maxLen > 2000) return tokenOverlap(a, b);\n const dist = levenshtein(a, b);\n return 1 - dist / maxLen;\n}\n\nfunction tokenOverlap(a: string, b: string): number {\n const ta = new Set(a.toLowerCase().split(/\\s+/).filter(Boolean));\n const tb = new Set(b.toLowerCase().split(/\\s+/).filter(Boolean));\n if (ta.size === 0 && tb.size === 0) return 1;\n let shared = 0;\n for (const t of ta) if (tb.has(t)) shared++;\n return (2 * shared) / (ta.size + tb.size);\n}\n\nfunction levenshtein(a: string, b: string): number {\n const m = a.length;\n const n = b.length;\n if (m === 0) return n;\n if (n === 0) return m;\n let prev = new Array(n + 1);\n let curr = new Array(n + 1);\n for (let j = 0; j <= n; j++) prev[j] = j;\n for (let i = 1; i <= m; i++) {\n curr[0] = i;\n for (let j = 1; j <= n; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1;\n curr[j] = Math.min(curr[j - 1] + 1, prev[j] + 1, prev[j - 1] + cost);\n }\n [prev, curr] = [curr, prev];\n }\n return prev[n];\n}\n\n// ---------- grouping ----------\n\ninterface TurnGroup {\n assistant?: TranscriptRecord;\n tools: TranscriptRecord[];\n}\n\nfunction groupByTurn(records: TranscriptRecord[]): Map<number, TurnGroup> {\n const out = new Map<number, TurnGroup>();\n for (const rec of records) {\n if (rec.role === \"user\") continue; // user msg is input to the turn, not its output\n const g = out.get(rec.turn) ?? { tools: [] };\n if (rec.role === \"assistant_final\") g.assistant = rec;\n else if (rec.role === \"tool\") g.tools.push(rec);\n out.set(rec.turn, g);\n }\n return out;\n}\n\n// ---------- rendering ----------\n\nexport interface RenderOptions {\n /** Monochrome output (for file redirection or piping). Defaults to true. */\n monochrome?: boolean;\n}\n\nexport function renderSummaryTable(report: DiffReport, _opts: RenderOptions = {}): string {\n const a = report.a;\n const b = report.b;\n const lines: string[] = [];\n lines.push(\"Comparing:\");\n lines.push(` A ${a.label}`);\n lines.push(` B ${b.label}`);\n lines.push(\"\");\n lines.push(row([\"\", \"A\", \"B\", \"Δ\"], [20, 14, 14, 14]));\n lines.push(\n row([\"─\".repeat(20), \"─\".repeat(14), \"─\".repeat(14), \"─\".repeat(14)], [20, 14, 14, 14]),\n );\n lines.push(statRow(\"model calls\", a.stats.turns, b.stats.turns));\n lines.push(statRow(\"user turns\", a.stats.userTurns, b.stats.userTurns));\n lines.push(statRow(\"tool calls\", a.stats.toolCalls, b.stats.toolCalls));\n lines.push(\n row(\n [\n \"cache hit\",\n `${pct(a.stats.cacheHitRatio)}`,\n `${pct(b.stats.cacheHitRatio)}`,\n signPct(b.stats.cacheHitRatio - a.stats.cacheHitRatio),\n ],\n [20, 14, 14, 14],\n ),\n );\n lines.push(\n row(\n [\n \"cost (USD)\",\n `$${a.stats.totalCostUsd.toFixed(6)}`,\n `$${b.stats.totalCostUsd.toFixed(6)}`,\n costDelta(a.stats.totalCostUsd, b.stats.totalCostUsd),\n ],\n [20, 14, 14, 14],\n ),\n );\n lines.push(statRow(\"prefix hashes\", a.stats.prefixHashes.length, b.stats.prefixHashes.length));\n // Harvest signal row — only surface when at least one side carries plan\n // state. Keeps no-harvest diffs visually identical to pre-v0.3 output.\n if (a.stats.harvestedTurns > 0 || b.stats.harvestedTurns > 0) {\n lines.push(\n row(\n [\n \"harvest turns\",\n `${a.stats.harvestedTurns}`,\n `${b.stats.harvestedTurns}`,\n signed(b.stats.harvestedTurns - a.stats.harvestedTurns),\n ],\n [20, 14, 14, 14],\n ),\n );\n lines.push(\n row(\n [\n \" subgoals\",\n `${a.stats.totalSubgoals}`,\n `${b.stats.totalSubgoals}`,\n signed(b.stats.totalSubgoals - a.stats.totalSubgoals),\n ],\n [20, 14, 14, 14],\n ),\n );\n lines.push(\n row(\n [\n \" uncertainties\",\n `${a.stats.totalUncertainties}`,\n `${b.stats.totalUncertainties}`,\n signed(b.stats.totalUncertainties - a.stats.totalUncertainties),\n ],\n [20, 14, 14, 14],\n ),\n );\n }\n lines.push(\"\");\n\n // Prefix stability story — the headline finding when comparing bench modes.\n const aPrefixStable = a.stats.prefixHashes.length <= 1;\n const bPrefixStable = b.stats.prefixHashes.length <= 1;\n if (aPrefixStable !== bPrefixStable) {\n const stable = aPrefixStable ? \"A\" : \"B\";\n const churn = aPrefixStable ? \"B\" : \"A\";\n const churnCount = aPrefixStable ? b.stats.prefixHashes.length : a.stats.prefixHashes.length;\n lines.push(\n `prefix stability: ${stable} stayed byte-stable across ${Math.max(\n a.stats.turns,\n b.stats.turns,\n )} turns; ${churn} churned ${churnCount} distinct prefixes.`,\n );\n lines.push(\"\");\n } else if (a.stats.prefixHashes[0] && a.stats.prefixHashes[0] === b.stats.prefixHashes[0]) {\n lines.push(\n `prefix: A and B share the same prefix hash (${a.stats.prefixHashes[0].slice(0, 12)}…) — cache delta is attributable to log stability, not prompt change.`,\n );\n lines.push(\"\");\n }\n\n if (report.firstDivergenceTurn !== null) {\n const p = report.pairs.find((p) => p.turn === report.firstDivergenceTurn);\n lines.push(\n `first divergence: turn ${report.firstDivergenceTurn} — ${p?.divergenceNote ?? \"?\"}`,\n );\n if (p?.aAssistant) lines.push(` A → ${truncate(p.aAssistant.content, 100)}`);\n if (p?.bAssistant) lines.push(` B → ${truncate(p.bAssistant.content, 100)}`);\n } else {\n lines.push(\"no material divergence detected (texts within similarity threshold).\");\n }\n\n return lines.join(\"\\n\");\n}\n\nexport function renderMarkdown(report: DiffReport): string {\n const a = report.a;\n const b = report.b;\n const out: string[] = [];\n out.push(`# Transcript diff: ${a.label} vs ${b.label}`);\n out.push(\"\");\n if (a.meta || b.meta) {\n out.push(\"## Meta\");\n out.push(\"\");\n out.push(`| | ${a.label} | ${b.label} |`);\n out.push(\"|---|---|---|\");\n out.push(`| source | ${a.meta?.source ?? \"—\"} | ${b.meta?.source ?? \"—\"} |`);\n out.push(`| model | ${a.meta?.model ?? \"—\"} | ${b.meta?.model ?? \"—\"} |`);\n out.push(`| task | ${a.meta?.task ?? \"—\"} | ${b.meta?.task ?? \"—\"} |`);\n out.push(`| startedAt | ${a.meta?.startedAt ?? \"—\"} | ${b.meta?.startedAt ?? \"—\"} |`);\n out.push(\"\");\n }\n\n out.push(\"## Summary\");\n out.push(\"\");\n out.push(`| metric | ${a.label} | ${b.label} | delta |`);\n out.push(\"|---|---:|---:|---:|\");\n out.push(\n `| model calls | ${a.stats.turns} | ${b.stats.turns} | ${signed(b.stats.turns - a.stats.turns)} |`,\n );\n out.push(\n `| user turns | ${a.stats.userTurns} | ${b.stats.userTurns} | ${signed(b.stats.userTurns - a.stats.userTurns)} |`,\n );\n out.push(\n `| tool calls | ${a.stats.toolCalls} | ${b.stats.toolCalls} | ${signed(b.stats.toolCalls - a.stats.toolCalls)} |`,\n );\n out.push(\n `| cache hit | ${pct(a.stats.cacheHitRatio)} | ${pct(b.stats.cacheHitRatio)} | **${signPct(b.stats.cacheHitRatio - a.stats.cacheHitRatio)}** |`,\n );\n out.push(\n `| cost (USD) | $${a.stats.totalCostUsd.toFixed(6)} | $${b.stats.totalCostUsd.toFixed(6)} | ${costDelta(a.stats.totalCostUsd, b.stats.totalCostUsd)} |`,\n );\n out.push(\n `| prefix hashes | ${a.stats.prefixHashes.length} | ${b.stats.prefixHashes.length} | — |`,\n );\n if (a.stats.harvestedTurns > 0 || b.stats.harvestedTurns > 0) {\n out.push(\n `| harvest turns | ${a.stats.harvestedTurns} | ${b.stats.harvestedTurns} | ${signed(b.stats.harvestedTurns - a.stats.harvestedTurns)} |`,\n );\n out.push(\n `| harvest subgoals | ${a.stats.totalSubgoals} | ${b.stats.totalSubgoals} | ${signed(b.stats.totalSubgoals - a.stats.totalSubgoals)} |`,\n );\n out.push(\n `| harvest uncertainties | ${a.stats.totalUncertainties} | ${b.stats.totalUncertainties} | ${signed(b.stats.totalUncertainties - a.stats.totalUncertainties)} |`,\n );\n }\n out.push(\"\");\n\n out.push(\"## Turn-by-turn\");\n out.push(\"\");\n out.push(`| turn | kind | ${a.label} tool calls | ${b.label} tool calls | note |`);\n out.push(\"|---:|:---:|---|---|---|\");\n for (const p of report.pairs) {\n const aTools =\n p.aTools\n .map((t) => t.tool)\n .filter(Boolean)\n .join(\", \") || \"—\";\n const bTools =\n p.bTools\n .map((t) => t.tool)\n .filter(Boolean)\n .join(\", \") || \"—\";\n out.push(`| ${p.turn} | ${p.kind} | ${aTools} | ${bTools} | ${p.divergenceNote ?? \"\"} |`);\n }\n out.push(\"\");\n\n if (report.firstDivergenceTurn !== null) {\n const p = report.pairs.find((x) => x.turn === report.firstDivergenceTurn);\n out.push(`## First divergence (turn ${report.firstDivergenceTurn})`);\n out.push(\"\");\n out.push(p?.divergenceNote ?? \"\");\n out.push(\"\");\n if (p?.aAssistant) {\n out.push(`**${a.label}:**`);\n out.push(\"\");\n out.push(\"```\");\n out.push(p.aAssistant.content);\n out.push(\"```\");\n out.push(\"\");\n }\n if (p?.bAssistant) {\n out.push(`**${b.label}:**`);\n out.push(\"\");\n out.push(\"```\");\n out.push(p.bAssistant.content);\n out.push(\"```\");\n out.push(\"\");\n }\n }\n return out.join(\"\\n\");\n}\n\n// ---------- formatting helpers ----------\n\nfunction row(cols: string[], widths: number[]): string {\n return cols.map((c, i) => padRight(c, widths[i] ?? c.length)).join(\" \");\n}\n\nfunction statRow(label: string, av: number, bv: number): string {\n return row([label, `${av}`, `${bv}`, signed(bv - av)], [20, 14, 14, 14]);\n}\n\nfunction padRight(s: string, w: number): string {\n return s.length >= w ? s : s + \" \".repeat(w - s.length);\n}\n\nfunction signed(n: number): string {\n if (n === 0) return \"0\";\n return `${n > 0 ? \"+\" : \"\"}${n}`;\n}\n\nfunction signPct(diff: number): string {\n if (diff === 0) return \"0pp\";\n const s = (diff * 100).toFixed(1);\n return `${diff > 0 ? \"+\" : \"\"}${s}pp`;\n}\n\nfunction pct(x: number): string {\n return `${(x * 100).toFixed(1)}%`;\n}\n\nfunction costDelta(a: number, b: number): string {\n if (a === 0 && b === 0) return \"—\";\n if (a === 0) return \"new\";\n const pctChange = ((b - a) / a) * 100;\n return `${pctChange > 0 ? \"+\" : \"\"}${pctChange.toFixed(1)}%`;\n}\n\nfunction truncate(s: string, n: number): string {\n return s.length > n ? `${s.slice(0, n)}…` : s;\n}\n","/**\n * MCP (Model Context Protocol) type definitions.\n *\n * Hand-rolled rather than importing @modelcontextprotocol/sdk because:\n * - Reasonix's value-add isn't reimplementing the protocol, but *caching*\n * it. Owning the types lets us tune them for our integration (strip\n * fields we don't use, add the ones we do like Reasonix's prefixHash).\n * - Zero dependencies — consistent with how we wrote the DeepSeek client.\n * - If Anthropic bumps the SDK and introduces a breaking change, we're\n * insulated as long as we keep up with the spec itself.\n *\n * Spec reference: https://spec.modelcontextprotocol.io/ (2024-11-05 draft\n * at time of writing). Reasonix models the subset it consumes: tools\n * list/call, resources list/read, prompts list/get, plus the init\n * handshake. Sampling and progress notifications remain deferred.\n *\n * Transport note: the wire format for stdio MCP is **newline-delimited\n * JSON** (NDJSON), not the LSP-style Content-Length header framing that\n * some readers might expect. One JSON-RPC message per line.\n */\n\n// ---------- JSON-RPC 2.0 base ----------\n\nexport type JsonRpcId = string | number;\n\nexport interface JsonRpcRequest<P = unknown> {\n jsonrpc: \"2.0\";\n id: JsonRpcId;\n method: string;\n params?: P;\n}\n\nexport interface JsonRpcNotification<P = unknown> {\n jsonrpc: \"2.0\";\n method: string;\n params?: P;\n}\n\nexport interface JsonRpcSuccess<R = unknown> {\n jsonrpc: \"2.0\";\n id: JsonRpcId;\n result: R;\n}\n\nexport interface JsonRpcError {\n jsonrpc: \"2.0\";\n id: JsonRpcId | null;\n error: {\n /** JSON-RPC standard codes: -32700 parse, -32600 invalid request, -32601 method not found, -32602 invalid params, -32603 internal. MCP also defines its own range. */\n code: number;\n message: string;\n data?: unknown;\n };\n}\n\nexport type JsonRpcResponse<R = unknown> = JsonRpcSuccess<R> | JsonRpcError;\n\nexport type JsonRpcMessage = JsonRpcRequest | JsonRpcNotification | JsonRpcSuccess | JsonRpcError;\n\n// ---------- MCP initialize ----------\n\nexport interface McpClientInfo {\n name: string;\n version: string;\n}\n\nexport interface McpClientCapabilities {\n /** Empty object advertises support without any optional sub-features. */\n tools?: Record<string, never>;\n /** Advertised when the client can consume `resources/list` + `resources/read`. */\n resources?: Record<string, never>;\n /** Advertised when the client can consume `prompts/list` + `prompts/get`. */\n prompts?: Record<string, never>;\n // sampling would go here — deferred.\n}\n\nexport interface InitializeParams {\n protocolVersion: string;\n capabilities: McpClientCapabilities;\n clientInfo: McpClientInfo;\n}\n\nexport interface InitializeResult {\n protocolVersion: string;\n serverInfo: { name: string; version: string };\n capabilities: {\n tools?: { listChanged?: boolean };\n resources?: unknown;\n prompts?: unknown;\n };\n instructions?: string;\n}\n\n// ---------- MCP tools ----------\n\nexport interface McpToolSchema {\n /** JSON Schema — compatible with Reasonix's tools.ts JSONSchema shape. */\n type?: string;\n properties?: Record<string, unknown>;\n required?: string[];\n [extra: string]: unknown;\n}\n\nexport interface McpTool {\n name: string;\n description?: string;\n /** MCP calls this `inputSchema`. Reasonix's `parameters` field is the same concept. */\n inputSchema: McpToolSchema;\n}\n\nexport interface ListToolsResult {\n tools: McpTool[];\n nextCursor?: string;\n}\n\nexport interface CallToolParams {\n name: string;\n arguments?: Record<string, unknown>;\n /**\n * MCP's `_meta` envelope carries out-of-band protocol metadata.\n * Setting `progressToken` here tells the server \"send me progress\n * notifications back using this token\"; the server must then emit\n * `notifications/progress` frames until the response arrives.\n */\n _meta?: { progressToken?: string | number };\n}\n\n/**\n * Server → client notification emitted during a long-running request\n * that the client subscribed to via `_meta.progressToken`. `progress`\n * and `total` are typically matched units (files scanned, bytes\n * processed, etc.); `total` may be missing when the server can't\n * estimate the upper bound up front.\n */\nexport interface ProgressNotificationParams {\n progressToken: string | number;\n progress: number;\n total?: number;\n message?: string;\n}\n\n/** Values a `ProgressHandler` receives — `progressToken` is already matched away. */\nexport interface McpProgressInfo {\n progress: number;\n total?: number;\n message?: string;\n}\n\nexport type McpProgressHandler = (info: McpProgressInfo) => void;\n\nexport interface McpContentBlockText {\n type: \"text\";\n text: string;\n}\n\nexport interface McpContentBlockImage {\n type: \"image\";\n data: string;\n mimeType: string;\n}\n\n/** MCP result content is an array of typed blocks. Reasonix consumes only text for now — image blocks get stringified with a placeholder. */\nexport type McpContentBlock = McpContentBlockText | McpContentBlockImage;\n\nexport interface CallToolResult {\n content: McpContentBlock[];\n /** True = tool raised an error; the content describes it. */\n isError?: boolean;\n}\n\n// ---------- MCP resources ----------\n\n/**\n * A resource the server can expose — think \"file the model can read.\"\n * The URI is opaque to the client: servers may use `file://`, custom\n * schemes, or bare strings. Reasonix doesn't interpret them.\n */\nexport interface McpResource {\n uri: string;\n name: string;\n description?: string;\n /** Hint for the content type (e.g. \"text/markdown\"). Purely informational. */\n mimeType?: string;\n}\n\nexport interface ListResourcesParams {\n /** Pagination cursor from a previous listResources response. */\n cursor?: string;\n}\n\nexport interface ListResourcesResult {\n resources: McpResource[];\n nextCursor?: string;\n}\n\nexport interface ReadResourceParams {\n uri: string;\n}\n\n/**\n * One resource can return multiple content blobs (e.g. the file + a\n * side-car). `text` is the common case for UTF-8 content; `blob` is\n * base64-encoded bytes for binary content. Servers populate exactly\n * one of the two for each entry.\n */\nexport interface McpResourceContentsText {\n uri: string;\n mimeType?: string;\n text: string;\n}\n\nexport interface McpResourceContentsBlob {\n uri: string;\n mimeType?: string;\n blob: string;\n}\n\nexport type McpResourceContents = McpResourceContentsText | McpResourceContentsBlob;\n\nexport interface ReadResourceResult {\n contents: McpResourceContents[];\n}\n\n// ---------- MCP prompts ----------\n\n/**\n * A parameterizable prompt template the server exposes. Clients fetch\n * it with `prompts/get` and pass the result to the model as-is.\n */\nexport interface McpPromptArgument {\n name: string;\n description?: string;\n required?: boolean;\n}\n\nexport interface McpPrompt {\n name: string;\n description?: string;\n arguments?: McpPromptArgument[];\n}\n\nexport interface ListPromptsParams {\n cursor?: string;\n}\n\nexport interface ListPromptsResult {\n prompts: McpPrompt[];\n nextCursor?: string;\n}\n\nexport interface GetPromptParams {\n name: string;\n arguments?: Record<string, string>;\n}\n\n/**\n * MCP prompt messages are modeled after chat completions: role + content.\n * Content can be a text block OR (per the spec) a resource/image block;\n * Reasonix cares about text in v1, but surfaces the raw array so callers\n * can render other kinds if they need to.\n */\nexport interface McpPromptMessage {\n role: \"user\" | \"assistant\";\n content: McpContentBlock | McpPromptResourceBlock;\n}\n\nexport interface McpPromptResourceBlock {\n type: \"resource\";\n resource: McpResourceContents;\n}\n\nexport interface GetPromptResult {\n description?: string;\n messages: McpPromptMessage[];\n}\n\n// ---------- convenience ----------\n\n/** Current MCP protocol version Reasonix is coded against. */\nexport const MCP_PROTOCOL_VERSION = \"2024-11-05\";\n\n/** Type guard — success vs error response. */\nexport function isJsonRpcError(msg: JsonRpcResponse): msg is JsonRpcError {\n return \"error\" in msg;\n}\n","/**\n * MCP client — request/response correlation, initialize handshake,\n * tools/list, tools/call. Built on top of a McpTransport so the same\n * logic works against a real stdio server or an in-process fake.\n */\n\nimport type { McpTransport } from \"./stdio.js\";\nimport {\n type CallToolParams,\n type CallToolResult,\n type GetPromptParams,\n type GetPromptResult,\n type InitializeParams,\n type InitializeResult,\n type JsonRpcId,\n type JsonRpcMessage,\n type JsonRpcRequest,\n type JsonRpcResponse,\n type ListPromptsParams,\n type ListPromptsResult,\n type ListResourcesParams,\n type ListResourcesResult,\n type ListToolsResult,\n MCP_PROTOCOL_VERSION,\n type McpClientInfo,\n type McpProgressHandler,\n type ProgressNotificationParams,\n type ReadResourceParams,\n type ReadResourceResult,\n isJsonRpcError,\n} from \"./types.js\";\n\nexport interface McpClientOptions {\n transport: McpTransport;\n clientInfo?: McpClientInfo;\n /** Per-request timeout. Default 60s. */\n requestTimeoutMs?: number;\n}\n\ninterface PendingRequest {\n resolve: (value: unknown) => void;\n reject: (err: Error) => void;\n timeout: NodeJS.Timeout;\n}\n\nexport class McpClient {\n private readonly transport: McpTransport;\n private readonly clientInfo: McpClientInfo;\n private readonly requestTimeoutMs: number;\n private readonly pending = new Map<JsonRpcId, PendingRequest>();\n private nextId = 1;\n private readerStarted = false;\n private initialized = false;\n private _serverCapabilities: InitializeResult[\"capabilities\"] = {};\n private _serverInfo: InitializeResult[\"serverInfo\"] = { name: \"\", version: \"\" };\n private _protocolVersion = \"\";\n private _instructions: string | undefined;\n // Progress-token → handler for notifications/progress routing. Tokens\n // are minted per call when the caller supplies an onProgress\n // callback; cleared when the final response lands (or the pending\n // request rejects). No leaks — the `try/finally` in callTool\n // guarantees cleanup even on timeout.\n private readonly progressHandlers = new Map<string | number, McpProgressHandler>();\n private nextProgressToken = 1;\n\n constructor(opts: McpClientOptions) {\n this.transport = opts.transport;\n this.clientInfo = opts.clientInfo ?? { name: \"reasonix\", version: \"0.3.0-dev\" };\n this.requestTimeoutMs = opts.requestTimeoutMs ?? 60_000;\n }\n\n /** Server's advertised capabilities, available after initialize(). */\n get serverCapabilities(): InitializeResult[\"capabilities\"] {\n return this._serverCapabilities;\n }\n\n /** Server's self-reported name + version, available after initialize(). */\n get serverInfo(): InitializeResult[\"serverInfo\"] {\n return this._serverInfo;\n }\n\n /** Protocol version the server agreed to during the handshake. */\n get protocolVersion(): string {\n return this._protocolVersion;\n }\n\n /** Optional free-form instructions the server provides at handshake. */\n get serverInstructions(): string | undefined {\n return this._instructions;\n }\n\n /**\n * Complete the initialize → initialized handshake. Must be called\n * before any other method (otherwise compliant servers reject).\n */\n async initialize(): Promise<InitializeResult> {\n if (this.initialized) throw new Error(\"MCP client already initialized\");\n this.startReaderIfNeeded();\n const result = await this.request<InitializeResult>(\"initialize\", {\n protocolVersion: MCP_PROTOCOL_VERSION,\n // Advertise every method the client can consume so servers know\n // they can send listChanged notifications etc. Sub-feature flags\n // (e.g. `resources.subscribe`) are omitted — we don't implement\n // those yet and the empty object means \"method-level support, no\n // sub-features.\"\n capabilities: { tools: {}, resources: {}, prompts: {} },\n clientInfo: this.clientInfo,\n } satisfies InitializeParams);\n this._serverCapabilities = result.capabilities ?? {};\n this._serverInfo = result.serverInfo ?? { name: \"\", version: \"\" };\n this._protocolVersion = result.protocolVersion ?? \"\";\n this._instructions = result.instructions;\n // Per spec: client sends notifications/initialized after receiving the\n // initialize response. Only then is the connection live for other\n // methods.\n await this.transport.send({\n jsonrpc: \"2.0\",\n method: \"notifications/initialized\",\n });\n this.initialized = true;\n return result;\n }\n\n /** List tools the server exposes. */\n async listTools(): Promise<ListToolsResult> {\n this.assertInitialized();\n return this.request<ListToolsResult>(\"tools/list\", {});\n }\n\n /**\n * Invoke a tool by name. When `onProgress` is supplied, attaches a\n * fresh progress token so the server can send incremental updates\n * via `notifications/progress`; they're routed to the callback until\n * the final response arrives (or the request times out, in which\n * case the handler is simply dropped — no extra notification).\n *\n * When `signal` is supplied, aborting it:\n * 1) fires `notifications/cancelled` to the server (MCP 2024-11-05\n * way of saying \"forget this request, I no longer care\"), and\n * 2) rejects the pending promise immediately with an AbortError,\n * so the caller doesn't have to wait for the subprocess to\n * finish its in-flight file write or network request.\n * The server MAY still emit a late response; we drop it in dispatch\n * since the request id is gone from `pending`.\n */\n async callTool(\n name: string,\n args?: Record<string, unknown>,\n opts: { onProgress?: McpProgressHandler; signal?: AbortSignal } = {},\n ): Promise<CallToolResult> {\n this.assertInitialized();\n const params: CallToolParams = { name, arguments: args ?? {} };\n let token: number | undefined;\n if (opts.onProgress) {\n token = this.nextProgressToken++;\n this.progressHandlers.set(token, opts.onProgress);\n params._meta = { progressToken: token };\n }\n try {\n return await this.request<CallToolResult>(\"tools/call\", params, opts.signal);\n } finally {\n if (token !== undefined) this.progressHandlers.delete(token);\n }\n }\n\n /**\n * List resources the server exposes. Supports a pagination cursor;\n * callers interested in the full set should loop on `nextCursor`.\n * Servers that don't support resources respond with method-not-found\n * (−32601) — we surface that as a thrown Error so callers can gate\n * on the `serverCapabilities.resources` field first.\n */\n async listResources(cursor?: string): Promise<ListResourcesResult> {\n this.assertInitialized();\n return this.request<ListResourcesResult>(\"resources/list\", {\n ...(cursor ? { cursor } : {}),\n } satisfies ListResourcesParams);\n }\n\n /** Read the contents of a resource by URI. */\n async readResource(uri: string): Promise<ReadResourceResult> {\n this.assertInitialized();\n return this.request<ReadResourceResult>(\"resources/read\", {\n uri,\n } satisfies ReadResourceParams);\n }\n\n /** List prompt templates the server exposes. */\n async listPrompts(cursor?: string): Promise<ListPromptsResult> {\n this.assertInitialized();\n return this.request<ListPromptsResult>(\"prompts/list\", {\n ...(cursor ? { cursor } : {}),\n } satisfies ListPromptsParams);\n }\n\n /**\n * Fetch a rendered prompt by name. `args` supplies values for any\n * required template arguments; the server validates. Returns messages\n * ready to prepend to the model's input.\n */\n async getPrompt(name: string, args?: Record<string, string>): Promise<GetPromptResult> {\n this.assertInitialized();\n return this.request<GetPromptResult>(\"prompts/get\", {\n name,\n ...(args ? { arguments: args } : {}),\n } satisfies GetPromptParams);\n }\n\n /** Close the transport and reject any outstanding requests. */\n async close(): Promise<void> {\n for (const [, pending] of this.pending) {\n clearTimeout(pending.timeout);\n pending.reject(new Error(\"MCP client closed\"));\n }\n this.pending.clear();\n await this.transport.close();\n }\n\n // ---------- internals ----------\n\n private assertInitialized(): void {\n if (!this.initialized) throw new Error(\"MCP client not initialized — call initialize() first\");\n }\n\n private async request<R>(method: string, params: unknown, signal?: AbortSignal): Promise<R> {\n const id = this.nextId++;\n const frame: JsonRpcRequest = { jsonrpc: \"2.0\", id, method, params };\n let abortHandler: (() => void) | null = null;\n const promise = new Promise<R>((resolve, reject) => {\n const timeout = setTimeout(() => {\n this.pending.delete(id);\n if (abortHandler && signal) signal.removeEventListener(\"abort\", abortHandler);\n reject(\n new Error(`MCP request ${method} (id=${id}) timed out after ${this.requestTimeoutMs}ms`),\n );\n }, this.requestTimeoutMs);\n this.pending.set(id, {\n resolve: resolve as (value: unknown) => void,\n reject,\n timeout,\n });\n // Wire up cancellation: when signal fires, send an MCP cancellation\n // notification to the server (so it can stop whatever it was doing)\n // and reject the caller immediately — no need to wait for the\n // subprocess to finish its in-flight work. Late responses from the\n // server are dropped by `dispatch` because the id is gone from\n // `pending`.\n if (signal) {\n if (signal.aborted) {\n this.pending.delete(id);\n clearTimeout(timeout);\n reject(new Error(`MCP request ${method} (id=${id}) aborted before send`));\n return;\n }\n abortHandler = () => {\n this.pending.delete(id);\n clearTimeout(timeout);\n void this.transport\n .send({\n jsonrpc: \"2.0\",\n method: \"notifications/cancelled\",\n params: { requestId: id, reason: \"aborted by user\" },\n })\n .catch(() => {\n // Transport may already be closing — swallow; we still\n // reject the caller below so they unblock.\n });\n reject(new Error(`MCP request ${method} (id=${id}) aborted by user`));\n };\n signal.addEventListener(\"abort\", abortHandler, { once: true });\n }\n });\n try {\n await this.transport.send(frame);\n } catch (err) {\n this.pending.delete(id);\n if (abortHandler && signal) signal.removeEventListener(\"abort\", abortHandler);\n throw err;\n }\n try {\n return await promise;\n } finally {\n if (abortHandler && signal) signal.removeEventListener(\"abort\", abortHandler);\n }\n }\n\n private startReaderIfNeeded(): void {\n if (this.readerStarted) return;\n this.readerStarted = true;\n // Fire-and-forget: the reader runs for the lifetime of the client.\n void this.readLoop();\n }\n\n private async readLoop(): Promise<void> {\n try {\n for await (const msg of this.transport.messages()) {\n this.dispatch(msg);\n }\n } catch (err) {\n // Surface as rejections on all pending requests so nobody hangs.\n for (const [, pending] of this.pending) {\n clearTimeout(pending.timeout);\n pending.reject(err as Error);\n }\n this.pending.clear();\n }\n }\n\n private dispatch(msg: JsonRpcMessage): void {\n // Notifications (no `id`): route by method. Progress notifications\n // go to the per-call handler if one was registered; everything\n // else is dropped silently (we don't yet handle tools/list_changed\n // or resources/list_changed).\n if (!(\"id\" in msg) || msg.id === null || msg.id === undefined) {\n if (\"method\" in msg && msg.method === \"notifications/progress\") {\n const p = msg.params as ProgressNotificationParams | undefined;\n if (!p || p.progressToken === undefined) return;\n const handler = this.progressHandlers.get(p.progressToken);\n if (!handler) return; // late notification after the call resolved\n handler({ progress: p.progress, total: p.total, message: p.message });\n }\n return;\n }\n if (!(\"result\" in msg) && !(\"error\" in msg)) return; // it's a request from server\n const pending = this.pending.get(msg.id);\n if (!pending) return; // late response after timeout; drop\n this.pending.delete(msg.id);\n clearTimeout(pending.timeout);\n const resp = msg as JsonRpcResponse;\n if (isJsonRpcError(resp)) {\n pending.reject(new Error(`MCP ${resp.error.code}: ${resp.error.message}`));\n } else {\n pending.resolve(resp.result);\n }\n }\n}\n","/**\n * Stdio transport for MCP.\n *\n * MCP's stdio wire format is **newline-delimited JSON** (one JSON-RPC\n * message per line). We spawn the server as a child process, write\n * frames to its stdin, parse its stdout line-by-line as they arrive.\n *\n * Transport is abstracted behind an interface so unit tests can fake it\n * with an in-process duplex pair — spawning real servers in unit tests\n * is flaky and slow.\n */\n\nimport { type ChildProcess, spawn } from \"node:child_process\";\nimport type { JsonRpcMessage } from \"./types.js\";\n\n/**\n * A transport sends JSON-RPC messages upstream and surfaces messages\n * arriving downstream via an async iterator. One instance per server\n * connection.\n */\nexport interface McpTransport {\n /** Send one JSON-RPC message. Resolves when the bytes are accepted. */\n send(message: JsonRpcMessage): Promise<void>;\n /** Async iterator over incoming messages. Ends when the connection closes. */\n messages(): AsyncIterableIterator<JsonRpcMessage>;\n /** Close the underlying resource (kill child process, close streams). */\n close(): Promise<void>;\n}\n\nexport interface StdioTransportOptions {\n /** Argv to spawn. First element is the command. */\n command: string;\n args?: string[];\n /** Env overlay — merged over process.env unless replaceEnv=true. */\n env?: Record<string, string>;\n /** When true, only the env above is visible to the child. Default false. */\n replaceEnv?: boolean;\n /** CWD for the child. Default: process.cwd(). */\n cwd?: string;\n /**\n * Spawn through a shell. Default: true on win32 (needed to resolve\n * `.cmd` wrappers like `npx.cmd`, `pnpm.cmd`), false elsewhere.\n * Explicitly pass `false` to opt out on Windows; pass `true` to force\n * it on POSIX (rarely needed).\n */\n shell?: boolean;\n}\n\n/**\n * Spawn `command args...` as a child process and use its stdin/stdout as\n * an MCP transport. Stderr is forwarded to the parent's stderr so server\n * diagnostics are still visible.\n */\nexport class StdioTransport implements McpTransport {\n private readonly child: ChildProcess;\n private readonly queue: JsonRpcMessage[] = [];\n private readonly waiters: Array<(m: JsonRpcMessage | null) => void> = [];\n private closed = false;\n private stdoutBuffer = \"\";\n\n constructor(opts: StdioTransportOptions) {\n const env = opts.replaceEnv ? { ...(opts.env ?? {}) } : { ...process.env, ...(opts.env ?? {}) };\n // Windows wraps binaries as .cmd/.bat shims (npx.cmd, pnpm.cmd, …).\n // child_process.spawn without shell:true can't resolve them, which\n // breaks `--mcp \"npx -y some-server\"` — the most common MCP setup.\n // Default shell:true on win32 and leave POSIX alone.\n const shell = opts.shell ?? process.platform === \"win32\";\n\n if (shell) {\n // Node's shell:true + args[] triggers DEP0190 because it concatenates\n // with spaces and doesn't quote args — unsafe if an arg contains\n // shell metacharacters. We build a single command line ourselves,\n // quoting ONLY the args (command stays bare so the shell's PATH /\n // PATHEXT lookup finds `npx` → `npx.cmd` on Windows).\n const line = [\n opts.command,\n ...(opts.args ?? []).map((a) => quoteArg(a, process.platform === \"win32\")),\n ].join(\" \");\n this.child = spawn(line, [], {\n env,\n cwd: opts.cwd,\n stdio: [\"pipe\", \"pipe\", \"inherit\"],\n shell: true,\n });\n } else {\n this.child = spawn(opts.command, opts.args ?? [], {\n env,\n cwd: opts.cwd,\n stdio: [\"pipe\", \"pipe\", \"inherit\"],\n });\n }\n this.child.stdout!.setEncoding(\"utf8\");\n this.child.stdout!.on(\"data\", (chunk: string) => this.onStdout(chunk));\n this.child.on(\"close\", () => this.onClose());\n this.child.on(\"error\", (err) => {\n // Surface spawn errors as a synthetic JsonRpcError so callers don't\n // hang on a stream that never emits anything.\n this.push({\n jsonrpc: \"2.0\",\n id: null,\n error: { code: -32000, message: `transport error: ${err.message}` },\n });\n });\n }\n\n async send(message: JsonRpcMessage): Promise<void> {\n if (this.closed) throw new Error(\"MCP transport is closed\");\n return new Promise((resolve, reject) => {\n const line = `${JSON.stringify(message)}\\n`;\n this.child.stdin!.write(line, \"utf8\", (err) => {\n if (err) reject(err);\n else resolve();\n });\n });\n }\n\n async *messages(): AsyncIterableIterator<JsonRpcMessage> {\n while (true) {\n if (this.queue.length > 0) {\n yield this.queue.shift()!;\n continue;\n }\n if (this.closed) return;\n const next = await new Promise<JsonRpcMessage | null>((resolve) => {\n this.waiters.push(resolve);\n });\n if (next === null) return; // closed while we were waiting\n yield next;\n }\n }\n\n async close(): Promise<void> {\n if (this.closed) return;\n this.closed = true;\n // Signal any pending waiters.\n while (this.waiters.length > 0) this.waiters.shift()!(null);\n try {\n this.child.stdin!.end();\n } catch {\n /* already ended */\n }\n if (this.child.exitCode === null && !this.child.killed) {\n this.child.kill(\"SIGTERM\");\n }\n }\n\n /** Parse incoming stdout chunks into NDJSON messages. */\n private onStdout(chunk: string): void {\n this.stdoutBuffer += chunk;\n let newlineIdx: number;\n // biome-ignore lint/suspicious/noAssignInExpressions: idiomatic loop shape\n while ((newlineIdx = this.stdoutBuffer.indexOf(\"\\n\")) !== -1) {\n const line = this.stdoutBuffer.slice(0, newlineIdx).trim();\n this.stdoutBuffer = this.stdoutBuffer.slice(newlineIdx + 1);\n if (!line) continue;\n try {\n const msg = JSON.parse(line) as JsonRpcMessage;\n this.push(msg);\n } catch {\n // Malformed lines are dropped — some servers emit startup banners\n // before the JSON-RPC loop begins. We surface the noise to stderr\n // via the inherited stderr stream, not our event queue.\n }\n }\n }\n\n private onClose(): void {\n this.closed = true;\n while (this.waiters.length > 0) this.waiters.shift()!(null);\n }\n\n private push(msg: JsonRpcMessage): void {\n const waiter = this.waiters.shift();\n if (waiter) waiter(msg);\n else this.queue.push(msg);\n }\n}\n\n/**\n * Quote a single argument for inclusion in a shell command line.\n * On Windows (cmd.exe): wrap in double quotes, escape internal `\"` as `\"\"`,\n * leave everything else alone. On POSIX: wrap in single quotes, escape\n * internal `'` as `'\\''`. Both handle spaces, wildcards, pipes, and all\n * other metacharacters correctly.\n */\nfunction quoteArg(s: string, windows: boolean): string {\n if (!windows) {\n // POSIX: single-quote, escape single quotes.\n return `'${s.replace(/'/g, \"'\\\\''\")}'`;\n }\n // cmd.exe: double-quote, escape internal quotes by doubling.\n return `\"${s.replace(/\"/g, '\"\"')}\"`;\n}\n","/**\n * HTTP+SSE transport for MCP (spec version 2024-11-05).\n *\n * Wire shape:\n * 1. Client opens GET to the SSE URL with `Accept: text/event-stream`.\n * 2. Server's first SSE event is `event: endpoint`, `data: <url>` — the\n * URL (relative or absolute) the client must POST JSON-RPC requests\n * to. All subsequent server → client messages arrive as `event: message`\n * SSE frames carrying a JSON-RPC response or server-initiated frame.\n * 3. Client POSTs each outgoing JSON-RPC frame to the endpoint URL.\n * The POST response body is ignored — replies land on the SSE stream.\n *\n * This transport exists so Reasonix can talk to hosted/remote MCP servers\n * (e.g. a company's internal knowledge server fronted by auth). Stdio\n * covers local subprocesses; SSE covers everything else.\n *\n * Note: the newer \"Streamable HTTP\" transport (2025 spec) folds the POST\n * and SSE streams onto a single endpoint. We stay on 2024-11-05 here —\n * that's what `MCP_PROTOCOL_VERSION` advertises in the initialize handshake\n * and what currently-published servers implement.\n */\n\nimport { createParser } from \"eventsource-parser\";\nimport type { McpTransport } from \"./stdio.js\";\nimport type { JsonRpcMessage } from \"./types.js\";\n\nexport interface SseTransportOptions {\n /** SSE endpoint URL, e.g. `https://mcp.example.com/sse`. */\n url: string;\n /** Extra headers sent on both the SSE GET and the JSON-RPC POSTs (e.g. `Authorization`). */\n headers?: Record<string, string>;\n}\n\n/**\n * Open an SSE stream to `url`, parse incoming events into JsonRpcMessages,\n * POST outgoing frames to the endpoint URL the server advertises.\n */\nexport class SseTransport implements McpTransport {\n private readonly url: string;\n private readonly headers: Record<string, string>;\n private readonly queue: JsonRpcMessage[] = [];\n private readonly waiters: Array<(m: JsonRpcMessage | null) => void> = [];\n private readonly controller = new AbortController();\n private closed = false;\n private postUrl: string | null = null;\n private readonly endpointReady: Promise<string>;\n private resolveEndpoint!: (url: string) => void;\n private rejectEndpoint!: (err: Error) => void;\n\n constructor(opts: SseTransportOptions) {\n this.url = opts.url;\n this.headers = opts.headers ?? {};\n this.endpointReady = new Promise<string>((resolve, reject) => {\n this.resolveEndpoint = resolve;\n this.rejectEndpoint = reject;\n });\n // Swallow unhandled-rejection noise if nobody ever calls send().\n this.endpointReady.catch(() => undefined);\n void this.runStream();\n }\n\n async send(message: JsonRpcMessage): Promise<void> {\n if (this.closed) throw new Error(\"MCP SSE transport is closed\");\n const postUrl = await this.endpointReady;\n const res = await fetch(postUrl, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", ...this.headers },\n body: JSON.stringify(message),\n signal: this.controller.signal,\n });\n // Drain body so the socket returns to the pool even if the server\n // elected to write one. We explicitly don't parse it — responses\n // arrive on the SSE channel.\n await res.arrayBuffer().catch(() => undefined);\n if (!res.ok) {\n throw new Error(`MCP SSE POST ${postUrl} failed: ${res.status} ${res.statusText}`);\n }\n }\n\n async *messages(): AsyncIterableIterator<JsonRpcMessage> {\n while (true) {\n if (this.queue.length > 0) {\n yield this.queue.shift()!;\n continue;\n }\n if (this.closed) return;\n const next = await new Promise<JsonRpcMessage | null>((resolve) => {\n this.waiters.push(resolve);\n });\n if (next === null) return;\n yield next;\n }\n }\n\n async close(): Promise<void> {\n if (this.closed) return;\n this.closed = true;\n while (this.waiters.length > 0) this.waiters.shift()!(null);\n // Reject any still-pending send() that was waiting for the endpoint.\n this.rejectEndpoint(new Error(\"MCP SSE transport closed before endpoint was ready\"));\n try {\n this.controller.abort();\n } catch {\n /* already aborted */\n }\n }\n\n // ---------- internals ----------\n\n private async runStream(): Promise<void> {\n let res: Response;\n try {\n res = await fetch(this.url, {\n method: \"GET\",\n headers: { accept: \"text/event-stream\", ...this.headers },\n signal: this.controller.signal,\n });\n } catch (err) {\n this.failHandshake(`SSE connect to ${this.url} failed: ${(err as Error).message}`);\n return;\n }\n if (!res.ok || !res.body) {\n // Drain body to free the socket before giving up.\n await res.body?.cancel().catch(() => undefined);\n this.failHandshake(`SSE handshake ${this.url} → ${res.status} ${res.statusText}`);\n return;\n }\n\n const parser = createParser({\n onEvent: (ev) => this.handleEvent(ev.event ?? \"message\", ev.data),\n });\n const decoder = new TextDecoder();\n try {\n for await (const chunk of res.body as AsyncIterable<Uint8Array>) {\n parser.feed(decoder.decode(chunk, { stream: true }));\n }\n } catch (err) {\n if (!this.closed) {\n this.pushError(`SSE stream error: ${(err as Error).message}`);\n }\n } finally {\n this.markClosed();\n }\n }\n\n private handleEvent(type: string, data: string): void {\n if (type === \"endpoint\") {\n if (this.postUrl) return; // ignore repeat announcements\n try {\n this.postUrl = new URL(data, this.url).toString();\n this.resolveEndpoint(this.postUrl);\n } catch (err) {\n this.failHandshake(`SSE endpoint event had bad URL \"${data}\": ${(err as Error).message}`);\n }\n return;\n }\n if (type === \"message\") {\n try {\n const parsed = JSON.parse(data) as JsonRpcMessage;\n this.pushMessage(parsed);\n } catch {\n // Malformed JSON-RPC on an SSE frame — drop it, same as stdio.\n }\n return;\n }\n // Unknown event types (server pings, custom extensions) — ignore.\n }\n\n private failHandshake(reason: string): void {\n this.rejectEndpoint(new Error(reason));\n this.pushError(reason);\n this.markClosed();\n }\n\n private pushMessage(msg: JsonRpcMessage): void {\n const waiter = this.waiters.shift();\n if (waiter) waiter(msg);\n else this.queue.push(msg);\n }\n\n private pushError(message: string): void {\n this.pushMessage({\n jsonrpc: \"2.0\",\n id: null,\n error: { code: -32000, message },\n });\n }\n\n private markClosed(): void {\n if (this.closed) return;\n this.closed = true;\n while (this.waiters.length > 0) this.waiters.shift()!(null);\n }\n}\n","/**\n * Split a shell-style command string into argv, respecting single and\n * double quotes. Intended for parsing the user's `--mcp \"cmd args...\"`\n * flag — NOT a full shell parser (no variable expansion, no subshells,\n * no globs, no `&&` / pipes).\n *\n * The tradeoff: users with paths containing spaces need to quote them\n * (e.g. `--mcp 'npx -y pkg \"/my path/here\"'`), which is how they'd\n * already quote them at the shell level.\n *\n * Throws on unterminated quotes — better than silently dropping half\n * the command.\n */\nexport function shellSplit(input: string): string[] {\n const tokens: string[] = [];\n let cur = \"\";\n let quote: '\"' | \"'\" | null = null;\n let i = 0;\n const s = input;\n\n while (i < s.length) {\n const ch = s[i]!;\n\n if (quote) {\n if (ch === quote) {\n quote = null;\n i++;\n continue;\n }\n // backslash escapes inside double quotes only\n if (ch === \"\\\\\" && quote === '\"' && i + 1 < s.length) {\n cur += s[i + 1];\n i += 2;\n continue;\n }\n cur += ch;\n i++;\n continue;\n }\n\n if (ch === '\"' || ch === \"'\") {\n quote = ch as '\"' | \"'\";\n i++;\n continue;\n }\n\n // Backslash escape ONLY applies inside double quotes (handled above).\n // Outside quotes, backslashes pass through literally — otherwise\n // Windows paths like `C:\\path\\to\\exe` get mangled. POSIX users who\n // want to escape a space outside quotes can use single quotes instead.\n\n if (ch === \" \" || ch === \"\\t\") {\n if (cur.length > 0) {\n tokens.push(cur);\n cur = \"\";\n }\n i++;\n continue;\n }\n\n cur += ch;\n i++;\n }\n\n if (quote) {\n throw new Error(\n `shellSplit: unterminated ${quote === '\"' ? \"double\" : \"single\"} quote in input`,\n );\n }\n if (cur.length > 0) tokens.push(cur);\n return tokens;\n}\n","/**\n * Parse the `--mcp` CLI argument into a transport-tagged spec.\n *\n * Accepted forms:\n * \"name=command args...\" → stdio, namespaced (tools prefixed with `name_`)\n * \"command args...\" → stdio, anonymous\n * \"name=https://host/sse\" → SSE, namespaced\n * \"https://host/sse\" → SSE, anonymous\n * (\"http://\" is also honored — useful for local dev servers.)\n *\n * The identifier regex before `=` is deliberately narrow\n * (`[a-zA-Z_][a-zA-Z0-9_]*`) so Windows drive letters (\"C:\\\\...\") and\n * other strings containing `=` or `:` don't accidentally trigger the\n * namespace branch. If a user ever wants their command to literally start\n * with `foo=...` as a bare command, they can wrap it in quotes inside the\n * shell command string.\n *\n * Transport is selected solely by whether the body begins with `http://`\n * or `https://`. Anything else is stdio — including ws:// (unsupported)\n * which will surface later as a spawn error, keeping the rule local.\n */\n\nimport { shellSplit } from \"./shell-split.js\";\n\nexport interface StdioMcpSpec {\n transport: \"stdio\";\n /** Namespace prefix applied to each registered tool, or null if anonymous. */\n name: string | null;\n /** Argv[0]. */\n command: string;\n /** Remaining argv. */\n args: string[];\n}\n\nexport interface SseMcpSpec {\n transport: \"sse\";\n name: string | null;\n /** Fully qualified SSE endpoint URL. */\n url: string;\n}\n\nexport type McpSpec = StdioMcpSpec | SseMcpSpec;\n\nconst NAME_PREFIX = /^([a-zA-Z_][a-zA-Z0-9_]*)=(.*)$/;\nconst HTTP_URL = /^https?:\\/\\//i;\n\nexport function parseMcpSpec(input: string): McpSpec {\n const trimmed = input.trim();\n if (!trimmed) {\n throw new Error(\"empty MCP spec\");\n }\n\n const nameMatch = NAME_PREFIX.exec(trimmed);\n const name = nameMatch ? nameMatch[1]! : null;\n const body = (nameMatch ? nameMatch[2]! : trimmed).trim();\n\n if (!body) {\n throw new Error(`MCP spec has name but no command: ${input}`);\n }\n\n if (HTTP_URL.test(body)) {\n return { transport: \"sse\", name, url: body };\n }\n\n const argv = shellSplit(body);\n if (argv.length === 0) {\n throw new Error(`MCP spec has name but no command: ${input}`);\n }\n const [command, ...args] = argv;\n return { transport: \"stdio\", name, command: command!, args };\n}\n","/**\n * Gather a full inspection report from an initialized MCP client:\n * server info, capabilities, tools, resources, prompts. Methods the\n * server doesn't support come back as `{ supported: false }` instead\n * of throwing, so a CLI or UI can render a consistent \"what this\n * server exposes\" summary even against minimal implementations.\n *\n * Pure with respect to I/O beyond the passed-in client — the CLI\n * layer owns argument parsing, connection setup, and printing.\n */\n\nimport type { McpClient } from \"./client.js\";\nimport type { McpPrompt, McpResource, McpTool } from \"./types.js\";\n\nexport interface InspectionReport {\n protocolVersion: string;\n serverInfo: { name: string; version: string };\n capabilities: Record<string, unknown>;\n instructions?: string;\n tools: SectionResult<McpTool>;\n resources: SectionResult<McpResource>;\n prompts: SectionResult<McpPrompt>;\n}\n\nexport type SectionResult<T> =\n | { supported: true; items: T[] }\n | { supported: false; reason: string };\n\n/**\n * Run an inspection against a **already-initialized** client. Caller\n * is responsible for `initialize()` before this and `close()` after.\n * We keep this pure so unit tests can feed in a FakeMcpTransport and\n * verify the aggregate shape without spinning up a real process.\n */\nexport async function inspectMcpServer(client: McpClient): Promise<InspectionReport> {\n // We always *try* the three listings so the client learns whether a\n // server without explicit capability flags still serves them —\n // some servers omit capabilities but still respond to the methods.\n const tools = await trySection<McpTool>(() => client.listTools().then((r) => r.tools));\n const resources = await trySection<McpResource>(() =>\n client.listResources().then((r) => r.resources),\n );\n const prompts = await trySection<McpPrompt>(() => client.listPrompts().then((r) => r.prompts));\n\n return {\n protocolVersion: client.protocolVersion || \"(unknown)\",\n serverInfo: client.serverInfo,\n capabilities: client.serverCapabilities ?? {},\n instructions: client.serverInstructions,\n tools,\n resources,\n prompts,\n };\n}\n\nasync function trySection<T>(load: () => Promise<T[]>): Promise<SectionResult<T>> {\n try {\n const items = await load();\n return { supported: true, items };\n } catch (err) {\n const msg = (err as Error).message ?? String(err);\n // -32601 is JSON-RPC \"method not found\" — the canonical response\n // from a server that doesn't implement this family. Treat it as\n // \"not supported\" rather than a hard error, so the CLI can render\n // a clean summary instead of aborting on the first missing method.\n if (/-32601/.test(msg) || /method not found/i.test(msg)) {\n return { supported: false, reason: \"method not found (-32601)\" };\n }\n return { supported: false, reason: msg };\n }\n}\n","/**\n * Aider-style SEARCH/REPLACE edit blocks.\n *\n * The model emits blocks in this exact shape, one or more per response:\n *\n * path/to/file.ts\n * <<<<<<< SEARCH\n * exact existing lines (whitespace-sensitive)\n * =======\n * replacement lines\n * >>>>>>> REPLACE\n *\n * We chose this over unified diffs because:\n * - Models produce it reliably — no line-number drift.\n * - It tolerates multi-edit responses without ambiguity over which\n * hunk belongs to which file.\n * - Aider has years of evidence that this format works even against\n * weaker models than DeepSeek R1, so it's a conservative pick.\n *\n * The SEARCH text must match the file byte-for-byte. Empty SEARCH is a\n * sentinel for \"create new file\" — the REPLACE becomes the whole file.\n * If SEARCH doesn't match we refuse the edit and surface the failure;\n * we do NOT guess or fuzzy-match. A wrong silent edit is worse than a\n * missing one — the user can re-ask with the exact current content.\n */\n\nimport { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from \"node:fs\";\nimport { dirname, resolve } from \"node:path\";\n\nexport interface EditBlock {\n /** Path as written by the model — relative to rootDir, or absolute. */\n path: string;\n /** Literal text to match in the target file. Empty → create new file. */\n search: string;\n /** Replacement text to write in place of `search`. */\n replace: string;\n /** Char offset in the source message where this block started. */\n offset: number;\n}\n\nexport type ApplyStatus =\n /** Edit landed on disk. */\n | \"applied\"\n /** New file created (SEARCH was empty and file didn't exist). */\n | \"created\"\n /** File exists but SEARCH block wasn't found in its content. */\n | \"not-found\"\n /** File doesn't exist and SEARCH was non-empty (can't create without content). */\n | \"file-missing\"\n /** Path escapes rootDir — refused on safety grounds. */\n | \"path-escape\"\n /** fs write / read threw. */\n | \"error\";\n\nexport interface ApplyResult {\n path: string;\n status: ApplyStatus;\n /** Extra detail (e.g. error message) for logs. */\n message?: string;\n}\n\n/**\n * One edit block per match. The regex is anchored to the 7-char marker\n * lines because those are visually distinct and unlikely to appear in\n * normal code.\n *\n * Anchored with `^` + `m` flag so the filename has to live on its own\n * line. Keeps us from matching e.g. a JS-import string that happens to\n * contain `<<<<<<< SEARCH` in inner text.\n */\n// `\\n?` before the =======/REPLACE separators makes the body optional:\n// empty SEARCH (new-file sentinel) works without requiring a gratuitous\n// empty line, and the same holds for empty REPLACE (file-deletion\n// semantics, not yet supported but cheaply representable).\nconst BLOCK_RE = /^(\\S[^\\n]*)\\n<{7} SEARCH\\n([\\s\\S]*?)\\n?={7}\\n([\\s\\S]*?)\\n?>{7} REPLACE/gm;\n\nexport function parseEditBlocks(text: string): EditBlock[] {\n const out: EditBlock[] = [];\n BLOCK_RE.lastIndex = 0;\n let m: RegExpExecArray | null = BLOCK_RE.exec(text);\n while (m !== null) {\n out.push({\n path: m[1]!.trim(),\n search: m[2]!,\n replace: m[3]!,\n offset: m.index,\n });\n m = BLOCK_RE.exec(text);\n }\n return out;\n}\n\nexport function applyEditBlock(block: EditBlock, rootDir: string): ApplyResult {\n const absRoot = resolve(rootDir);\n const absTarget = resolve(absRoot, block.path);\n // Refuse paths that escape rootDir. `resolve` normalizes `..`, so\n // startsWith on the normalized pair is enough.\n if (absTarget !== absRoot && !absTarget.startsWith(`${absRoot}${sep()}`)) {\n return {\n path: block.path,\n status: \"path-escape\",\n message: `resolved path ${absTarget} is outside rootDir ${absRoot}`,\n };\n }\n\n const searchEmpty = block.search.length === 0;\n const exists = existsSync(absTarget);\n\n try {\n if (!exists) {\n if (!searchEmpty) {\n return {\n path: block.path,\n status: \"file-missing\",\n message: \"file does not exist; to create it, use an empty SEARCH block\",\n };\n }\n mkdirSync(dirname(absTarget), { recursive: true });\n writeFileSync(absTarget, block.replace, \"utf8\");\n return { path: block.path, status: \"created\" };\n }\n\n const content = readFileSync(absTarget, \"utf8\");\n if (searchEmpty) {\n return {\n path: block.path,\n status: \"not-found\",\n message: \"empty SEARCH only creates new files — this file already exists\",\n };\n }\n const idx = content.indexOf(block.search);\n if (idx === -1) {\n return {\n path: block.path,\n status: \"not-found\",\n message: \"SEARCH text does not match the current file content exactly\",\n };\n }\n // Replace only the first occurrence — if the model needs multiple\n // identical edits it should emit multiple blocks (each anchored by\n // more surrounding context). Auto-expanding to replace-all is a\n // footgun when the same string legitimately appears in several\n // unrelated places.\n const replaced = `${content.slice(0, idx)}${block.replace}${content.slice(idx + block.search.length)}`;\n writeFileSync(absTarget, replaced, \"utf8\");\n return { path: block.path, status: \"applied\" };\n } catch (err) {\n return { path: block.path, status: \"error\", message: (err as Error).message };\n }\n}\n\nexport function applyEditBlocks(blocks: EditBlock[], rootDir: string): ApplyResult[] {\n return blocks.map((b) => applyEditBlock(b, rootDir));\n}\n\n// ---------- snapshot / restore (for /undo) ----------\n\nexport interface EditSnapshot {\n /** Path relative to rootDir, as the block named it. */\n path: string;\n /**\n * File content before the edit batch was applied. `null` means the\n * file didn't exist yet — restoring that means deleting whatever the\n * edit created.\n */\n prevContent: string | null;\n}\n\n/**\n * Capture the current state of every file an edit batch is about to\n * touch, so `/undo` can roll back if the user doesn't like the result.\n * De-duplicates by path because one batch can contain multiple blocks\n * for the same file, and we only want one \"before\" snapshot per file.\n */\nexport function snapshotBeforeEdits(blocks: EditBlock[], rootDir: string): EditSnapshot[] {\n const absRoot = resolve(rootDir);\n const seen = new Set<string>();\n const snapshots: EditSnapshot[] = [];\n for (const b of blocks) {\n if (seen.has(b.path)) continue;\n seen.add(b.path);\n const abs = resolve(absRoot, b.path);\n if (!existsSync(abs)) {\n snapshots.push({ path: b.path, prevContent: null });\n continue;\n }\n try {\n snapshots.push({ path: b.path, prevContent: readFileSync(abs, \"utf8\") });\n } catch {\n // Unreadable (permission / binary) — record null so we at least\n // don't pretend the snapshot is authoritative. The restore path\n // will treat null as \"delete on undo\", which is wrong in that\n // case but the file wasn't ours to begin with.\n snapshots.push({ path: b.path, prevContent: null });\n }\n }\n return snapshots;\n}\n\n/**\n * Restore files to their snapshotted state. Snapshots with\n * `prevContent === null` were created by the edit, so undo = delete.\n * Otherwise the prior content is written back, replacing whatever the\n * edit left behind.\n */\nexport function restoreSnapshots(snapshots: EditSnapshot[], rootDir: string): ApplyResult[] {\n const absRoot = resolve(rootDir);\n return snapshots.map((snap) => {\n const abs = resolve(absRoot, snap.path);\n if (abs !== absRoot && !abs.startsWith(`${absRoot}${sep()}`)) {\n return {\n path: snap.path,\n status: \"path-escape\",\n message: \"snapshot path escapes rootDir — refusing to restore\",\n };\n }\n try {\n if (snap.prevContent === null) {\n if (existsSync(abs)) unlinkSync(abs);\n return {\n path: snap.path,\n status: \"applied\",\n message: \"removed (the edit had created it)\",\n };\n }\n writeFileSync(abs, snap.prevContent, \"utf8\");\n return {\n path: snap.path,\n status: \"applied\",\n message: \"restored to pre-edit content\",\n };\n } catch (err) {\n return { path: snap.path, status: \"error\", message: (err as Error).message };\n }\n });\n}\n\n/** Platform separator — `\\` on Windows, `/` elsewhere. */\nfunction sep(): string {\n return process.platform === \"win32\" ? \"\\\\\" : \"/\";\n}\n","/**\n * System prompt used by `reasonix code`. Teaches the model:\n *\n * 1. It has a filesystem MCP bridge rooted at the user's CWD.\n * 2. To modify files it emits SEARCH/REPLACE blocks (not\n * `write_file` — that would whole-file rewrite and kill diff\n * reviewability).\n * 3. Read first, edit second — SEARCH must match byte-for-byte.\n * 4. Be concise. The user can read a diff faster than prose.\n *\n * Kept short on purpose. Long system prompts eat context budget that\n * the Cache-First Loop is trying to conserve. The SEARCH/REPLACE spec\n * is the one unavoidable bloat; we trim everything else.\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { applyMemoryStack } from \"../user-memory.js\";\n\nexport const CODE_SYSTEM_PROMPT = `You are Reasonix Code, a coding assistant. You have filesystem tools (read_file, write_file, list_directory, search_files, etc.) rooted at the user's working directory.\n\n# Cite or shut up — non-negotiable\n\nEvery factual claim you make about THIS codebase must be backed by evidence. Reasonix VALIDATES the citations you write — broken paths or out-of-range lines render in **red strikethrough with ❌** in front of the user.\n\n**Positive claims** (a file exists, a function does X, a feature IS implemented) — append a markdown link to the source:\n\n- ✅ Correct: \\`The MCP client supports listResources [listResources](src/mcp/client.ts:142).\\`\n- ❌ Wrong: \\`The MCP client supports listResources.\\` ← no citation, looks authoritative but unverifiable.\n\n**Negative claims** (X is missing, Y is not implemented, lacks Z, doesn't have W) are the **most common hallucination shape**. They feel safe to write because no citation seems possible — but that's exactly why you must NOT write them on instinct.\n\nIf you are about to write \"X is missing\" or \"Y is not implemented\" — **STOP**. Call \\`search_content\\` for the relevant symbol or term FIRST. Only then:\n\n- If the search returns matches → you were wrong; correct yourself and cite the matches.\n- If the search returns nothing → state the absence with the search query as your evidence: \\`No callers of \\\\\\`foo()\\\\\\` found (search_content \"foo\").\\`\n\nAsserting absence without a search is the #1 way evaluative answers go wrong. Treat the urge to write \"missing\" as a red flag in your own reasoning.\n\n# When to propose a plan (submit_plan)\n\nYou have a \\`submit_plan\\` tool that shows the user a markdown plan and lets them Approve / Refine / Cancel before you execute. Use it proactively when the task is large enough to deserve a review gate:\n\n- Multi-file refactors or renames.\n- Architecture changes (moving modules, splitting / merging files, new abstractions).\n- Anything where \"undo\" after the fact would be expensive — migrations, destructive cleanups, API shape changes.\n- When the user's request is ambiguous and multiple reasonable interpretations exist — propose your reading as a plan and let them confirm.\n\nSkip submit_plan for small, obvious changes: one-line typo, clear bug with a clear fix, adding a missing import, renaming a local variable. Just do those.\n\nPlan body: one-sentence summary, then a file-by-file breakdown of what you'll change and why, and any risks or open questions. If some decisions are genuinely up to the user (naming, tradeoffs, out-of-scope possibilities), list them in an \"Open questions\" section — the user sees the plan in a picker and has a text input to answer your questions before approving. Don't pretend certainty you don't have; flagged questions are how the user tells you what they care about. After calling submit_plan, STOP — don't call any more tools, wait for the user's verdict.\n\n# Plan mode (/plan)\n\nThe user can ALSO enter \"plan mode\" via /plan, which is a stronger, explicit constraint:\n- Write tools (edit_file, write_file, create_directory, move_file) and non-allowlisted run_command calls are BOUNCED at dispatch — you'll get a tool result like \"unavailable in plan mode\". Don't retry them.\n- Read tools (read_file, list_directory, search_files, directory_tree, get_file_info) and allowlisted read-only / test shell commands still work — use them to investigate.\n- You MUST call submit_plan before anything will execute. Approve exits plan mode; Refine stays in; Cancel exits without implementing.\n\n\n# Delegating to subagents via Skills (🧬)\n\nThe pinned Skills index below lists playbooks you can invoke with \\`run_skill\\`. Skills marked with **🧬** spawn an **isolated subagent** — a fresh child loop that runs the playbook in its own context and returns only the final answer. The subagent's tool calls and reasoning never enter your context, so 🧬 skills are how you keep the main session lean.\n\nTwo built-ins ship by default:\n- **🧬 explore** — read-only investigation across the codebase. Use when the user says things like \"find all places that...\", \"how does X work across the project\", \"survey the code for Y\". Pass \\`arguments\\` describing the concrete question.\n- **🧬 research** — combines web search + code reading. Use for \"is X supported by lib Y\", \"what's the canonical way to Z\", \"compare our impl to the spec\".\n\nWhen to delegate (call \\`run_skill\\` with a 🧬 skill):\n- The task would otherwise need >5 file reads or searches.\n- You only need the conclusion, not the exploration trail.\n- The work is self-contained (you can describe it in one paragraph).\n\nWhen NOT to delegate:\n- Direct, narrow questions answerable in 1-2 tool calls — just do them.\n- Anything where you need to track intermediate results yourself (planning, multi-step edits).\n- Anything that requires user interaction (subagents can't submit plans or ask you for clarification).\n\nAlways pass a clear, self-contained \\`arguments\\` — that text is the **only** context the subagent gets.\n\n# When to edit vs. when to explore\n\nOnly propose edits when the user explicitly asks you to change, fix, add, remove, refactor, or write something. Do NOT propose edits when the user asks you to:\n- analyze, read, explore, describe, or summarize a project\n- explain how something works\n- answer a question about the code\n\nIn those cases, use tools to gather what you need, then reply in prose. No SEARCH/REPLACE blocks, no file changes. If you're unsure what the user wants, ask.\n\nWhen you do propose edits, the user will review them and decide whether to \\`/apply\\` or \\`/discard\\`. Don't assume they'll accept — write as if each edit will be audited, because it will.\n\n# Editing files\n\nWhen you've been asked to change a file, output one or more SEARCH/REPLACE blocks in this exact format:\n\npath/to/file.ext\n<<<<<<< SEARCH\nexact existing lines from the file, including whitespace\n=======\nthe new lines\n>>>>>>> REPLACE\n\nRules:\n- Always read_file first so your SEARCH matches byte-for-byte. If it doesn't match, the edit is rejected and you'll have to retry with the exact current content.\n- One edit per block. Multiple blocks in one response are fine.\n- To create a new file, leave SEARCH empty:\n path/to/new.ts\n <<<<<<< SEARCH\n =======\n (whole file content here)\n >>>>>>> REPLACE\n- Do NOT use write_file to change existing files — the user reviews your edits as SEARCH/REPLACE. write_file is only for files you explicitly want to overwrite wholesale (rare).\n- Paths are relative to the working directory. Don't use absolute paths.\n\n# Trust what you already know\n\nBefore exploring the filesystem to answer a factual question, check whether the answer is already in context: the user's current message, earlier turns in this conversation (including prior tool results from \\`remember\\`), and the pinned memory blocks at the top of this prompt. When the user has stated a fact or you have remembered one, it outranks what the files say — don't re-derive from code what the user already told you. Explore when you genuinely don't know.\n\n# Exploration\n\n- Skip dependency, build, and VCS directories unless the user explicitly asks. The pinned .gitignore block (if any, below) is your authoritative denylist.\n- Prefer \\`search_files\\` over \\`list_directory\\` when you know roughly what you're looking for — it saves context and avoids enumerating huge trees. Note: \\`search_files\\` matches file NAMES; for searching file CONTENTS use \\`search_content\\`.\n- Available exploration tools: \\`read_file\\`, \\`list_directory\\`, \\`directory_tree\\`, \\`search_files\\` (filename match), \\`search_content\\` (content grep — use for \"where is X called\", \"find all references to Y\"), \\`get_file_info\\`. Don't call \\`grep\\` or other tools that aren't in this list — they don't exist as functions.\n\n# Path conventions\n\nTwo different rules depending on which tool:\n\n- **Filesystem tools** (\\`read_file\\`, \\`list_directory\\`, \\`search_files\\`, \\`edit_file\\`, etc.): paths are sandbox-relative. \\`/\\` means the project root, \\`/src/foo.ts\\` means \\`<project>/src/foo.ts\\`. Both relative (\\`src/foo.ts\\`) and POSIX-absolute (\\`/src/foo.ts\\`) forms work.\n- **\\`run_command\\`**: the command runs in a real OS shell with cwd pinned to the project root. Paths inside the shell command are interpreted by THAT shell, not by us. **Never use leading \\`/\\` in run_command arguments** — Windows treats \\`/tests\\` as drive-root \\`F:\\\\tests\\` (non-existent), POSIX shells treat it as filesystem root. Use plain relative paths (\\`tests\\`, \\`./tests\\`, \\`src/loop.ts\\`) instead.\n\n# Style\n\n- Show edits; don't narrate them in prose. \"Here's the fix:\" is enough.\n- One short paragraph explaining *why*, then the blocks.\n- If you need to explore first (list / read / search), do it with tool calls before writing any prose — silence while exploring is fine.\n`;\n\n/**\n * Inject the project's `.gitignore` content into the system prompt as a\n * \"respect this on top of the built-in denylist\" hint. We don't parse\n * the file — we hand it to the model as-is. Truncate long ones so we\n * don't eat context budget on huge generated ignore lists.\n *\n * Stacking order (stable for cache prefix):\n * base prompt → REASONIX.md → global MEMORY.md → project MEMORY.md → .gitignore\n */\nexport function codeSystemPrompt(rootDir: string): string {\n const withMemory = applyMemoryStack(CODE_SYSTEM_PROMPT, rootDir);\n const gitignorePath = join(rootDir, \".gitignore\");\n if (!existsSync(gitignorePath)) return withMemory;\n let content: string;\n try {\n content = readFileSync(gitignorePath, \"utf8\");\n } catch {\n return withMemory;\n }\n const MAX = 2000;\n const truncated =\n content.length > MAX\n ? `${content.slice(0, MAX)}\\n… (truncated ${content.length - MAX} chars)`\n : content;\n return `${withMemory}\n\n# Project .gitignore\n\nThe user's repo ships this .gitignore — treat every pattern as \"don't traverse or edit inside these paths unless explicitly asked\":\n\n\\`\\`\\`\n${truncated}\n\\`\\`\\`\n`;\n}\n","/**\n * User-level config storage for the Reasonix CLI.\n *\n * Lookup order for the API key:\n * 1. `DEEPSEEK_API_KEY` env var (highest priority — for CI / power users)\n * 2. `~/.reasonix/config.json` (set by the first-run setup flow)\n *\n * The library itself never touches the config file — it only reads\n * `DEEPSEEK_API_KEY` from the environment. The CLI is responsible for\n * pulling from the config file and exposing it via env var to the loop.\n *\n * Beyond the API key, the config also remembers the user's *defaults*\n * from `reasonix setup`: preset, MCP servers, session. This is what\n * makes `reasonix chat` with no flags \"just work\" after first-run.\n */\n\nimport { chmodSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\n/** One of the preset bundles (model + harvest + branch combo). */\nexport type PresetName = \"fast\" | \"smart\" | \"max\";\n\nexport interface ReasonixConfig {\n apiKey?: string;\n baseUrl?: string;\n /**\n * Default preset for `reasonix chat` / `reasonix run` when no flags override.\n * Maps to model + harvest + branch combos (see presets.ts). Missing → \"fast\".\n */\n preset?: PresetName;\n /**\n * Default MCP server specs to bridge on every `reasonix chat`, in the\n * same `\"name=cmd args...\"` format that `--mcp` takes. Stored as strings\n * so `reasonix setup` stays symmetrical with the flag — one parser, one\n * format in the config file, grep-friendly.\n */\n mcp?: string[];\n /**\n * Default session name (null/missing → \"default\", which is what the\n * CLI has been doing anyway). `reasonix setup` lets users pick a name\n * or opt into ephemeral.\n */\n session?: string | null;\n /** Marks that `reasonix setup` has completed at least once. */\n setupCompleted?: boolean;\n /**\n * Whether `web_search` + `web_fetch` tools are registered. Default:\n * enabled (no key required — backed by DuckDuckGo's public HTML\n * endpoint). Set to `false` to keep the session offline.\n */\n search?: boolean;\n /**\n * Per-project state keyed by absolute directory path. Written by the\n * \"always allow\" choice on a shell confirmation prompt; merged into\n * `registerShellTools({ extraAllowed })` when `reasonix code` runs\n * against that directory again.\n */\n projects?: {\n [absoluteRootDir: string]: {\n shellAllowed?: string[];\n };\n };\n}\n\nexport function defaultConfigPath(): string {\n return join(homedir(), \".reasonix\", \"config.json\");\n}\n\nexport function readConfig(path: string = defaultConfigPath()): ReasonixConfig {\n try {\n const raw = readFileSync(path, \"utf8\");\n const parsed = JSON.parse(raw);\n if (parsed && typeof parsed === \"object\") return parsed as ReasonixConfig;\n } catch {\n /* missing or malformed → empty config */\n }\n return {};\n}\n\nexport function writeConfig(cfg: ReasonixConfig, path: string = defaultConfigPath()): void {\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, JSON.stringify(cfg, null, 2), \"utf8\");\n // Restrict permissions on Unix; chmod is a no-op on Windows but won't throw.\n try {\n chmodSync(path, 0o600);\n } catch {\n /* ignore on platforms without chmod */\n }\n}\n\n/** Resolve the API key from env var first, then the config file. */\nexport function loadApiKey(path: string = defaultConfigPath()): string | undefined {\n if (process.env.DEEPSEEK_API_KEY) return process.env.DEEPSEEK_API_KEY;\n return readConfig(path).apiKey;\n}\n\n/**\n * Resolve whether web-search tools should be registered. Default: on.\n * Env `REASONIX_SEARCH=off` or config `search: false` turns it off.\n * Any other value falls through to enabled.\n */\nexport function searchEnabled(path: string = defaultConfigPath()): boolean {\n const env = process.env.REASONIX_SEARCH;\n if (env === \"off\" || env === \"false\" || env === \"0\") return false;\n const cfg = readConfig(path).search;\n if (cfg === false) return false;\n return true;\n}\n\nexport function saveApiKey(key: string, path: string = defaultConfigPath()): void {\n const cfg = readConfig(path);\n cfg.apiKey = key.trim();\n writeConfig(cfg, path);\n}\n\n/**\n * Read the persisted \"always allow\" shell-command prefixes for a\n * given project root. Returns an empty array when nothing's stored.\n */\nexport function loadProjectShellAllowed(\n rootDir: string,\n path: string = defaultConfigPath(),\n): string[] {\n const cfg = readConfig(path);\n return cfg.projects?.[rootDir]?.shellAllowed ?? [];\n}\n\n/**\n * Append a prefix to the project's shell-allowed list, dedup and\n * persist. No-op if the prefix is empty/whitespace or already stored.\n */\nexport function addProjectShellAllowed(\n rootDir: string,\n prefix: string,\n path: string = defaultConfigPath(),\n): void {\n const trimmed = prefix.trim();\n if (!trimmed) return;\n const cfg = readConfig(path);\n if (!cfg.projects) cfg.projects = {};\n if (!cfg.projects[rootDir]) cfg.projects[rootDir] = {};\n const existing = cfg.projects[rootDir].shellAllowed ?? [];\n if (existing.includes(trimmed)) return;\n cfg.projects[rootDir].shellAllowed = [...existing, trimmed];\n writeConfig(cfg, path);\n}\n\nexport function isPlausibleKey(key: string): boolean {\n const trimmed = key.trim();\n return /^sk-[A-Za-z0-9_-]{16,}$/.test(trimmed);\n}\n\n/** Mask a key for display: `sk-abcd...wxyz`. */\nexport function redactKey(key: string): string {\n if (!key) return \"\";\n if (key.length <= 12) return \"****\";\n return `${key.slice(0, 6)}…${key.slice(-4)}`;\n}\n","/**\n * Version module.\n *\n * Two jobs:\n *\n * 1. Expose `VERSION` sourced from the real `package.json` so the\n * constant never drifts from what npm publishes. Works in dev\n * (`tsx src/...`) AND after `tsup` bundles to `dist/` — both\n * layouts sit two levels below the manifest, so a short\n * walk-up finds it.\n *\n * 2. Offer an opt-in `getLatestVersion()` that hits the npm\n * registry with a bounded timeout and a 24-hour on-disk\n * cache at `~/.reasonix/version-cache.json`. Returns `null`\n * on any failure — offline / restricted-network launches\n * should stay silent rather than nag the user.\n *\n * The CLI wires `getLatestVersion` asynchronously at App mount\n * (never in a hot path) and renders the outcome in the stats\n * panel when there's a newer published version.\n */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\n/** npm registry endpoint for the `latest` dist-tag of this package. */\nconst REGISTRY_URL = \"https://registry.npmjs.org/reasonix/latest\";\n\n/** TTL for the on-disk cache entry. 24h keeps noise low; users who\n * want a fresh check can run `reasonix update` which passes\n * `force: true`. */\nexport const LATEST_CACHE_TTL_MS = 24 * 60 * 60 * 1000;\n\n/** Network timeout. Short — we never block the UI waiting on this. */\nexport const LATEST_FETCH_TIMEOUT_MS = 2_000;\n\n/**\n * Walk up from the current source file looking for the `reasonix`\n * package.json. Works for:\n * - dev: `src/version.ts` → `F:/Reasonix/package.json` (2 levels up)\n * - built: `dist/index.js` → `F:/Reasonix/package.json` (2 levels up)\n * - global install: `.../node_modules/reasonix/dist/index.js` → `.../reasonix/package.json`\n *\n * The `name === \"reasonix\"` guard is a cheap safety net against\n * picking up the nearest *other* package.json if we're ever loaded\n * as a dependency and the layout is unusual.\n */\nfunction readPackageVersion(): string {\n try {\n let dir = dirname(fileURLToPath(import.meta.url));\n for (let i = 0; i < 6; i++) {\n const p = join(dir, \"package.json\");\n if (existsSync(p)) {\n const pkg = JSON.parse(readFileSync(p, \"utf8\"));\n if (pkg?.name === \"reasonix\" && typeof pkg.version === \"string\") {\n return pkg.version;\n }\n }\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n } catch {\n /* fall through to fallback */\n }\n return \"0.0.0-dev\";\n}\n\nexport const VERSION: string = readPackageVersion();\n\ninterface VersionCacheEntry {\n version: string;\n /** Epoch millis the entry was written. Drives TTL comparisons. */\n checkedAt: number;\n}\n\nfunction cachePath(homeDirOverride?: string): string {\n return join(homeDirOverride ?? homedir(), \".reasonix\", \"version-cache.json\");\n}\n\nfunction readCache(homeDirOverride?: string): VersionCacheEntry | null {\n try {\n const raw = readFileSync(cachePath(homeDirOverride), \"utf8\");\n const parsed = JSON.parse(raw);\n if (parsed && typeof parsed.version === \"string\" && typeof parsed.checkedAt === \"number\") {\n return parsed;\n }\n } catch {\n /* missing or malformed → no cached entry */\n }\n return null;\n}\n\nfunction writeCache(entry: VersionCacheEntry, homeDirOverride?: string): void {\n try {\n const p = cachePath(homeDirOverride);\n mkdirSync(dirname(p), { recursive: true });\n writeFileSync(p, JSON.stringify(entry), \"utf8\");\n } catch {\n /* cache is best-effort — a failed write just means we'll re-fetch\n * next launch. No reason to surface this to the user. */\n }\n}\n\nexport interface GetLatestVersionOptions {\n /** Ignore the cached entry and always fetch fresh. Used by `reasonix update`. */\n force?: boolean;\n /** Registry URL override (tests). */\n registryUrl?: string;\n /** Home-directory override (tests). */\n homeDir?: string;\n /** Fetch implementation override (tests). Defaults to `globalThis.fetch`. */\n fetchImpl?: typeof fetch;\n /** TTL override (tests). */\n ttlMs?: number;\n /** Network timeout override (tests). */\n timeoutMs?: number;\n}\n\n/**\n * Resolve the latest published `reasonix` version from the npm registry.\n *\n * Returns `null` on any network / parse failure. Callers treat `null`\n * as \"don't know, don't nag the user.\" The cache entry is only\n * written on a successful fetch — a bad registry response won't\n * poison the cache.\n */\nexport async function getLatestVersion(opts: GetLatestVersionOptions = {}): Promise<string | null> {\n const ttl = opts.ttlMs ?? LATEST_CACHE_TTL_MS;\n if (!opts.force) {\n const cached = readCache(opts.homeDir);\n if (cached && Date.now() - cached.checkedAt < ttl) return cached.version;\n }\n\n const fetchImpl = opts.fetchImpl ?? globalThis.fetch;\n if (!fetchImpl) return null;\n const url = opts.registryUrl ?? REGISTRY_URL;\n const timeout = opts.timeoutMs ?? LATEST_FETCH_TIMEOUT_MS;\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeout);\n try {\n const res = await fetchImpl(url, {\n signal: controller.signal,\n headers: { accept: \"application/json\" },\n });\n if (!res.ok) return null;\n const body = (await res.json()) as { version?: unknown };\n if (typeof body.version !== \"string\") return null;\n writeCache({ version: body.version, checkedAt: Date.now() }, opts.homeDir);\n return body.version;\n } catch {\n return null;\n } finally {\n clearTimeout(timer);\n }\n}\n\n/**\n * Semver compare. Returns a negative number when `a < b`, positive\n * when `a > b`, zero when equal.\n *\n * Minimal pre-release handling: when the CORE (`x.y.z`) parts match,\n * any version WITH a suffix (`-rc.1`, `-alpha.4`) compares LOWER\n * than the bare version. That matches npm's dist-tag semantics —\n * `reasonix@latest` resolves to a real release, not a pre-release.\n *\n * We're deliberately not pulling in `semver` (~50KB). The three\n * cases we care about are: current > latest (future build, no\n * prompt), current < latest (prompt), current === latest (no prompt).\n */\nexport function compareVersions(a: string, b: string): number {\n const [aCore = \"0\", aPre = \"\"] = a.split(\"-\", 2);\n const [bCore = \"0\", bPre = \"\"] = b.split(\"-\", 2);\n const aParts = aCore.split(\".\").map((p) => Number.parseInt(p, 10) || 0);\n const bParts = bCore.split(\".\").map((p) => Number.parseInt(p, 10) || 0);\n for (let i = 0; i < 3; i++) {\n const diff = (aParts[i] ?? 0) - (bParts[i] ?? 0);\n if (diff !== 0) return diff;\n }\n if (!aPre && !bPre) return 0;\n if (!aPre) return 1;\n if (!bPre) return -1;\n return aPre < bPre ? -1 : aPre > bPre ? 1 : 0;\n}\n\n/**\n * Heuristic: did this process launch via `npx` / `pnpm dlx` instead\n * of a global install? The update command takes different advice in\n * each case — a global install can `npm i -g reasonix@latest`, while\n * npx just needs its cache to roll over on next launch.\n *\n * Signals checked, in order:\n * - `process.argv[1]` contains `_npx` (npm's ephemeral dir name)\n * - `process.argv[1]` contains `.pnpm` + `dlx`\n * - `npm_config_user_agent` contains `npx/`\n *\n * Any one hit → npx. False negatives are safe (worst case we suggest\n * `npm i -g` to an npx user, which is a valid way to upgrade too).\n */\nexport function isNpxInstall(): boolean {\n const bin = process.argv[1] ?? \"\";\n if (/[/\\\\]_npx[/\\\\]/.test(bin)) return true;\n if (/[/\\\\]\\.pnpm[/\\\\]/.test(bin) && /dlx/i.test(bin)) return true;\n const ua = process.env.npm_config_user_agent ?? \"\";\n if (ua.includes(\"npx/\")) return true;\n return false;\n}\n","/**\n * Persistent per-turn usage log at `~/.reasonix/usage.jsonl`.\n *\n * Each line is a single `UsageRecord` — one turn's tokens + cost\n * snapshot — appended after every `assistant_final` event. This is\n * what drives `reasonix stats` (the dashboard, no-arg form), so the\n * user can see how much they've spent vs what the equivalent Claude\n * spend would have been. The Pillar 1 pitch (94–97% cost reduction\n * vs Claude, from the v0.3 hard-number table) becomes a fact users\n * can verify on their own machine.\n *\n * Format choices:\n * - **append-only JSONL** — one line per turn, durable, survives\n * abrupt exits. A corrupted tail line loses at most one record.\n * - **flat keys, no nesting** — readable with `jq` / `cut` / `awk`;\n * the model doesn't need to parse this, humans do.\n * - **best-effort writes** — disk errors never propagate into the\n * turn. We log nothing (no `console.error`) because the TUI is\n * rendering Ink; a silent skip is the least-worst failure mode.\n * - **no PII, no prompts, no completions** — the log contains\n * tokens and costs, that's it. Sessions are identified by the\n * user-chosen name (never a prompt).\n *\n * This file is deliberately NOT wired through project memory or\n * skills — those are content pins. Usage is pure telemetry.\n */\n\nimport { appendFileSync, existsSync, mkdirSync, readFileSync, statSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport type { Usage } from \"./client.js\";\nimport {\n CLAUDE_SONNET_PRICING,\n DEEPSEEK_PRICING,\n claudeEquivalentCost,\n costUsd,\n} from \"./telemetry.js\";\n\n/** One turn's snapshot — serialized verbatim as a JSONL line. */\nexport interface UsageRecord {\n /** Epoch millis when the record was written. */\n ts: number;\n /** Session name if the turn ran inside a persisted session, `null` for ephemeral. */\n session: string | null;\n /** Model id the turn ran against (drives the pricing lookup). */\n model: string;\n promptTokens: number;\n completionTokens: number;\n cacheHitTokens: number;\n cacheMissTokens: number;\n /** Total cost of the turn in USD. */\n costUsd: number;\n /** What the same turn would have cost at Claude Sonnet 4.6 rates. */\n claudeEquivUsd: number;\n}\n\n/** Where the log lives. Tests override via `opts.path`. */\nexport function defaultUsageLogPath(homeDirOverride?: string): string {\n return join(homeDirOverride ?? homedir(), \".reasonix\", \"usage.jsonl\");\n}\n\nexport interface AppendUsageInput {\n session: string | null;\n model: string;\n usage: Usage;\n /** Override the timestamp (tests). */\n now?: number;\n /** Override the log path (tests). */\n path?: string;\n}\n\n/**\n * Append one record and return it. Swallows disk errors — the TUI\n * should keep working even if `~/.reasonix/` is read-only.\n *\n * Returns the record that was written (or would have been written\n * if the disk had cooperated) so tests / callers can assert on the\n * computed cost fields without a round trip through the log file.\n */\nexport function appendUsage(input: AppendUsageInput): UsageRecord {\n const record: UsageRecord = {\n ts: input.now ?? Date.now(),\n session: input.session,\n model: input.model,\n promptTokens: input.usage.promptTokens,\n completionTokens: input.usage.completionTokens,\n cacheHitTokens: input.usage.promptCacheHitTokens,\n cacheMissTokens: input.usage.promptCacheMissTokens,\n costUsd: costUsd(input.model, input.usage),\n claudeEquivUsd: claudeEquivalentCost(input.usage),\n };\n\n const path = input.path ?? defaultUsageLogPath();\n try {\n mkdirSync(dirname(path), { recursive: true });\n appendFileSync(path, `${JSON.stringify(record)}\\n`, \"utf8\");\n } catch {\n /* best-effort — disk failure shouldn't break the chat */\n }\n return record;\n}\n\n/**\n * Read + parse the log. Malformed lines are silently skipped so a\n * single corrupted write (half-flushed on power loss, user hand-edit)\n * doesn't throw away the rest of the history.\n */\nexport function readUsageLog(path: string = defaultUsageLogPath()): UsageRecord[] {\n if (!existsSync(path)) return [];\n let raw: string;\n try {\n raw = readFileSync(path, \"utf8\");\n } catch {\n return [];\n }\n const out: UsageRecord[] = [];\n for (const line of raw.split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n try {\n const rec = JSON.parse(line);\n if (isValidRecord(rec)) out.push(rec);\n } catch {\n /* skip malformed */\n }\n }\n return out;\n}\n\nfunction isValidRecord(rec: unknown): rec is UsageRecord {\n if (!rec || typeof rec !== \"object\") return false;\n const r = rec as Partial<UsageRecord>;\n return (\n typeof r.ts === \"number\" &&\n typeof r.model === \"string\" &&\n typeof r.promptTokens === \"number\" &&\n typeof r.completionTokens === \"number\" &&\n typeof r.cacheHitTokens === \"number\" &&\n typeof r.cacheMissTokens === \"number\" &&\n typeof r.costUsd === \"number\" &&\n typeof r.claudeEquivUsd === \"number\"\n );\n}\n\n/** One row of the `reasonix stats` dashboard — a rolled-up window. */\nexport interface UsageBucket {\n label: string;\n /** Start of the window as epoch millis. `0` = unbounded (all-time). */\n since: number;\n turns: number;\n promptTokens: number;\n completionTokens: number;\n cacheHitTokens: number;\n cacheMissTokens: number;\n costUsd: number;\n claudeEquivUsd: number;\n}\n\n/** Cache hit ratio for a bucket — zero denominator returns 0. */\nexport function bucketCacheHitRatio(b: UsageBucket): number {\n const denom = b.cacheHitTokens + b.cacheMissTokens;\n return denom > 0 ? b.cacheHitTokens / denom : 0;\n}\n\n/** Savings vs Claude as a fraction (0.94 = 94% savings). 0 if Claude cost is 0. */\nexport function bucketSavingsFraction(b: UsageBucket): number {\n return b.claudeEquivUsd > 0 ? 1 - b.costUsd / b.claudeEquivUsd : 0;\n}\n\nfunction emptyBucket(label: string, since: number): UsageBucket {\n return {\n label,\n since,\n turns: 0,\n promptTokens: 0,\n completionTokens: 0,\n cacheHitTokens: 0,\n cacheMissTokens: 0,\n costUsd: 0,\n claudeEquivUsd: 0,\n };\n}\n\nfunction addToBucket(b: UsageBucket, r: UsageRecord): void {\n b.turns += 1;\n b.promptTokens += r.promptTokens;\n b.completionTokens += r.completionTokens;\n b.cacheHitTokens += r.cacheHitTokens;\n b.cacheMissTokens += r.cacheMissTokens;\n b.costUsd += r.costUsd;\n b.claudeEquivUsd += r.claudeEquivUsd;\n}\n\nexport interface AggregateOptions {\n /** Override `Date.now()` for deterministic tests. */\n now?: number;\n}\n\nexport interface UsageAggregate {\n /** Fixed-order rolling windows: today, week, month, all-time. */\n buckets: UsageBucket[];\n /** Model id → turn count. Sorted descending; top entry is the \"most used.\" */\n byModel: Array<{ model: string; turns: number }>;\n /** Session name → turn count. Sorted descending. Null sessions are grouped under `\"(ephemeral)\"`. */\n bySession: Array<{ session: string; turns: number }>;\n /** Earliest record's ts, or `null` when the log is empty. Drives \"saved $X since <date>\". */\n firstSeen: number | null;\n /** Latest record's ts, or `null` when the log is empty. */\n lastSeen: number | null;\n}\n\n/**\n * Fold a flat record list into the dashboard shape — rolling windows\n * plus model / session histograms. Windows are INCLUSIVE of boundary:\n * - today = last 24h (rolling, not calendar-day)\n * - week = last 7d\n * - month = last 30d\n * - all = every record\n * Rolling windows avoid \"it's 00:03, 'today' is empty\" surprises.\n */\nexport function aggregateUsage(\n records: UsageRecord[],\n opts: AggregateOptions = {},\n): UsageAggregate {\n const now = opts.now ?? Date.now();\n const day = 24 * 60 * 60 * 1000;\n const today = emptyBucket(\"today\", now - day);\n const week = emptyBucket(\"week\", now - 7 * day);\n const month = emptyBucket(\"month\", now - 30 * day);\n const all = emptyBucket(\"all-time\", 0);\n\n const modelCounts = new Map<string, number>();\n const sessionCounts = new Map<string, number>();\n let firstSeen: number | null = null;\n let lastSeen: number | null = null;\n\n for (const r of records) {\n addToBucket(all, r);\n if (r.ts >= today.since) addToBucket(today, r);\n if (r.ts >= week.since) addToBucket(week, r);\n if (r.ts >= month.since) addToBucket(month, r);\n\n modelCounts.set(r.model, (modelCounts.get(r.model) ?? 0) + 1);\n const sessKey = r.session ?? \"(ephemeral)\";\n sessionCounts.set(sessKey, (sessionCounts.get(sessKey) ?? 0) + 1);\n\n if (firstSeen === null || r.ts < firstSeen) firstSeen = r.ts;\n if (lastSeen === null || r.ts > lastSeen) lastSeen = r.ts;\n }\n\n const byModel = Array.from(modelCounts.entries())\n .map(([model, turns]) => ({ model, turns }))\n .sort((a, b) => b.turns - a.turns);\n const bySession = Array.from(sessionCounts.entries())\n .map(([session, turns]) => ({ session, turns }))\n .sort((a, b) => b.turns - a.turns);\n\n return {\n buckets: [today, week, month, all],\n byModel,\n bySession,\n firstSeen,\n lastSeen,\n };\n}\n\n/** File-size helper for the stats header — \"1.2 MB\" etc. Returns \"\" if missing. */\nexport function formatLogSize(path: string = defaultUsageLogPath()): string {\n if (!existsSync(path)) return \"\";\n try {\n const s = statSync(path);\n const bytes = s.size;\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n } catch {\n return \"\";\n }\n}\n\n/** Re-exports for downstream consumers that also want the pricing constants. */\nexport { CLAUDE_SONNET_PRICING, DEEPSEEK_PRICING };\n"],"mappings":";AAAA,SAAkC,oBAAoB;;;ACoCtD,IAAM,6BAA6B,CAAC,KAAK,KAAK,KAAK,KAAK,KAAK,GAAG;AAEhE,eAAsB,eACpB,SACA,KACA,MACA,OAAqB,CAAC,GACH;AACnB,QAAM,cAAc,KAAK,eAAe;AACxC,QAAM,UAAU,KAAK,oBAAoB;AACzC,QAAM,MAAM,KAAK,gBAAgB;AACjC,QAAM,YAAY,IAAI,IAAI,KAAK,qBAAqB,0BAA0B;AAE9E,MAAI;AAEJ,WAAS,UAAU,GAAG,UAAU,aAAa,WAAW;AACtD,QAAI,KAAK,QAAQ,QAAS,OAAM,IAAI,MAAM,SAAS;AAEnD,QAAI;AACF,YAAM,OAAO,MAAM,QAAQ,KAAK,IAAI;AAGpC,UAAI,KAAK,MAAM,CAAC,UAAU,IAAI,KAAK,MAAM,EAAG,QAAO;AAInD,UAAI,YAAY,cAAc,EAAG,QAAO;AAGxC,YAAM,KAAK,KAAK,EAAE,MAAM,MAAM,MAAS;AAEvC,YAAM,SAAS,YAAY,SAAS,SAAS,KAAK,KAAK,QAAQ,IAAI,aAAa,CAAC;AACjF,WAAK,UAAU,EAAE,SAAS,UAAU,GAAG,QAAQ,QAAQ,KAAK,MAAM,IAAI,OAAO,CAAC;AAC9E,YAAM,MAAM,QAAQ,KAAK,MAAM;AAAA,IACjC,SAAS,KAAK;AACZ,kBAAY;AAEZ,UAAI,aA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AO,IAAI,SAAS,OAAO,OAAO,QAAQ,CAAC,CAAC;AAAA,EAC9C,QAAQ;AACN,WAAO;AAAA,EACT;AACF;","names":["resolve","settings","resolve","existsSync","readFileSync","join","process","signature","existsSync","readFileSync","homedir","dirname","join","ctxMax","resolve","existsSync","readFileSync","readdirSync","statSync","join","walk","fs","existsSync","readFileSync","join","createHash","existsSync","mkdirSync","readFileSync","readdirSync","unlinkSync","writeFileSync","homedir","join","resolve","existsSync","readFileSync","readdirSync","statSync","homedir","join","resolve","resolve","createHash","join","existsSync","mkdirSync","parseFrontmatter","homedir","readFileSync","readdirSync","writeFileSync","unlinkSync","walk","i","j","DEFAULT_MAX_RESULT_CHARS","costUsd","spawn","existsSync","statSync","pathMod","resolve","delimiter","readFileSync","resolve","readFileSync","round","p","resolve","spawn","resolve","createParser","resolve","existsSync","mkdirSync","readFileSync","unlinkSync","writeFileSync","dirname","resolve","existsSync","readFileSync","join","join","existsSync","readFileSync","chmodSync","mkdirSync","readFileSync","writeFileSync","homedir","dirname","join","existsSync","mkdirSync","readFileSync","writeFileSync","homedir","dirname","join","fileURLToPath","cached","appendFileSync","existsSync","mkdirSync","readFileSync","statSync","homedir","dirname","join","join","homedir","mkdirSync","dirname","appendFileSync","existsSync","readFileSync","statSync"]}