@warlock.js/ai-cli 0.0.0-stage → 5.31.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +31 -0
- package/LICENSE +21 -0
- package/README.md +69 -2
- package/cjs/index.cjs +4576 -0
- package/cjs/index.cjs.map +1 -0
- package/esm/adapters/aider.d.mts +41 -0
- package/esm/adapters/aider.d.mts.map +1 -0
- package/esm/adapters/aider.mjs +294 -0
- package/esm/adapters/aider.mjs.map +1 -0
- package/esm/adapters/amp.d.mts +33 -0
- package/esm/adapters/amp.d.mts.map +1 -0
- package/esm/adapters/amp.mjs +119 -0
- package/esm/adapters/amp.mjs.map +1 -0
- package/esm/adapters/antigravity.d.mts +37 -0
- package/esm/adapters/antigravity.d.mts.map +1 -0
- package/esm/adapters/antigravity.mjs +235 -0
- package/esm/adapters/antigravity.mjs.map +1 -0
- package/esm/adapters/claude-code.d.mts +30 -0
- package/esm/adapters/claude-code.d.mts.map +1 -0
- package/esm/adapters/claude-code.mjs +121 -0
- package/esm/adapters/claude-code.mjs.map +1 -0
- package/esm/adapters/claude-stream.d.mts +32 -0
- package/esm/adapters/claude-stream.d.mts.map +1 -0
- package/esm/adapters/claude-stream.mjs +140 -0
- package/esm/adapters/claude-stream.mjs.map +1 -0
- package/esm/adapters/codex.d.mts +37 -0
- package/esm/adapters/codex.d.mts.map +1 -0
- package/esm/adapters/codex.mjs +320 -0
- package/esm/adapters/codex.mjs.map +1 -0
- package/esm/adapters/copilot.d.mts +35 -0
- package/esm/adapters/copilot.d.mts.map +1 -0
- package/esm/adapters/copilot.mjs +244 -0
- package/esm/adapters/copilot.mjs.map +1 -0
- package/esm/adapters/cursor.d.mts +35 -0
- package/esm/adapters/cursor.d.mts.map +1 -0
- package/esm/adapters/cursor.mjs +203 -0
- package/esm/adapters/cursor.mjs.map +1 -0
- package/esm/adapters/droid.d.mts +32 -0
- package/esm/adapters/droid.d.mts.map +1 -0
- package/esm/adapters/droid.mjs +183 -0
- package/esm/adapters/droid.mjs.map +1 -0
- package/esm/adapters/grok.d.mts +32 -0
- package/esm/adapters/grok.d.mts.map +1 -0
- package/esm/adapters/grok.mjs +199 -0
- package/esm/adapters/grok.mjs.map +1 -0
- package/esm/adapters/index.d.mts +16 -0
- package/esm/adapters/index.mjs +18 -0
- package/esm/adapters/kimi.d.mts +34 -0
- package/esm/adapters/kimi.d.mts.map +1 -0
- package/esm/adapters/kimi.mjs +162 -0
- package/esm/adapters/kimi.mjs.map +1 -0
- package/esm/adapters/mistral-vibe.d.mts +32 -0
- package/esm/adapters/mistral-vibe.d.mts.map +1 -0
- package/esm/adapters/mistral-vibe.mjs +252 -0
- package/esm/adapters/mistral-vibe.mjs.map +1 -0
- package/esm/adapters/opencode.d.mts +36 -0
- package/esm/adapters/opencode.d.mts.map +1 -0
- package/esm/adapters/opencode.mjs +219 -0
- package/esm/adapters/opencode.mjs.map +1 -0
- package/esm/adapters/qwen-code.d.mts +30 -0
- package/esm/adapters/qwen-code.d.mts.map +1 -0
- package/esm/adapters/qwen-code.mjs +94 -0
- package/esm/adapters/qwen-code.mjs.map +1 -0
- package/esm/adapters/reasonix.d.mts +31 -0
- package/esm/adapters/reasonix.d.mts.map +1 -0
- package/esm/adapters/reasonix.mjs +250 -0
- package/esm/adapters/reasonix.mjs.map +1 -0
- package/esm/adapters/shared.d.mts +78 -0
- package/esm/adapters/shared.d.mts.map +1 -0
- package/esm/adapters/shared.mjs +161 -0
- package/esm/adapters/shared.mjs.map +1 -0
- package/esm/cli-agent.d.mts +40 -0
- package/esm/cli-agent.d.mts.map +1 -0
- package/esm/cli-agent.mjs +207 -0
- package/esm/cli-agent.mjs.map +1 -0
- package/esm/cli.d.mts +53 -0
- package/esm/cli.d.mts.map +1 -0
- package/esm/cli.mjs +61 -0
- package/esm/cli.mjs.map +1 -0
- package/esm/contracts/adapter.contract.d.mts +154 -0
- package/esm/contracts/adapter.contract.d.mts.map +1 -0
- package/esm/contracts/events.type.d.mts +111 -0
- package/esm/contracts/events.type.d.mts.map +1 -0
- package/esm/contracts/index.d.mts +4 -0
- package/esm/contracts/mcp.type.d.mts +29 -0
- package/esm/contracts/mcp.type.d.mts.map +1 -0
- package/esm/contracts/options.type.d.mts +87 -0
- package/esm/contracts/options.type.d.mts.map +1 -0
- package/esm/errors.d.mts +46 -0
- package/esm/errors.d.mts.map +1 -0
- package/esm/errors.mjs +32 -0
- package/esm/errors.mjs.map +1 -0
- package/esm/index.d.mts +31 -0
- package/esm/index.mjs +28 -0
- package/esm/model/cli-model.d.mts +48 -0
- package/esm/model/cli-model.d.mts.map +1 -0
- package/esm/model/cli-model.mjs +133 -0
- package/esm/model/cli-model.mjs.map +1 -0
- package/esm/probe/probe.d.mts +18 -0
- package/esm/probe/probe.d.mts.map +1 -0
- package/esm/probe/probe.mjs +148 -0
- package/esm/probe/probe.mjs.map +1 -0
- package/esm/session/aggregate.mjs +86 -0
- package/esm/session/aggregate.mjs.map +1 -0
- package/esm/session/environment.mjs +71 -0
- package/esm/session/environment.mjs.map +1 -0
- package/esm/session/run-directory.mjs +74 -0
- package/esm/session/run-directory.mjs.map +1 -0
- package/esm/session/session.mjs +188 -0
- package/esm/session/session.mjs.map +1 -0
- package/esm/spawn/invocation.d.mts +35 -0
- package/esm/spawn/invocation.d.mts.map +1 -0
- package/esm/spawn/invocation.mjs +76 -0
- package/esm/spawn/invocation.mjs.map +1 -0
- package/esm/spawn/process-tree.mjs +57 -0
- package/esm/spawn/process-tree.mjs.map +1 -0
- package/esm/spawn/resolve-command.d.mts +73 -0
- package/esm/spawn/resolve-command.d.mts.map +1 -0
- package/esm/spawn/resolve-command.mjs +109 -0
- package/esm/spawn/resolve-command.mjs.map +1 -0
- package/esm/stream/event-log.mjs +52 -0
- package/esm/stream/event-log.mjs.map +1 -0
- package/esm/stream/json-lines.d.mts +33 -0
- package/esm/stream/json-lines.d.mts.map +1 -0
- package/esm/stream/json-lines.mjs +65 -0
- package/esm/stream/json-lines.mjs.map +1 -0
- package/esm/stream/line-splitter.mjs +53 -0
- package/esm/stream/line-splitter.mjs.map +1 -0
- package/esm/utils/toml.d.mts +22 -0
- package/esm/utils/toml.d.mts.map +1 -0
- package/esm/utils/toml.mjs +53 -0
- package/esm/utils/toml.mjs.map +1 -0
- package/llms-full.txt +373 -0
- package/llms.txt +10 -0
- package/package.json +39 -4
- package/skills/README.md +13 -0
- package/skills/index.md +22 -0
- package/skills/run-cli-agents/SKILL.md +186 -0
- package/skills/write-a-cli-adapter/SKILL.md +173 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["ProviderError","path","StringDecoder","path","constants","path","path","path","path","path","path","path","path","path","path","path","path","path","path","path","path"],"sources":["../../../../../../../packages/ai-cli/src/errors.ts","../../../../../../../packages/ai-cli/src/model/cli-model.ts","../../../../../../../packages/ai-cli/src/spawn/process-tree.ts","../../../../../../../packages/ai-cli/src/spawn/invocation.ts","../../../../../../../packages/ai-cli/src/probe/probe.ts","../../../../../../../packages/ai-cli/src/session/environment.ts","../../../../../../../packages/ai-cli/src/session/run-directory.ts","../../../../../../../packages/ai-cli/src/stream/event-log.ts","../../../../../../../packages/ai-cli/src/stream/line-splitter.ts","../../../../../../../packages/ai-cli/src/session/aggregate.ts","../../../../../../../packages/ai-cli/src/session/session.ts","../../../../../../../packages/ai-cli/src/spawn/resolve-command.ts","../../../../../../../packages/ai-cli/src/cli-agent.ts","../../../../../../../packages/ai-cli/src/stream/json-lines.ts","../../../../../../../packages/ai-cli/src/utils/toml.ts","../../../../../../../packages/ai-cli/src/adapters/shared.ts","../../../../../../../packages/ai-cli/src/adapters/aider.ts","../../../../../../../packages/ai-cli/src/adapters/claude-stream.ts","../../../../../../../packages/ai-cli/src/adapters/amp.ts","../../../../../../../packages/ai-cli/src/adapters/antigravity.ts","../../../../../../../packages/ai-cli/src/adapters/claude-code.ts","../../../../../../../packages/ai-cli/src/adapters/codex.ts","../../../../../../../packages/ai-cli/src/adapters/copilot.ts","../../../../../../../packages/ai-cli/src/adapters/cursor.ts","../../../../../../../packages/ai-cli/src/adapters/droid.ts","../../../../../../../packages/ai-cli/src/adapters/grok.ts","../../../../../../../packages/ai-cli/src/adapters/kimi.ts","../../../../../../../packages/ai-cli/src/adapters/mistral-vibe.ts","../../../../../../../packages/ai-cli/src/adapters/opencode.ts","../../../../../../../packages/ai-cli/src/adapters/qwen-code.ts","../../../../../../../packages/ai-cli/src/adapters/reasonix.ts","../../../../../../../packages/ai-cli/src/cli.ts"],"sourcesContent":["import { type AIErrorOptions, ProviderError } from \"@warlock.js/ai\";\n\n/**\n * Why a CLI agent refused or failed a run.\n *\n * - `not-found` — the executable is not on `PATH` (or the given path does not exist).\n * - `capability` — the installed CLI's `--help` does not list a flag the run needs.\n * - `probe-failed` — `--help`/`--version` could not be run.\n * - `unsupported-option` — the adapter has no way to honour an option (effort, MCP, home, …).\n * - `prompt-transport` — the prompt fits neither argv nor stdin for this CLI and platform.\n * - `run-failed` — the session ended `failed` or `timeout` (raised by the model adapter).\n */\nexport type CliErrorType =\n | \"not-found\"\n | \"capability\"\n | \"probe-failed\"\n | \"unsupported-option\"\n | \"prompt-transport\"\n | \"run-failed\";\n\nexport type CliErrorOptions = AIErrorOptions & {\n type: CliErrorType;\n /** Adapter name, e.g. `\"codex\"`. */\n adapter: string;\n /** The missing flag, for `capability`. */\n flag?: string;\n /** Detected CLI version, when known. */\n version?: string;\n /** Resolved executable, when known. */\n executable?: string;\n};\n\n/**\n * A CLI agent error. Extends the framework `ProviderError`, so agents,\n * fallbacks and observers treat it like any other provider failure; branch\n * on `error.type` for the specific reason.\n *\n * @example\n * try {\n * await claude.run(\"hi\");\n * } catch (error) {\n * if (error instanceof CliError && error.type === \"capability\") {\n * console.error(`Upgrade ${error.adapter}: missing ${error.flag} in ${error.version}`);\n * }\n * }\n */\nexport class CliError extends ProviderError {\n public readonly type: CliErrorType;\n public readonly adapter: string;\n public readonly flag?: string;\n public readonly version?: string;\n public readonly executable?: string;\n\n public constructor(message: string, options: CliErrorOptions) {\n super(\n message,\n options,\n options.type === \"unsupported-option\" || options.type === \"prompt-transport\"\n ? \"PROVIDER_INVALID_REQUEST\"\n : \"PROVIDER_ERROR\",\n );\n\n this.name = \"CliError\";\n this.type = options.type;\n this.adapter = options.adapter;\n this.flag = options.flag;\n this.version = options.version;\n this.executable = options.executable;\n }\n}\n","import type {\n Message,\n ModelCallOptions,\n ModelCapabilities,\n ModelContract,\n ModelPricing,\n ModelResponse,\n ModelStreamChunk,\n Usage,\n} from \"@warlock.js/ai\";\nimport type { CliAgent } from \"../cli-agent\";\nimport type { CliResult, CliRunOptions, CliUsage } from \"../contracts\";\nimport { CliError } from \"../errors\";\n\n/** Configuration of a CLI-backed model. Run options apply to every call. */\nexport type CliModelConfig = CliRunOptions & {\n /** Model name reported to the agent, reports and observers. Default: `model`, else the adapter name. */\n name?: string;\n /** Per-million-token pricing, so the agent computes `Usage.cost` (and USD budgets apply). */\n pricing?: ModelPricing;\n};\n\n/** The text of one message; CLI models accept text only. */\nfunction messageText(message: Message, adapter: string): string {\n if (typeof message.content === \"string\") {\n return message.content;\n }\n\n return message.content\n .map((part) => {\n if (part.type !== \"text\") {\n throw new CliError(\n `${adapter}: CLI models accept text only; a \"${part.type}\" attachment cannot be passed to the CLI.`,\n { type: \"unsupported-option\", adapter },\n );\n }\n\n return part.text;\n })\n .join(\"\\n\");\n}\n\n/**\n * Render an agent conversation into one CLI prompt. System messages become\n * a leading instruction block; a single user turn is passed as-is; a longer\n * history is rendered as a labelled transcript ending with the latest turn.\n *\n * @example\n * renderPrompt([{ role: \"system\", content: \"Be brief.\" }, { role: \"user\", content: \"Hi\" }], \"codex\");\n * // \"Be brief.\\n\\nHi\"\n */\nexport function renderPrompt(messages: Message[], adapter: string): string {\n const system = messages\n .filter((message) => message.role === \"system\")\n .map((message) => messageText(message, adapter).trim())\n .filter((text) => text.length > 0);\n const turns = messages.filter((message) => message.role !== \"system\");\n const only = turns.length === 1 ? turns[0] : undefined;\n const body =\n only !== undefined && only.role === \"user\"\n ? messageText(only, adapter)\n : turns\n .map((message) => {\n const label =\n message.role === \"user\"\n ? \"User\"\n : message.role === \"assistant\"\n ? \"Assistant\"\n : `Tool result${message.toolCallId ? ` (${message.toolCallId})` : \"\"}`;\n\n return `${label}:\\n${messageText(message, adapter)}`;\n })\n .join(\"\\n\\n\");\n\n return [...system, body].filter((part) => part.length > 0).join(\"\\n\\n\");\n}\n\n/** Map CLI usage to the framework `Usage` (zeros when the CLI reported none). */\nexport function toUsage(usage: CliUsage | undefined): Usage {\n if (usage === undefined) {\n return { input: 0, output: 0, total: 0 };\n }\n\n const mapped: Usage = { input: usage.input, output: usage.output, total: usage.total };\n\n if (usage.cachedTokens !== undefined) mapped.cachedTokens = usage.cachedTokens;\n if (usage.cacheWriteTokens !== undefined) mapped.cacheWriteTokens = usage.cacheWriteTokens;\n if (usage.reasoningTokens !== undefined) mapped.reasoningTokens = usage.reasoningTokens;\n\n return mapped;\n}\n\nfunction abortError(message: string): Error {\n const error = new Error(message);\n\n error.name = \"AbortError\";\n\n return error;\n}\n\n/**\n * A `ModelContract` backed by a CLI agent, so `ai.agent({ model })` — and\n * its budget, guardrail, observer and fallback middleware — can drive a\n * coding CLI.\n *\n * Each call is one fresh CLI session: the conversation is rendered into a\n * single prompt (see {@link renderPrompt}) and the session's final answer\n * becomes the response. The CLI runs its own tools; framework tools cannot\n * be handed to it this way (give the CLI MCP servers with `mcp` instead),\n * so a call carrying `tools` is refused. `stream()` yields the final answer\n * once the session ends — read `session.events` from `agent.run()` for live\n * progress.\n *\n * @example\n * const coder = cli.codex({ cwd: \"/srv/repo\" });\n * const reviewer = ai.agent({\n * model: cliModel(coder, { name: \"codex\" }),\n * middleware: [budget({ maxTokens: 200_000 })],\n * });\n * const { text } = await reviewer.execute(\"Review the last commit.\");\n */\nexport function cliModel(agent: CliAgent, config: CliModelConfig = {}): ModelContract {\n const { adapter } = agent;\n const capabilities: ModelCapabilities = { reasoning: adapter.effort === true };\n\n const execute = async (\n messages: Message[],\n options: ModelCallOptions = {},\n ): Promise<CliResult> => {\n if (options.tools !== undefined && options.tools.length > 0) {\n throw new CliError(\n `${adapter.title}: a CLI model runs the CLI's own tools; pass framework tools to the CLI as MCP servers (\\`mcp\\`) instead of agent \\`tools\\`.`,\n { type: \"unsupported-option\", adapter: adapter.name },\n );\n }\n\n const { name: _name, pricing: _pricing, ...runDefaults } = config;\n const effort = options.reasoning?.effort;\n const session = await agent.run(renderPrompt(messages, adapter.name), {\n ...runDefaults,\n signal: options.signal ?? runDefaults.signal,\n effort: adapter.effort === true && effort !== undefined ? effort : runDefaults.effort,\n });\n const result = await session.done();\n\n if (result.status === \"cancelled\") {\n throw abortError(result.error ?? `${adapter.name} run was cancelled`);\n }\n\n if (result.status !== \"completed\") {\n throw new CliError(`${adapter.title}: ${result.error ?? `run ${result.status}`}`, {\n type: \"run-failed\",\n adapter: adapter.name,\n context: {\n status: result.status,\n exitCode: result.exitCode,\n sessionRef: result.sessionRef,\n },\n });\n }\n\n return result;\n };\n\n return {\n name: config.name ?? config.model ?? agent.options.model ?? adapter.name,\n provider: adapter.name,\n capabilities,\n pricing: config.pricing,\n async complete(messages: Message[], options?: ModelCallOptions): Promise<ModelResponse> {\n const result = await execute(messages, options);\n\n return { content: result.text, finishReason: \"stop\", usage: toUsage(result.usage) };\n },\n async *stream(\n messages: Message[],\n options?: ModelCallOptions,\n ): AsyncIterable<ModelStreamChunk> {\n const result = await execute(messages, options);\n\n if (result.text.length > 0) {\n yield { type: \"delta\", content: result.text };\n }\n\n yield { type: \"done\", finishReason: \"stop\", usage: toUsage(result.usage) };\n },\n };\n}\n","import { type ChildProcess, spawn } from \"node:child_process\";\n\n/**\n * Terminate a CLI and everything it started.\n *\n * Coding CLIs spawn shells, language servers and MCP servers, so signalling\n * the direct child alone would leave grandchildren running.\n *\n * - **POSIX** — the child was spawned `detached` (its own process group), so\n * the whole group gets `SIGTERM`, then `SIGKILL` after `graceMs`.\n * - **Windows** — `taskkill /T /F` walks and kills the PID's tree (console\n * programs ignore a polite close, so there is no grace step).\n *\n * Only the tree this package spawned is ever signalled: the child's own PID\n * (Windows) or its own process group (POSIX) — never a name, port or\n * pattern. The SIGKILL follows even when the leader exits on SIGTERM, so a\n * grandchild that ignores SIGTERM (and keeps the pipes open) is still\n * reaped; a process group id cannot be reused while any member is alive.\n * Call the returned function once the session's pipes have closed (the\n * whole tree is gone) to cancel that pending SIGKILL.\n */\nexport function killProcessTree(\n child: ChildProcess,\n platform: NodeJS.Platform,\n graceMs: number,\n): () => void {\n const pid = child.pid;\n\n if (pid === undefined) {\n child.kill(\"SIGKILL\");\n\n return () => undefined;\n }\n\n if (platform === \"win32\") {\n const killer = spawn(\"taskkill\", [\"/pid\", String(pid), \"/T\", \"/F\"], { windowsHide: true });\n\n // A missing taskkill must not crash the process with an unhandled\n // 'error' event; fall back to the direct child.\n killer.on(\"error\", () => {\n child.kill(\"SIGKILL\");\n });\n\n return () => undefined;\n }\n\n const signalGroup = (signal: NodeJS.Signals): void => {\n try {\n process.kill(-pid, signal);\n } catch {\n // The group is already gone, or the child is not a group leader.\n try {\n child.kill(signal);\n } catch {\n // Already exited.\n }\n }\n };\n\n signalGroup(\"SIGTERM\");\n\n const timer = setTimeout(() => signalGroup(\"SIGKILL\"), Math.max(0, graceMs));\n\n timer.unref();\n\n return () => clearTimeout(timer);\n}\n","import type { SpawnTarget } from \"./resolve-command\";\n\n/** A ready-to-spawn invocation. */\nexport type Invocation = {\n file: string;\n args: string[];\n /** Set for `cmd.exe` so Node does not re-quote the already-quoted command line. */\n windowsVerbatimArguments: boolean;\n};\n\n/**\n * Bytes `cmd.exe` cannot carry inside a double-quoted argument: a quote ends\n * the quoted span, `%` expands variables even inside quotes, and a newline\n * ends the command (the BatBadBut / CVE-2024-24576 class). An argument\n * holding one of them is refused rather than escaped.\n */\nconst CMD_UNSAFE = /[\"%\\r\\n\\0]/;\n\n/** `cmd.exe` command-line limit (8191 characters), with headroom for the wrapper. */\nexport const CMD_LINE_LIMIT = 8000;\n\n/** `CreateProcess` command-line limit (32767 characters), with headroom. */\nexport const WINDOWS_LINE_LIMIT = 32000;\n\n/** Linux `MAX_ARG_STRLEN` (128 KiB per argument), with headroom. */\nexport const POSIX_ARGUMENT_LIMIT = 120 * 1024;\n\n/** Conservative total argv budget on POSIX (ARG_MAX is shared with the environment). */\nexport const POSIX_TOTAL_LIMIT = 512 * 1024;\n\n/**\n * Quote one argument for a `cmd.exe /s /c \"...\"` line, or return `null` when\n * it holds a byte cmd cannot quote safely. Inside double quotes `& | < > ^`\n * are literal; trailing backslashes are doubled so the target program's\n * argv parser does not read the closing quote as escaped.\n */\nexport function quoteForCmd(argument: string): string | null {\n if (CMD_UNSAFE.test(argument)) {\n return null;\n }\n\n const trailing = /\\\\+$/.exec(argument)?.[0] ?? \"\";\n\n return `\"${argument}${trailing}\"`;\n}\n\n/**\n * Build the invocation for a target and argv. A `cmd` target becomes\n * `cmd.exe /d /v:off /s /c \"\"batch\" \"arg\" …\"` — AutoRun disabled, delayed\n * expansion off (so `!` stays literal), each element quoted. Returns a\n * `refused` reason when an argument cannot be quoted safely.\n */\nexport function buildInvocation(\n target: SpawnTarget,\n args: string[],\n comspec: string,\n): Invocation | { refused: string } {\n if (target.type === \"direct\") {\n return {\n file: target.file,\n args: [...target.prefixArgs, ...args],\n windowsVerbatimArguments: false,\n };\n }\n\n const quoted: string[] = [];\n\n for (const element of [target.file, ...args]) {\n const safe = quoteForCmd(element);\n\n if (safe === null) {\n return {\n refused:\n 'an argument contains \", %, a newline or a NUL byte, which cmd.exe cannot carry safely',\n };\n }\n\n quoted.push(safe);\n }\n\n return {\n file: comspec,\n args: [\"/d\", \"/v:off\", \"/s\", \"/c\", `\"${quoted.join(\" \")}\"`],\n windowsVerbatimArguments: true,\n };\n}\n\n/**\n * Whether an invocation's argv fits the platform's limits. Windows counts\n * the whole command line (8191 for `cmd.exe`, 32767 for `CreateProcess`,\n * each argument quoted); POSIX limits a single argument to 128 KiB on Linux\n * and shares `ARG_MAX` with the environment.\n */\nexport function fitsCommandLine(invocation: Invocation, platform: NodeJS.Platform): boolean {\n if (platform === \"win32\") {\n const length = [invocation.file, ...invocation.args].reduce(\n (total, element) => total + element.length + 3,\n 0,\n );\n\n return length <= (invocation.windowsVerbatimArguments ? CMD_LINE_LIMIT : WINDOWS_LINE_LIMIT);\n }\n\n let total = 0;\n\n for (const element of [invocation.file, ...invocation.args]) {\n const bytes = Buffer.byteLength(element, \"utf8\") + 1;\n\n if (bytes > POSIX_ARGUMENT_LIMIT) {\n return false;\n }\n\n total += bytes;\n }\n\n return total <= POSIX_TOTAL_LIMIT;\n}\n","import { spawn } from \"node:child_process\";\nimport type { CliAdapter, CliProbeResult } from \"../contracts\";\nimport { CliError } from \"../errors\";\nimport { killProcessTree } from \"../spawn/process-tree\";\nimport { buildInvocation } from \"../spawn/invocation\";\nimport type { SpawnTarget } from \"../spawn/resolve-command\";\n\n/** How long a single `--help`/`--version` call may take. */\nexport const PROBE_TIMEOUT_MS = 30_000;\n\n/** Output cap per probe call; help screens are a few KiB. */\nconst PROBE_OUTPUT_LIMIT = 1024 * 1024;\n\nfunction escapeRegExp(text: string): string {\n return text.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * Whether a help screen lists a flag or subcommand. Flags (`--json`, `-p`)\n * must appear as a whole token — `--json` does not match `--json-schema`;\n * a bare word (`exec`) is matched as a whole word.\n *\n * @example\n * helpLists(\" -p, --print Print response\", \"--print\"); // true\n * helpLists(\" --output-format <format>\", \"--output\"); // false\n */\nexport function helpLists(help: string, flag: string): boolean {\n const escaped = escapeRegExp(flag);\n\n if (flag.startsWith(\"-\")) {\n return new RegExp(`(^|[\\\\s,\\\\[(|/\"'\\`])${escaped}(?=$|[\\\\s,=\\\\])|<\\\\[.:;\"'\\`])`, \"m\").test(\n help,\n );\n }\n\n return new RegExp(`(^|[^\\\\w-])${escaped}(?=$|[^\\\\w-])`, \"m\").test(help);\n}\n\n/** The first version-looking token of `--version` output, else its first line. */\nexport function parseVersion(output: string): string {\n const match = /\\d+\\.\\d+(?:\\.\\d+)?(?:[-+][0-9A-Za-z.-]+)?/.exec(output);\n\n if (match) {\n return match[0];\n }\n\n const firstLine = output.trim().split(/\\r?\\n/)[0]?.trim();\n\n return firstLine && firstLine.length > 0 ? firstLine : \"unknown\";\n}\n\n/** Flags a plan requires that the help screen does not list. */\nexport function missingFlags(help: string, required: readonly string[]): string[] {\n return required.filter((flag) => !helpLists(help, flag));\n}\n\ntype CaptureInput = {\n target: SpawnTarget;\n args: string[];\n env: Record<string, string>;\n cwd: string;\n comspec: string;\n platform: NodeJS.Platform;\n};\n\n/** Run a probe invocation and capture stdout + stderr (help is printed to either). */\nfunction capture(\n input: CaptureInput,\n): Promise<{ output: string; exitCode: number | null; error?: Error }> {\n return new Promise((resolve) => {\n const invocation = buildInvocation(input.target, input.args, input.comspec);\n\n if (\"refused\" in invocation) {\n resolve({ output: \"\", exitCode: null, error: new Error(invocation.refused) });\n\n return;\n }\n\n const child = spawn(invocation.file, invocation.args, {\n cwd: input.cwd,\n env: input.env,\n shell: false,\n windowsHide: true,\n windowsVerbatimArguments: invocation.windowsVerbatimArguments,\n detached: input.platform !== \"win32\",\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n\n const chunks: Buffer[] = [];\n let size = 0;\n let settled = false;\n\n const collect = (chunk: Buffer): void => {\n if (size < PROBE_OUTPUT_LIMIT) {\n chunks.push(chunk);\n size += chunk.length;\n }\n };\n\n const timer = setTimeout(() => {\n killProcessTree(child, input.platform, 0);\n }, PROBE_TIMEOUT_MS);\n\n const finish = (exitCode: number | null, error?: Error): void => {\n if (settled) {\n return;\n }\n\n settled = true;\n clearTimeout(timer);\n resolve({ output: Buffer.concat(chunks).toString(\"utf8\"), exitCode, error });\n };\n\n child.stdout?.on(\"data\", collect);\n child.stderr?.on(\"data\", collect);\n child.on(\"error\", (error) => finish(null, error));\n child.on(\"close\", (code) => finish(code));\n });\n}\n\nexport type ProbeInput = Omit<CaptureInput, \"args\"> & { adapter: CliAdapter };\n\n/**\n * Read the CLI's version and help screens. A help invocation that cannot\n * run at all (spawn error, no output) fails the probe; a non-zero exit with\n * output is accepted, because several CLIs exit 1 after printing help.\n */\nexport async function probeCli(input: ProbeInput): Promise<CliProbeResult> {\n const { adapter } = input;\n const versionRun = await capture({ ...input, args: adapter.probe.version });\n\n if (versionRun.error !== undefined) {\n throw new CliError(\n `${adapter.title}: could not run \"${input.target.executable} ${adapter.probe.version.join(\" \")}\": ${versionRun.error.message}`,\n {\n type: \"probe-failed\",\n adapter: adapter.name,\n executable: input.target.executable,\n cause: versionRun.error,\n },\n );\n }\n\n const version = parseVersion(versionRun.output);\n const helps: string[] = [];\n\n for (const args of adapter.probe.help) {\n const helpRun = await capture({ ...input, args });\n\n if (helpRun.error !== undefined || helpRun.output.trim().length === 0) {\n throw new CliError(\n `${adapter.title} ${version}: \"${input.target.executable} ${args.join(\" \")}\" printed no help` +\n (helpRun.error ? ` (${helpRun.error.message})` : \"\") +\n \"; the capability probe cannot verify the flags this adapter needs.\",\n {\n type: \"probe-failed\",\n adapter: adapter.name,\n version,\n executable: input.target.executable,\n cause: helpRun.error,\n },\n );\n }\n\n helps.push(helpRun.output);\n }\n\n return { executable: input.target.executable, version, help: helps.join(\"\\n\") };\n}\n\n/** Throw a `capability` error naming the first required flag the help does not list. */\nexport function assertCapabilities(\n adapter: CliAdapter,\n probe: CliProbeResult,\n required: readonly string[],\n): void {\n const missing = missingFlags(probe.help, required);\n const flag = missing[0];\n\n if (flag === undefined) {\n return;\n }\n\n const helpCommands = adapter.probe.help\n .map((args) => `${adapter.command} ${args.join(\" \")}`)\n .join(\", \");\n\n throw new CliError(\n `${adapter.title} ${probe.version} (${probe.executable}) does not support ${missing.join(\", \")}: ` +\n `not listed in \"${helpCommands}\". This adapter was verified against ${adapter.title} ` +\n `${adapter.verification.version}; install a compatible version or drop the option that needs ${flag}.`,\n {\n type: \"capability\",\n adapter: adapter.name,\n flag,\n version: probe.version,\n executable: probe.executable,\n },\n );\n}\n","/**\n * Variables a CLI needs to start at all: executable lookup, home and temp\n * directories, locale, TLS/proxy settings and the Windows system set.\n * Passed through even with `inheritEnv: false`.\n */\nexport const MINIMAL_ENV = [\n \"PATH\",\n \"PATHEXT\",\n \"HOME\",\n \"USERPROFILE\",\n \"HOMEDRIVE\",\n \"HOMEPATH\",\n \"APPDATA\",\n \"LOCALAPPDATA\",\n \"SYSTEMROOT\",\n \"SYSTEMDRIVE\",\n \"WINDIR\",\n \"COMSPEC\",\n \"TEMP\",\n \"TMP\",\n \"TMPDIR\",\n \"LANG\",\n \"LC_ALL\",\n \"LC_CTYPE\",\n \"TERM\",\n \"SHELL\",\n \"USER\",\n \"LOGNAME\",\n \"XDG_RUNTIME_DIR\",\n \"HTTP_PROXY\",\n \"HTTPS_PROXY\",\n \"NO_PROXY\",\n \"http_proxy\",\n \"https_proxy\",\n \"no_proxy\",\n \"NODE_EXTRA_CA_CERTS\",\n \"SSL_CERT_FILE\",\n \"SSL_CERT_DIR\",\n] as const;\n\nexport type BuildEnvironmentInput = {\n source: Record<string, string | undefined>;\n inherit: boolean | readonly string[];\n /** Variables the adapter manages (config home); never inherited from `source`. */\n managed: readonly string[];\n /** Adapter plan variables (config home, …). */\n plan?: Record<string, string>;\n /** Caller variables; win over everything else. */\n user?: Record<string, string>;\n /** API key and the variable it goes to. */\n apiKey?: { name: string; value: string };\n platform: NodeJS.Platform;\n};\n\n/**\n * Build a CLI's environment. Precedence, lowest first: inherited variables\n * (minus the adapter's managed home variables), the adapter plan, the API\n * key, then the caller's `env`. Windows variable names compare\n * case-insensitively.\n */\nexport function buildEnvironment(input: BuildEnvironmentInput): Record<string, string> {\n const normalize = (name: string): string =>\n input.platform === \"win32\" ? name.toUpperCase() : name;\n const managed = new Set(input.managed.map(normalize));\n const allowed =\n input.inherit === true\n ? undefined\n : new Set([...MINIMAL_ENV, ...(input.inherit === false ? [] : input.inherit)].map(normalize));\n\n const environment: Record<string, string> = {};\n\n for (const [name, value] of Object.entries(input.source)) {\n if (value === undefined || managed.has(normalize(name))) {\n continue;\n }\n\n if (allowed !== undefined && !allowed.has(normalize(name))) {\n continue;\n }\n\n environment[name] = value;\n }\n\n const assign = (name: string, value: string): void => {\n if (input.platform === \"win32\") {\n for (const existing of Object.keys(environment)) {\n if (existing.toUpperCase() === name.toUpperCase()) {\n delete environment[existing];\n }\n }\n }\n\n environment[name] = value;\n };\n\n for (const [name, value] of Object.entries(input.plan ?? {})) {\n assign(name, value);\n }\n\n if (input.apiKey !== undefined) {\n assign(input.apiKey.name, input.apiKey.value);\n }\n\n for (const [name, value] of Object.entries(input.user ?? {})) {\n assign(name, value);\n }\n\n return environment;\n}\n","import { chmod, mkdir, mkdtemp, rm, writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport path from \"node:path\";\nimport type { CliHome, CliLaunchFile } from \"../contracts\";\n\n/** The directories one run uses. */\nexport type RunDirectories = {\n /** Private per-run directory (0700) for run-scoped files. */\n runDir: string;\n /** The CLI's config home, or `undefined` for `home: \"inherit\"`. */\n home?: string;\n /** Whether `home` lives inside `runDir` (created for this run, deleted after it). */\n homeIsPrivate: boolean;\n /** Remove everything this run created. Never touches a caller-owned home. */\n dispose(): Promise<void>;\n};\n\n/**\n * Create the run's private directory and resolve its config home.\n *\n * The run directory is `mkdtemp`'d under the OS temp dir with mode 0700, so\n * other local users cannot read the MCP config (and the tokens in it)\n * written there. A `\"private\"` home is a `home/` folder inside it.\n */\nexport async function createRunDirectories(home: CliHome, cwd: string): Promise<RunDirectories> {\n const runDir = await mkdtemp(path.join(tmpdir(), \"warlock-cli-\"));\n\n await chmod(runDir, 0o700);\n\n const dispose = async (): Promise<void> => {\n await rm(runDir, { recursive: true, force: true });\n };\n\n if (home === \"inherit\") {\n return { runDir, homeIsPrivate: false, dispose };\n }\n\n if (home === \"private\") {\n const privateHome = path.join(runDir, \"home\");\n\n await mkdir(privateHome, { mode: 0o700 });\n\n return { runDir, home: privateHome, homeIsPrivate: true, dispose };\n }\n\n const ownedHome = path.resolve(cwd, home);\n\n await mkdir(ownedHome, { recursive: true, mode: 0o700 });\n\n return { runDir, home: ownedHome, homeIsPrivate: false, dispose };\n}\n\n/**\n * Write launch files with owner-only permissions (0600; parent directories\n * 0700). Only paths inside the run directory or a private home are\n * accepted, so an adapter can never overwrite a file in a caller-owned\n * home or elsewhere on disk.\n */\nexport async function writeLaunchFiles(\n files: readonly CliLaunchFile[],\n directories: RunDirectories,\n): Promise<void> {\n const roots = [directories.runDir];\n\n for (const file of files) {\n const target = path.resolve(file.path);\n const inside = roots.some((root) => {\n const relative = path.relative(root, target);\n\n return relative.length > 0 && !relative.startsWith(\"..\") && !path.isAbsolute(relative);\n });\n\n if (!inside) {\n throw new Error(\n `Refusing to write ${target}: launch files must live inside the run directory.`,\n );\n }\n\n await mkdir(path.dirname(target), { recursive: true, mode: 0o700 });\n await writeFile(target, file.content, { mode: 0o600 });\n await chmod(target, 0o600);\n }\n}\n","/**\n * An append-only event log that any number of async iterators can read.\n * Each iterator starts at the first event and ends once the log is closed\n * and drained, so a late consumer still sees the whole session.\n */\nexport class EventLog<T> implements AsyncIterable<T> {\n private readonly items: T[] = [];\n private closed = false;\n private waiters: Array<() => void> = [];\n\n public push(item: T): void {\n if (this.closed) {\n return;\n }\n\n this.items.push(item);\n this.wake();\n }\n\n public close(): void {\n this.closed = true;\n this.wake();\n }\n\n public get size(): number {\n return this.items.length;\n }\n\n public [Symbol.asyncIterator](): AsyncIterator<T> {\n let index = 0;\n\n return {\n next: async (): Promise<IteratorResult<T>> => {\n while (index >= this.items.length && !this.closed) {\n await new Promise<void>((resolve) => this.waiters.push(resolve));\n }\n\n if (index < this.items.length) {\n const value = this.items[index] as T;\n\n index += 1;\n\n return { value, done: false };\n }\n\n return { value: undefined, done: true };\n },\n };\n }\n\n private wake(): void {\n const waiters = this.waiters;\n\n this.waiters = [];\n\n for (const waiter of waiters) {\n waiter();\n }\n }\n}\n","import { StringDecoder } from \"node:string_decoder\";\n\n/** Longest line kept in memory; a longer one is dropped (reported via `onOverflow`). */\nexport const MAX_LINE_BYTES = 32 * 1024 * 1024;\n\n/**\n * Split a byte stream into lines. Multi-byte UTF-8 characters split across\n * chunks are decoded correctly, `\\r\\n` and `\\n` both end a line, and a final\n * line without a newline is flushed by `end()`.\n *\n * @example\n * const splitter = createLineSplitter((line) => console.log(line));\n * splitter.write(Buffer.from('{\"a\":1}\\n{\"b\"'));\n * splitter.write(Buffer.from(\":2}\\n\"));\n * splitter.end();\n */\nexport function createLineSplitter(\n onLine: (line: string) => void,\n onOverflow: () => void = () => undefined,\n): { write(chunk: Buffer): void; end(): void } {\n const decoder = new StringDecoder(\"utf8\");\n let pending = \"\";\n let overflowed = false;\n\n const consume = (text: string): void => {\n pending += text;\n\n let newline = pending.indexOf(\"\\n\");\n\n while (newline !== -1) {\n const line = pending.slice(0, newline).replace(/\\r$/, \"\");\n\n pending = pending.slice(newline + 1);\n\n if (overflowed) {\n overflowed = false;\n } else {\n onLine(line);\n }\n\n newline = pending.indexOf(\"\\n\");\n }\n\n if (pending.length > MAX_LINE_BYTES) {\n pending = \"\";\n\n if (!overflowed) {\n overflowed = true;\n onOverflow();\n }\n }\n };\n\n return {\n write(chunk: Buffer): void {\n consume(decoder.write(chunk));\n },\n end(): void {\n consume(decoder.end());\n\n if (pending.length > 0 && !overflowed) {\n onLine(pending.replace(/\\r$/, \"\"));\n }\n\n pending = \"\";\n },\n };\n}\n","import type { CliParsedEvent, CliUsage } from \"../contracts\";\n\nfunction sum(a: number | undefined, b: number | undefined): number | undefined {\n return a === undefined && b === undefined ? undefined : (a ?? 0) + (b ?? 0);\n}\n\n/** Add two usages field by field; optional fields stay absent unless either side has them. */\nexport function addUsage(left: CliUsage | undefined, right: CliUsage): CliUsage {\n if (left === undefined) {\n return { ...right };\n }\n\n const merged: CliUsage = {\n input: left.input + right.input,\n output: left.output + right.output,\n total: left.total + right.total,\n };\n\n const cachedTokens = sum(left.cachedTokens, right.cachedTokens);\n const cacheWriteTokens = sum(left.cacheWriteTokens, right.cacheWriteTokens);\n const reasoningTokens = sum(left.reasoningTokens, right.reasoningTokens);\n const costUSD = sum(left.costUSD, right.costUSD);\n\n if (cachedTokens !== undefined) merged.cachedTokens = cachedTokens;\n if (cacheWriteTokens !== undefined) merged.cacheWriteTokens = cacheWriteTokens;\n if (reasoningTokens !== undefined) merged.reasoningTokens = reasoningTokens;\n if (costUSD !== undefined) merged.costUSD = costUSD;\n\n return merged;\n}\n\n/**\n * Folds parsed events into the pieces of a `CliResult`: the session ref,\n * usage, every complete message, and the final answer.\n *\n * Final-answer rule: the last `final: true` message (the vendor's own\n * result record) wins; otherwise the newest assistant text — a complete\n * message, or the deltas streamed since the last message or tool activity.\n */\nexport class ResultAggregator {\n public sessionRef?: string;\n public usage?: CliUsage;\n public readonly messages: string[] = [];\n public fatalError?: string;\n private finalText?: string;\n private deltaBuffer = \"\";\n private lastCompleteText?: string;\n\n public constructor(resume?: string) {\n this.sessionRef = resume;\n }\n\n public add(event: CliParsedEvent): void {\n switch (event.type) {\n case \"session.started\":\n if (event.sessionRef) {\n this.sessionRef = event.sessionRef;\n }\n break;\n case \"message\":\n if (event.delta) {\n this.deltaBuffer += event.text;\n break;\n }\n\n if (event.final) {\n this.finalText = event.text;\n break;\n }\n\n this.messages.push(event.text);\n this.lastCompleteText = event.text;\n this.deltaBuffer = \"\";\n break;\n case \"tool.call\":\n case \"tool.result\":\n this.flushDeltas();\n break;\n case \"usage\":\n this.usage = event.cumulative ? { ...event.usage } : addUsage(this.usage, event.usage);\n break;\n case \"error\":\n if (event.fatal && this.fatalError === undefined) {\n this.fatalError = event.message;\n }\n break;\n }\n }\n\n /** Close the stream: deltas never followed by a complete message count as one. */\n public finish(): void {\n this.flushDeltas();\n }\n\n public get text(): string {\n if (this.finalText !== undefined) {\n return this.finalText;\n }\n\n return this.deltaBuffer.length > 0 ? this.deltaBuffer : (this.lastCompleteText ?? \"\");\n }\n\n private flushDeltas(): void {\n if (this.deltaBuffer.trim().length > 0) {\n this.messages.push(this.deltaBuffer);\n this.lastCompleteText = this.deltaBuffer;\n }\n\n this.deltaBuffer = \"\";\n }\n}\n","import { spawn } from \"node:child_process\";\nimport type {\n CliEndStatus,\n CliEvent,\n CliParsedEvent,\n CliResult,\n CliSession,\n CliStreamParser,\n} from \"../contracts\";\nimport type { Invocation } from \"../spawn/invocation\";\nimport { killProcessTree } from \"../spawn/process-tree\";\nimport { EventLog } from \"../stream/event-log\";\nimport { createLineSplitter } from \"../stream/line-splitter\";\nimport { ResultAggregator } from \"./aggregate\";\n\n/** stderr kept for the result (the tail). */\nconst STDERR_LIMIT = 64 * 1024;\n\nexport type StartSessionInput = {\n adapter: string;\n invocation: Invocation;\n cwd: string;\n env: Record<string, string>;\n stdin?: string;\n parser: CliStreamParser;\n signal?: AbortSignal;\n timeoutMs?: number;\n killGraceMs: number;\n platform: NodeJS.Platform;\n resume?: string;\n /** Runs after the process exits and before `done()` resolves (removes the run directory). */\n cleanup: () => Promise<void>;\n};\n\n/**\n * Spawn the CLI and expose it as a {@link CliSession}: stdout lines go\n * through the adapter's parser into a replayable event log, and the\n * process's end becomes the `session.ended` event and the `done()` result.\n */\nexport function startSession(input: StartSessionInput): CliSession {\n const startedAt = Date.now();\n const log = new EventLog<CliEvent>();\n const aggregator = new ResultAggregator(input.resume);\n const controller = new AbortController();\n let stderr = \"\";\n let timedOut = false;\n let cancelled = false;\n // Every pipe has closed: the process group is gone and its id may be\n // reused by an unrelated process, so nothing may signal it any more.\n let closed = false;\n let spawnError: Error | undefined;\n\n const emit = (events: CliParsedEvent[]): void => {\n for (const event of events) {\n aggregator.add(event);\n log.push(event);\n }\n };\n\n const parse = (step: () => CliParsedEvent[]): void => {\n try {\n emit(step());\n } catch (error) {\n emit([\n {\n type: \"error\",\n message: `stream parser failed: ${error instanceof Error ? error.message : String(error)}`,\n },\n ]);\n }\n };\n\n const child = spawn(input.invocation.file, input.invocation.args, {\n cwd: input.cwd,\n env: input.env,\n shell: false,\n windowsHide: true,\n windowsVerbatimArguments: input.invocation.windowsVerbatimArguments,\n // POSIX: own process group, so cancellation reaps the whole tree.\n detached: input.platform !== \"win32\",\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n });\n\n let cancelPendingKill: (() => void) | undefined;\n\n const kill = (): void => {\n cancelPendingKill = killProcessTree(child, input.platform, input.killGraceMs);\n };\n\n const onAbort = (): void => {\n if (closed || timedOut || cancelled) {\n return;\n }\n\n cancelled = true;\n kill();\n };\n\n input.signal?.addEventListener(\"abort\", onAbort, { once: true });\n controller.signal.addEventListener(\"abort\", onAbort, { once: true });\n\n if (input.signal?.aborted) {\n onAbort();\n }\n\n const timer =\n input.timeoutMs !== undefined && input.timeoutMs > 0\n ? setTimeout(() => {\n if (cancelled) {\n return;\n }\n\n timedOut = true;\n kill();\n }, input.timeoutMs)\n : undefined;\n\n const splitter = createLineSplitter(\n (line) => parse(() => input.parser.line(line)),\n () => emit([{ type: \"error\", message: \"dropped an output line longer than 32 MiB\" }]),\n );\n\n child.stdout?.on(\"data\", (chunk: Buffer) => splitter.write(chunk));\n child.stderr?.on(\"data\", (chunk: Buffer) => {\n stderr = (stderr + chunk.toString(\"utf8\")).slice(-STDERR_LIMIT);\n });\n\n // A CLI that exits before reading its prompt closes the pipe; that EPIPE\n // must not crash the host process.\n child.stdin?.on(\"error\", () => undefined);\n child.stdin?.end(input.stdin ?? \"\");\n\n const done = new Promise<CliResult>((resolve) => {\n let settled = false;\n\n const settle = async (exitCode: number | null, signal: string | null): Promise<void> => {\n if (settled) {\n return;\n }\n\n settled = true;\n\n if (timer !== undefined) {\n clearTimeout(timer);\n }\n\n input.signal?.removeEventListener(\"abort\", onAbort);\n controller.signal.removeEventListener(\"abort\", onAbort);\n splitter.end();\n parse(() => input.parser.end());\n aggregator.finish();\n\n const lateRef = input.parser.sessionRef?.();\n\n if (lateRef !== undefined && lateRef.length > 0) {\n aggregator.sessionRef = lateRef;\n }\n\n const status: CliEndStatus = cancelled\n ? \"cancelled\"\n : timedOut\n ? \"timeout\"\n : spawnError === undefined && exitCode === 0 && aggregator.fatalError === undefined\n ? \"completed\"\n : \"failed\";\n\n let error: string | undefined;\n\n if (status === \"failed\") {\n error =\n aggregator.fatalError ??\n (spawnError\n ? `could not start ${input.invocation.file}: ${spawnError.message}`\n : `${input.adapter} exited with ${signal ?? `code ${exitCode}`}` +\n (stderr.trim() ? `: ${stderr.trim().slice(-2000)}` : \"\"));\n\n if (aggregator.fatalError === undefined) {\n emit([{ type: \"error\", message: error, fatal: true }]);\n }\n } else if (status === \"timeout\") {\n error = `${input.adapter} timed out after ${input.timeoutMs} ms`;\n } else if (status === \"cancelled\") {\n error = `${input.adapter} run was cancelled`;\n }\n\n const durationMs = Date.now() - startedAt;\n\n log.push({\n type: \"session.ended\",\n status,\n exitCode,\n signal,\n sessionRef: aggregator.sessionRef,\n durationMs,\n });\n log.close();\n\n try {\n await input.cleanup();\n } catch {\n // A leftover temp directory must not turn a finished run into a failure.\n }\n\n resolve({\n status,\n text: aggregator.text,\n messages: [...aggregator.messages],\n usage: aggregator.usage,\n sessionRef: aggregator.sessionRef,\n exitCode,\n signal,\n error,\n stderr,\n durationMs,\n });\n };\n\n child.on(\"error\", (error) => {\n // Only a failed spawn ends the session here; any other 'error' (a\n // failed kill) is followed by the real 'close'.\n if (child.pid === undefined) {\n closed = true;\n spawnError = error;\n void settle(null, null);\n }\n });\n\n child.on(\"close\", (code, signal) => {\n // Every pipe is closed: the tree is gone, so the delayed SIGKILL for\n // this process group must not fire, and a later cancel() or abort\n // must not signal it (the pid may already belong to someone else).\n closed = true;\n cancelPendingKill?.();\n void settle(code, signal);\n });\n });\n\n return {\n adapter: input.adapter,\n pid: child.pid,\n events: log,\n done: () => done,\n cancel: () => controller.abort(),\n };\n}\n\n/**\n * A session for a run whose signal was already aborted: nothing is spawned,\n * the stream is a single `session.ended`, and `done()` resolves `cancelled`.\n */\nexport function cancelledSession(adapter: string, resume?: string): CliSession {\n const log = new EventLog<CliEvent>();\n const error = `${adapter} run was cancelled before it started`;\n\n log.push({\n type: \"session.ended\",\n status: \"cancelled\",\n exitCode: null,\n signal: null,\n sessionRef: resume,\n durationMs: 0,\n });\n log.close();\n\n const result: CliResult = {\n status: \"cancelled\",\n text: \"\",\n messages: [],\n sessionRef: resume,\n exitCode: null,\n signal: null,\n error,\n stderr: \"\",\n durationMs: 0,\n };\n\n return {\n adapter,\n pid: undefined,\n events: log,\n done: () => Promise.resolve(result),\n cancel: () => undefined,\n };\n}\n","import path from \"node:path\";\n\n/**\n * Host facts the resolver needs, injected so every rule is a pure function\n * that tests can drive for Windows on any OS.\n */\nexport type CommandLookup = {\n platform: NodeJS.Platform;\n env: Record<string, string | undefined>;\n /** Whether a regular, runnable file exists at this absolute path. */\n isFile(filePath: string): boolean;\n /** Read a small text file (used only for npm `.cmd` shims). */\n readFile(filePath: string): string | undefined;\n /** Node binary used to run a JavaScript entry behind an npm shim. */\n execPath: string;\n};\n\n/**\n * How to start a resolved command.\n *\n * - `direct` — spawn `file` with `prefixArgs` + the CLI's argv, no shell.\n * - `cmd` — a batch file Node cannot spawn without a shell (Node refuses\n * `.cmd`/`.bat` since CVE-2024-27980); it runs through `cmd.exe` with\n * every argument quoted (see {@link buildInvocation}).\n */\nexport type SpawnTarget =\n | { type: \"direct\"; file: string; prefixArgs: string[]; executable: string }\n | { type: \"cmd\"; file: string; executable: string };\n\n/** Windows' default `PATHEXT` when the variable is unset. */\nconst DEFAULT_PATHEXT = \".COM;.EXE;.BAT;.CMD\";\n\n/** Case-insensitive read on Windows (`Path` vs `PATH`), exact elsewhere. */\nexport function readEnv(\n env: Record<string, string | undefined>,\n name: string,\n platform: NodeJS.Platform,\n): string | undefined {\n if (platform !== \"win32\") {\n return env[name];\n }\n\n const wanted = name.toUpperCase();\n\n for (const [key, value] of Object.entries(env)) {\n if (key.toUpperCase() === wanted && value !== undefined) {\n return value;\n }\n }\n\n return undefined;\n}\n\nfunction pathApi(platform: NodeJS.Platform): typeof path.posix {\n return platform === \"win32\" ? path.win32 : path.posix;\n}\n\n/**\n * Find an executable the way the platform's shell would.\n *\n * POSIX walks `PATH`. Windows walks `PATH` trying each `PATHEXT` extension\n * (`claude` → `claude.cmd`), and also accepts a name that already carries\n * one of those extensions. A command containing a path separator is\n * checked directly instead of searched.\n *\n * @example\n * findExecutable(\"claude\", { platform: \"win32\", env: { PATH: \"C:\\\\npm\", PATHEXT: \".EXE;.CMD\" }, ... });\n * // → \"C:\\\\npm\\\\claude.cmd\"\n */\nexport function findExecutable(command: string, lookup: CommandLookup): string | undefined {\n const api = pathApi(lookup.platform);\n const isWindows = lookup.platform === \"win32\";\n const extensions = isWindows\n ? (readEnv(lookup.env, \"PATHEXT\", \"win32\") ?? DEFAULT_PATHEXT)\n .split(\";\")\n .map((extension) => extension.trim())\n .filter((extension) => extension.length > 0)\n : [];\n\n const candidatesFor = (base: string): string[] => {\n if (!isWindows) {\n return [base];\n }\n\n const hasKnownExtension = extensions.some((extension) =>\n base.toUpperCase().endsWith(extension.toUpperCase()),\n );\n const withExtensions = extensions.map((extension) => base + extension.toLowerCase());\n\n return hasKnownExtension ? [base, ...withExtensions] : withExtensions;\n };\n\n const hasSeparator = isWindows ? /[\\\\/]/.test(command) : command.includes(\"/\");\n\n if (hasSeparator || api.isAbsolute(command)) {\n return candidatesFor(api.resolve(command)).find((candidate) => lookup.isFile(candidate));\n }\n\n const searchPath = readEnv(lookup.env, \"PATH\", lookup.platform) ?? \"\";\n const directories = searchPath\n .split(isWindows ? \";\" : \":\")\n .map((directory) => directory.trim().replace(/^\"(.*)\"$/, \"$1\"))\n .filter((directory) => directory.length > 0);\n\n for (const directory of directories) {\n for (const candidate of candidatesFor(api.join(directory, command))) {\n if (lookup.isFile(candidate)) {\n return candidate;\n }\n }\n }\n\n return undefined;\n}\n\n/** What an npm/pnpm `.cmd` shim launches. */\nexport type CmdShimTarget = { type: \"node\"; script: string } | { type: \"native\"; file: string };\n\n/**\n * Read the target of an npm (`cmd-shim`) or pnpm `.cmd` shim.\n *\n * Both generators end the shim with a line that runs the target with `%*`;\n * the target is a quoted path relative to the shim's own directory\n * (`\"%dp0%\\node_modules\\pkg\\cli.js\"` for npm, `\"%~dp0\\..\\pkg\\cli.js\"` for\n * pnpm). A JavaScript target is run by Node; an `.exe`/`.com` target is run\n * directly. Anything else returns `undefined` and the caller falls back to\n * `cmd.exe`.\n */\nexport function parseCmdShim(content: string, shimPath: string): CmdShimTarget | undefined {\n const directory = path.win32.dirname(shimPath);\n const lines = content.split(/\\r?\\n/).filter((line) => line.includes(\"%*\"));\n const line = lines.at(-1);\n\n if (line === undefined) {\n return undefined;\n }\n\n const quoted = [...line.matchAll(/\"(%~?dp0%?[\\\\/][^\"]+)\"/gi)]\n .map((match) => match[1] ?? \"\")\n .filter((target) => !/[\\\\/]node(\\.exe)?$/i.test(target));\n const raw = quoted.at(-1);\n\n if (raw === undefined) {\n return undefined;\n }\n\n const relative = raw.replace(/^%~?dp0%?[\\\\/]/i, \"\");\n const target = path.win32.resolve(directory, relative);\n\n if (/\\.(c|m)?js$/i.test(target)) {\n return { type: \"node\", script: target };\n }\n\n if (/\\.(exe|com)$/i.test(target)) {\n return { type: \"native\", file: target };\n }\n\n return undefined;\n}\n\n/**\n * Resolve a command to something `child_process.spawn` can start without a\n * shell. On Windows a `.cmd`/`.bat` npm shim is unwrapped to\n * `node <script>` (or its native `.exe`), so argv reaches the CLI intact\n * with no `cmd.exe` parsing in between; any other batch file falls back\n * to `cmd.exe`.\n */\nexport function resolveSpawnTarget(\n command: string,\n lookup: CommandLookup,\n): SpawnTarget | undefined {\n const executable = findExecutable(command, lookup);\n\n if (executable === undefined) {\n return undefined;\n }\n\n if (lookup.platform !== \"win32\" || !/\\.(cmd|bat)$/i.test(executable)) {\n return { type: \"direct\", file: executable, prefixArgs: [], executable };\n }\n\n const shim = parseCmdShim(lookup.readFile(executable) ?? \"\", executable);\n\n if (shim?.type === \"node\") {\n const bundledNode = path.win32.join(path.win32.dirname(executable), \"node.exe\");\n const node = lookup.isFile(bundledNode) ? bundledNode : lookup.execPath;\n\n return { type: \"direct\", file: node, prefixArgs: [shim.script], executable };\n }\n\n if (shim?.type === \"native\" && lookup.isFile(shim.file)) {\n return { type: \"direct\", file: shim.file, prefixArgs: [], executable };\n }\n\n return { type: \"cmd\", file: executable, executable };\n}\n","import { accessSync, constants, readFileSync, statSync } from \"node:fs\";\nimport path from \"node:path\";\nimport type {\n CliAdapter,\n CliAgentOptions,\n CliLaunchContext,\n CliLaunchPlan,\n CliProbeResult,\n CliRunOptions,\n CliSession,\n} from \"./contracts\";\nimport type { ModelContract } from \"@warlock.js/ai\";\nimport { CliError } from \"./errors\";\nimport { type CliModelConfig, cliModel } from \"./model/cli-model\";\nimport { assertCapabilities, probeCli } from \"./probe/probe\";\nimport { buildEnvironment } from \"./session/environment\";\nimport { createRunDirectories, writeLaunchFiles } from \"./session/run-directory\";\nimport { cancelledSession, startSession } from \"./session/session\";\nimport { buildInvocation, fitsCommandLine, type Invocation } from \"./spawn/invocation\";\nimport {\n type CommandLookup,\n readEnv,\n resolveSpawnTarget,\n type SpawnTarget,\n} from \"./spawn/resolve-command\";\n\n/** A configured coding CLI: run prompts, probe the binary, or use it as an `ai.agent` model. */\nexport type CliAgent = {\n readonly adapter: CliAdapter;\n readonly options: Readonly<CliAgentOptions>;\n /**\n * Start a session. Rejects (with {@link CliError}) only for setup problems\n * — executable not found, a flag missing from `--help`, an unsupported\n * option; the run's own outcome is reported by `session.done()`.\n */\n run(prompt: string, options?: CliRunOptions): Promise<CliSession>;\n /** Run (or reuse) the capability probe: resolved executable, version and help text. */\n probe(): Promise<CliProbeResult>;\n /** This CLI as an `ai.agent` model (see {@link cliModel}). */\n model(config?: CliModelConfig): ModelContract;\n};\n\n/** Host facts, injectable for tests. */\nexport type CliHost = CommandLookup & { comspec: string };\n\nfunction isRunnableFile(filePath: string, platform: NodeJS.Platform): boolean {\n try {\n if (!statSync(filePath).isFile()) {\n return false;\n }\n\n if (platform !== \"win32\") {\n accessSync(filePath, constants.X_OK);\n }\n\n return true;\n } catch {\n return false;\n }\n}\n\n/** The current machine as a {@link CliHost}. */\nexport function currentHost(): CliHost {\n const platform = process.platform;\n\n return {\n platform,\n env: process.env,\n isFile: (filePath) => isRunnableFile(filePath, platform),\n readFile: (filePath) => {\n try {\n return readFileSync(filePath, \"utf8\");\n } catch {\n return undefined;\n }\n },\n execPath: process.execPath,\n comspec: readEnv(process.env, \"ComSpec\", platform) ?? \"cmd.exe\",\n };\n}\n\nfunction unsupported(adapter: CliAdapter, message: string): CliError {\n return new CliError(`${adapter.title}: ${message}`, {\n type: \"unsupported-option\",\n adapter: adapter.name,\n });\n}\n\n/**\n * Create a CLI agent from an adapter. The vendor factories\n * (`cli.claudeCode(...)`, `cli.codex(...)`, …) call this with their\n * built-in adapter; call it directly with your own {@link CliAdapter}.\n *\n * @example\n * const agent = createCliAgent(myAdapter, { model: \"fast\", permission: \"standard\" });\n * const session = await agent.run(\"Summarize README.md\", { cwd: \"/srv/repo\" });\n * console.log((await session.done()).text);\n */\nexport function createCliAgent(\n adapter: CliAdapter,\n options: CliAgentOptions = {},\n host: CliHost = currentHost(),\n): CliAgent {\n const probes = new Map<string, Promise<CliProbeResult>>();\n const command = options.command ?? adapter.command;\n\n const resolveTarget = (): SpawnTarget => {\n const target = resolveSpawnTarget(command, host);\n\n if (target === undefined) {\n throw new CliError(\n `${adapter.title}: could not find \"${command}\" on PATH. Install the CLI or pass its absolute path as \\`command\\`.`,\n { type: \"not-found\", adapter: adapter.name },\n );\n }\n\n return target;\n };\n\n const probeEnvironment = (): Record<string, string> =>\n buildEnvironment({\n source: host.env,\n inherit: options.inheritEnv ?? true,\n managed: [],\n user: options.env,\n platform: host.platform,\n });\n\n const probeTarget = (target: SpawnTarget): Promise<CliProbeResult> => {\n const cached = probes.get(target.executable);\n\n if (cached !== undefined) {\n return cached;\n }\n\n const pending = probeCli({\n adapter,\n target,\n env: probeEnvironment(),\n cwd: path.resolve(options.cwd ?? process.cwd()),\n comspec: host.comspec,\n platform: host.platform,\n });\n\n probes.set(target.executable, pending);\n // A failed probe is retried on the next run instead of being cached.\n pending.catch(() => probes.delete(target.executable));\n\n return pending;\n };\n\n const run = async (prompt: string, runOptions: CliRunOptions = {}): Promise<CliSession> => {\n const merged: CliRunOptions = {\n ...options,\n ...runOptions,\n env: { ...options.env, ...runOptions.env },\n args: [...(options.args ?? []), ...(runOptions.args ?? [])],\n mcp: runOptions.mcp ?? options.mcp,\n };\n const permission = merged.permission ?? \"standard\";\n\n if (permission !== \"standard\" && permission !== \"bypass\") {\n throw unsupported(\n adapter,\n `unknown permission \"${String(permission)}\" (use \"standard\" or \"bypass\").`,\n );\n }\n\n if (merged.effort !== undefined && adapter.effort !== true) {\n throw unsupported(adapter, \"this CLI has no reasoning-effort control; drop `effort`.\");\n }\n\n const mcp =\n merged.mcp !== undefined && Object.keys(merged.mcp).length > 0 ? merged.mcp : undefined;\n\n if (mcp !== undefined && adapter.mcp !== true) {\n throw unsupported(adapter, \"this CLI cannot attach per-run MCP servers; drop `mcp`.\");\n }\n\n if (merged.apiKey !== undefined && adapter.apiKeyEnv.length === 0) {\n throw unsupported(adapter, \"this CLI reads no API key from the environment; drop `apiKey`.\");\n }\n\n const home = options.home ?? \"private\";\n\n if (home !== \"inherit\" && adapter.homeEnv.length === 0) {\n throw unsupported(\n adapter,\n 'this CLI cannot relocate its config home; use `home: \"inherit\"`.',\n );\n }\n\n const cwd = path.resolve(merged.cwd ?? process.cwd());\n const target = resolveTarget();\n const probe = options.probe === false ? undefined : await probeTarget(target);\n\n if (merged.signal?.aborted) {\n return cancelledSession(adapter.name, merged.resume);\n }\n\n const directories = await createRunDirectories(home, cwd);\n\n try {\n let chosen:\n | { plan: CliLaunchPlan; invocation: Invocation; context: CliLaunchContext }\n | undefined;\n const reasons: string[] = [];\n\n for (const transport of adapter.transports) {\n const context: CliLaunchContext = {\n prompt,\n transport,\n cwd,\n model: merged.model,\n effort: merged.effort,\n permission,\n resume: merged.resume,\n mcp,\n apiKey: merged.apiKey,\n home: directories.home,\n homeIsPrivate: directories.homeIsPrivate,\n runDir: directories.runDir,\n platform: host.platform,\n };\n const plan = adapter.plan(context);\n\n if (probe !== undefined) {\n assertCapabilities(adapter, probe, plan.requires);\n }\n\n const invocation = buildInvocation(\n target,\n [...plan.args, ...(merged.args ?? []), ...(plan.tail ?? [])],\n host.comspec,\n );\n\n if (\"refused\" in invocation) {\n reasons.push(`${transport}: ${invocation.refused}`);\n continue;\n }\n\n if (!fitsCommandLine(invocation, host.platform)) {\n reasons.push(`${transport}: the command line exceeds the platform limit`);\n continue;\n }\n\n chosen = { plan, invocation, context };\n break;\n }\n\n if (chosen === undefined) {\n throw new CliError(\n `${adapter.title}: the prompt cannot be passed to \"${target.executable}\" (${reasons.join(\"; \")}).`,\n { type: \"prompt-transport\", adapter: adapter.name, executable: target.executable },\n );\n }\n\n await writeLaunchFiles(chosen.plan.files ?? [], directories);\n\n const apiKeyEnv = adapter.apiKeyEnv[0];\n const env = buildEnvironment({\n source: host.env,\n inherit: options.inheritEnv ?? true,\n managed: home === \"inherit\" ? [] : adapter.homeEnv,\n // A CLI that prefers $PWD over its real cwd must not see the host's.\n plan: host.platform === \"win32\" ? chosen.plan.env : { PWD: cwd, ...chosen.plan.env },\n user: merged.env,\n apiKey:\n merged.apiKey !== undefined && apiKeyEnv !== undefined\n ? { name: apiKeyEnv, value: merged.apiKey }\n : undefined,\n platform: host.platform,\n });\n\n return startSession({\n adapter: adapter.name,\n invocation: chosen.invocation,\n cwd,\n env,\n stdin: chosen.plan.stdin,\n parser: adapter.parser(chosen.context),\n signal: merged.signal,\n timeoutMs: merged.timeoutMs,\n killGraceMs: options.killGraceMs ?? 2000,\n platform: host.platform,\n resume: merged.resume,\n cleanup: directories.dispose,\n });\n } catch (error) {\n await directories.dispose();\n throw error;\n }\n };\n\n const agent: CliAgent = {\n adapter,\n options,\n run,\n probe: () => probeTarget(resolveTarget()),\n model: (config) => cliModel(agent, config),\n };\n\n return agent;\n}\n","import type { CliParsedEvent, CliStreamParser } from \"../contracts\";\n\n/** A plain JSON object. */\nexport type JsonRecord = Record<string, unknown>;\n\n/** `value` as a JSON object, or `undefined`. */\nexport function asRecord(value: unknown): JsonRecord | undefined {\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? (value as JsonRecord)\n : undefined;\n}\n\n/** `value` as an array, or an empty array. */\nexport function asArray(value: unknown): unknown[] {\n return Array.isArray(value) ? value : [];\n}\n\n/** A string field, or `undefined`. */\nexport function stringField(record: JsonRecord | undefined, key: string): string | undefined {\n const value = record?.[key];\n\n return typeof value === \"string\" ? value : undefined;\n}\n\n/** A finite number field, or `undefined`. */\nexport function numberField(record: JsonRecord | undefined, key: string): number | undefined {\n const value = record?.[key];\n\n return typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n}\n\n/** A nested object field, or `undefined`. */\nexport function recordField(record: JsonRecord | undefined, key: string): JsonRecord | undefined {\n return asRecord(record?.[key]);\n}\n\n/** Tool output as text: strings verbatim, text-block arrays joined, anything else as JSON. */\nexport function outputText(value: unknown): string {\n if (typeof value === \"string\") {\n return value;\n }\n\n if (value === undefined || value === null) {\n return \"\";\n }\n\n if (Array.isArray(value)) {\n const texts = value.map((item) => {\n const block = asRecord(item);\n const text = stringField(block, \"text\");\n\n return text ?? (typeof item === \"string\" ? item : JSON.stringify(item));\n });\n\n return texts.join(\"\\n\");\n }\n\n return JSON.stringify(value);\n}\n\n/** Parse one line as a JSON object; anything else (banners, blank lines) is `undefined`. */\nexport function parseJsonLine(line: string): JsonRecord | undefined {\n const trimmed = line.trim();\n\n if (!trimmed.startsWith(\"{\")) {\n return undefined;\n }\n\n try {\n return asRecord(JSON.parse(trimmed));\n } catch {\n return undefined;\n }\n}\n\n/**\n * Build a parser for a JSONL/NDJSON stream. Non-JSON lines (progress\n * banners, warnings) are skipped; each JSON object goes to `onRecord`.\n * `onEnd` may flush buffered state when stdout closes.\n *\n * @example\n * const parser = jsonLinesParser((record) =>\n * record.type === \"text\" ? [{ type: \"message\", text: String(record.text), delta: false }] : [],\n * );\n */\nexport function jsonLinesParser(\n onRecord: (record: JsonRecord) => CliParsedEvent[],\n onEnd: () => CliParsedEvent[] = () => [],\n): CliStreamParser {\n return {\n line(line: string): CliParsedEvent[] {\n const record = parseJsonLine(line);\n\n return record === undefined ? [] : onRecord(record);\n },\n end: onEnd,\n };\n}\n","/** A TOML value this writer supports. */\nexport type TomlValue = string | number | boolean | TomlValue[] | TomlTable;\n\n/** A TOML table. */\nexport type TomlTable = { [key: string]: TomlValue | undefined };\n\nfunction isTable(value: TomlValue): value is TomlTable {\n return typeof value === \"object\" && !Array.isArray(value);\n}\n\n/** A bare key when possible, else a quoted one. */\nexport function tomlKey(key: string): string {\n return /^[A-Za-z0-9_-]+$/.test(key) ? key : JSON.stringify(key);\n}\n\n/** A TOML scalar or inline value. JSON string escapes are valid TOML basic-string escapes. */\nfunction inlineValue(value: TomlValue): string {\n if (typeof value === \"string\") {\n return JSON.stringify(value);\n }\n\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) {\n throw new Error(\"TOML cannot encode a non-finite number\");\n }\n\n return String(value);\n }\n\n if (typeof value === \"boolean\") {\n return value ? \"true\" : \"false\";\n }\n\n if (Array.isArray(value)) {\n return `[${value.map(inlineValue).join(\", \")}]`;\n }\n\n const entries = Object.entries(value).filter(\n (entry): entry is [string, TomlValue] => entry[1] !== undefined,\n );\n\n return `{ ${entries.map(([key, item]) => `${tomlKey(key)} = ${inlineValue(item)}`).join(\", \")} }`;\n}\n\n/**\n * Serialize a table to TOML: scalars and arrays first, then each nested\n * table as a `[dotted.header]` section. Enough for the CLI config files\n * this package writes (Codex and Mistral Vibe MCP sections).\n *\n * @example\n * toToml({ mcp_servers: { docs: { command: \"npx\", args: [\"-y\", \"docs-mcp\"] } } });\n * // [mcp_servers.docs]\n * // command = \"npx\"\n * // args = [\"-y\", \"docs-mcp\"]\n */\nexport function toToml(table: TomlTable, prefix: string[] = []): string {\n const lines: string[] = [];\n const nested: Array<[string, TomlTable]> = [];\n\n for (const [key, value] of Object.entries(table)) {\n if (value === undefined) {\n continue;\n }\n\n if (isTable(value)) {\n nested.push([key, value]);\n continue;\n }\n\n lines.push(`${tomlKey(key)} = ${inlineValue(value)}`);\n }\n\n const sections: string[] = [];\n\n if (lines.length > 0) {\n sections.push(\n (prefix.length > 0 ? `[${prefix.map(tomlKey).join(\".\")}]\\n` : \"\") + lines.join(\"\\n\"),\n );\n }\n\n for (const [key, value] of nested) {\n const section = toToml(value, [...prefix, key]);\n\n if (section.length > 0) {\n sections.push(section.trimEnd());\n }\n }\n\n return sections.length > 0 ? `${sections.join(\"\\n\\n\")}\\n` : \"\";\n}\n","import path from \"node:path\";\nimport type { ReasoningEffort } from \"@warlock.js/ai\";\nimport type { CliLaunchContext, CliLaunchFile, CliMcpServers, CliUsage } from \"../contracts\";\nimport { CliError } from \"../errors\";\n\n/**\n * The prompt as an argv value. A prompt starting with `-` would be read as a\n * flag by the CLI's argument parser, so it gets one leading space (harmless\n * to the model, and no parser treats it as an option).\n */\nexport function argvPrompt(prompt: string): string {\n return prompt.startsWith(\"-\") ? ` ${prompt}` : prompt;\n}\n\n/** The prompt written to `prompt.txt` in the run directory, for `transport: \"file\"`. */\nexport function promptFile(context: CliLaunchContext): CliLaunchFile {\n return { path: path.join(context.runDir, \"prompt.txt\"), content: context.prompt };\n}\n\n/**\n * Fail closed when an option needs a file inside the CLI's config home but\n * the home is not private to this run (writing it into a caller-owned or\n * inherited home would leak tokens into it and race concurrent runs).\n */\nexport function requirePrivateHome(\n context: CliLaunchContext,\n adapter: { name: string; title: string },\n option: string,\n): string {\n if (context.home === undefined || !context.homeIsPrivate) {\n throw new CliError(\n `${adapter.title} reads ${option} only from its config home; use \\`home: \"private\"\\` (the default) for runs with ${option}.`,\n { type: \"unsupported-option\", adapter: adapter.name },\n );\n }\n\n return context.home;\n}\n\n/** A `.env` file body. Values are written verbatim; newlines are refused. */\nexport function dotenvFile(values: Record<string, string>): string {\n return Object.entries(values)\n .map(([name, value]) => {\n if (/[\\r\\n]/.test(value)) {\n throw new Error(`${name} contains a newline and cannot be written to a .env file`);\n }\n\n return `${name}=${value}`;\n })\n .join(\"\\n\")\n .concat(\"\\n\");\n}\n\n/** The framework effort scale, lowest first. */\nconst EFFORT_ORDER: readonly ReasoningEffort[] = [\n \"none\",\n \"minimal\",\n \"low\",\n \"medium\",\n \"high\",\n \"xhigh\",\n \"max\",\n];\n\n/**\n * Map a framework effort to a vendor's levels, following the framework\n * rule: an exact level wins; otherwise the nearest higher level the vendor\n * has (so `minimal` becomes `low`); a level above the vendor's highest is\n * clamped to it.\n *\n * @example\n * mapEffort(\"xhigh\", { low: \"low\", medium: \"medium\", high: \"high\" }); // \"high\"\n * mapEffort(\"minimal\", { low: \"low\", medium: \"medium\", high: \"high\" }); // \"low\"\n */\nexport function mapEffort(\n effort: ReasoningEffort,\n levels: Partial<Record<ReasoningEffort, string>>,\n): string {\n const exact = levels[effort];\n\n if (exact !== undefined) {\n return exact;\n }\n\n const requested = EFFORT_ORDER.indexOf(effort);\n const supported = EFFORT_ORDER.filter((level) => levels[level] !== undefined);\n const higher = supported.find((level) => EFFORT_ORDER.indexOf(level) > requested);\n const chosen = higher ?? supported.at(-1);\n const value = chosen === undefined ? undefined : levels[chosen];\n\n if (value === undefined) {\n throw new Error(\"mapEffort needs at least one vendor level\");\n }\n\n return value;\n}\n\n/**\n * The common `mcpServers` JSON shape (Claude Code, Cursor, Kimi, Droid,\n * Copilot, Amp, Qwen Code …): stdio servers as `command`/`args`/`env`,\n * remote servers as `url`/`headers`. `typeField` adds the `type` key the\n * vendor expects (`\"stdio\"`, `\"http\"`, `\"sse\"`), or a renamed remote\n * transport (`\"streamable-http\"`).\n */\nexport function mcpServersJson(\n servers: CliMcpServers,\n options: {\n /** Emit a `type` key on every server. */\n typeField?: boolean;\n /** Value of `type` for streamable HTTP servers. Default `\"http\"`. */\n httpType?: string;\n /** Extra keys merged into every server (for example `tools: [\"*\"]`). */\n extra?: Record<string, unknown>;\n /** Key holding a streamable-HTTP URL. Default `\"url\"`. */\n httpUrlKey?: string;\n } = {},\n): Record<string, Record<string, unknown>> {\n const rendered: Record<string, Record<string, unknown>> = {};\n\n for (const [name, server] of Object.entries(servers)) {\n if (server.type === \"stdio\") {\n rendered[name] = {\n ...(options.typeField ? { type: \"stdio\" } : {}),\n command: server.command,\n args: server.args ?? [],\n ...(server.env !== undefined ? { env: server.env } : {}),\n ...options.extra,\n };\n continue;\n }\n\n const urlKey = server.type === \"http\" ? (options.httpUrlKey ?? \"url\") : \"url\";\n\n rendered[name] = {\n ...(options.typeField\n ? { type: server.type === \"http\" ? (options.httpType ?? \"http\") : \"sse\" }\n : {}),\n [urlKey]: server.url,\n ...(server.headers !== undefined ? { headers: server.headers } : {}),\n ...options.extra,\n };\n }\n\n return rendered;\n}\n\n/** JSON for a config file, pretty-printed with a trailing newline. */\nexport function jsonFile(value: unknown): string {\n return `${JSON.stringify(value, null, 2)}\\n`;\n}\n\n/** Build a `CliUsage`, computing `total` when the vendor omits it. */\nexport function usageOf(fields: {\n input?: number;\n output?: number;\n total?: number;\n cachedTokens?: number;\n cacheWriteTokens?: number;\n reasoningTokens?: number;\n costUSD?: number;\n}): CliUsage {\n const input = fields.input ?? 0;\n const output = fields.output ?? 0;\n const usage: CliUsage = { input, output, total: fields.total ?? input + output };\n\n if (fields.cachedTokens !== undefined) usage.cachedTokens = fields.cachedTokens;\n if (fields.cacheWriteTokens !== undefined) usage.cacheWriteTokens = fields.cacheWriteTokens;\n if (fields.reasoningTokens !== undefined) usage.reasoningTokens = fields.reasoningTokens;\n if (fields.costUSD !== undefined) usage.costUSD = fields.costUSD;\n\n return usage;\n}\n\n/** The first `undefined`-free value. */\nexport function firstDefined<T>(...values: Array<T | undefined>): T | undefined {\n return values.find((value) => value !== undefined);\n}\n\n/** An `unsupported-option` error for an adapter. */\nexport function unsupportedOption(\n adapter: { name: string; title: string },\n message: string,\n): CliError {\n return new CliError(`${adapter.title}: ${message}`, {\n type: \"unsupported-option\",\n adapter: adapter.name,\n });\n}\n\n/** Parse a JSON-encoded tool-arguments string; keeps the raw string when it is not JSON. */\nexport function parseArguments(value: unknown): unknown {\n if (typeof value !== \"string\") {\n return value;\n }\n\n try {\n return JSON.parse(value) as unknown;\n } catch {\n return value;\n }\n}\n\n/**\n * Usage in the Anthropic Messages shape (`input_tokens` excludes cache reads\n * and writes, which are reported separately). `input` is the sum of all\n * three, matching the framework rule that `input` includes cached tokens.\n */\nexport function anthropicUsage(\n usage: Record<string, unknown> | undefined,\n costUSD?: number,\n): CliUsage | undefined {\n if (usage === undefined) {\n return undefined;\n }\n\n const read = (key: string): number | undefined => {\n const value = usage[key];\n\n return typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n };\n const uncached = read(\"input_tokens\") ?? 0;\n const cacheRead = read(\"cache_read_input_tokens\");\n const cacheWrite = read(\"cache_creation_input_tokens\");\n const output = read(\"output_tokens\") ?? 0;\n const input = uncached + (cacheRead ?? 0) + (cacheWrite ?? 0);\n\n return usageOf({\n input,\n output,\n cachedTokens: cacheRead !== undefined && cacheRead > 0 ? cacheRead : undefined,\n cacheWriteTokens: cacheWrite !== undefined && cacheWrite > 0 ? cacheWrite : undefined,\n reasoningTokens: read(\"reasoning_tokens\") || undefined,\n costUSD,\n });\n}\n","import { readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport type {\n CliAdapter,\n CliLaunchContext,\n CliLaunchFile,\n CliParsedEvent,\n CliStreamParser,\n} from \"../contracts\";\nimport { numberField, parseJsonLine, recordField, stringField } from \"../stream/json-lines\";\nimport { argvPrompt, mapEffort, promptFile, unsupportedOption, usageOf } from \"./shared\";\n\n/** Local analytics log the adapter asks Aider to write (exact token counts). */\nconst ANALYTICS_LOG = \"aider-analytics.jsonl\";\n\n/**\n * Aider (`aider`, PyPI `aider-chat`).\n *\n * Verified against the official docs (`aider.chat/docs/scripting.html`,\n * `/docs/config/options.html`, `/docs/config/reasoning.html`) and the\n * source at tag v0.86.2 (`aider/main.py`, `aider/args.py`,\n * `aider/coders/base_coder.py`, `aider/analytics.py`); Aider needs Python\n * 3.10+, so no real `--help` was run, 2026-10-17. The capability probe\n * checks every flag against the installed `--help`.\n *\n * - Headless: `aider --message <text>` (or `--message-file`). Aider has **no\n * machine-readable output**: the parser reads the plain-text stdout —\n * startup banner (`Main model: …`), the reply, the usage line\n * (`Tokens: 2.4k sent, 61 received. Cost: $0.0081 message, …`),\n * `Applied edit to <path>` (reported as an `edit` tool call) and\n * `Commit <hash> <message>`. Exact token counts and cost come from the\n * local `--analytics-log` file (`message_send` events), read when the\n * stream ends.\n * - Aider exits 0 even when the model call fails, so `litellm.*Error` lines\n * and the \"not able to authenticate you\" notice are reported as fatal.\n * - Permissions: Aider applies edits without approval and, headless with\n * `--yes-always`, never runs the shell commands it suggests; there is no\n * stricter or looser mode, so `standard` and `bypass` behave the same.\n * Auto-commits are turned off (`--no-auto-commits`); pass\n * `args: [\"--auto-commits\"]` to keep them.\n * - No session ids (`resume` is refused) and no MCP. Chat and input\n * history are written to the run directory, not the repository.\n * - Home: Aider uses `HOME`; provider keys use their own variables\n * (`OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, …) via `env`. Always pass\n * `model` — without one Aider may start an interactive OAuth flow.\n */\nexport const aiderAdapter: CliAdapter = {\n name: \"aider\",\n title: \"Aider\",\n command: \"aider\",\n apiKeyEnv: [],\n homeEnv: [\"HOME\", \"USERPROFILE\"],\n transports: [\"argv\", \"file\"],\n effort: true,\n mcp: false,\n probe: { help: [[\"--help\"]], version: [\"--version\"] },\n verification: {\n version: \"0.86.2\",\n verifiedBy: \"docs\",\n sources: [\n \"https://aider.chat/docs/scripting.html\",\n \"https://aider.chat/docs/config/options.html\",\n \"https://aider.chat/docs/config/reasoning.html\",\n \"https://github.com/Aider-AI/aider/tree/v0.86.2\",\n ],\n checkedAt: \"2026-10-17\",\n },\n plan(context) {\n if (context.resume !== undefined) {\n throw unsupportedOption(\n aiderAdapter,\n \"Aider has no session ids, so `resume` is not supported.\",\n );\n }\n\n const args = [\n \"--yes-always\",\n \"--no-pretty\",\n \"--no-stream\",\n \"--no-fancy-input\",\n \"--no-auto-commits\",\n \"--no-check-update\",\n \"--no-show-release-notes\",\n \"--no-analytics\",\n \"--no-show-model-warnings\",\n \"--no-gitignore\",\n \"--analytics-log\",\n path.join(context.runDir, ANALYTICS_LOG),\n \"--chat-history-file\",\n path.join(context.runDir, \"chat-history.md\"),\n \"--input-history-file\",\n path.join(context.runDir, \"input-history\"),\n ];\n const requires = [\n \"--yes-always\",\n \"--no-pretty\",\n \"--no-stream\",\n \"--no-auto-commits\",\n \"--analytics-log\",\n \"--chat-history-file\",\n \"--input-history-file\",\n ];\n const files: CliLaunchFile[] = [];\n let tail: string[];\n\n if (context.model !== undefined) {\n args.push(\"--model\", context.model);\n requires.push(\"--model\");\n }\n\n if (context.effort !== undefined) {\n args.push(\n \"--reasoning-effort\",\n mapEffort(context.effort, { low: \"low\", medium: \"medium\", high: \"high\" }),\n );\n requires.push(\"--reasoning-effort\");\n }\n\n if (context.transport === \"file\") {\n const prompt = promptFile(context);\n\n files.push(prompt);\n tail = [\"--message-file\", prompt.path];\n requires.push(\"--message-file\");\n } else {\n tail = [\"--message\", argvPrompt(context.prompt)];\n requires.push(\"--message\");\n }\n\n return {\n args,\n tail,\n env: {\n ...(context.home !== undefined ? { HOME: context.home, USERPROFILE: context.home } : {}),\n TERM: \"dumb\",\n },\n files,\n requires,\n };\n },\n parser: createAiderParser,\n};\n\n/** `2.4k` → 2400, `12k` → 12000, `61` → 61. */\nexport function parseAiderCount(value: string | undefined): number | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n const match = /^([\\d.]+)(k|M)?$/.exec(value.trim());\n\n if (!match) {\n return undefined;\n }\n\n const number = Number(match[1]);\n const scale = match[2] === \"k\" ? 1_000 : match[2] === \"M\" ? 1_000_000 : 1;\n\n return Number.isFinite(number) ? Math.round(number * scale) : undefined;\n}\n\nconst TOKENS_LINE =\n /^Tokens: ([\\d.]+[kM]?) sent(?:, ([\\d.]+[kM]?) cache write)?(?:, ([\\d.]+[kM]?) cache hit)?, ([\\d.]+[kM]?) received\\.(?:\\s+Cost: \\$([\\d.]+) message, \\$([\\d.]+) session\\.)?/;\n\nconst BANNER = [\n /^Aider v\\d/,\n /^Main model: /,\n /^Weak model: /,\n /^Editor model: /,\n /^Model: /,\n /^Git repo: /,\n /^Repo-map: /,\n /^Added .+ to the chat\\.$/,\n /^Cost: \\$[\\d.]+ message, \\$[\\d.]+ session\\.$/,\n /^Use \\/help /,\n];\n\n/** Usage from the analytics log (`message_send` events), summed. */\nfunction analyticsUsage(context: CliLaunchContext | undefined): CliParsedEvent | undefined {\n if (context === undefined) {\n return undefined;\n }\n\n let content: string;\n\n try {\n content = readFileSync(path.join(context.runDir, ANALYTICS_LOG), \"utf8\");\n } catch {\n return undefined;\n }\n\n let input = 0;\n let output = 0;\n let cost: number | undefined;\n let seen = false;\n\n for (const line of content.split(/\\r?\\n/)) {\n const record = parseJsonLine(line);\n\n if (stringField(record, \"event\") !== \"message_send\") {\n continue;\n }\n\n const properties = recordField(record, \"properties\");\n\n seen = true;\n input += numberField(properties, \"prompt_tokens\") ?? 0;\n output += numberField(properties, \"completion_tokens\") ?? 0;\n\n const messageCost = numberField(properties, \"cost\");\n\n if (messageCost !== undefined) {\n cost = (cost ?? 0) + messageCost;\n }\n }\n\n return seen\n ? { type: \"usage\", cumulative: true, usage: usageOf({ input, output, costUSD: cost }) }\n : undefined;\n}\n\n/** Parser for Aider's plain-text stdout (plus its analytics log). */\nexport function createAiderParser(context?: CliLaunchContext): CliStreamParser {\n let started = false;\n let body: string[] = [];\n\n const flush = (): CliParsedEvent[] => {\n const text = body.join(\"\\n\").trim();\n\n body = [];\n\n return text.length > 0 ? [{ type: \"message\", text, delta: false }] : [];\n };\n\n return {\n line(line: string): CliParsedEvent[] {\n const events: CliParsedEvent[] = [];\n const model = /^Main model: (\\S+)/.exec(line);\n\n // One `session.started`: on the model line of the banner, or on the\n // first line of output when the banner has none.\n if (\n !started &&\n (model || (line.trim().length > 0 && !BANNER.some((pattern) => pattern.test(line))))\n ) {\n started = true;\n events.push({ type: \"session.started\", model: model?.[1] });\n }\n\n if (BANNER.some((pattern) => pattern.test(line))) {\n return events;\n }\n\n const tokens = TOKENS_LINE.exec(line);\n\n if (tokens) {\n const cacheWrite = parseAiderCount(tokens[2]);\n const cacheHit = parseAiderCount(tokens[3]);\n const sent = parseAiderCount(tokens[1]) ?? 0;\n\n events.push(...flush(), {\n type: \"usage\",\n cumulative: false,\n usage: usageOf({\n input: sent,\n output: parseAiderCount(tokens[4]),\n cachedTokens: cacheHit,\n cacheWriteTokens: cacheWrite,\n costUSD: tokens[5] !== undefined ? Number(tokens[5]) : undefined,\n }),\n });\n\n return events;\n }\n\n const applied = /^Applied edit to (.+)$/.exec(line);\n\n if (applied) {\n const file = applied[1] ?? \"\";\n const id = `edit-${file}`;\n\n events.push(\n ...flush(),\n { type: \"tool.call\", id, name: \"edit\", input: { path: file } },\n { type: \"tool.result\", id, output: line, isError: false },\n );\n\n return events;\n }\n\n const commit = /^Commit ([0-9a-f]{7,40}) (.*)$/.exec(line);\n\n if (commit) {\n const id = `commit-${commit[1] ?? \"\"}`;\n\n events.push(\n { type: \"tool.call\", id, name: \"commit\", input: { hash: commit[1], message: commit[2] } },\n { type: \"tool.result\", id, output: line, isError: false },\n );\n\n return events;\n }\n\n if (\n /^litellm\\.\\w+Error:/.test(line) ||\n line.startsWith(\"The API provider is not able to authenticate you\")\n ) {\n events.push({ type: \"error\", message: line, fatal: true });\n\n return events;\n }\n\n if (/^Retrying in [\\d.]+ seconds/.test(line)) {\n events.push({ type: \"error\", message: line });\n\n return events;\n }\n\n body.push(line);\n\n return events;\n },\n end(): CliParsedEvent[] {\n const events = flush();\n const usage = analyticsUsage(context);\n\n return usage !== undefined ? [...events, usage] : events;\n },\n };\n}\n","import type { CliParsedEvent, CliStreamParser, CliUsage } from \"../contracts\";\nimport {\n asArray,\n asRecord,\n jsonLinesParser,\n numberField,\n outputText,\n recordField,\n stringField,\n type JsonRecord,\n} from \"../stream/json-lines\";\nimport { anthropicUsage, usageOf } from \"./shared\";\n\n/**\n * How a Claude-style stream reports input tokens.\n *\n * - `anthropic` — `input_tokens` excludes cache reads/writes (Claude Code).\n * - `inclusive` — `input_tokens` already includes cached tokens (Qwen Code).\n */\nexport type ClaudeStreamUsage = \"anthropic\" | \"inclusive\";\n\nfunction inclusiveUsage(usage: JsonRecord | undefined, costUSD?: number): CliUsage | undefined {\n if (usage === undefined) {\n return undefined;\n }\n\n const cached = numberField(usage, \"cache_read_input_tokens\");\n const written = numberField(usage, \"cache_creation_input_tokens\");\n\n return usageOf({\n input: numberField(usage, \"input_tokens\"),\n output: numberField(usage, \"output_tokens\"),\n total: numberField(usage, \"total_tokens\"),\n cachedTokens: cached !== undefined && cached > 0 ? cached : undefined,\n cacheWriteTokens: written !== undefined && written > 0 ? written : undefined,\n costUSD,\n });\n}\n\n/**\n * Parser for the Claude Code `stream-json` format, which several CLIs\n * reproduce (Qwen Code, Grok Build's `streaming-messages-json`):\n *\n * - `{\"type\":\"system\",\"subtype\":\"init\",\"session_id\",\"model\",…}`\n * - `{\"type\":\"assistant\",\"message\":{\"content\":[text | tool_use | thinking]}}`\n * - `{\"type\":\"user\",\"message\":{\"content\":[{\"type\":\"tool_result\",\"tool_use_id\",\"content\",\"is_error\"}]}}`\n * - `{\"type\":\"stream_event\",\"event\":{\"type\":\"content_block_delta\",\"delta\":{\"type\":\"text_delta\",\"text\"}}}`\n * (only with partial messages enabled)\n * - `{\"type\":\"result\",\"subtype\",\"is_error\",\"result\",\"session_id\",\"usage\",\"total_cost_usd\"}`\n *\n * Per-message `usage` is ignored (Claude Code repeats it on every content\n * block of a message); the `result` totals are reported as cumulative usage.\n * Sub-agent traffic (`parent_tool_use_id` set) is reported like the main\n * thread's, so its tool calls stay visible.\n */\nexport function createClaudeStreamParser(\n options: { usage?: ClaudeStreamUsage; vendor?: string } = {},\n): CliStreamParser {\n const style = options.usage ?? \"anthropic\";\n const vendor = options.vendor ?? \"The CLI\";\n\n return jsonLinesParser((record): CliParsedEvent[] => {\n switch (stringField(record, \"type\")) {\n case \"system\": {\n const subtype = stringField(record, \"subtype\");\n\n if (subtype?.startsWith(\"error\") && stringField(record, \"error\") !== undefined) {\n return [{ type: \"error\", message: stringField(record, \"error\") ?? subtype, raw: record }];\n }\n\n return subtype === \"init\" || subtype === \"session_start\"\n ? [\n {\n type: \"session.started\",\n sessionRef: stringField(record, \"session_id\"),\n model: stringField(record, \"model\"),\n raw: record,\n },\n ]\n : [];\n }\n case \"assistant\": {\n const events: CliParsedEvent[] = [];\n\n for (const item of asArray(recordField(record, \"message\")?.content)) {\n const block = asRecord(item);\n const blockType = stringField(block, \"type\");\n\n if (blockType === \"text\") {\n const text = stringField(block, \"text\") ?? \"\";\n\n if (text.length > 0) {\n events.push({ type: \"message\", text, delta: false, raw: record });\n }\n } else if (blockType === \"tool_use\" || blockType === \"server_tool_use\") {\n events.push({\n type: \"tool.call\",\n id: stringField(block, \"id\") ?? \"\",\n name: stringField(block, \"name\") ?? \"\",\n input: block?.input,\n raw: record,\n });\n }\n }\n\n return events;\n }\n case \"user\": {\n const events: CliParsedEvent[] = [];\n\n for (const item of asArray(recordField(record, \"message\")?.content)) {\n const block = asRecord(item);\n\n if (stringField(block, \"type\") === \"tool_result\") {\n events.push({\n type: \"tool.result\",\n id: stringField(block, \"tool_use_id\") ?? \"\",\n output: outputText(block?.content),\n isError: block?.is_error === true,\n raw: record,\n });\n }\n }\n\n return events;\n }\n case \"stream_event\": {\n const event = recordField(record, \"event\");\n const delta = recordField(event, \"delta\");\n\n if (\n stringField(event, \"type\") === \"content_block_delta\" &&\n stringField(delta, \"type\") === \"text_delta\"\n ) {\n const text = stringField(delta, \"text\") ?? \"\";\n\n return text.length > 0 ? [{ type: \"message\", text, delta: true, raw: record }] : [];\n }\n\n return [];\n }\n case \"result\": {\n const events: CliParsedEvent[] = [];\n const cost = numberField(record, \"total_cost_usd\");\n const usage =\n style === \"anthropic\"\n ? anthropicUsage(recordField(record, \"usage\"), cost)\n : inclusiveUsage(recordField(record, \"usage\"), cost);\n\n if (usage !== undefined) {\n events.push({ type: \"usage\", usage, cumulative: true, raw: record });\n }\n\n const result = stringField(record, \"result\");\n\n if (record.is_error === true) {\n const errors = asArray(record.errors)\n .map((item) =>\n typeof item === \"string\" ? item : (stringField(asRecord(item), \"message\") ?? \"\"),\n )\n .filter((item) => item.length > 0)\n .join(\"; \");\n const message =\n stringField(recordField(record, \"error\"), \"message\") ||\n stringField(record, \"error\") ||\n errors ||\n result ||\n `${vendor} run ended with ${stringField(record, \"subtype\") ?? \"an error\"}`;\n\n events.push({ type: \"error\", message, fatal: true, raw: record });\n } else if (result !== undefined && result.length > 0) {\n events.push({ type: \"message\", text: result, delta: false, final: true, raw: record });\n }\n\n return events;\n }\n default:\n return [];\n }\n });\n}\n","import path from \"node:path\";\nimport type { CliAdapter, CliLaunchFile } from \"../contracts\";\nimport { createClaudeStreamParser } from \"./claude-stream\";\nimport { argvPrompt, jsonFile, mapEffort, mcpServersJson, unsupportedOption } from \"./shared\";\n\n/**\n * Amp (`amp`, npm `@ampcode/cli`; `@sourcegraph/amp` is a shim to it).\n *\n * Verified against the real `amp --help` of 0.0.1792254886-g14d018 and the\n * docs (`ampcode.com/docs/cli/{streaming-json,execute-mode,settings}`,\n * `/docs/tools`), 2026-10-17.\n *\n * - Headless: `amp -x <prompt> --stream-json` (with `-x` and no message,\n * stdin is the prompt); resume is `amp threads continue <T-id> -x …`.\n * Threads are kept unarchived (`--no-archive-after-execute`) so they can\n * be continued.\n * - Stream: Claude Code-compatible (`system/init` with `session_id`\n * `T-…`, `assistant` text/`tool_use`, `user` `tool_result`, `result`),\n * no deltas and no cost.\n * - Model: Amp has no model flag; the mode (`-m low|medium|high|ultra`)\n * picks model and effort, so `effort` maps to the mode and `model` is\n * refused.\n * - Permissions: Amp's own rules (tools run without approval by default;\n * anything that needs approval is rejected in execute mode). Bypass passes\n * `--dangerously-allow-all`, which the CLI accepts but no longer lists in\n * `--help`, so it is not part of the capability probe — a CLI that drops\n * it rejects the run as an unknown option.\n * - MCP: `--mcp-config <file>` holding the server map itself (no\n * `mcpServers` wrapper), written to the run directory.\n * - Home: Amp follows XDG (`$XDG_CONFIG_HOME/amp/settings.json`); auth\n * `AMP_API_KEY`; update checks off with `AMP_SKIP_UPDATE_CHECK=1`.\n */\nexport const ampAdapter: CliAdapter = {\n name: \"amp\",\n title: \"Amp\",\n command: \"amp\",\n apiKeyEnv: [\"AMP_API_KEY\"],\n homeEnv: [\"XDG_CONFIG_HOME\", \"XDG_DATA_HOME\", \"XDG_STATE_HOME\", \"XDG_CACHE_HOME\"],\n transports: [\"argv\", \"stdin\"],\n effort: true,\n mcp: true,\n probe: { help: [[\"--help\"]], version: [\"--version\"] },\n verification: {\n version: \"0.0.1792254886-g14d018\",\n verifiedBy: \"help\",\n sources: [\n \"https://ampcode.com/docs/cli/streaming-json\",\n \"https://ampcode.com/docs/cli/execute-mode\",\n \"https://ampcode.com/docs/cli/settings\",\n ],\n checkedAt: \"2026-10-17\",\n },\n plan(context) {\n if (context.model !== undefined) {\n throw unsupportedOption(\n ampAdapter,\n \"Amp has no model flag; its mode picks the model — use `effort` instead of `model`.\",\n );\n }\n\n const args: string[] =\n context.resume !== undefined ? [\"threads\", \"continue\", context.resume] : [];\n const requires = [\"--execute\", \"--stream-json\", \"--no-archive-after-execute\"];\n const files: CliLaunchFile[] = [];\n\n if (context.resume !== undefined) {\n requires.push(\"threads\");\n }\n\n args.push(\"--stream-json\", \"--no-archive-after-execute\");\n\n if (context.effort !== undefined) {\n args.push(\n \"--mode\",\n mapEffort(context.effort, { low: \"low\", medium: \"medium\", high: \"high\", max: \"ultra\" }),\n );\n requires.push(\"--mode\");\n }\n\n if (context.permission === \"bypass\") {\n args.push(\"--dangerously-allow-all\");\n }\n\n if (context.mcp !== undefined) {\n const file = path.join(context.runDir, \"amp-mcp.json\");\n\n files.push({ path: file, content: jsonFile(mcpServersJson(context.mcp)) });\n args.push(\"--mcp-config\", file);\n requires.push(\"--mcp-config\");\n }\n\n const env: Record<string, string> = { AMP_SKIP_UPDATE_CHECK: \"1\" };\n\n if (context.home !== undefined) {\n env.XDG_CONFIG_HOME = path.join(context.home, \"config\");\n env.XDG_DATA_HOME = path.join(context.home, \"data\");\n env.XDG_STATE_HOME = path.join(context.home, \"state\");\n env.XDG_CACHE_HOME = path.join(context.home, \"cache\");\n }\n\n return {\n args,\n tail:\n context.transport === \"argv\" ? [\"--execute\", argvPrompt(context.prompt)] : [\"--execute\"],\n stdin: context.transport === \"stdin\" ? context.prompt : undefined,\n env,\n files,\n requires,\n };\n },\n parser: () => createClaudeStreamParser({ usage: \"anthropic\", vendor: \"Amp\" }),\n};\n","import path from \"node:path\";\nimport type {\n CliAdapter,\n CliLaunchFile,\n CliMcpServers,\n CliParsedEvent,\n CliStreamParser,\n} from \"../contracts\";\nimport {\n jsonLinesParser,\n numberField,\n recordField,\n stringField,\n type JsonRecord,\n} from \"../stream/json-lines\";\nimport { argvPrompt, jsonFile, mapEffort, requirePrivateHome, usageOf } from \"./shared\";\n\n/**\n * Google Antigravity CLI (`agy`), installed by the\n * `antigravity.google/cli/install.sh` script (no npm package). Not Gemini\n * CLI, which it succeeds.\n *\n * Verified against the official docs only (the binary is distributed by a\n * curl installer, which was not run): `antigravity.google/docs/cli/headless`,\n * `/docs/cli/reference`, `/docs/mcp`, `/docs/permissions`, `/docs/settings`,\n * `/docs/install`, and the 1.4.0 release notes, 2026-10-17. The capability\n * probe checks every flag against the installed binary's `--help`.\n *\n * - Headless: `agy -p <prompt> --output-format stream-json`. For long\n * prompts the adapter uses the documented stdin protocol instead:\n * `--input-format stream-json` with one `{\"event\":\"user\",\"message\":\n * {\"content\":…}}` line, then stdin is closed.\n * - Stream: `{\"event\":X, X:{…}}` lines — `init` (with `conversation_id`),\n * `step_update` (`agent_response` steps carry `text_delta` fragments;\n * `tool` steps carry `tool_info{name,parameters,output,error}` with call\n * and result together, correlated by `step_index`) and a final `result`\n * (`status`, `response`, `error`, cumulative `usage`). No cost field.\n * - Permissions: headless soft-denies tools that need approval (the run\n * continues and exits 0); bypass is `--dangerously-skip-permissions`.\n * - Home: no variable relocates `~/.gemini`, so a private/owned home sets\n * `HOME` (and `USERPROFILE`). MCP goes to\n * `$HOME/.gemini/config/mcp_config.json` (remote servers use `serverUrl`).\n * - Auth: `GEMINI_API_KEY` only works with `\"modelProvider\": \"gemini\"` in\n * `$HOME/.gemini/antigravity-cli/settings.json`; the adapter writes that\n * file when `apiKey` is set on a private home.\n */\nexport const antigravityAdapter: CliAdapter = {\n name: \"antigravity\",\n title: \"Antigravity CLI\",\n command: \"agy\",\n apiKeyEnv: [\"GEMINI_API_KEY\"],\n homeEnv: [\"HOME\", \"USERPROFILE\"],\n transports: [\"argv\", \"stdin\"],\n effort: true,\n mcp: true,\n probe: { help: [[\"--help\"]], version: [\"--version\"] },\n verification: {\n version: \"1.4.0\",\n verifiedBy: \"docs\",\n sources: [\n \"https://antigravity.google/docs/cli/headless\",\n \"https://antigravity.google/docs/cli/reference\",\n \"https://antigravity.google/docs/mcp\",\n \"https://antigravity.google/docs/permissions\",\n \"https://github.com/google-antigravity/antigravity-cli\",\n ],\n checkedAt: \"2026-10-17\",\n },\n plan(context) {\n const args = [\"--output-format\", \"stream-json\"];\n const requires = [\"--output-format\", \"stream-json\"];\n const files: CliLaunchFile[] = [];\n\n if (context.model !== undefined) {\n args.push(\"--model\", context.model);\n requires.push(\"--model\");\n }\n\n if (context.effort !== undefined) {\n // Documented levels: low | medium | high.\n args.push(\n \"--effort\",\n mapEffort(context.effort, { low: \"low\", medium: \"medium\", high: \"high\" }),\n );\n requires.push(\"--effort\");\n }\n\n if (context.resume !== undefined) {\n args.push(\"--conversation\", context.resume);\n requires.push(\"--conversation\");\n }\n\n if (context.permission === \"bypass\") {\n args.push(\"--dangerously-skip-permissions\");\n requires.push(\"--dangerously-skip-permissions\");\n }\n\n if (context.mcp !== undefined) {\n const home = requirePrivateHome(context, antigravityAdapter, \"MCP servers\");\n\n files.push({\n path: path.join(home, \".gemini\", \"config\", \"mcp_config.json\"),\n content: jsonFile({ mcpServers: antigravityMcp(context.mcp) }),\n });\n }\n\n if (context.apiKey !== undefined && context.homeIsPrivate && context.home !== undefined) {\n files.push({\n path: path.join(context.home, \".gemini\", \"antigravity-cli\", \"settings.json\"),\n content: jsonFile({ modelProvider: \"gemini\" }),\n });\n }\n\n const env: Record<string, string> =\n context.home !== undefined ? { HOME: context.home, USERPROFILE: context.home } : {};\n\n if (context.transport === \"stdin\") {\n // Documented form: `agy --input-format stream-json --output-format stream-json`, no `-p`.\n args.push(\"--input-format\", \"stream-json\");\n requires.push(\"--input-format\");\n\n return {\n args,\n stdin: `${JSON.stringify({ event: \"user\", message: { content: context.prompt } })}\\n`,\n env,\n files,\n requires,\n };\n }\n\n requires.push(\"-p\");\n\n return { args, tail: [\"-p\", argvPrompt(context.prompt)], env, files, requires };\n },\n parser: createAntigravityParser,\n};\n\nfunction antigravityMcp(servers: CliMcpServers): Record<string, unknown> {\n const rendered: Record<string, unknown> = {};\n\n for (const [name, server] of Object.entries(servers)) {\n rendered[name] =\n server.type === \"stdio\"\n ? {\n command: server.command,\n args: server.args ?? [],\n ...(server.env ? { env: server.env } : {}),\n }\n : { serverUrl: server.url, ...(server.headers ? { headers: server.headers } : {}) };\n }\n\n return rendered;\n}\n\nfunction stepUsage(usage: JsonRecord | undefined) {\n if (usage === undefined) {\n return undefined;\n }\n\n const cached = numberField(usage, \"cache_read_tokens\");\n\n return usageOf({\n input: numberField(usage, \"input_tokens\"),\n output: numberField(usage, \"output_tokens\"),\n total: numberField(usage, \"total_tokens\"),\n cachedTokens: cached !== undefined && cached > 0 ? cached : undefined,\n reasoningTokens: numberField(usage, \"thinking_tokens\") || undefined,\n });\n}\n\n/** Parser for `agy -p … --output-format stream-json`. */\nexport function createAntigravityParser(): CliStreamParser {\n return jsonLinesParser((record): CliParsedEvent[] => {\n const event = stringField(record, \"event\");\n\n if (event === \"init\") {\n const init = recordField(record, \"init\");\n\n return [\n {\n type: \"session.started\",\n sessionRef: stringField(record, \"conversation_id\"),\n model: stringField(init, \"model\"),\n raw: record,\n },\n ];\n }\n\n if (event === \"step_update\") {\n const step = recordField(record, \"step_update\");\n const stepType = stringField(step, \"step_type\");\n const events: CliParsedEvent[] = [];\n\n if (stepType === \"agent_response\") {\n const text = stringField(step, \"text_delta\") ?? \"\";\n\n if (text.length > 0) {\n events.push({ type: \"message\", text, delta: true, raw: record });\n }\n }\n\n if (stepType === \"tool\" && stringField(step, \"state\") === \"DONE\") {\n const info = recordField(step, \"tool_info\");\n const error = recordField(info, \"error\");\n const id = `step-${numberField(step, \"step_index\") ?? 0}`;\n\n events.push(\n {\n type: \"tool.call\",\n id,\n name: stringField(info, \"name\") ?? stringField(step, \"tool_name\") ?? \"\",\n input: info?.parameters,\n raw: record,\n },\n {\n type: \"tool.result\",\n id,\n output:\n error !== undefined\n ? (stringField(error, \"message\") ?? stringField(error, \"type\") ?? \"tool failed\")\n : (stringField(info, \"output\") ?? \"\"),\n isError: error !== undefined,\n raw: record,\n },\n );\n }\n\n const usage = stepUsage(recordField(step, \"usage\"));\n\n if (usage !== undefined) {\n events.push({ type: \"usage\", usage, cumulative: false, raw: record });\n }\n\n return events;\n }\n\n if (event === \"result\") {\n const result = recordField(record, \"result\");\n const events: CliParsedEvent[] = [];\n const usage = stepUsage(recordField(result, \"usage\"));\n\n if (usage !== undefined) {\n events.push({ type: \"usage\", usage, cumulative: true, raw: record });\n }\n\n const status = stringField(result, \"status\");\n\n if (status !== undefined && status !== \"SUCCESS\") {\n events.push({\n type: \"error\",\n message: stringField(result, \"error\") || `Antigravity run ended ${status}`,\n fatal: true,\n raw: record,\n });\n } else {\n const response = stringField(result, \"response\") ?? \"\";\n\n if (response.length > 0) {\n events.push({ type: \"message\", text: response, delta: false, final: true, raw: record });\n }\n }\n\n return events;\n }\n\n return [];\n });\n}\n","import path from \"node:path\";\nimport type { CliAdapter, CliLaunchFile } from \"../contracts\";\nimport { createClaudeStreamParser } from \"./claude-stream\";\nimport { jsonFile, mapEffort, mcpServersJson, argvPrompt } from \"./shared\";\n\n/**\n * Claude Code (`claude`, npm `@anthropic-ai/claude-code`).\n *\n * Verified against the real `claude --help` of 2.1.302, the event types of\n * `@anthropic-ai/claude-agent-sdk` 0.3.302 and the docs\n * (`code.claude.com/docs/en/{headless,cli-reference,mcp,env-vars,\n * permission-modes}`), 2026-10-17.\n *\n * - Headless: `claude -p --output-format stream-json --verbose\n * --include-partial-messages <prompt>` (`--verbose` is required with\n * stream-json in print mode); piped stdin is the prompt when no positional\n * prompt is given.\n * - Stream: `system/init` (`session_id`), `stream_event` text deltas,\n * `assistant` messages (text / `tool_use`), `user` messages with\n * `tool_result`, and a final `result` (`result`, `usage`,\n * `total_cost_usd`, `is_error`, `errors[]`).\n * - Permissions: print mode auto-denies anything that would prompt; bypass\n * is `--dangerously-skip-permissions` (Claude Code refuses it as root\n * outside a recognised sandbox).\n * - MCP: `--mcp-config <file>` with `{\"mcpServers\":…}`, written to the run\n * directory.\n * - Home: `CLAUDE_CONFIG_DIR`; auth `ANTHROPIC_API_KEY` (or a home you\n * logged in to); auto-update off with `DISABLE_AUTOUPDATER=1`.\n */\nexport const claudeCodeAdapter: CliAdapter = {\n name: \"claude-code\",\n title: \"Claude Code\",\n command: \"claude\",\n apiKeyEnv: [\"ANTHROPIC_API_KEY\"],\n homeEnv: [\"CLAUDE_CONFIG_DIR\"],\n transports: [\"argv\", \"stdin\"],\n effort: true,\n mcp: true,\n probe: { help: [[\"--help\"]], version: [\"--version\"] },\n verification: {\n version: \"2.1.302\",\n verifiedBy: \"help\",\n sources: [\n \"https://code.claude.com/docs/en/headless\",\n \"https://code.claude.com/docs/en/cli-reference\",\n \"https://code.claude.com/docs/en/mcp\",\n \"https://code.claude.com/docs/en/env-vars\",\n ],\n checkedAt: \"2026-10-17\",\n },\n plan(context) {\n const args = [\n \"--print\",\n \"--output-format\",\n \"stream-json\",\n \"--verbose\",\n \"--include-partial-messages\",\n ];\n const requires = [\n \"--print\",\n \"--output-format\",\n \"stream-json\",\n \"--verbose\",\n \"--include-partial-messages\",\n ];\n const files: CliLaunchFile[] = [];\n\n if (context.model !== undefined) {\n args.push(\"--model\", context.model);\n requires.push(\"--model\");\n }\n\n if (context.effort !== undefined) {\n args.push(\n \"--effort\",\n mapEffort(context.effort, {\n low: \"low\",\n medium: \"medium\",\n high: \"high\",\n xhigh: \"xhigh\",\n max: \"max\",\n }),\n );\n requires.push(\"--effort\");\n }\n\n if (context.resume !== undefined) {\n args.push(\"--resume\", context.resume);\n requires.push(\"--resume\");\n }\n\n if (context.permission === \"bypass\") {\n args.push(\"--dangerously-skip-permissions\");\n requires.push(\"--dangerously-skip-permissions\");\n }\n\n if (context.mcp !== undefined) {\n const file = path.join(context.runDir, \"mcp.json\");\n\n files.push({\n path: file,\n content: jsonFile({ mcpServers: mcpServersJson(context.mcp, { typeField: true }) }),\n });\n args.push(\"--mcp-config\", file);\n requires.push(\"--mcp-config\");\n }\n\n return {\n args,\n tail: context.transport === \"argv\" ? [argvPrompt(context.prompt)] : [],\n stdin: context.transport === \"stdin\" ? context.prompt : undefined,\n env: {\n ...(context.home !== undefined ? { CLAUDE_CONFIG_DIR: context.home } : {}),\n DISABLE_AUTOUPDATER: \"1\",\n },\n files,\n requires,\n };\n },\n parser: () => createClaudeStreamParser({ usage: \"anthropic\", vendor: \"Claude Code\" }),\n};\n","import path from \"node:path\";\nimport type {\n CliAdapter,\n CliLaunchFile,\n CliMcpServers,\n CliParsedEvent,\n CliStreamParser,\n} from \"../contracts\";\nimport {\n jsonLinesParser,\n numberField,\n outputText,\n recordField,\n stringField,\n} from \"../stream/json-lines\";\nimport { type TomlTable, tomlKey, toToml } from \"../utils/toml\";\nimport { argvPrompt, mapEffort, unsupportedOption, usageOf } from \"./shared\";\n\n/**\n * OpenAI Codex CLI (`codex`, npm `@openai/codex`).\n *\n * Verified against the real `codex exec --help` / `codex exec resume\n * --help` of 0.163.0, the source at tag `rust-v0.163.0` (`exec_events.rs`,\n * the JSONL event processor, `cli.rs`) and the docs (non-interactive mode,\n * config reference), 2026-10-17.\n *\n * - Headless: `codex exec --json --skip-git-repo-check <prompt>` (`-` reads\n * the prompt from stdin); resume is `codex exec resume … <thread_id>\n * <prompt>`.\n * - Stream: `thread.started` (`thread_id`), `item.started`/`item.completed`\n * with `item.type` `agent_message`, `reasoning`, `command_execution`,\n * `file_change`, `mcp_tool_call`, `web_search`, `error`; `turn.completed`\n * with the thread's cumulative `usage` (`input_tokens` includes\n * `cached_input_tokens`); `turn.failed` and `error` on failure. No text\n * deltas and no cost field.\n * - Permissions: exec never asks (approval policy \"never\"); `standard` keeps\n * Codex's default **read-only** sandbox — allow edits with\n * `args: [\"-c\", \"sandbox_mode=workspace-write\"]`. Bypass is\n * `--dangerously-bypass-approvals-and-sandbox`.\n * - Effort: `-c model_reasoning_effort=<level>`.\n * - MCP: no flag. With a private home the servers go into\n * `$CODEX_HOME/config.toml` (0600). With a caller-owned or inherited home\n * they are passed as `-c mcp_servers.<name>.…` overrides that carry only\n * the command, args and URL; secret `env` values and headers travel in the\n * process environment, named through `env_vars` / `env_http_headers`.\n * - Home `CODEX_HOME`; auth `CODEX_API_KEY`.\n */\nexport const codexAdapter: CliAdapter = {\n name: \"codex\",\n title: \"Codex CLI\",\n command: \"codex\",\n apiKeyEnv: [\"CODEX_API_KEY\"],\n homeEnv: [\"CODEX_HOME\"],\n transports: [\"argv\", \"stdin\"],\n effort: true,\n mcp: true,\n probe: {\n help: [\n [\"exec\", \"--help\"],\n [\"exec\", \"resume\", \"--help\"],\n ],\n version: [\"--version\"],\n },\n verification: {\n version: \"0.163.0\",\n verifiedBy: \"help\",\n sources: [\n \"https://developers.openai.com/codex/noninteractive\",\n \"https://developers.openai.com/codex/config-reference\",\n \"https://github.com/openai/codex/blob/rust-v0.163.0/codex-rs/exec/src/exec_events.rs\",\n ],\n checkedAt: \"2026-10-17\",\n },\n plan(context) {\n const args = [\"exec\"];\n const requires = [\"exec\", \"--json\", \"--skip-git-repo-check\"];\n const files: CliLaunchFile[] = [];\n const env: Record<string, string> = {};\n\n if (context.resume !== undefined) {\n args.push(\"resume\");\n requires.push(\"resume\");\n }\n\n args.push(\"--json\", \"--skip-git-repo-check\", \"-c\", \"check_for_update_on_startup=false\");\n\n if (context.model !== undefined) {\n args.push(\"--model\", context.model);\n requires.push(\"--model\");\n }\n\n if (context.effort !== undefined) {\n const effort = mapEffort(context.effort, {\n low: \"low\",\n medium: \"medium\",\n high: \"high\",\n xhigh: \"xhigh\",\n max: \"max\",\n });\n\n args.push(\"-c\", `model_reasoning_effort=${effort}`);\n requires.push(\"--config\");\n }\n\n if (context.permission === \"bypass\") {\n args.push(\"--dangerously-bypass-approvals-and-sandbox\");\n requires.push(\"--dangerously-bypass-approvals-and-sandbox\");\n }\n\n if (context.mcp !== undefined) {\n if (context.home !== undefined && context.homeIsPrivate) {\n files.push({\n path: path.join(context.home, \"config.toml\"),\n content: toToml({ mcp_servers: codexMcpTable(context.mcp) }),\n });\n } else {\n args.push(...codexMcpOverrides(context.mcp, env));\n requires.push(\"--config\");\n }\n }\n\n if (context.home !== undefined) {\n env.CODEX_HOME = context.home;\n }\n\n const prompt = context.transport === \"argv\" ? argvPrompt(context.prompt) : \"-\";\n\n return {\n args,\n tail: context.resume !== undefined ? [context.resume, prompt] : [prompt],\n stdin: context.transport === \"stdin\" ? context.prompt : undefined,\n env,\n files,\n requires,\n };\n },\n parser: createCodexParser,\n};\n\n/** `[mcp_servers.<name>]` tables for a private `config.toml`. */\nfunction codexMcpTable(servers: CliMcpServers): TomlTable {\n const table: TomlTable = {};\n\n for (const [name, server] of Object.entries(servers)) {\n if (server.type === \"sse\") {\n throw unsupportedOption(\n codexAdapter,\n `MCP server \"${name}\" uses SSE; Codex supports stdio and streamable HTTP.`,\n );\n }\n\n table[name] =\n server.type === \"stdio\"\n ? { command: server.command, args: server.args ?? [], env: server.env }\n : { url: server.url, http_headers: server.headers };\n }\n\n return table;\n}\n\n/** A TOML string for a `-c key=value` override. */\nfunction tomlString(value: string): string {\n return JSON.stringify(value);\n}\n\n/**\n * `-c` overrides that carry no secret: env values and header values are put\n * in `env` (the Codex process environment) and only their names go to argv.\n */\nfunction codexMcpOverrides(servers: CliMcpServers, env: Record<string, string>): string[] {\n const overrides: string[] = [];\n const claim = (name: string, value: string): void => {\n if (env[name] !== undefined && env[name] !== value) {\n throw unsupportedOption(\n codexAdapter,\n `two MCP servers set ${name} to different values; with a shared home they share one environment.`,\n );\n }\n\n env[name] = value;\n };\n\n for (const [name, server] of Object.entries(servers)) {\n const prefix = `mcp_servers.${tomlKey(name)}`;\n\n if (server.type === \"sse\") {\n throw unsupportedOption(\n codexAdapter,\n `MCP server \"${name}\" uses SSE; Codex supports stdio and streamable HTTP.`,\n );\n }\n\n if (server.type === \"stdio\") {\n overrides.push(\"-c\", `${prefix}.command=${tomlString(server.command)}`);\n overrides.push(\"-c\", `${prefix}.args=[${(server.args ?? []).map(tomlString).join(\",\")}]`);\n\n const names = Object.keys(server.env ?? {});\n\n for (const [key, value] of Object.entries(server.env ?? {})) {\n claim(key, value);\n }\n\n if (names.length > 0) {\n overrides.push(\"-c\", `${prefix}.env_vars=[${names.map(tomlString).join(\",\")}]`);\n }\n\n continue;\n }\n\n overrides.push(\"-c\", `${prefix}.url=${tomlString(server.url)}`);\n\n const headers = Object.entries(server.headers ?? {});\n\n if (headers.length > 0) {\n const mapping = headers.map(([header, value], index) => {\n const variable = `WARLOCK_MCP_${name.replace(/\\W/g, \"_\").toUpperCase()}_HEADER_${index}`;\n\n claim(variable, value);\n\n return `${tomlString(header)}=${tomlString(variable)}`;\n });\n\n overrides.push(\"-c\", `${prefix}.env_http_headers={${mapping.join(\",\")}}`);\n }\n }\n\n return overrides;\n}\n\nconst TOOL_ITEMS = new Set([\n \"command_execution\",\n \"file_change\",\n \"mcp_tool_call\",\n \"web_search\",\n \"collab_tool_call\",\n]);\n\nfunction toolCall(item: Record<string, unknown>): { name: string; input: unknown } {\n switch (stringField(item, \"type\")) {\n case \"command_execution\":\n return { name: \"shell\", input: { command: item.command } };\n case \"file_change\":\n return { name: \"apply_patch\", input: { changes: item.changes } };\n case \"mcp_tool_call\":\n return {\n name: `${stringField(item, \"server\") ?? \"mcp\"}.${stringField(item, \"tool\") ?? \"tool\"}`,\n input: item.arguments,\n };\n case \"web_search\":\n return { name: \"web_search\", input: { query: item.query } };\n default:\n return { name: stringField(item, \"type\") ?? \"tool\", input: item };\n }\n}\n\nfunction toolResult(item: Record<string, unknown>): { output: string; isError: boolean } {\n const status = stringField(item, \"status\");\n const failed = status === \"failed\" || status === \"declined\";\n\n switch (stringField(item, \"type\")) {\n case \"command_execution\": {\n const exitCode = numberField(item, \"exit_code\");\n\n return {\n output: stringField(item, \"aggregated_output\") ?? \"\",\n isError: failed || (exitCode !== undefined && exitCode !== 0),\n };\n }\n case \"mcp_tool_call\": {\n const error = stringField(recordField(item, \"error\"), \"message\");\n\n return error !== undefined\n ? { output: error, isError: true }\n : { output: outputText(recordField(item, \"result\")?.content), isError: failed };\n }\n default:\n return { output: outputText(item.changes ?? item.result ?? \"\"), isError: failed };\n }\n}\n\n/** Parser for `codex exec --json`. */\nexport function createCodexParser(): CliStreamParser {\n const announced = new Set<string>();\n\n return jsonLinesParser((record): CliParsedEvent[] => {\n const type = stringField(record, \"type\");\n const item = recordField(record, \"item\");\n const itemType = stringField(item, \"type\");\n const id = stringField(item, \"id\") ?? \"\";\n\n if (type === \"thread.started\") {\n return [\n { type: \"session.started\", sessionRef: stringField(record, \"thread_id\"), raw: record },\n ];\n }\n\n if (\n type === \"item.started\" &&\n item !== undefined &&\n itemType !== undefined &&\n TOOL_ITEMS.has(itemType)\n ) {\n announced.add(id);\n\n return [{ type: \"tool.call\", id, ...toolCall(item), raw: record }];\n }\n\n if (type === \"item.completed\" && item !== undefined) {\n if (itemType === \"agent_message\") {\n const text = stringField(item, \"text\") ?? \"\";\n\n return text.length > 0 ? [{ type: \"message\", text, delta: false, raw: record }] : [];\n }\n\n if (itemType === \"error\") {\n return [{ type: \"error\", message: stringField(item, \"message\") ?? \"error\", raw: record }];\n }\n\n if (itemType !== undefined && TOOL_ITEMS.has(itemType)) {\n const events: CliParsedEvent[] = [];\n\n if (!announced.has(id)) {\n events.push({ type: \"tool.call\", id, ...toolCall(item), raw: record });\n }\n\n events.push({ type: \"tool.result\", id, ...toolResult(item), raw: record });\n\n return events;\n }\n\n return [];\n }\n\n if (type === \"turn.completed\") {\n const usage = recordField(record, \"usage\");\n\n if (usage === undefined) {\n return [];\n }\n\n const cached = numberField(usage, \"cached_input_tokens\");\n const written = numberField(usage, \"cache_write_input_tokens\");\n\n return [\n {\n type: \"usage\",\n cumulative: true,\n usage: usageOf({\n input: numberField(usage, \"input_tokens\"),\n output: numberField(usage, \"output_tokens\"),\n cachedTokens: cached !== undefined && cached > 0 ? cached : undefined,\n cacheWriteTokens: written !== undefined && written > 0 ? written : undefined,\n reasoningTokens: numberField(usage, \"reasoning_output_tokens\") || undefined,\n }),\n raw: record,\n },\n ];\n }\n\n if (type === \"turn.failed\") {\n return [\n {\n type: \"error\",\n message: stringField(recordField(record, \"error\"), \"message\") ?? \"Codex turn failed\",\n fatal: true,\n raw: record,\n },\n ];\n }\n\n if (type === \"error\") {\n return [\n {\n type: \"error\",\n message: stringField(record, \"message\") ?? \"Codex error\",\n fatal: true,\n raw: record,\n },\n ];\n }\n\n return [];\n });\n}\n","import { readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport type {\n CliAdapter,\n CliLaunchContext,\n CliLaunchFile,\n CliParsedEvent,\n CliStreamParser,\n} from \"../contracts\";\nimport {\n asRecord,\n jsonLinesParser,\n numberField,\n outputText,\n parseJsonLine,\n recordField,\n stringField,\n} from \"../stream/json-lines\";\nimport { argvPrompt, jsonFile, mcpServersJson, usageOf } from \"./shared\";\n\n/** Usage file (inside the run directory) Copilot writes on exit. */\nconst USAGE_FILE = \"copilot-usage.json\";\n\n/**\n * GitHub Copilot CLI (`copilot`, npm `@github/copilot`).\n *\n * Verified against the real `copilot --help` of 1.0.98, the JSONL writer in\n * the shipped CLI, the event types of `@github/copilot-sdk` 1.0.22 and the\n * docs (`docs.github.com/copilot/how-tos/copilot-cli/…`, programmatic and\n * command references), 2026-10-17.\n *\n * - Headless: `copilot -p <prompt> --output-format json --stream on`\n * (piped stdin is the prompt when `-p` is absent). Stream lines are\n * session events `{type,data,id,timestamp}`: `assistant.message_delta`\n * (`deltaContent`), `assistant.message` (`content`),\n * `tool.execution_start` (`toolCallId`, `toolName`, `arguments`),\n * `tool.execution_complete` (`success`, `result.content`,\n * `error.message`), `session.error`, and a final CLI-built `result`\n * (`sessionId`, `exitCode`, premium-request usage).\n * - Tokens are not in the stream; the adapter passes `--usage-output-file`\n * and reads `modelMetrics.*.usage` from it when the stream ends. Billing\n * is in premium requests, so no USD cost is reported.\n * - Permissions: unapproved tool requests are auto-denied in `-p` mode;\n * bypass is `--allow-all` (tools, paths and URLs). `--no-ask-user` and\n * `--no-auto-update` are always passed.\n * - MCP: `--additional-mcp-config @<file>` (`mcpServers`, `type`\n * `local`/`http`/`sse`, `tools: [\"*\"]`), written to the run directory.\n * - Home `COPILOT_HOME`; auth `COPILOT_GITHUB_TOKEN`. Resume with\n * `--session-id <id>`.\n */\nexport const copilotAdapter: CliAdapter = {\n name: \"copilot\",\n title: \"Copilot CLI\",\n command: \"copilot\",\n apiKeyEnv: [\"COPILOT_GITHUB_TOKEN\"],\n homeEnv: [\"COPILOT_HOME\"],\n transports: [\"argv\", \"stdin\"],\n effort: true,\n mcp: true,\n probe: { help: [[\"--help\"]], version: [\"--version\"] },\n verification: {\n version: \"1.0.98\",\n verifiedBy: \"help\",\n sources: [\n \"https://docs.github.com/en/copilot/how-tos/copilot-cli/automate-copilot-cli/run-cli-programmatically\",\n \"https://docs.github.com/en/copilot/reference/copilot-cli-reference/cli-command-reference\",\n \"https://www.npmjs.com/package/@github/copilot\",\n ],\n checkedAt: \"2026-10-17\",\n },\n plan(context) {\n const args = [\n \"--output-format\",\n \"json\",\n \"--stream\",\n \"on\",\n \"--no-ask-user\",\n \"--no-auto-update\",\n \"--usage-output-file\",\n path.join(context.runDir, USAGE_FILE),\n ];\n const requires = [\n \"--output-format\",\n \"--stream\",\n \"--no-ask-user\",\n \"--no-auto-update\",\n \"--usage-output-file\",\n ];\n const files: CliLaunchFile[] = [];\n\n if (context.model !== undefined) {\n args.push(\"--model\", context.model);\n requires.push(\"--model\");\n }\n\n if (context.effort !== undefined) {\n // Copilot accepts the framework scale verbatim: none … max.\n args.push(\"--reasoning-effort\", context.effort);\n requires.push(\"--reasoning-effort\");\n }\n\n if (context.resume !== undefined) {\n args.push(\"--session-id\", context.resume);\n requires.push(\"--session-id\");\n }\n\n if (context.permission === \"bypass\") {\n args.push(\"--allow-all\");\n requires.push(\"--allow-all\");\n }\n\n if (context.mcp !== undefined) {\n const file = path.join(context.runDir, \"copilot-mcp.json\");\n const servers = mcpServersJson(context.mcp, { typeField: true, extra: { tools: [\"*\"] } });\n\n for (const server of Object.values(servers)) {\n if (server.type === \"stdio\") {\n server.type = \"local\";\n }\n }\n\n files.push({ path: file, content: jsonFile({ mcpServers: servers }) });\n args.push(\"--additional-mcp-config\", `@${file}`);\n requires.push(\"--additional-mcp-config\");\n }\n\n return {\n args,\n tail: context.transport === \"argv\" ? [\"-p\", argvPrompt(context.prompt)] : [],\n stdin: context.transport === \"stdin\" ? context.prompt : undefined,\n env: context.home !== undefined ? { COPILOT_HOME: context.home } : undefined,\n files,\n requires: context.transport === \"argv\" ? [...requires, \"-p\"] : requires,\n };\n },\n parser: createCopilotParser,\n};\n\n/** Token usage summed over `modelMetrics` of the usage file. */\nfunction usageFileEvent(context: CliLaunchContext | undefined): CliParsedEvent | undefined {\n if (context === undefined) {\n return undefined;\n }\n\n let report: Record<string, unknown> | undefined;\n\n try {\n report = parseJsonLine(readFileSync(path.join(context.runDir, USAGE_FILE), \"utf8\"));\n } catch {\n return undefined;\n }\n\n const metrics = recordField(report, \"modelMetrics\");\n\n if (metrics === undefined) {\n return undefined;\n }\n\n let input = 0;\n let output = 0;\n let cached = 0;\n let written = 0;\n let reasoning = 0;\n\n for (const value of Object.values(metrics)) {\n const usage = recordField(asRecord(value), \"usage\");\n\n input += numberField(usage, \"inputTokens\") ?? 0;\n output += numberField(usage, \"outputTokens\") ?? 0;\n cached += numberField(usage, \"cacheReadTokens\") ?? 0;\n written += numberField(usage, \"cacheWriteTokens\") ?? 0;\n reasoning += numberField(usage, \"reasoningTokens\") ?? 0;\n }\n\n return {\n type: \"usage\",\n cumulative: true,\n usage: usageOf({\n input,\n output,\n cachedTokens: cached > 0 ? cached : undefined,\n cacheWriteTokens: written > 0 ? written : undefined,\n reasoningTokens: reasoning > 0 ? reasoning : undefined,\n }),\n raw: report,\n };\n}\n\n/** Parser for `copilot -p … --output-format json` (plus its usage file). */\nexport function createCopilotParser(context?: CliLaunchContext): CliStreamParser {\n let started = false;\n let sessionRef: string | undefined;\n\n const parser = jsonLinesParser(\n (record): CliParsedEvent[] => {\n const events: CliParsedEvent[] = [];\n const type = stringField(record, \"type\");\n const data = recordField(record, \"data\");\n\n if (!started) {\n started = true;\n events.push({\n type: \"session.started\",\n sessionRef: stringField(data, \"sessionId\"),\n raw: record,\n });\n }\n\n switch (type) {\n case \"assistant.message_delta\": {\n const text = stringField(data, \"deltaContent\") ?? \"\";\n\n if (text.length > 0) {\n events.push({ type: \"message\", text, delta: true, raw: record });\n }\n break;\n }\n case \"assistant.message\": {\n const text = stringField(data, \"content\") ?? \"\";\n\n if (text.length > 0) {\n events.push({ type: \"message\", text, delta: false, raw: record });\n }\n break;\n }\n case \"tool.execution_start\":\n events.push({\n type: \"tool.call\",\n id: stringField(data, \"toolCallId\") ?? \"\",\n name: stringField(data, \"toolName\") ?? \"\",\n input: data?.arguments,\n raw: record,\n });\n break;\n case \"tool.execution_complete\": {\n const success = data?.success === true;\n\n events.push({\n type: \"tool.result\",\n id: stringField(data, \"toolCallId\") ?? \"\",\n output: success\n ? outputText(recordField(data, \"result\")?.content)\n : (stringField(recordField(data, \"error\"), \"message\") ?? \"tool failed\"),\n isError: !success,\n raw: record,\n });\n break;\n }\n case \"session.error\":\n events.push({\n type: \"error\",\n message: stringField(data, \"message\") ?? \"Copilot session error\",\n fatal: true,\n raw: record,\n });\n break;\n case \"result\":\n sessionRef = stringField(record, \"sessionId\") ?? sessionRef;\n break;\n case \"error\":\n events.push({\n type: \"error\",\n message: stringField(record, \"message\") ?? \"error\",\n raw: record,\n });\n break;\n }\n\n return events;\n },\n () => {\n const usage = usageFileEvent(context);\n\n return usage !== undefined ? [usage] : [];\n },\n );\n\n return { ...parser, sessionRef: () => sessionRef };\n}\n","import path from \"node:path\";\nimport type { CliAdapter, CliLaunchFile, CliParsedEvent, CliStreamParser } from \"../contracts\";\nimport {\n asArray,\n asRecord,\n jsonLinesParser,\n numberField,\n outputText,\n recordField,\n stringField,\n} from \"../stream/json-lines\";\nimport {\n argvPrompt,\n jsonFile,\n mcpServersJson,\n parseArguments,\n requirePrivateHome,\n usageOf,\n} from \"./shared\";\n\n/**\n * Cursor CLI (`cursor-agent`, also installed as `agent`), installed by the\n * `cursor.com/install` script (no official npm package).\n *\n * Verified against the official docs (`cursor.com/docs/cli/{headless,mcp}`,\n * `/docs/cli/reference/{output-format,parameters,authentication,\n * permissions,configuration}`) and the option strings of the\n * 2026.10.16-e3cb207 release bundle (read, not executed), 2026-10-17. The\n * capability probe checks every flag against the installed `--help`.\n *\n * - Headless: `cursor-agent -p --output-format stream-json --trust <prompt>`;\n * with no positional prompt, stdin is the prompt. `--trust` is passed\n * because print mode exits in a directory that was never trusted — the\n * run's `cwd` is the caller's explicit choice.\n * - Stream: `system/init` (`session_id`, `model`), `user` echo, `assistant`\n * messages (`message.content[].text`), `tool_call` `started`/`completed`\n * (`call_id`; the tool is the single key of `tool_call`, e.g.\n * `readToolCall{args,result{success}}`), and a final `result` with\n * `usage{inputTokens (net of cache), outputTokens, cacheReadTokens,\n * cacheWriteTokens}`. Errors are not JSON: stderr and a non-zero exit.\n * - Permissions: headless default is the allowlist mode (unlisted actions are\n * rejected, changes only proposed); bypass is `--force`.\n * - MCP: no flag; `$HOME/.cursor/mcp.json` (the path ignores\n * `CURSOR_CONFIG_DIR`), plus `--approve-mcps` — needs a private home.\n * - Home: `HOME`/`USERPROFILE`, `CURSOR_CONFIG_DIR` and `CURSOR_DATA_DIR`\n * are pointed into it. Auth: `CURSOR_API_KEY`.\n */\nexport const cursorAdapter: CliAdapter = {\n name: \"cursor\",\n title: \"Cursor CLI\",\n command: \"cursor-agent\",\n apiKeyEnv: [\"CURSOR_API_KEY\"],\n homeEnv: [\"HOME\", \"USERPROFILE\", \"CURSOR_CONFIG_DIR\", \"CURSOR_DATA_DIR\"],\n transports: [\"argv\", \"stdin\"],\n effort: false,\n mcp: true,\n probe: { help: [[\"--help\"]], version: [\"--version\"] },\n verification: {\n version: \"2026.10.16-e3cb207\",\n verifiedBy: \"docs\",\n sources: [\n \"https://cursor.com/docs/cli/headless\",\n \"https://cursor.com/docs/cli/reference/output-format\",\n \"https://cursor.com/docs/cli/reference/parameters\",\n \"https://cursor.com/docs/cli/mcp\",\n ],\n checkedAt: \"2026-10-17\",\n },\n plan(context) {\n const args = [\"--print\", \"--output-format\", \"stream-json\", \"--trust\"];\n const requires = [\"--print\", \"--output-format\", \"stream-json\", \"--trust\"];\n const files: CliLaunchFile[] = [];\n\n if (context.model !== undefined) {\n args.push(\"--model\", context.model);\n requires.push(\"--model\");\n }\n\n if (context.resume !== undefined) {\n args.push(\"--resume\", context.resume);\n requires.push(\"--resume\");\n }\n\n if (context.permission === \"bypass\") {\n args.push(\"--force\");\n requires.push(\"--force\");\n }\n\n if (context.mcp !== undefined) {\n const home = requirePrivateHome(context, cursorAdapter, \"MCP servers\");\n\n files.push({\n path: path.join(home, \".cursor\", \"mcp.json\"),\n content: jsonFile({ mcpServers: mcpServersJson(context.mcp, { typeField: true }) }),\n });\n args.push(\"--approve-mcps\");\n requires.push(\"--approve-mcps\");\n }\n\n const env: Record<string, string> =\n context.home !== undefined\n ? {\n HOME: context.home,\n USERPROFILE: context.home,\n CURSOR_CONFIG_DIR: path.join(context.home, \".cursor\"),\n CURSOR_DATA_DIR: path.join(context.home, \".cursor\"),\n }\n : {};\n\n return {\n args,\n tail: context.transport === \"argv\" ? [argvPrompt(context.prompt)] : [],\n stdin: context.transport === \"stdin\" ? context.prompt : undefined,\n env,\n files,\n requires,\n };\n },\n parser: createCursorParser,\n};\n\n/** `readToolCall` → `read`; the documented `function{name}` fallback is used as-is. */\nfunction toolOf(toolCall: Record<string, unknown> | undefined): {\n name: string;\n body: Record<string, unknown> | undefined;\n} {\n const fn = recordField(toolCall, \"function\");\n\n if (fn !== undefined) {\n return { name: stringField(fn, \"name\") ?? \"function\", body: fn };\n }\n\n const key = Object.keys(toolCall ?? {})[0] ?? \"tool\";\n\n return { name: key.replace(/ToolCall$/, \"\"), body: recordField(toolCall, key) };\n}\n\n/** Parser for `cursor-agent -p --output-format stream-json`. */\nexport function createCursorParser(): CliStreamParser {\n return jsonLinesParser((record): CliParsedEvent[] => {\n switch (stringField(record, \"type\")) {\n case \"system\":\n return stringField(record, \"subtype\") === \"init\"\n ? [\n {\n type: \"session.started\",\n sessionRef: stringField(record, \"session_id\"),\n model: stringField(record, \"model\"),\n raw: record,\n },\n ]\n : [];\n case \"assistant\": {\n const text = asArray(recordField(record, \"message\")?.content)\n .map((block) => stringField(asRecord(block), \"text\") ?? \"\")\n .join(\"\");\n\n return text.length > 0 ? [{ type: \"message\", text, delta: false, raw: record }] : [];\n }\n case \"tool_call\": {\n const id = stringField(record, \"call_id\") ?? \"\";\n const { name, body } = toolOf(recordField(record, \"tool_call\"));\n\n if (stringField(record, \"subtype\") === \"started\") {\n return [\n {\n type: \"tool.call\",\n id,\n name,\n input: body?.args ?? parseArguments(body?.arguments),\n raw: record,\n },\n ];\n }\n\n if (stringField(record, \"subtype\") === \"completed\") {\n const result = recordField(body, \"result\");\n const success = recordField(result, \"success\");\n const content = stringField(success, \"content\");\n\n return [\n {\n type: \"tool.result\",\n id,\n output: success !== undefined ? (content ?? outputText(success)) : outputText(result),\n isError: success === undefined,\n raw: record,\n },\n ];\n }\n\n return [];\n }\n case \"result\": {\n const events: CliParsedEvent[] = [];\n const usage = recordField(record, \"usage\");\n\n if (usage !== undefined) {\n const cacheRead = numberField(usage, \"cacheReadTokens\") ?? 0;\n const cacheWrite = numberField(usage, \"cacheWriteTokens\") ?? 0;\n\n events.push({\n type: \"usage\",\n cumulative: true,\n usage: usageOf({\n input: (numberField(usage, \"inputTokens\") ?? 0) + cacheRead + cacheWrite,\n output: numberField(usage, \"outputTokens\"),\n cachedTokens: cacheRead > 0 ? cacheRead : undefined,\n cacheWriteTokens: cacheWrite > 0 ? cacheWrite : undefined,\n }),\n raw: record,\n });\n }\n\n if (record.is_error === true) {\n events.push({\n type: \"error\",\n message: stringField(record, \"result\") || \"Cursor CLI reported an error\",\n fatal: true,\n raw: record,\n });\n }\n\n // `result` concatenates every assistant message, so the final answer\n // is taken from the last assistant message instead.\n return events;\n }\n default:\n return [];\n }\n });\n}\n","import path from \"node:path\";\nimport type { CliAdapter, CliLaunchFile, CliParsedEvent, CliStreamParser } from \"../contracts\";\nimport { jsonLinesParser, outputText, recordField, stringField } from \"../stream/json-lines\";\nimport {\n anthropicUsage,\n argvPrompt,\n jsonFile,\n mcpServersJson,\n promptFile,\n requirePrivateHome,\n} from \"./shared\";\n\n/**\n * Factory Droid (`droid`, npm `droid` / `@factory/cli`).\n *\n * Verified against the real `droid exec --help` of 0.244.0, a real\n * `droid exec` run without credentials (init and error lines), the field\n * names in the shipped code and the docs (`docs.factory.ai/cli/droid-exec`,\n * `/cli/configuration/mcp`), 2026-10-17.\n *\n * - Headless: `droid exec -o stream-json <prompt>` (or `-f <file>`).\n * - Stream: `system/init` (`session_id`, `model`), whole `message` records\n * (`role`, `text`), `tool_call` (`id`, `toolName`, `parameters`),\n * `tool_result` (`id`, `isError`, `value` | `error.message`), a final\n * `completion` (`finalText`, `usage` with Anthropic-style\n * `input_tokens`/`cache_read_input_tokens`/`cache_creation_input_tokens`,\n * read with Anthropic semantics) and `error` (`source`, `message`).\n * Billing is in Factory credits; no USD cost is reported.\n * - Permissions: `standard` is Droid's default **read-only** autonomy; raise\n * it with `args: [\"--auto\", \"medium\"]` (low | medium | high). Bypass is\n * `--skip-permissions-unsafe`. Blocked actions end the run non-zero.\n * - MCP: `<home>/.factory/mcp.json` (`mcpServers`); the home is relocated\n * with `FACTORY_HOME_OVERRIDE` (found in the shipped code and confirmed\n * with `droid mcp list`), so per-run MCP needs a private home.\n * - Auth: `FACTORY_API_KEY`.\n */\nexport const droidAdapter: CliAdapter = {\n name: \"droid\",\n title: \"Factory Droid\",\n command: \"droid\",\n apiKeyEnv: [\"FACTORY_API_KEY\"],\n homeEnv: [\"FACTORY_HOME_OVERRIDE\"],\n transports: [\"argv\", \"file\"],\n effort: true,\n mcp: true,\n probe: { help: [[\"exec\", \"--help\"]], version: [\"--version\"] },\n verification: {\n version: \"0.244.0\",\n verifiedBy: \"help\",\n sources: [\n \"https://docs.factory.ai/cli/droid-exec/overview\",\n \"https://docs.factory.ai/cli/configuration/mcp\",\n \"https://www.npmjs.com/package/droid\",\n ],\n checkedAt: \"2026-10-17\",\n },\n plan(context) {\n const args = [\"exec\", \"--output-format\", \"stream-json\", \"--cwd\", context.cwd];\n const requires = [\"--output-format\", \"stream-json\", \"--cwd\"];\n const files: CliLaunchFile[] = [];\n let tail: string[];\n\n if (context.model !== undefined) {\n args.push(\"--model\", context.model);\n requires.push(\"--model\");\n }\n\n if (context.effort !== undefined) {\n // Accepted per model from off | none | minimal | low | medium | high | xhigh | max.\n args.push(\"--reasoning-effort\", context.effort);\n requires.push(\"--reasoning-effort\");\n }\n\n if (context.resume !== undefined) {\n args.push(\"--session-id\", context.resume);\n requires.push(\"--session-id\");\n }\n\n if (context.permission === \"bypass\") {\n args.push(\"--skip-permissions-unsafe\");\n requires.push(\"--skip-permissions-unsafe\");\n }\n\n if (context.mcp !== undefined) {\n const home = requirePrivateHome(context, droidAdapter, \"MCP servers\");\n\n files.push({\n path: path.join(home, \".factory\", \"mcp.json\"),\n content: jsonFile({ mcpServers: mcpServersJson(context.mcp, { typeField: true }) }),\n });\n }\n\n if (context.transport === \"file\") {\n const prompt = promptFile(context);\n\n files.push(prompt);\n tail = [\"--file\", prompt.path];\n requires.push(\"--file\");\n } else {\n tail = [argvPrompt(context.prompt)];\n }\n\n return {\n args,\n tail,\n env: {\n ...(context.home !== undefined ? { FACTORY_HOME_OVERRIDE: context.home } : {}),\n FACTORY_DROID_AUTO_UPDATE_ENABLED: \"false\",\n },\n files,\n requires,\n };\n },\n parser: createDroidParser,\n};\n\n/** Parser for `droid exec -o stream-json`. */\nexport function createDroidParser(): CliStreamParser {\n return jsonLinesParser((record): CliParsedEvent[] => {\n switch (stringField(record, \"type\")) {\n case \"system\":\n return stringField(record, \"subtype\") === \"init\"\n ? [\n {\n type: \"session.started\",\n sessionRef: stringField(record, \"session_id\"),\n model: stringField(record, \"model\"),\n raw: record,\n },\n ]\n : [];\n case \"message\": {\n const text = stringField(record, \"text\") ?? \"\";\n\n return stringField(record, \"role\") === \"assistant\" && text.length > 0\n ? [{ type: \"message\", text, delta: false, raw: record }]\n : [];\n }\n case \"tool_call\":\n return [\n {\n type: \"tool.call\",\n id: stringField(record, \"id\") ?? \"\",\n name: stringField(record, \"toolName\") ?? stringField(record, \"toolId\") ?? \"\",\n input: record.parameters,\n raw: record,\n },\n ];\n case \"tool_result\": {\n const error = recordField(record, \"error\");\n const isError = record.isError === true || error !== undefined;\n\n return [\n {\n type: \"tool.result\",\n id: stringField(record, \"id\") ?? \"\",\n output:\n isError && error !== undefined\n ? (stringField(error, \"message\") ?? \"\")\n : outputText(record.value),\n isError,\n raw: record,\n },\n ];\n }\n case \"completion\": {\n const events: CliParsedEvent[] = [];\n const usage = anthropicUsage(recordField(record, \"usage\"));\n\n if (usage !== undefined) {\n const thinking = recordField(record, \"usage\")?.thinking_tokens;\n\n if (typeof thinking === \"number\" && thinking > 0) {\n usage.reasoningTokens = thinking;\n }\n\n events.push({ type: \"usage\", usage, cumulative: true, raw: record });\n }\n\n const text = stringField(record, \"finalText\") ?? \"\";\n\n if (text.length > 0) {\n events.push({ type: \"message\", text, delta: false, final: true, raw: record });\n }\n\n return events;\n }\n case \"error\":\n return [\n {\n type: \"error\",\n message: stringField(record, \"message\") ?? \"Droid reported an error\",\n fatal: true,\n raw: record,\n },\n ];\n default:\n return [];\n }\n });\n}\n","import path from \"node:path\";\nimport type {\n CliAdapter,\n CliLaunchFile,\n CliMcpServers,\n CliParsedEvent,\n CliStreamParser,\n} from \"../contracts\";\nimport {\n jsonLinesParser,\n numberField,\n outputText,\n recordField,\n stringField,\n} from \"../stream/json-lines\";\nimport { type TomlTable, toToml } from \"../utils/toml\";\nimport {\n anthropicUsage,\n argvPrompt,\n promptFile,\n requirePrivateHome,\n unsupportedOption,\n} from \"./shared\";\n\n/**\n * Grok Build (`grok`) — xAI's official coding-agent CLI, installed by the\n * `x.ai/cli/install.sh` script (no npm package).\n *\n * Verified against the docs and source only (the binary is distributed by\n * a curl installer, which was not run): the repo user guide\n * `crates/codegen/xai-grok-pager/docs/user-guide/{14-headless-mode,\n * 07-mcp-servers,05-configuration,22-permissions-and-safety}.md`, the clap\n * definitions in `xai-grok-pager/src/app/cli.rs` and the headless reducer\n * `headless/reducer/acp.rs`, at source version 1.0.45; latest stable 1.0.62\n * (2026-10-17). The capability probe checks every flag against the\n * installed binary's `--help` before the first run.\n *\n * - Headless: `grok -p <prompt>` or `--prompt-file <path>`; piped stdin is\n * not read. `--output-format streaming-json` prints `type`-tagged lines:\n * `text`, `thought`, `tool_call`, `tool_call_update`, `usage` (per model\n * response, `input_tokens` uncached) and a final `end` (session id, totals,\n * `total_cost_usd`); failures print `{\"type\":\"error\",\"message\"}`.\n * - Permissions: headless mode answers every approval request with\n * \"cancelled\" (auto-deny); bypass is `--always-approve`.\n * - MCP: no flag; `[mcp_servers.<name>]` in `$GROK_HOME/config.toml`.\n * - Auth: `XAI_API_KEY`. Update checks are disabled with\n * `GROK_DISABLE_AUTOUPDATER=1`.\n */\nexport const grokAdapter: CliAdapter = {\n name: \"grok\",\n title: \"Grok Build\",\n command: \"grok\",\n apiKeyEnv: [\"XAI_API_KEY\"],\n homeEnv: [\"GROK_HOME\"],\n transports: [\"argv\", \"file\"],\n effort: true,\n mcp: true,\n probe: { help: [[\"--help\"]], version: [\"--version\"] },\n verification: {\n version: \"1.0.62\",\n verifiedBy: \"docs\",\n sources: [\n \"https://docs.x.ai/build/cli/headless-scripting\",\n \"https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/docs/user-guide/14-headless-mode.md\",\n \"https://github.com/xai-org/grok-build/blob/main/crates/codegen/xai-grok-pager/docs/user-guide/07-mcp-servers.md\",\n ],\n checkedAt: \"2026-10-17\",\n },\n plan(context) {\n const args = [\"--output-format\", \"streaming-json\"];\n const requires = [\"--output-format\", \"streaming-json\"];\n const files: CliLaunchFile[] = [];\n let tail: string[];\n\n if (context.model !== undefined) {\n args.push(\"--model\", context.model);\n requires.push(\"--model\");\n }\n\n if (context.effort !== undefined) {\n // Grok accepts the framework scale verbatim (none … max, model-dependent).\n args.push(\"--reasoning-effort\", context.effort);\n requires.push(\"--reasoning-effort\");\n }\n\n if (context.resume !== undefined) {\n args.push(\"--resume\", context.resume);\n requires.push(\"--resume\");\n }\n\n if (context.permission === \"bypass\") {\n args.push(\"--always-approve\");\n requires.push(\"--always-approve\");\n }\n\n if (context.mcp !== undefined) {\n const home = requirePrivateHome(context, grokAdapter, \"MCP servers\");\n\n files.push({\n path: path.join(home, \"config.toml\"),\n content: toToml({ mcp_servers: grokMcp(context.mcp) }),\n });\n }\n\n if (context.transport === \"file\") {\n const prompt = promptFile(context);\n\n files.push(prompt);\n tail = [\"--prompt-file\", prompt.path];\n requires.push(\"--prompt-file\");\n } else {\n tail = [\"-p\", argvPrompt(context.prompt)];\n requires.push(\"-p\");\n }\n\n return {\n args,\n tail,\n env: {\n ...(context.home !== undefined ? { GROK_HOME: context.home } : {}),\n GROK_DISABLE_AUTOUPDATER: \"1\",\n },\n files,\n requires,\n };\n },\n parser: createGrokParser,\n};\n\nfunction grokMcp(servers: CliMcpServers): TomlTable {\n const table: TomlTable = {};\n\n for (const [name, server] of Object.entries(servers)) {\n if (server.type === \"sse\") {\n throw unsupportedOption(\n grokAdapter,\n `MCP server \"${name}\" uses SSE; Grok Build supports stdio and HTTP servers.`,\n );\n }\n\n table[name] =\n server.type === \"stdio\"\n ? { command: server.command, args: server.args ?? [], env: server.env }\n : { url: server.url, headers: server.headers };\n }\n\n return table;\n}\n\n/** Parser for `grok -p … --output-format streaming-json`. */\nexport function createGrokParser(): CliStreamParser {\n let started = false;\n let sessionRef: string | undefined;\n\n const parser = jsonLinesParser((record): CliParsedEvent[] => {\n const events: CliParsedEvent[] = [];\n\n if (!started) {\n started = true;\n events.push({ type: \"session.started\" });\n }\n\n switch (stringField(record, \"type\")) {\n case \"text\": {\n const text = stringField(record, \"data\") ?? \"\";\n\n if (text.length > 0) {\n events.push({ type: \"message\", text, delta: true, raw: record });\n }\n break;\n }\n case \"tool_call\":\n events.push({\n type: \"tool.call\",\n id: stringField(record, \"toolCallId\") ?? \"\",\n name: stringField(record, \"toolName\") ?? stringField(record, \"title\") ?? \"\",\n input: record.rawInput,\n raw: record,\n });\n break;\n case \"tool_call_update\": {\n const status = stringField(record, \"status\");\n\n if (status === \"completed\" || status === \"failed\") {\n events.push({\n type: \"tool.result\",\n id: stringField(record, \"toolCallId\") ?? \"\",\n output: outputText(record.rawOutput ?? record.content),\n isError: status === \"failed\",\n raw: record,\n });\n }\n break;\n }\n case \"usage\": {\n const usage = anthropicUsage(recordField(record, \"usage\"));\n\n if (usage !== undefined) {\n events.push({ type: \"usage\", usage, cumulative: false, raw: record });\n }\n break;\n }\n case \"end\": {\n sessionRef = stringField(record, \"sessionId\") ?? sessionRef;\n\n const usage = anthropicUsage(\n recordField(record, \"usage\"),\n numberField(record, \"total_cost_usd\"),\n );\n\n if (usage !== undefined) {\n events.push({ type: \"usage\", usage, cumulative: true, raw: record });\n }\n break;\n }\n case \"error\":\n events.push({\n type: \"error\",\n message: stringField(record, \"message\") ?? \"Grok Build reported an error\",\n fatal: true,\n raw: record,\n });\n break;\n }\n\n return events;\n });\n\n return { ...parser, sessionRef: () => sessionRef };\n}\n","import path from \"node:path\";\nimport type {\n CliAdapter,\n CliLaunchFile,\n CliMcpServers,\n CliParsedEvent,\n CliStreamParser,\n} from \"../contracts\";\nimport { asArray, asRecord, jsonLinesParser, outputText, stringField } from \"../stream/json-lines\";\nimport {\n argvPrompt,\n jsonFile,\n mcpServersJson,\n parseArguments,\n requirePrivateHome,\n unsupportedOption,\n} from \"./shared\";\n\n/**\n * Kimi Code CLI (`kimi`, npm `@moonshot-ai/kimi-code`) — Moonshot AI's\n * coding agent, the successor of the archived Python `kimi-cli`.\n *\n * Verified against the real `kimi --help` of 2.2.0 and the docs/source at\n * that tag (`docs/en/reference/kimi-command.md`, `apps/kimi-code/src/cli/\n * {options.ts,prompt-render.ts,v2/run-v2-print.ts}`), 2026-10-17.\n *\n * - Headless: `kimi -p <prompt> --output-format stream-json`; the prompt is\n * an argv value only (print mode never reads stdin).\n * - Stream: OpenAI-chat-shaped messages, one per line, never deltas:\n * `{\"role\":\"assistant\",\"content\",\"tool_calls\"}`, `{\"role\":\"tool\",\n * \"tool_call_id\",\"content\"}`, and `{\"role\":\"meta\",\"type\":…}` records. The\n * session id appears only in the final `session.resume_hint` record.\n * No token usage is printed.\n * - Permissions: print mode always runs in \"Never Ask\" mode (every tool call\n * runs; only static deny rules apply) and rejects `--yolo`/`--plan`, so\n * there is no standard mode to choose. The adapter refuses\n * `permission: \"standard\"` instead of pretending to enforce it; pass\n * `\"bypass\"` to accept the CLI's behaviour.\n * - MCP: no flag; `$KIMI_CODE_HOME/mcp.json` (`mcpServers`), so per-run MCP\n * needs a private home.\n * - Auth: shell `KIMI_API_KEY`/`MOONSHOT_API_KEY` are not read. For an API\n * key set `KIMI_MODEL_NAME` (and optionally `KIMI_MODEL_PROVIDER_TYPE`,\n * `KIMI_MODEL_BASE_URL`) in `env`; `apiKey` becomes `KIMI_MODEL_API_KEY`.\n */\nexport const kimiAdapter: CliAdapter = {\n name: \"kimi\",\n title: \"Kimi Code\",\n command: \"kimi\",\n apiKeyEnv: [\"KIMI_MODEL_API_KEY\"],\n homeEnv: [\"KIMI_CODE_HOME\"],\n transports: [\"argv\"],\n effort: false,\n mcp: true,\n probe: { help: [[\"--help\"]], version: [\"--version\"] },\n verification: {\n version: \"2.2.0\",\n verifiedBy: \"help\",\n sources: [\n \"https://moonshotai.github.io/kimi-code/\",\n \"https://github.com/MoonshotAI/kimi-code/blob/%40moonshot-ai/kimi-code%402.2.0/docs/en/reference/kimi-command.md\",\n \"https://github.com/MoonshotAI/kimi-code/blob/%40moonshot-ai/kimi-code%402.2.0/docs/en/customization/mcp.md\",\n ],\n checkedAt: \"2026-10-17\",\n },\n plan(context) {\n if (context.permission !== \"bypass\") {\n throw unsupportedOption(\n kimiAdapter,\n 'print mode runs every tool call without asking and has no standard approval mode; pass `permission: \"bypass\"` to run it.',\n );\n }\n\n const args = [\"--output-format\", \"stream-json\"];\n const requires = [\"-p\", \"--output-format\", \"stream-json\"];\n const files: CliLaunchFile[] = [];\n\n if (context.model !== undefined) {\n args.push(\"--model\", context.model);\n requires.push(\"--model\");\n }\n\n if (context.resume !== undefined) {\n args.push(\"--session\", context.resume);\n requires.push(\"--session\");\n }\n\n if (context.mcp !== undefined) {\n const home = requirePrivateHome(context, kimiAdapter, \"MCP servers\");\n\n files.push({\n path: path.join(home, \"mcp.json\"),\n content: jsonFile({ mcpServers: kimiMcp(context.mcp) }),\n });\n }\n\n return {\n args,\n tail: [\"-p\", argvPrompt(context.prompt)],\n env: {\n ...(context.home !== undefined ? { KIMI_CODE_HOME: context.home } : {}),\n KIMI_CODE_NO_AUTO_UPDATE: \"1\",\n KIMI_DISABLE_TELEMETRY: \"1\",\n },\n files,\n requires,\n };\n },\n parser: createKimiParser,\n};\n\n/** Kimi's `mcpServers`: SSE servers are marked with `transport: \"sse\"`. */\nfunction kimiMcp(servers: CliMcpServers): Record<string, unknown> {\n const rendered = mcpServersJson(servers);\n\n for (const [name, server] of Object.entries(servers)) {\n const entry = rendered[name];\n\n if (server.type === \"sse\" && entry !== undefined) {\n entry.transport = \"sse\";\n }\n }\n\n return rendered;\n}\n\n/** Parser for `kimi -p … --output-format stream-json`. */\nexport function createKimiParser(): CliStreamParser {\n let sessionRef: string | undefined;\n\n const parser = jsonLinesParser((record): CliParsedEvent[] => {\n const role = stringField(record, \"role\");\n\n if (role === \"meta\") {\n const type = stringField(record, \"type\");\n\n if (type === \"system.version\") {\n return [{ type: \"session.started\", raw: record }];\n }\n\n if (type === \"session.resume_hint\") {\n sessionRef = stringField(record, \"session_id\");\n\n return [];\n }\n\n if (type === \"turn.step.retrying\") {\n return [\n {\n type: \"error\",\n message: `retrying after ${stringField(record, \"error_name\") ?? \"error\"}: ${stringField(record, \"error_message\") ?? \"\"}`,\n raw: record,\n },\n ];\n }\n\n return [];\n }\n\n if (role === \"assistant\") {\n const events: CliParsedEvent[] = [];\n const content = stringField(record, \"content\");\n\n if (content !== undefined && content.length > 0) {\n events.push({ type: \"message\", text: content, delta: false, raw: record });\n }\n\n for (const item of asArray(record.tool_calls)) {\n const call = asRecord(item);\n const fn = asRecord(call?.function);\n\n events.push({\n type: \"tool.call\",\n id: stringField(call, \"id\") ?? \"\",\n name: stringField(fn, \"name\") ?? \"\",\n input: parseArguments(fn?.arguments),\n raw: item,\n });\n }\n\n return events;\n }\n\n if (role === \"tool\") {\n return [\n {\n type: \"tool.result\",\n id: stringField(record, \"tool_call_id\") ?? \"\",\n output: outputText(record.content),\n isError: false,\n raw: record,\n },\n ];\n }\n\n return [];\n });\n\n return { ...parser, sessionRef: () => sessionRef };\n}\n","import { readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport type {\n CliAdapter,\n CliLaunchContext,\n CliLaunchFile,\n CliMcpServers,\n CliParsedEvent,\n CliStreamParser,\n} from \"../contracts\";\nimport {\n asArray,\n asRecord,\n jsonLinesParser,\n numberField,\n outputText,\n parseJsonLine,\n recordField,\n stringField,\n} from \"../stream/json-lines\";\nimport { type TomlTable, toToml } from \"../utils/toml\";\nimport { argvPrompt, promptFile, requirePrivateHome, usageOf } from \"./shared\";\n\n/** Folder (inside the run directory) Vibe writes `export.json` to. */\nconst EXPORT_DIR = \"vibe-output\";\n\n/**\n * Mistral Vibe (`vibe`, PyPI `mistral-vibe`).\n *\n * Verified against the official repo at tag v2.26.1 only (README,\n * `vibe/cli/entrypoint.py`, `vibe/cli/programmatic.py`,\n * `vibe/app_server/run_export.py`, `vibe/core/config/*`); Vibe needs Python\n * 3.12, so no real `--help` was run, 2026-10-17. The capability probe checks\n * every flag against the installed `--help`.\n *\n * - Headless: `vibe -p <prompt> --output streaming` (or `--prompt-file`;\n * `-p` with no value reads stdin). The stream is NDJSON of completed\n * history entries (camelCase): `message` (`role`, `content[].text`), and\n * `effect` — a tool call and its result in one line (`detail.toolName`,\n * `detail.input`, `state.status`, `state.outputText`/`state.error`).\n * There is no usage, cost or final record in the stream, so the adapter\n * adds `--output-dir` and reads usage, cost, session id and outcome from\n * `export.json` when the stream ends.\n * - Model: no flag; `VIBE_ACTIVE_MODEL=<alias>` (set from `model`). Effort\n * is a per-model config field, so `effort` is refused.\n * - Permissions: headless auto-denies every approval (the default agent\n * only auto-approves file edits); bypass is `--auto-approve`.\n * - MCP: `[[mcp_servers]]` in `$VIBE_HOME/config.toml` (private home).\n * - Auth: `MISTRAL_API_KEY`; home `VIBE_HOME`.\n */\nexport const mistralVibeAdapter: CliAdapter = {\n name: \"mistral-vibe\",\n title: \"Mistral Vibe\",\n command: \"vibe\",\n apiKeyEnv: [\"MISTRAL_API_KEY\"],\n homeEnv: [\"VIBE_HOME\"],\n transports: [\"argv\", \"file\", \"stdin\"],\n effort: false,\n mcp: true,\n probe: { help: [[\"--help\"]], version: [\"--version\"] },\n verification: {\n version: \"2.26.1\",\n verifiedBy: \"docs\",\n sources: [\n \"https://github.com/mistralai/mistral-vibe/blob/v2.26.1/README.md\",\n \"https://github.com/mistralai/mistral-vibe/blob/v2.26.1/vibe/cli/entrypoint.py\",\n \"https://github.com/mistralai/mistral-vibe/blob/v2.26.1/vibe/cli/programmatic.py\",\n ],\n checkedAt: \"2026-10-17\",\n },\n plan(context) {\n const args = [\"--output\", \"streaming\", \"--output-dir\", path.join(context.runDir, EXPORT_DIR)];\n const requires = [\"--output\", \"streaming\", \"--output-dir\"];\n const files: CliLaunchFile[] = [];\n const env: Record<string, string> = {};\n\n if (context.model !== undefined) {\n env.VIBE_ACTIVE_MODEL = context.model;\n }\n\n if (context.resume !== undefined) {\n args.push(\"--resume\", context.resume);\n requires.push(\"--resume\");\n }\n\n if (context.permission === \"bypass\") {\n args.push(\"--auto-approve\");\n requires.push(\"--auto-approve\");\n }\n\n if (context.mcp !== undefined) {\n const home = requirePrivateHome(context, mistralVibeAdapter, \"MCP servers\");\n\n files.push({\n path: path.join(home, \"config.toml\"),\n content: toToml({ mcp_servers: vibeMcp(context.mcp) }),\n });\n }\n\n if (context.home !== undefined) {\n env.VIBE_HOME = context.home;\n }\n\n if (context.transport === \"file\") {\n const prompt = promptFile(context);\n\n files.push(prompt);\n requires.push(\"--prompt-file\");\n\n return { args, tail: [\"--prompt-file\", prompt.path], env, files, requires };\n }\n\n requires.push(\"-p\");\n\n if (context.transport === \"stdin\") {\n return { args, tail: [\"-p\"], stdin: context.prompt, env, files, requires };\n }\n\n return { args, tail: [\"-p\", argvPrompt(context.prompt)], env, files, requires };\n },\n parser: createVibeParser,\n};\n\nfunction vibeMcp(servers: CliMcpServers): TomlTable[] {\n return Object.entries(servers).map(([name, server]): TomlTable =>\n server.type === \"stdio\"\n ? {\n name,\n transport: \"stdio\",\n command: server.command,\n args: server.args ?? [],\n env: server.env,\n }\n : {\n name,\n transport: server.type === \"http\" ? \"streamable-http\" : \"http\",\n url: server.url,\n auth:\n server.headers !== undefined ? { type: \"static\", headers: server.headers } : undefined,\n },\n );\n}\n\n/** Read Vibe's `export.json`: usage, cost, session id and outcome of the run. */\nfunction exportEvents(context: CliLaunchContext | undefined): {\n events: CliParsedEvent[];\n sessionRef?: string;\n} {\n if (context === undefined) {\n return { events: [] };\n }\n\n let report: Record<string, unknown> | undefined;\n\n try {\n report = parseJsonLine(\n readFileSync(path.join(context.runDir, EXPORT_DIR, \"export.json\"), \"utf8\"),\n );\n } catch {\n return { events: [] };\n }\n\n if (report === undefined) {\n return { events: [] };\n }\n\n const events: CliParsedEvent[] = [];\n const usage = recordField(report, \"usage\");\n\n if (usage !== undefined) {\n const cached = numberField(usage, \"cached_input_tokens\");\n\n events.push({\n type: \"usage\",\n cumulative: true,\n usage: usageOf({\n input: numberField(usage, \"input_tokens\"),\n output: numberField(usage, \"output_tokens\"),\n total: numberField(usage, \"total_tokens\"),\n cachedTokens: cached !== undefined && cached > 0 ? cached : undefined,\n costUSD: numberField(report, \"cost_usd\"),\n }),\n raw: report,\n });\n }\n\n const outcome = stringField(report, \"outcome\");\n\n if (outcome !== undefined && outcome !== \"finished\") {\n events.push({\n type: \"error\",\n message:\n stringField(recordField(report, \"error\"), \"message\") ?? `Mistral Vibe stopped: ${outcome}`,\n fatal: true,\n raw: report,\n });\n }\n\n return { events, sessionRef: stringField(report, \"session_id\") };\n}\n\n/** Parser for `vibe -p … --output streaming` (plus the run's `export.json`). */\nexport function createVibeParser(context?: CliLaunchContext): CliStreamParser {\n let started = false;\n let sessionRef: string | undefined;\n\n const parser = jsonLinesParser(\n (record): CliParsedEvent[] => {\n const events: CliParsedEvent[] = [];\n const session = stringField(record, \"sessionId\");\n\n if (session !== undefined) {\n sessionRef = session;\n }\n\n if (!started) {\n started = true;\n events.push({ type: \"session.started\", sessionRef: session, raw: record });\n }\n\n switch (stringField(record, \"type\")) {\n case \"message\": {\n if (stringField(record, \"role\") !== \"assistant\") {\n break;\n }\n\n const text = asArray(record.content)\n .map((block) => stringField(asRecord(block), \"text\") ?? \"\")\n .join(\"\");\n\n if (text.length > 0) {\n events.push({ type: \"message\", text, delta: false, raw: record });\n }\n break;\n }\n case \"effect\": {\n const detail = recordField(record, \"detail\");\n const state = recordField(record, \"state\");\n const status = stringField(state, \"status\");\n const id = stringField(record, \"id\") ?? \"\";\n\n events.push({\n type: \"tool.call\",\n id,\n name: stringField(detail, \"toolName\") ?? stringField(record, \"title\") ?? \"\",\n input: detail?.input,\n raw: record,\n });\n\n if (\n status === \"completed\" ||\n status === \"failed\" ||\n status === \"cancelled\" ||\n status === \"skipped\"\n ) {\n const error = stringField(recordField(state, \"error\"), \"message\");\n\n events.push({\n type: \"tool.result\",\n id,\n output: error ?? stringField(state, \"outputText\") ?? outputText(state?.output),\n isError: status !== \"completed\",\n raw: record,\n });\n }\n break;\n }\n case \"notice\":\n if (stringField(record, \"level\") === \"error\") {\n events.push({\n type: \"error\",\n message: stringField(record, \"message\") ?? \"error\",\n raw: record,\n });\n }\n break;\n }\n\n return events;\n },\n () => {\n const exported = exportEvents(context);\n\n sessionRef = exported.sessionRef ?? sessionRef;\n\n return exported.events;\n },\n );\n\n return { ...parser, sessionRef: () => sessionRef };\n}\n","import path from \"node:path\";\nimport type {\n CliAdapter,\n CliLaunchFile,\n CliMcpServers,\n CliParsedEvent,\n CliStreamParser,\n} from \"../contracts\";\nimport {\n asRecord,\n jsonLinesParser,\n numberField,\n recordField,\n stringField,\n} from \"../stream/json-lines\";\nimport { argvPrompt, jsonFile, usageOf } from \"./shared\";\n\n/**\n * OpenCode (`opencode`, npm `opencode-ai`).\n *\n * Verified against the real `opencode --help` / `opencode run --help` of\n * 1.19.3, the CLI source at that tag (`packages/opencode/src/cli/cmd/run.ts`)\n * and the docs (`cli.mdx`, `config.mdx`, `mcp-servers.mdx`,\n * `permissions.mdx`), 2026-10-17.\n *\n * - Headless: `opencode run --format json <message..>`; with no message,\n * piped stdin is the prompt.\n * - Stream: `{\"type\",\"timestamp\",\"sessionID\",\"part\"|\"error\"}` lines of six\n * types: `step_start`, `text` (whole text blocks, no deltas), `reasoning`,\n * `tool_use` (emitted once the tool finished — call and result together,\n * `state.status` `completed`/`error`), `step_finish` (per-step `cost` in\n * USD and `tokens{input,output,reasoning,cache{read,write}}`, input net of\n * cache) and `error{error:{name,data:{message}}}`. No init or final record.\n * - Permissions: `standard` keeps OpenCode's own rules (permissive by\n * default; anything that would ask is auto-rejected in `run`); bypass is\n * `--auto`.\n * - MCP: the `mcp` key of a config file named by `OPENCODE_CONFIG`, written\n * to the run directory — works with any home.\n * - Home: OpenCode follows XDG; a private/owned home sets `XDG_CONFIG_HOME`,\n * `XDG_DATA_HOME` (auth lives here), `XDG_STATE_HOME` and `XDG_CACHE_HOME`\n * beneath it. Provider keys use the provider's own variable\n * (`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, …) — pass them through `env`.\n * - The working directory is passed with `--dir`, because OpenCode prefers a\n * (possibly stale) `PWD` over the process cwd.\n */\nexport const opencodeAdapter: CliAdapter = {\n name: \"opencode\",\n title: \"OpenCode\",\n command: \"opencode\",\n apiKeyEnv: [],\n homeEnv: [\"XDG_CONFIG_HOME\", \"XDG_DATA_HOME\", \"XDG_STATE_HOME\", \"XDG_CACHE_HOME\"],\n transports: [\"argv\", \"stdin\"],\n effort: true,\n mcp: true,\n probe: { help: [[\"run\", \"--help\"]], version: [\"--version\"] },\n verification: {\n version: \"1.19.3\",\n verifiedBy: \"help\",\n sources: [\n \"https://opencode.ai/docs/cli/\",\n \"https://opencode.ai/docs/mcp-servers/\",\n \"https://opencode.ai/docs/permissions/\",\n \"https://github.com/anomalyco/opencode/blob/v1.19.3/packages/opencode/src/cli/cmd/run.ts\",\n ],\n checkedAt: \"2026-10-17\",\n },\n plan(context) {\n const args = [\"run\", \"--format\", \"json\", \"--dir\", context.cwd];\n const requires = [\"--format\", \"--dir\"];\n const files: CliLaunchFile[] = [];\n const env: Record<string, string> = { OPENCODE_DISABLE_AUTOUPDATE: \"1\" };\n\n if (context.model !== undefined) {\n args.push(\"--model\", context.model);\n requires.push(\"--model\");\n }\n\n if (context.effort !== undefined) {\n // `--variant` is provider-specific (\"high, max, minimal\"); the level is passed as-is.\n args.push(\"--variant\", context.effort);\n requires.push(\"--variant\");\n }\n\n if (context.resume !== undefined) {\n args.push(\"--session\", context.resume);\n requires.push(\"--session\");\n }\n\n if (context.permission === \"bypass\") {\n args.push(\"--auto\");\n requires.push(\"--auto\");\n }\n\n if (context.mcp !== undefined) {\n const file = path.join(context.runDir, \"opencode.json\");\n\n files.push({\n path: file,\n content: jsonFile({\n $schema: \"https://opencode.ai/config.json\",\n mcp: opencodeMcp(context.mcp),\n }),\n });\n env.OPENCODE_CONFIG = file;\n }\n\n if (context.home !== undefined) {\n env.XDG_CONFIG_HOME = path.join(context.home, \"config\");\n env.XDG_DATA_HOME = path.join(context.home, \"data\");\n env.XDG_STATE_HOME = path.join(context.home, \"state\");\n env.XDG_CACHE_HOME = path.join(context.home, \"cache\");\n }\n\n return {\n args,\n tail: context.transport === \"argv\" ? [argvPrompt(context.prompt)] : [],\n stdin: context.transport === \"stdin\" ? context.prompt : undefined,\n env,\n files,\n requires,\n };\n },\n parser: createOpencodeParser,\n};\n\nfunction opencodeMcp(servers: CliMcpServers): Record<string, unknown> {\n const rendered: Record<string, unknown> = {};\n\n for (const [name, server] of Object.entries(servers)) {\n rendered[name] =\n server.type === \"stdio\"\n ? {\n type: \"local\",\n command: [server.command, ...(server.args ?? [])],\n ...(server.env !== undefined ? { environment: server.env } : {}),\n enabled: true,\n }\n : {\n type: \"remote\",\n url: server.url,\n ...(server.headers !== undefined ? { headers: server.headers } : {}),\n enabled: true,\n };\n }\n\n return rendered;\n}\n\n/** Parser for `opencode run --format json`. */\nexport function createOpencodeParser(): CliStreamParser {\n let started = false;\n\n return jsonLinesParser((record): CliParsedEvent[] => {\n const events: CliParsedEvent[] = [];\n const part = recordField(record, \"part\");\n\n if (!started) {\n started = true;\n events.push({\n type: \"session.started\",\n sessionRef: stringField(record, \"sessionID\"),\n raw: record,\n });\n }\n\n switch (stringField(record, \"type\")) {\n case \"text\": {\n const text = stringField(part, \"text\") ?? \"\";\n\n if (text.length > 0) {\n events.push({ type: \"message\", text, delta: false, raw: record });\n }\n break;\n }\n case \"tool_use\": {\n const state = recordField(part, \"state\");\n const id = stringField(part, \"callID\") ?? stringField(part, \"id\") ?? \"\";\n const failed = stringField(state, \"status\") === \"error\";\n\n events.push(\n {\n type: \"tool.call\",\n id,\n name: stringField(part, \"tool\") ?? \"\",\n input: state?.input,\n raw: record,\n },\n {\n type: \"tool.result\",\n id,\n output: (failed ? stringField(state, \"error\") : stringField(state, \"output\")) ?? \"\",\n isError: failed,\n raw: record,\n },\n );\n break;\n }\n case \"step_finish\": {\n const tokens = recordField(part, \"tokens\");\n const cache = recordField(tokens, \"cache\");\n\n if (tokens !== undefined) {\n const uncached = numberField(tokens, \"input\") ?? 0;\n const cacheRead = numberField(cache, \"read\") ?? 0;\n const cacheWrite = numberField(cache, \"write\") ?? 0;\n\n events.push({\n type: \"usage\",\n cumulative: false,\n usage: usageOf({\n input: uncached + cacheRead + cacheWrite,\n output: numberField(tokens, \"output\"),\n cachedTokens: cacheRead > 0 ? cacheRead : undefined,\n cacheWriteTokens: cacheWrite > 0 ? cacheWrite : undefined,\n reasoningTokens: numberField(tokens, \"reasoning\") || undefined,\n costUSD: numberField(part, \"cost\"),\n }),\n raw: record,\n });\n }\n break;\n }\n case \"error\": {\n const error = asRecord(record.error);\n const name = stringField(error, \"name\") ?? \"Error\";\n const message = stringField(recordField(error, \"data\"), \"message\") ?? name;\n\n events.push({ type: \"error\", message: `${name}: ${message}`, fatal: true, raw: record });\n break;\n }\n }\n\n return events;\n });\n}\n","import path from \"node:path\";\nimport type { CliAdapter, CliLaunchFile } from \"../contracts\";\nimport { createClaudeStreamParser } from \"./claude-stream\";\nimport { argvPrompt, jsonFile, mcpServersJson } from \"./shared\";\n\n/**\n * Qwen Code (`qwen`, npm `@qwen-code/qwen-code`), a Gemini CLI fork.\n *\n * Verified against the real `qwen --help` of 0.25.2 and the docs/source at\n * tag v0.25.2 (`docs/users/features/headless.md`, `nonInteractive/types.ts`),\n * 2026-10-17.\n *\n * - Headless: positional prompt (`-p` is deprecated) with\n * `--output-format stream-json`; piped stdin is used as the prompt when no\n * positional prompt is given.\n * - Stream: the Claude Code `stream-json` shape (`system/init`, `assistant`,\n * `user` tool results, `result`), with `input_tokens` that already include\n * cached tokens and no cost field.\n * - Permissions: headless auto-denies tools that need confirmation (the tool\n * result says so and `permission_denials` lists it); bypass is `--yolo`.\n * - MCP: `--mcp-config <file>` with `{\"mcpServers\":…}` — written to the run\n * directory, so it works with any home. Remote servers use `httpUrl`\n * (streamable HTTP) or `url` (SSE).\n * - Home: `QWEN_HOME`. Auth depends on the auth type: `OPENAI_API_KEY`\n * (default for `apiKey`), or `ANTHROPIC_API_KEY` / `GEMINI_API_KEY` with\n * `--auth-type` in `args`.\n * - Effort has no flag (it is the `model.reasoningEffort` setting), so\n * `effort` is refused.\n */\nexport const qwenCodeAdapter: CliAdapter = {\n name: \"qwen-code\",\n title: \"Qwen Code\",\n command: \"qwen\",\n apiKeyEnv: [\"OPENAI_API_KEY\"],\n homeEnv: [\"QWEN_HOME\"],\n transports: [\"argv\", \"stdin\"],\n effort: false,\n mcp: true,\n probe: { help: [[\"--help\"]], version: [\"--version\"] },\n verification: {\n version: \"0.25.2\",\n verifiedBy: \"help\",\n sources: [\n \"https://qwenlm.github.io/qwen-code-docs/\",\n \"https://github.com/QwenLM/qwen-code/blob/v0.25.2/docs/users/features/headless.md\",\n ],\n checkedAt: \"2026-10-17\",\n },\n plan(context) {\n const args = [\"--output-format\", \"stream-json\"];\n const requires = [\"--output-format\", \"stream-json\"];\n const files: CliLaunchFile[] = [];\n\n if (context.model !== undefined) {\n args.push(\"--model\", context.model);\n requires.push(\"--model\");\n }\n\n if (context.resume !== undefined) {\n args.push(\"--resume\", context.resume);\n requires.push(\"--resume\");\n }\n\n if (context.permission === \"bypass\") {\n args.push(\"--yolo\");\n requires.push(\"--yolo\");\n }\n\n if (context.mcp !== undefined) {\n const file = path.join(context.runDir, \"mcp.json\");\n\n files.push({\n path: file,\n content: jsonFile({ mcpServers: mcpServersJson(context.mcp, { httpUrlKey: \"httpUrl\" }) }),\n });\n args.push(\"--mcp-config\", file);\n requires.push(\"--mcp-config\");\n }\n\n return {\n args,\n tail: context.transport === \"argv\" ? [argvPrompt(context.prompt)] : [],\n stdin: context.transport === \"stdin\" ? context.prompt : undefined,\n env: {\n ...(context.home !== undefined ? { QWEN_HOME: context.home } : {}),\n QWEN_CODE_SUPPRESS_YOLO_WARNING: \"1\",\n },\n files,\n requires,\n };\n },\n parser: () => createClaudeStreamParser({ usage: \"inclusive\", vendor: \"Qwen Code\" }),\n};\n","import path from \"node:path\";\nimport type {\n CliAdapter,\n CliLaunchFile,\n CliMcpServers,\n CliParsedEvent,\n CliStreamParser,\n CliUsage,\n} from \"../contracts\";\nimport {\n asRecord,\n jsonLinesParser,\n numberField,\n recordField,\n stringField,\n type JsonRecord,\n} from \"../stream/json-lines\";\nimport { type TomlTable, toToml } from \"../utils/toml\";\nimport {\n argvPrompt,\n dotenvFile,\n mapEffort,\n parseArguments,\n requirePrivateHome,\n usageOf,\n} from \"./shared\";\n\n/**\n * Reasonix (`reasonix`, npm `reasonix`) — a cache-first coding agent built\n * around DeepSeek (now multi-provider); the npm package launches a prebuilt\n * Go binary.\n *\n * Verified against the real `reasonix run --help` / `--version` of 2.43.0,\n * real stream-json output (captured against a local fake model server) and\n * the docs at that tag (`docs/CLI.md`, `docs/CONFIG_PATHS.md`), 2026-10-17.\n *\n * - Headless: `reasonix run --output-format stream-json <task>`; with no\n * positional task, piped stdin is the prompt.\n * - Stream: every line has `kind` (`text` deltas, `message` full text,\n * `tool_dispatch`/`tool_started`/`tool_result` with a `tool` object whose\n * non-empty `err` marks a failure, `usage` per model call, `turn_done`) plus\n * `sessionId`; the final line is `{\"type\":\"result\",…}` with totals.\n * - Permissions: headless \"ask\" mode refuses writes (listed in\n * `permission_denials`; exit 4 in an untrusted folder); bypass is `--yolo`.\n * - MCP: no flag; `[[plugins]]` in `$REASONIX_HOME/config.toml`.\n * - Auth: provider keys are read only from `$REASONIX_HOME/.env`, never the\n * shell environment, so `apiKey` is written there (0600) as\n * `DEEPSEEK_API_KEY` — this needs a private home. For another provider,\n * put its variable in that file yourself via a caller-owned home.\n */\nexport const reasonixAdapter: CliAdapter = {\n name: \"reasonix\",\n title: \"Reasonix\",\n command: \"reasonix\",\n apiKeyEnv: [\"DEEPSEEK_API_KEY\"],\n homeEnv: [\"REASONIX_HOME\"],\n transports: [\"argv\", \"stdin\"],\n effort: true,\n mcp: true,\n probe: { help: [[\"run\", \"--help\"]], version: [\"--version\"] },\n verification: {\n version: \"2.43.0\",\n verifiedBy: \"help\",\n sources: [\n \"https://github.com/esengine/DeepSeek-Reasonix/blob/v2.43.0/docs/CLI.md\",\n \"https://github.com/esengine/DeepSeek-Reasonix/blob/v2.43.0/docs/CONFIG_PATHS.md\",\n \"https://www.npmjs.com/package/reasonix\",\n ],\n checkedAt: \"2026-10-17\",\n },\n plan(context) {\n const args = [\"run\", \"--output-format\", \"stream-json\"];\n const requires = [\"--output-format\", \"stream-json\"];\n const files: CliLaunchFile[] = [];\n\n if (context.model !== undefined) {\n args.push(\"--model\", context.model);\n requires.push(\"--model\");\n }\n\n if (context.effort !== undefined) {\n // DeepSeek levels per docs/REASONING_PROVIDERS.md: auto | disabled | low | high | max.\n args.push(\n \"--effort\",\n mapEffort(context.effort, { none: \"disabled\", low: \"low\", high: \"high\", max: \"max\" }),\n );\n requires.push(\"--effort\");\n }\n\n if (context.resume !== undefined) {\n args.push(\"--resume\", context.resume);\n requires.push(\"--resume\");\n }\n\n if (context.permission === \"bypass\") {\n args.push(\"--yolo\");\n requires.push(\"--yolo\");\n }\n\n if (context.mcp !== undefined) {\n const home = requirePrivateHome(context, reasonixAdapter, \"MCP servers\");\n\n files.push({\n path: path.join(home, \"config.toml\"),\n content: toToml({ plugins: reasonixPlugins(context.mcp) }),\n });\n }\n\n if (context.apiKey !== undefined) {\n const home = requirePrivateHome(context, reasonixAdapter, \"API keys (its .env file)\");\n\n files.push({\n path: path.join(home, \".env\"),\n content: dotenvFile({ DEEPSEEK_API_KEY: context.apiKey }),\n });\n }\n\n return {\n args,\n tail: context.transport === \"argv\" ? [argvPrompt(context.prompt)] : [],\n stdin: context.transport === \"stdin\" ? context.prompt : undefined,\n env: {\n ...(context.home !== undefined ? { REASONIX_HOME: context.home } : {}),\n REASONIX_TELEMETRY: \"off\",\n },\n files,\n requires,\n };\n },\n parser: createReasonixParser,\n};\n\nfunction reasonixPlugins(servers: CliMcpServers): TomlTable[] {\n return Object.entries(servers).map(([name, server]): TomlTable =>\n server.type === \"stdio\"\n ? { name, type: \"stdio\", command: server.command, args: server.args ?? [], env: server.env }\n : { name, type: server.type, url: server.url, headers: server.headers },\n );\n}\n\n/** Reasonix per-call usage (`promptTokens` includes cache hits). */\nfunction callUsage(usage: JsonRecord | undefined): CliUsage | undefined {\n if (usage === undefined) {\n return undefined;\n }\n\n const cacheHit = numberField(usage, \"cacheHitTokens\");\n\n return usageOf({\n input: numberField(usage, \"promptTokens\"),\n output: numberField(usage, \"completionTokens\"),\n total: numberField(usage, \"totalTokens\"),\n cachedTokens: cacheHit !== undefined && cacheHit > 0 ? cacheHit : undefined,\n reasoningTokens: numberField(usage, \"reasoningTokens\"),\n costUSD: numberField(usage, \"costUsd\"),\n });\n}\n\n/** Parser for `reasonix run --output-format stream-json`. */\nexport function createReasonixParser(): CliStreamParser {\n let started = false;\n let sessionRef: string | undefined;\n\n return {\n ...jsonLinesParser((record): CliParsedEvent[] => {\n const events: CliParsedEvent[] = [];\n const recordSession = stringField(record, \"sessionId\") ?? stringField(record, \"session_id\");\n\n if (recordSession !== undefined) {\n sessionRef = recordSession;\n }\n\n if (!started && recordSession !== undefined) {\n started = true;\n events.push({ type: \"session.started\", sessionRef: recordSession, raw: record });\n }\n\n if (stringField(record, \"type\") === \"result\") {\n const usage = recordField(record, \"usage\");\n\n if (usage !== undefined) {\n events.push({\n type: \"usage\",\n cumulative: true,\n usage: usageOf({\n input: numberField(usage, \"input_tokens\"),\n output: numberField(usage, \"output_tokens\"),\n cachedTokens: numberField(usage, \"cache_read_input_tokens\") || undefined,\n costUSD: numberField(record, \"total_cost_usd\"),\n }),\n raw: record,\n });\n }\n\n const result = stringField(record, \"result\") ?? \"\";\n\n if (record.is_error === true) {\n events.push({\n type: \"error\",\n message: result || \"Reasonix run failed\",\n fatal: true,\n raw: record,\n });\n } else if (result.length > 0) {\n events.push({ type: \"message\", text: result, delta: false, final: true, raw: record });\n }\n\n return events;\n }\n\n const tool = asRecord(record.tool);\n\n switch (stringField(record, \"kind\")) {\n case \"text\": {\n const text = stringField(record, \"text\") ?? \"\";\n\n if (text.length > 0) {\n events.push({ type: \"message\", text, delta: true, raw: record });\n }\n break;\n }\n case \"message\":\n events.push({\n type: \"message\",\n text: stringField(record, \"text\") ?? \"\",\n delta: false,\n raw: record,\n });\n break;\n case \"tool_dispatch\":\n // The first dispatch streams arguments (`partial: true`); report the complete one.\n if (tool !== undefined && tool.partial !== true) {\n events.push({\n type: \"tool.call\",\n id: stringField(tool, \"id\") ?? \"\",\n name: stringField(tool, \"name\") ?? \"\",\n input: parseArguments(tool.args),\n raw: record,\n });\n }\n break;\n case \"tool_result\": {\n const error = stringField(tool, \"err\") ?? \"\";\n\n events.push({\n type: \"tool.result\",\n id: stringField(tool, \"id\") ?? \"\",\n output: error.length > 0 ? error : (stringField(tool, \"output\") ?? \"\"),\n isError: error.length > 0,\n raw: record,\n });\n break;\n }\n case \"usage\": {\n const usage = callUsage(recordField(record, \"usage\"));\n\n if (usage !== undefined) {\n events.push({ type: \"usage\", usage, cumulative: false, raw: record });\n }\n break;\n }\n case \"turn_done\":\n if (stringField(record, \"status\") === \"failed\") {\n events.push({\n type: \"error\",\n message: stringField(record, \"err\") ?? \"Reasonix turn failed\",\n fatal: true,\n raw: record,\n });\n }\n break;\n }\n\n return events;\n }),\n sessionRef: () => sessionRef,\n };\n}\n","import { ai } from \"@warlock.js/ai\";\nimport { aiderAdapter } from \"./adapters/aider\";\nimport { ampAdapter } from \"./adapters/amp\";\nimport { antigravityAdapter } from \"./adapters/antigravity\";\nimport { claudeCodeAdapter } from \"./adapters/claude-code\";\nimport { codexAdapter } from \"./adapters/codex\";\nimport { copilotAdapter } from \"./adapters/copilot\";\nimport { cursorAdapter } from \"./adapters/cursor\";\nimport { droidAdapter } from \"./adapters/droid\";\nimport { grokAdapter } from \"./adapters/grok\";\nimport { kimiAdapter } from \"./adapters/kimi\";\nimport { mistralVibeAdapter } from \"./adapters/mistral-vibe\";\nimport { opencodeAdapter } from \"./adapters/opencode\";\nimport { qwenCodeAdapter } from \"./adapters/qwen-code\";\nimport { reasonixAdapter } from \"./adapters/reasonix\";\nimport { type CliAgent, createCliAgent } from \"./cli-agent\";\nimport type { CliAdapter, CliAgentOptions } from \"./contracts\";\nimport { cliModel } from \"./model/cli-model\";\n\n/** Every built-in adapter, keyed by its factory name. */\nexport const cliAdapters = {\n claudeCode: claudeCodeAdapter,\n codex: codexAdapter,\n antigravity: antigravityAdapter,\n qwenCode: qwenCodeAdapter,\n kimi: kimiAdapter,\n cursor: cursorAdapter,\n copilot: copilotAdapter,\n grok: grokAdapter,\n opencode: opencodeAdapter,\n amp: ampAdapter,\n droid: droidAdapter,\n mistralVibe: mistralVibeAdapter,\n aider: aiderAdapter,\n reasonix: reasonixAdapter,\n} as const;\n\n/** Name of a built-in adapter factory. */\nexport type CliVendor = keyof typeof cliAdapters;\n\ntype VendorFactories = { [Vendor in CliVendor]: (options?: CliAgentOptions) => CliAgent };\n\nconst factories = Object.fromEntries(\n Object.entries(cliAdapters).map(([vendor, adapter]) => [\n vendor,\n (options?: CliAgentOptions) => createCliAgent(adapter, options),\n ]),\n) as VendorFactories;\n\n/**\n * The CLI-agent namespace: one factory per vendor, `custom()` for your own\n * adapter, `model()` to hand a CLI agent to `ai.agent`. Also available as\n * `ai.cli` once the package is imported.\n *\n * @example\n * import { cli } from \"@warlock.js/ai-cli\";\n *\n * const claude = cli.claudeCode({ model: \"sonnet\", cwd: \"/srv/repo\" });\n * const session = await claude.run(\"Fix the failing test\");\n * for await (const event of session.events) console.log(event.type);\n * const { text, usage, sessionRef } = await session.done();\n */\nexport const cli: VendorFactories & {\n /** A CLI agent for an adapter you wrote. */\n custom(adapter: CliAdapter, options?: CliAgentOptions): CliAgent;\n /** A CLI agent as an `ai.agent` model. */\n model: typeof cliModel;\n /** The built-in adapters, for inspection or extension. */\n adapters: typeof cliAdapters;\n} = {\n ...factories,\n custom: (adapter, options) => createCliAgent(adapter, options),\n model: cliModel,\n adapters: cliAdapters,\n};\n\ndeclare module \"@warlock.js/ai\" {\n interface Ai {\n /** Drive vendor coding CLIs (Claude Code, Codex, Copilot, …) as agents. */\n cli: typeof cli;\n }\n}\n\n// Runtime registration: importing the package attaches `cli` to the shared `ai` object.\nai.cli = cli;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,IAAa,WAAb,cAA8BA,6BAAc;CAO1C,AAAO,YAAY,SAAiB,SAA0B;EAC5D,MACE,SACA,SACA,QAAQ,SAAS,wBAAwB,QAAQ,SAAS,qBACtD,6BACA,gBACN;EAEA,KAAK,OAAO;EACZ,KAAK,OAAO,QAAQ;EACpB,KAAK,UAAU,QAAQ;EACvB,KAAK,OAAO,QAAQ;EACpB,KAAK,UA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