@agentproto/adapter-claude-code 2.4.9 → 2.5.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/dist/index.mjs CHANGED
@@ -366,7 +366,13 @@ var claudeCode = defineAgentCli({
366
366
  // Claude Code has a verified native TUI resume path:
367
367
  // `claude --resume <conversation-id>`. Governs provider-native
368
368
  // terminal restart, distinct from ACP-level `resumable`.
369
- nativeTerminalResume: true
369
+ nativeTerminalResume: true,
370
+ // Claude Code defers MCP tool schemas behind its own `ToolSearch`
371
+ // tool (docs: code.claude.com/docs/en/mcp "MCP Tool Search"; modes
372
+ // standard/tst/tst-auto in the pinned binary, see the `lean` mode below).
373
+ // The daemon therefore mounts itself eager here — see
374
+ // `resolveSpawnDeferredTools` (packages/runtime/src/deferred-tools.ts).
375
+ nativeToolSearch: true
370
376
  },
371
377
  // Only the `lean` context mode remains a manifest `modes[]` entry (SPEC
372
378
  // §3.4a). Posture (plan / accept-edits / bypass-permissions) and the gateway
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/usage.ts","../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;AAkDA,IAAM,GAAA,GAAM,CAAC,CAAA,KACX,OAAO,CAAA,KAAM,YAAY,MAAA,CAAO,QAAA,CAAS,CAAC,CAAA,GAAI,CAAA,GAAI,MAAA;AAIpD,SAAS,QAAA,CAAS,OAAkB,IAAA,EAAoB;AACtD,EAAA,MAAM,OAAA,GAAU,KAAK,IAAA,EAAK;AAC1B,EAAA,IAAI,CAAC,OAAA,EAAS;AACd,EAAA,IAAI,KAAA;AACJ,EAAA,IAAI;AACF,IAAA,KAAA,GAAQ,IAAA,CAAK,MAAM,OAAO,CAAA;AAAA,EAC5B,CAAA,CAAA,MAAQ;AACN,IAAA;AAAA,EACF;AACA,EAAA,IAAI,CAAC,KAAA,IAAS,OAAO,KAAA,KAAU,QAAA,EAAU;AACzC,EAAA,MAAM,CAAA,GAAI,KAAA;AAKV,EAA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A,EACA,YAAA,EAAc;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAWZ,OAAA,EAAS,eAAA;AAAA,IACT,SAAA,EAAW,CAAC,eAAA,EAAiB,gBAAA,EAAkB,cAAc,MAAM,CAAA;AAAA,IACnE,cAAA,EAAgB;AAAA,MACd,eAAA,EAAiB,IAAA;AAAA,MACjB,SAAA,EAAW,CAAC,cAAA,EAAgB,UAAU;AAAA;AACxC,GACF;AAAA,EACA,MAAM,CAAC,aAAA,EAAe,WAAA,EAAa,KAAA,EAAO,iBAAiB,QAAQ,CAAA;AAAA,EACnE,QAAA,EAAU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAOR,MAAA,EAAQ;AAAA,MACN,MAAA,EAAQ,eAAA;AAAA,MACR,IAAA,EAAM,YAAA;AAAA,MACN,MAAA,EAAQ;AAAA;AACV;AAEJ,CAAC;AAEM,SAAS,iBAAA,GAAqC;AACnD,EAAA,OAAO,sBAAsB,UAAU,CAAA;AACzC","file":"index.mjs","sourcesContent":["/**\n * Real per-turn token usage for a claude-code session, read from Claude\n * Code's own transcript JSONL.\n *\n * Over ACP, claude-agent-acp's `usage_update` only carries cost + context\n * size/used — no input/output split and no prompt-cache split. Claude Code\n * itself writes every API response's `usage` block into\n * `<CLAUDE_CONFIG_DIR|~/.claude>/projects/<slug(cwd)>/<sessionId>.jsonl`\n * (Task sub-agents into `<sessionId>/subagents/*.jsonl` next to it), so the\n * daemon's `readUsage` hook sums those instead.\n *\n * One API response is written as SEVERAL lines (one per content block), each\n * repeating the same `message.id` and the same `usage` — so usage is keyed by\n * message id (last line wins) and summed once per response.\n *\n * Reads are incremental: the daemon polls this every few seconds while the\n * session runs, so each file keeps a byte offset and only the appended tail\n * is parsed on the next call.\n */\n\nimport { open, readdir, stat } from \"node:fs/promises\"\nimport { homedir } from \"node:os\"\nimport { join, resolve } from \"node:path\"\n\n/** Cumulative token usage for one claude-code session. Fields are omitted\n * when no response reported them (never zero-filled). */\nexport interface ClaudeCodeUsage {\n tokensIn?: number\n tokensOut?: number\n cacheReadTokens?: number\n cacheWriteTokens?: number\n reasoningTokens?: number\n}\n\ninterface ResponseUsage {\n input?: number\n output?: number\n cacheRead?: number\n cacheWrite?: number\n reasoning?: number\n}\n\n/** Per-response usage keyed by message id, plus the parse cursor. */\ninterface FileState {\n /** Byte offset just past the last complete (newline-terminated) line. */\n offset: number\n responses: Map<string, ResponseUsage>\n anon: number\n}\n\nconst num = (v: unknown): number | undefined =>\n typeof v === \"number\" && Number.isFinite(v) ? v : undefined\n\n/** Fold one JSONL line into `state`. Non-assistant / usage-less / malformed\n * lines are ignored. */\nfunction foldLine(state: FileState, line: string): void {\n const trimmed = line.trim()\n if (!trimmed) return\n let entry: unknown\n try {\n entry = JSON.parse(trimmed)\n } catch {\n return\n }\n if (!entry || typeof entry !== \"object\") return\n const e = entry as {\n type?: unknown\n requestId?: unknown\n message?: { id?: unknown; usage?: Record<string, unknown> }\n }\n if (e.type !== \"assistant\") return\n const usage = e.message?.usage\n if (!usage || typeof usage !== \"object\") return\n const details = usage.output_tokens_details as Record<string, unknown> | undefined\n const r: ResponseUsage = {}\n const input = num(usage.input_tokens)\n const output = num(usage.output_tokens)\n const cacheRead = num(usage.cache_read_input_tokens)\n const cacheWrite = num(usage.cache_creation_input_tokens)\n const reasoning = num(details?.thinking_tokens) ?? num(details?.reasoning_tokens)\n if (input !== undefined) r.input = input\n if (output !== undefined) r.output = output\n if (cacheRead !== undefined) r.cacheRead = cacheRead\n if (cacheWrite !== undefined) r.cacheWrite = cacheWrite\n if (reasoning !== undefined) r.reasoning = reasoning\n const key =\n typeof e.message?.id === \"string\"\n ? e.message.id\n : typeof e.requestId === \"string\"\n ? `req:${e.requestId}`\n : `anon:${state.anon++}`\n state.responses.set(key, r)\n}\n\nfunction newState(): FileState {\n return { offset: 0, responses: new Map(), anon: 0 }\n}\n\n/** Parse a whole transcript's text in one go. Exposed for tests + one-shot\n * callers; the incremental reader below folds lines through the same path. */\nexport function parseClaudeCodeTranscriptUsage(text: string): ClaudeCodeUsage | null {\n const state = newState()\n for (const line of text.split(\"\\n\")) foldLine(state, line)\n return sumResponses([state])\n}\n\nfunction sumResponses(states: readonly FileState[]): ClaudeCodeUsage | null {\n const out: ClaudeCodeUsage = {}\n let any = false\n const add = (k: keyof ClaudeCodeUsage, v: number | undefined): void => {\n if (v === undefined) return\n out[k] = (out[k] ?? 0) + v\n }\n for (const state of states) {\n for (const r of state.responses.values()) {\n any = true\n add(\"tokensIn\", r.input)\n add(\"tokensOut\", r.output)\n add(\"cacheReadTokens\", r.cacheRead)\n add(\"cacheWriteTokens\", r.cacheWrite)\n add(\"reasoningTokens\", r.reasoning)\n }\n }\n return any ? out : null\n}\n\n/** Incremental parse state, keyed by absolute file path. */\nconst fileStates = new Map<string, FileState>()\n\n/** Bring `path`'s state up to date with the file on disk. Returns undefined\n * when the file doesn't exist. */\nasync function refreshFile(path: string): Promise<FileState | undefined> {\n let size: number\n try {\n size = (await stat(path)).size\n } catch {\n fileStates.delete(path)\n return undefined\n }\n let state = fileStates.get(path)\n // Shrunk = rewritten (e.g. a resumed transcript), start over.\n if (!state || size < state.offset) {\n state = newState()\n fileStates.set(path, state)\n }\n if (size === state.offset) return state\n const start = state.offset\n const fh = await open(path, \"r\")\n try {\n const len = size - start\n const buf = Buffer.alloc(len)\n const { bytesRead } = await fh.read(buf, 0, len, start)\n // An overlapping call (turn-end read racing the live poller) already\n // consumed this range; folding is keyed so it'd be harmless, but the\n // offset must not advance twice.\n if (state.offset !== start || fileStates.get(path) !== state) return state\n // Only consume through the last newline: anything after it is a line\n // still being written, re-read whole on the next call (cutting on a\n // byte boundary could also split a multi-byte character).\n const end = buf.subarray(0, bytesRead).lastIndexOf(0x0a)\n if (end < 0) return state\n state.offset = start + end + 1\n for (const line of buf.subarray(0, end).toString(\"utf8\").split(\"\\n\")) {\n foldLine(state, line)\n }\n } finally {\n await fh.close()\n }\n return state\n}\n\n/** Transcript paths for `sessionId`: the main JSONL plus any Task\n * sub-agent transcripts beside it. */\nasync function transcriptPaths(projectDir: string, sessionId: string): Promise<string[]> {\n const paths = [join(projectDir, `${sessionId}.jsonl`)]\n const subDir = join(projectDir, sessionId, \"subagents\")\n try {\n for (const name of (await readdir(subDir)).sort()) {\n if (name.endsWith(\".jsonl\")) paths.push(join(subDir, name))\n }\n } catch {\n // no sub-agents\n }\n return paths\n}\n\n/** Claude Code's project-dir slug: every non-alphanumeric char → \"-\". */\nexport function claudeCodeProjectSlug(cwd: string): string {\n return cwd.replace(/[^a-zA-Z0-9]/g, \"-\")\n}\n\n/**\n * Best-effort cumulative usage for a claude-code session. Looks under the\n * session's isolated `configDir` first, then `~/.claude`. Returns null when\n * no transcript (or no usage in it) is found; never throws.\n */\nexport async function readClaudeCodeUsage(\n sessionId: string,\n ctx?: { cwd?: string; configDir?: string },\n): Promise<ClaudeCodeUsage | null> {\n try {\n if (!ctx?.cwd) return null\n const slug = claudeCodeProjectSlug(ctx.cwd)\n const bases = [\n ...(ctx.configDir ? [ctx.configDir] : []),\n resolve(homedir(), \".claude\"),\n ]\n for (const base of bases) {\n const projectDir = resolve(base, \"projects\", slug)\n const states: FileState[] = []\n for (const path of await transcriptPaths(projectDir, sessionId)) {\n const state = await refreshFile(path)\n if (state) states.push(state)\n }\n // The main transcript decides which base is the session's store.\n if (states.length > 0) return sumResponses(states)\n }\n return null\n } catch {\n return null\n }\n}\n\n/** Test hook: drop the incremental parse cache. */\nexport function resetClaudeCodeUsageCache(): void {\n fileStates.clear()\n}\n","/**\n * @agentproto/adapter-claude-code — AIP-45 adapter for Anthropic's\n * Claude Code via the @agentclientprotocol/claude-agent-acp wrapper.\n */\n\nimport {\n createAgentCliRuntime,\n defineAgentCli,\n type AgentCliHandle,\n type AgentCliRuntime,\n} from \"@agentproto/driver-agent-cli\"\nimport { ANTHROPIC_CORE_SCRUB_ENV } from \"@agentproto/provider-presets\"\nimport {\n listNativeModelIds,\n listOpencodeAnthropicModelRefs,\n} from \"@agentproto/model-catalog/llm\"\n\n// Cloud-provider redirect toggles that must be scrubbed alongside the core\n// ANTHROPIC_API_KEY whenever the claude binary is pointed at a non-Anthropic\n// gateway — a leftover toggle would override ANTHROPIC_BASE_URL and silently\n// route back to Bedrock/Vertex/etc. The core ANTHROPIC_API_KEY scrub itself\n// is sourced from @agentproto/provider-presets (the single source of truth for\n// gateway facts), so a new native-Anthropic credential env var added there is\n// picked up here automatically. Shared by the moonshot/openrouter modes and\n// the base_url option.\nconst CLAUDE_CODE_CLOUD_TOGGLES: string[] = [\n \"CLAUDE_CODE_USE_BEDROCK\",\n \"CLAUDE_CODE_USE_VERTEX\",\n \"CLAUDE_CODE_USE_FOUNDRY\",\n \"CLAUDE_CODE_USE_ANTHROPIC_AWS\",\n \"CLAUDE_CODE_USE_MANTLE\",\n \"CLAUDE_CODE_USE_GATEWAY\",\n]\nconst CLAUDE_CODE_GATEWAY_ENV_UNSET: string[] = [\n ...ANTHROPIC_CORE_SCRUB_ENV,\n ...CLAUDE_CODE_CLOUD_TOGGLES,\n]\n\n// Native-Anthropic model menu, derived from the catalog's own synced\n// `/v1/models` listing (see `listNativeModelIds` — never a hand-typed id\n// list, see agentproto#186 / the removal note below for why that used to\n// be one). An id landing here the moment Anthropic publishes it is the\n// whole point: no PR needed for the next model. Nothing is known to need\n// hiding today, so the denylist starts empty — it exists purely as the\n// one sanctioned manual override (a specific id we've vetted and want\n// OFF this adapter), never as a stand-in for a hand-typed allowlist.\nconst NATIVE_ANTHROPIC_DENYLIST = new Set<string>([])\nconst NATIVE_ANTHROPIC_MODELS = listNativeModelIds(\"anthropic\")\n .filter(id => !NATIVE_ANTHROPIC_DENYLIST.has(id))\n .map(id => ({ id, provider: \"anthropic\" as const }))\n\n// OpenCode Go / OpenCode Zen, both fronted through their Anthropic-compatible\n// gateway presets (`opencode-go` / `opencode` in @agentproto/provider-presets).\n// Derived, not hand-typed, and deliberately NOT the endpoints' full lineups:\n// each endpoint serves three wire surfaces behind one base URL and only the\n// `/v1/messages` subset is reachable from the claude binary, so the menu comes\n// from the catalog's generated per-model surface discriminator\n// (`listOpencodeAnthropicModelRefs`). Zen's subset is the entire Claude family\n// — the valuable path here, since it drives this very harness on real Claude\n// models against a Zen balance. Go's is four ids (minimax-m2.5/m2.7/m3,\n// qwen3.8-flash). The refs carry NO `@route` suffix: for these endpoints the\n// route IS the id's leading segment (`opencode/claude-sonnet-4-6`), which is\n// what the catalog keys and what `modelIdPrefixProvider` reads.\nconst OPENCODE_ANTHROPIC_MODELS = [\n ...listOpencodeAnthropicModelRefs(\"opencode-go\").map(id => ({\n id,\n provider: \"opencode-go\" as const,\n })),\n ...listOpencodeAnthropicModelRefs(\"opencode\").map(id => ({\n id,\n provider: \"opencode\" as const,\n })),\n]\n\nexport const claudeCode: AgentCliHandle = defineAgentCli({\n name: \"claude-code\",\n id: \"claude-code\",\n description:\n \"Anthropic's Claude Code wrapped as an ACP agent via @agentclientprotocol/claude-agent-acp. Spawned via `npx -y @agentclientprotocol/claude-agent-acp` and driven over stdio JSON-RPC.\",\n version: \"0.1.0\",\n bin: \"npx\",\n // Pinned for reproducibility. 0.81.2 bundles @anthropic-ai/claude-agent-sdk\n // 0.3.280 = Claude Code 2.1.280, the FLOOR for the current Opus generation:\n // the 0.75.1 pin shipped CC 2.1.257, which rejects `claude-opus-5-5` outright\n // (\"API Error: 400 … does not support this model; version 2.1.280 or newer is\n // required\") — a spawn-time failure, not a silent fallback. Nothing between\n // 0.75.1 and 0.81.2 breaks this adapter: the one ⚠ BREAKING entry (0.77.0,\n // `claudeCode.options.agent` no longer forwarded + the agent-picker exports\n // removed) is library-API surface for in-process consumers, and we drive the\n // wrapper as a spawned ACP server over stdio and never set that option. The\n // config options we DO apply (`model`, `effort`, `mode` via\n // `session/set_config_option`) and `session/new` are unchanged.\n bin_args: [\"-y\", \"@agentclientprotocol/claude-agent-acp@0.81.2\"],\n install: [\n {\n method: \"npm\",\n package: \"@agentclientprotocol/claude-agent-acp\",\n global: true,\n },\n ],\n version_check: {\n // PRESENCE probe — must be local, not a registry query. `npm view` would\n // succeed on every networked machine, installed or not, making `install`\n // report \"already installed\" forever on a virgin box. This probes exactly\n // what install[] creates (the global npm package): exit 1 when absent.\n // npx wrinkle: the adapter also runs via `npx -y …` without any global\n // install, but that path doesn't need this verb — and this probe can\n // never report \"installed\" when nothing is on the machine.\n cmd: \"npm ls -g @agentclientprotocol/claude-agent-acp --depth=0\",\n parse: \"(\\\\d+\\\\.\\\\d+\\\\.\\\\d+)\",\n range: \">=0.30.0\",\n timeout_ms: 15_000,\n },\n auth: {\n ref: \"./SECRETS.md\",\n state: { env: [\"ANTHROPIC_API_KEY\"] },\n },\n // Deterministic billing-auth (subscription vs api-key), resolved by the\n // runtime (@agentproto/runtime's resolveAuthSpec) and applied MECHANICALLY\n // by the driver. EXPLICIT credential selection, not scrub-by-absence: the\n // resolver SETS exactly one credential env var (from a named config/store\n // ref, never the ambient shell) and SCRUBS the conflicting one(s), so which\n // credential — and thus which billing — a spawn uses is *stated*, never\n // inferred from whatever the daemon's launching shell exported (the outage\n // this surface exists to prevent).\n //\n // provider \"anthropic\" ⇒ api-key mode SETS providerEnvVar(\"anthropic\") =\n // ANTHROPIC_API_KEY (derived from the catalog, not re-listed here) and\n // scrubs the subscription-family creds (CLAUDE_CODE_OAUTH_TOKEN +\n // ANTHROPIC_AUTH_TOKEN). authEnforce \"always\" preserves #312: claude-code\n // engages on EVERY spawn and fails fast with no credential.\n //\n // authSubscription: \"subscription\" SETS CLAUDE_CODE_OAUTH_TOKEN to a bearer\n // token minted via `claude setup-token` (bills Max/Pro, not API credits) —\n // the var Claude Code documents for that token and the ONLY one that yields\n // the clean native claude.ai-login path. (The same token as\n // ANTHROPIC_AUTH_TOKEN authenticates but is treated as a generic override\n // that disables connectors — the degraded path, so it's a `conflictEnv` to\n // scrub, never the setEnv.) `conflictEnv` (ANTHROPIC_AUTH_TOKEN) is scrubbed\n // in BOTH modes; `unsetEnvAdd` (cloud toggles + ANTHROPIC_BASE_URL) only in\n // subscription (native) mode — matching #312's exact byte-for-byte scrub set\n // in each mode (asserted by the regression snapshot test). ANTHROPIC_API_KEY\n // is NOT listed in unsetEnvAdd because it derives from providerEnvVar and is\n // scrubbed as the non-set credential automatically.\n provider: \"anthropic\",\n // A model's route is an independent choice here: the gateway modes\n // (moonshot/openrouter/…) re-point ANTHROPIC_BASE_URL, so the same model\n // can go direct-Anthropic or via any gateway → free route selection.\n routeSelection: \"free\",\n authEnforce: \"always\",\n authSubscription: {\n setEnv: \"CLAUDE_CODE_OAUTH_TOKEN\",\n conflictEnv: [\"ANTHROPIC_AUTH_TOKEN\"],\n unsetEnvAdd: [...CLAUDE_CODE_CLOUD_TOGGLES, \"ANTHROPIC_BASE_URL\"],\n },\n // How this adapter receives a GATEWAY-routed bearer credential (D4) —\n // ANTHROPIC_AUTH_TOKEN, the SAME var as the `auth_token` option below\n // (env: { ANTHROPIC_AUTH_TOKEN: \"{value}\" }) and the one the claude binary\n // actually sends as `Authorization: Bearer`. Distinct from a gateway\n // preset's own `keyEnv` (OPENROUTER_API_KEY, MOONSHOT_API_KEY, …) — that's\n // merely where the operator's providers.json stores the key; the runtime's\n // resolveAuthSpec now injects the resolved credential HERE for a gateway\n // route instead, so it lands in a var the claude binary actually reads.\n gatewayAuth: { setEnv: \"ANTHROPIC_AUTH_TOKEN\" },\n sandbox: \"./SANDBOX.md\",\n protocol: \"acp\",\n acp: \"./claude-code-acp.ACP.md\",\n session: {\n mode: \"persistent\",\n idle_timeout_ms: 1_800_000,\n context_carryover: true,\n },\n // Every id below is validated against the wrapper's live\n // `session/new` → configOptions[model] selector: the wrapper resolves\n // these (via its own `resolveModelPreference`) and rejects anything it\n // can't. That USED to be fatal — a rejected `session/set_config_option`\n // killed the whole spawn (agentproto#186) — which is why the native\n // Anthropic ids used to be a small hand-picked subset with stale entries\n // pruned by hand whenever the wrapper's own menu drifted. The apply is\n // now best-effort (see @agentproto/acp's `newSession`: a rejected model\n // is caught, logged, and recorded as `modelApplyRejection` — the session\n // continues on the agent's default rather than dying), so that risk is\n // gone and the native Anthropic ids below are derived from the catalog's\n // synced model list instead (`NATIVE_ANTHROPIC_MODELS`) — a model the\n // wrapper doesn't yet recognize just no-ops back to its default, it\n // doesn't take the spawn down with it.\n //\n // The gateway (Moonshot/OpenRouter/Requesty) models keep their `provider`\n // annotation but NO LONGER carry a `mode:` binding: the route to a gateway\n // is derived from the model catalog's `@route` route-identity, not an\n // adapter mode (SPEC §3.4a) — the gateway `modes[]` entries were deleted.\n // The claude binary still reaches those endpoints via the per-spawn\n // `base_url` / `auth_token` options (below) until the catalog route\n // apply-path lands.\n models: {\n default: \"claude-sonnet-5\",\n allowed: [\n // Native Anthropic — every id the catalog's own `/v1/models` sync\n // currently carries for this provider (see NATIVE_ANTHROPIC_MODELS\n // above), not a hand-typed subset.\n ...NATIVE_ANTHROPIC_MODELS,\n // Moonshot (Kimi) — route resolved from the catalog `@route`\n { id: \"kimi-k3\", provider: \"moonshot\" },\n { id: \"kimi-k2.7-code\", provider: \"moonshot\" },\n // OpenRouter — route resolved from the catalog `@route` route-identity\n // suffix (a bare 2-segment id resolves to the direct vendor route, which\n // is dead here; `@openrouter` pins the catalog join to the OpenRouter\n // gateway, reachable via ANTHROPIC_BASE_URL like moonshot).\n { id: \"z-ai/glm-5.2@openrouter\", provider: \"openrouter\" },\n { id: \"deepseek/deepseek-v4-pro@openrouter\", provider: \"openrouter\" },\n { id: \"moonshotai/kimi-k2@openrouter\", provider: \"openrouter\" },\n { id: \"x-ai/grok-4.5@openrouter\", provider: \"openrouter\" },\n { id: \"x-ai/grok-4.20@openrouter\", provider: \"openrouter\" },\n { id: \"x-ai/grok-4.3@openrouter\", provider: \"openrouter\" },\n { id: \"google/gemini-3.1-pro-preview@openrouter\", provider: \"openrouter\" },\n { id: \"google/gemini-3.5-flash@openrouter\", provider: \"openrouter\" },\n { id: \"google/gemini-2.5-flash@openrouter\", provider: \"openrouter\" },\n { id: \"google/gemini-2.5-pro@openrouter\", provider: \"openrouter\" },\n { id: \"moonshotai/kimi-k2.7-code@openrouter\", provider: \"openrouter\" },\n // OpenAI gpt-5.6 series via OpenRouter — reachable via ANTHROPIC_BASE_URL\n // + ANTHROPIC_AUTH_TOKEN (the gatewayAuth setEnv above) like the other\n // gateway rows. The `@openrouter` suffix pins the catalog join to the\n // OpenRouter gateway (the bare id would resolve to the direct-OpenAI\n // route, which this Anthropic client can't speak). These are real,\n // already-priced OpenRouter chat models, not invented specialist ids.\n { id: \"openai/gpt-5.6-luna@openrouter\", provider: \"openrouter\" },\n { id: \"openai/gpt-5.6-sol@openrouter\", provider: \"openrouter\" },\n // Requesty — route resolved from the catalog `@route`\n { id: \"sference/thinkingcap-qwen3.6-27b@requesty\", provider: \"requesty\" },\n { id: \"sference/glm-5.2@requesty\", provider: \"requesty\" },\n // OpenCode Go + OpenCode Zen — see OPENCODE_ANTHROPIC_MODELS above.\n ...OPENCODE_ANTHROPIC_MODELS,\n // Local llm-endpoint proxy — route resolved from the catalog `@route`\n // (registerBuiltinRoutes registers `llm-endpoint` → Anthropic surface at\n // localhost:18090). A SMALL curated set from the proxy's own `default`\n // pack (packages/llm-endpoint/src/packs.ts) — vendor prefix is the proxy's\n // transparent-provider name so the boundary-stripped `vendor/product`\n // upstream id (e.g. `moonshot/kimi-k2.7-code`) transparently routes.\n { id: \"moonshot/kimi-k3@llm-endpoint\", provider: \"llm-endpoint\" },\n { id: \"moonshot/kimi-k2.7-code@llm-endpoint\", provider: \"llm-endpoint\" },\n { id: \"moonshot/kimi-k2.6@llm-endpoint\", provider: \"llm-endpoint\" },\n { id: \"zai/glm-5.2@llm-endpoint\", provider: \"llm-endpoint\" },\n { id: \"openai/gpt-4.1@llm-endpoint\", provider: \"llm-endpoint\" },\n { id: \"openai/gpt-4o-mini@llm-endpoint\", provider: \"llm-endpoint\" },\n ],\n env: { anthropic: \"ANTHROPIC_API_KEY\" },\n },\n capabilities: {\n streaming: true,\n tool_calls: true,\n sub_agents: false,\n file_io: true,\n // ACP wrapper forwards `image` content blocks in user prompts\n // straight to Anthropic Messages API. Hosts SHOULD send images\n // inline (see CLAUDE-CODE.md) instead of passing paths and\n // hoping the model uses Read.\n multimodal: true,\n // The wrapper (@agentclientprotocol/claude-agent-acp >= 0.30)\n // advertises `loadSession: true` and exposes the full session\n // lifecycle (newSession / loadSession / resumeSession / forkSession)\n // over JSON-RPC. Pairs with `continuation.default: native-resume`\n // below — the host persists the sessionId and reattaches to the\n // existing session across cold starts (api restart, sandbox reap,\n // multi-machine).\n resumable: true,\n bidirectional: true,\n // Claude Code's Read tool can ingest any absolute path the host\n // surfaces via the prompt. Pair with the daemon's POST /files/upload\n // route + a host UI drag-drop handler: drop a file → daemon writes\n // to `cwd/.agentproto-attachments/<name>` → host pastes the path\n // into the terminal → Claude reads it natively. No protocol-level\n // multimodal round-trip needed; pure file-path injection.\n file_attach: true,\n // Claude Code has a verified native TUI resume path:\n // `claude --resume <conversation-id>`. Governs provider-native\n // terminal restart, distinct from ACP-level `resumable`.\n nativeTerminalResume: true,\n },\n // Only the `lean` context mode remains a manifest `modes[]` entry (SPEC\n // §3.4a). Posture (plan / accept-edits / bypass-permissions) and the gateway\n // routes (moonshot / openrouter / requesty / deepseek) were BOTH removed from\n // here:\n // - posture now comes from the harness's own ACP mode registry\n // (`SessionModeState.availableModes`) plus the daemon's canonical-posture\n // layer (step 2c). The `CLAUDE_CONFIG_DIR` ENFORCEMENT MECHANISM in the\n // driver (`resolveClaudeCodePermissionMode` in define-agent-cli.ts) is\n // unchanged — it still points a per-session `CLAUDE_CONFIG_DIR` at a\n // throwaway `settings.json` with `{\"permissions\":{\"defaultMode\":\n // \"<value>\"}}` (the ACP wrapper ignores `--permission-mode` on argv). But\n // its INPUT changed: it looks the value up in `modes[]` by `config.mode`,\n // and with the posture modes removed here that lookup no longer matches\n // for `plan`/`accept-edits`/`bypass-permissions` — so the `config.mode`-\n // driven path is now DORMANT (returns undefined) until step 2c re-sources\n // the requested posture from the canonical layer and feeds it in. The\n // known limitation still holds once it does: a target repo that commits\n // its own escalated `.claude/settings.json` `permissions.defaultMode`\n // defeats OUR requested mode in the same merge pass and the session falls\n // back to \"default\" (never the original silent-write bug).\n // - route now comes from the model catalog's `@route` route-identity; the\n // gateway endpoint is still reachable per-spawn via the `base_url` /\n // `auth_token` options (below), which carry the same ANTHROPIC_API_KEY +\n // cloud-toggle scrub via `env_unset`.\n modes: [\n {\n id: \"lean\",\n description:\n \"Drop Claude Code's bundled skills and workflows from context (built-in slash \" +\n \"commands stay typable but are hidden from the model), AND turn on Claude \" +\n \"Code's own native MCP tool-search (deferred tool-schema loading) so its \" +\n \"turn-0 tools/list payload — including whatever this session's own \" +\n \"`mcpServers` mount (e.g. the daemon self-mount) advertises — shrinks the \" +\n \"same way `tool_search` does on the daemon's gateway. Plugins, project \" +\n \"`.claude/skills/`, and `.claude/commands/` are unaffected. Both knobs are \" +\n \"env-only — the ACP wrapper exposes no CLI flag for either, and the \" +\n \"underlying claude binary reads them directly.\",\n // CLAUDE_CODE_DISABLE_BUNDLED_SKILLS: unchanged from before this mode existed.\n //\n // ENABLE_TOOL_SEARCH: UNDOCUMENTED — there is no public Anthropic reference\n // for it. Confirmed present and wired (not a guess) by extracting readable\n // strings from the EXACT pinned binary this adapter spawns\n // (`~/.local/share/claude/versions/2.1.280`, the build\n // `@agentclientprotocol/claude-agent-acp@0.81.2` bundles — see the pin\n // comment on `bin_args` above): `ENABLE_TOOL_SEARCH` appears in the CLI's\n // own recognized-env-var table (alongside `MCP_TIMEOUT`,\n // `MAX_MCP_OUTPUT_TOKENS`, etc.) and drives a real decision function\n // (minified as `Het()` in that build) that resolves to one of three modes:\n // `\"standard\"` (today's eager behaviour, the default when unset in most\n // cohorts), `\"tst\"` (tool-search-tool: MCP/tool schemas deferred behind a\n // native search tool — the ACTUAL feature this mirrors), or `\"tst-auto\"`\n // (auto-threshold via `auto:<N>`, `0 <= N <= 100`). The value parser\n // (minified `Co`/`De` in that build) accepts the literal strings\n // `\"1\"`/`\"true\"`/`\"yes\"`/`\"on\"` for on and `\"0\"`/`\"false\"`/`\"no\"`/`\"off\"`\n // for off — `\"1\"` here is a valid, intentional value, not a placeholder.\n // NOT independently verified against a live model turn in this\n // environment (no authenticated Claude Code login available when this\n // was investigated) — only that `claude -p` accepts the env var and\n // proceeds past argument parsing to the auth check without erroring on\n // it. If Anthropic ever removes or renames this (it is explicitly\n // unstable — the binary also guards it behind\n // `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS`), the worst case is a no-op:\n // an unrecognized env var the claude binary already ignores today.\n env: { CLAUDE_CODE_DISABLE_BUNDLED_SKILLS: \"1\", ENABLE_TOOL_SEARCH: \"1\" },\n kind: \"context\",\n },\n ],\n options: [\n {\n id: \"model\",\n // string (not enum) so any valid Anthropic model ID is accepted\n // without requiring a code change to expand the list. Applied via\n // ANTHROPIC_MODEL env var so the claude binary picks it up directly\n // — the claude-agent-acp wrapper only forwards CLI args when --cli\n // is passed, otherwise it runs in ACP mode and ignores argv.\n type: \"string\" as const,\n description:\n \"Anthropic model ID or wrapper alias (e.g. 'claude-opus-4-8', \" +\n \"'claude-sonnet-5', 'sonnet', 'opus'). Set via ANTHROPIC_MODEL env \" +\n \"var so the claude binary uses it directly. Omit to use the claude-code default.\",\n env: { ANTHROPIC_MODEL: \"{value}\" },\n },\n {\n id: \"effort\",\n type: \"enum\" as const,\n // Effort is model-dependent: the same label maps to different\n // underlying compute budgets across models, and the model's own\n // default differs (Sonnet 4.6 / Opus 4.8 default to \"high\";\n // Opus 4.7 defaults to \"xhigh\"). \"max\" and \"ultracode\" are\n // session-only — not valid in persisted settings. Omit to keep\n // the model's own default rather than hardcoding one here.\n enum: [\"low\", \"medium\", \"high\", \"xhigh\", \"max\", \"ultracode\"],\n description:\n \"Reasoning effort level. Model-dependent: the same label ≠ the same \" +\n \"compute budget across models, and defaults differ by model \" +\n \"(e.g. Sonnet 4.6 / Opus 4.8 default to 'high'; Opus 4.7 to 'xhigh'). \" +\n \"'max' and 'ultracode' are session-only. Omit to keep the model's own default.\",\n },\n {\n id: \"max_turns\",\n type: \"integer\" as const,\n min: 1,\n max: 200,\n description:\n \"Hard cap on tool-use turns within a single send. Claude Code stops after this many cycles.\",\n bin_args_template: [\"--max-turns\", \"{value}\"],\n },\n {\n id: \"tool_search\",\n // Same `ENABLE_TOOL_SEARCH` env var the `lean` mode sets (see the long\n // note there for where it's read and which values the binary accepts).\n // \"false\" is the one a workflow agent step with a declared `tools`\n // allowlist gets (sessions-registry-agent-host.ts): its gateway mount\n // is already scoped to a handful of tools, so deferring them behind\n // Claude Code's own search only costs the model ToolSearch round-trips\n // before it can call the tool it was told to call.\n type: \"enum\" as const,\n enum: [\"true\", \"false\", \"auto\"],\n description:\n \"Claude Code's own MCP tool search (deferred tool-schema loading), via \" +\n \"ENABLE_TOOL_SEARCH. 'false' loads every mounted MCP tool eagerly; 'true' \" +\n \"always defers; 'auto' defers past a size threshold. Omit to keep Claude \" +\n \"Code's default.\",\n env: { ENABLE_TOOL_SEARCH: \"{value}\" },\n },\n {\n id: \"base_url\",\n // Injected into the child env as ANTHROPIC_BASE_URL — the claude binary\n // honors it, so this fronts real Anthropic, Bedrock/Vertex/Azure, or an\n // Anthropic-compatible gateway (LiteLLM / claude-code-router / Moonshot\n // / OpenRouter). Auto-scrubs the ambient ANTHROPIC_API_KEY + cloud\n // redirect toggles the moment it's set (symmetric with the moonshot/\n // openrouter modes and with claude-sdk's buildQueryOptions scrub) so the\n // real Anthropic credential can never leak to a third-party host — pair\n // with `auth_token` to supply the gateway key. A base_url pointed at a\n // real-Anthropic mirror that still wants the ambient key is the one\n // shape this breaks; that's an acceptable trade for the default being\n // leak-safe (matches claude-sdk).\n type: \"string\" as const,\n description:\n \"Custom Anthropic base URL. Injected as ANTHROPIC_BASE_URL in the \" +\n \"child env — front real Anthropic, Bedrock/Vertex/Azure, or an \" +\n \"Anthropic-compatible gateway. Auto-scrubs the ambient \" +\n \"ANTHROPIC_API_KEY + cloud redirect toggles when set (so the real \" +\n \"key can't leak to a third-party host) — pair with `auth_token` to \" +\n \"supply the gateway credential. For Moonshot/OpenRouter the dedicated \" +\n \"modes pre-wire the URL too. Omit to use the default endpoint.\",\n env: { ANTHROPIC_BASE_URL: \"{value}\" },\n env_unset: CLAUDE_CODE_GATEWAY_ENV_UNSET,\n },\n {\n id: \"auth_token\",\n // Injected into the child env as ANTHROPIC_AUTH_TOKEN — the claude\n // binary sends it as `Authorization: Bearer <token>`, which\n // Anthropic-compatible gateways (Moonshot, OpenRouter) accept. Pair\n // with base_url (or a gateway mode) for a per-spawn key instead of the\n // ambient ANTHROPIC_API_KEY.\n type: \"string\" as const,\n description:\n \"Bearer token for the Anthropic API or a compatible gateway. Injected \" +\n \"as ANTHROPIC_AUTH_TOKEN in the child env (sent as `Authorization: \" +\n \"Bearer`). Pair with `base_url` (or a `moonshot`/`openrouter` mode) \" +\n \"to target a gateway with a per-spawn key instead of the ambient \" +\n \"ANTHROPIC_API_KEY. Omit to use ANTHROPIC_API_KEY from the environment.\",\n env: { ANTHROPIC_AUTH_TOKEN: \"{value}\" },\n },\n ],\n continuation: {\n // native-resume: each turn cold-spawns claude, then ACP `loadSession`\n // reattaches to the saved sessionId. Survives api restarts, sandbox\n // reaps, multi-machine — claude reads its own JSONL session store.\n // Requires the host to register `configureNativeResume({load, save})`\n // hooks; without them the strategy degrades to per-spawn behaviour\n // (no continuity).\n //\n // pinned-session is still supported as a fallback for hosts that\n // haven't wired the resume hooks yet — same warm-process semantics\n // as pre-AIP-45-extension behaviour.\n default: \"native-resume\",\n supported: [\"native-resume\", \"pinned-session\", \"transcript\", \"none\"],\n pinned_session: {\n idle_timeout_ms: 1_800_000,\n key_scope: [\"conversation\", \"operator\"],\n },\n },\n tags: [\"claude-code\", \"anthropic\", \"acp\", \"agent-runtime\", \"coding\"],\n metadata: {\n // Opts claude-code into `agentproto install skill/<slug>` fan-out (no\n // --target given). Claude Code skills install as a whole plugin\n // bundle, not per-skill drops — `unit: \"whole-pack\"` tells the\n // fan-out dispatcher to emit the pack once, not once per requested\n // skill slug. See\n // packages/cli/src/commands/skill-install/types.ts `AdapterSkillsTarget`.\n skills: {\n format: \"claude-plugin\",\n unit: \"whole-pack\",\n outDir: \"~/.claude/plugins/agentproto\",\n },\n },\n})\n\nexport function claudeCodeRuntime(): AgentCliRuntime {\n return createAgentCliRuntime(claudeCode)\n}\n\nexport {\n claudeCodeProjectSlug,\n parseClaudeCodeTranscriptUsage,\n readClaudeCodeUsage,\n resetClaudeCodeUsageCache,\n type ClaudeCodeUsage,\n} from \"./usage.js\"\n\nexport type { AgentCliHandle, AgentCliRuntime }\n"]}
1
+ {"version":3,"sources":["../src/usage.ts","../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;AAkDA,IAAM,GAAA,GAAM,CAAC,CAAA,KACX,OAAO,CAAA,KAAM,YAAY,MAAA,CAAO,QAAA,CAAS,CAAC,CAAA,GAAI,CAAA,GAAI,MAAA;AAIpD,SAAS,QAAA,CAAS,OAAkB,IAAA,EAAoB;AACtD,EAAA,MAAM,OAAA,GAAU,KAAK,IAAA,EAAK;AAC1B,EAAA,IAAI,CAAC,OAAA,EAAS;AACd,EAAA,IAAI,KAAA;AACJ,EAAA,IAAI;AACF,IAAA,KAAA,GAAQ,IAAA,CAAK,MAAM,OAAO,CAAA;AAAA,EAC5B,CAAA,CAAA,MAAQ;AACN,IAAA;AAAA,EACF;AACA,EAAA,IAAI,CAAC,KAAA,IAAS,OAAO,KAAA,KAAU,QAAA,EAAU;AACzC,EAAA,MAAM,CAAA,GAAI,KAAA;AAKV,EAAA,IAAI,CAAA,CAAE,SAAS,WAAA,EAAa;AAC5B,EAAA,MAAM,KAAA,GAAQ,EAAE,OAAA,EAAS,KAAA;AACzB,EAAA,IAAI,CAAC,KAAA,IAAS,OAAO,KAAA,KAAU,QAAA,EAAU;AACzC,EAAA,MAAM,UAAU,KAAA,CAAM,qBAAA;AACtB,EAAA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,gBAAA,EAAkB,cAAc,MAAM,CAAA;AAAA,IACnE,cAAA,EAAgB;AAAA,MACd,eAAA,EAAiB,IAAA;AAAA,MACjB,SAAA,EAAW,CAAC,cAAA,EAAgB,UAAU;AAAA;AACxC,GACF;AAAA,EACA,MAAM,CAAC,aAAA,EAAe,WAAA,EAAa,KAAA,EAAO,iBAAiB,QAAQ,CAAA;AAAA,EACnE,QAAA,EAAU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAOR,MAAA,EAAQ;AAAA,MACN,MAAA,EAAQ,eAAA;AAAA,MACR,IAAA,EAAM,YAAA;AAAA,MACN,MAAA,EAAQ;AAAA;AACV;AAEJ,CAAC;AAEM,SAAS,iBAAA,GAAqC;AACnD,EAAA,OAAO,sBAAsB,UAAU,CAAA;AACzC","file":"index.mjs","sourcesContent":["/**\n * Real per-turn token usage for a claude-code session, read from Claude\n * Code's own transcript JSONL.\n *\n * Over ACP, claude-agent-acp's `usage_update` only carries cost + context\n * size/used — no input/output split and no prompt-cache split. Claude Code\n * itself writes every API response's `usage` block into\n * `<CLAUDE_CONFIG_DIR|~/.claude>/projects/<slug(cwd)>/<sessionId>.jsonl`\n * (Task sub-agents into `<sessionId>/subagents/*.jsonl` next to it), so the\n * daemon's `readUsage` hook sums those instead.\n *\n * One API response is written as SEVERAL lines (one per content block), each\n * repeating the same `message.id` and the same `usage` — so usage is keyed by\n * message id (last line wins) and summed once per response.\n *\n * Reads are incremental: the daemon polls this every few seconds while the\n * session runs, so each file keeps a byte offset and only the appended tail\n * is parsed on the next call.\n */\n\nimport { open, readdir, stat } from \"node:fs/promises\"\nimport { homedir } from \"node:os\"\nimport { join, resolve } from \"node:path\"\n\n/** Cumulative token usage for one claude-code session. Fields are omitted\n * when no response reported them (never zero-filled). */\nexport interface ClaudeCodeUsage {\n tokensIn?: number\n tokensOut?: number\n cacheReadTokens?: number\n cacheWriteTokens?: number\n reasoningTokens?: number\n}\n\ninterface ResponseUsage {\n input?: number\n output?: number\n cacheRead?: number\n cacheWrite?: number\n reasoning?: number\n}\n\n/** Per-response usage keyed by message id, plus the parse cursor. */\ninterface FileState {\n /** Byte offset just past the last complete (newline-terminated) line. */\n offset: number\n responses: Map<string, ResponseUsage>\n anon: number\n}\n\nconst num = (v: unknown): number | undefined =>\n typeof v === \"number\" && Number.isFinite(v) ? v : undefined\n\n/** Fold one JSONL line into `state`. Non-assistant / usage-less / malformed\n * lines are ignored. */\nfunction foldLine(state: FileState, line: string): void {\n const trimmed = line.trim()\n if (!trimmed) return\n let entry: unknown\n try {\n entry = JSON.parse(trimmed)\n } catch {\n return\n }\n if (!entry || typeof entry !== \"object\") return\n const e = entry as {\n type?: unknown\n requestId?: unknown\n message?: { id?: unknown; usage?: Record<string, unknown> }\n }\n if (e.type !== \"assistant\") return\n const usage = e.message?.usage\n if (!usage || typeof usage !== \"object\") return\n const details = usage.output_tokens_details as Record<string, unknown> | undefined\n const r: ResponseUsage = {}\n const input = num(usage.input_tokens)\n const output = num(usage.output_tokens)\n const cacheRead = num(usage.cache_read_input_tokens)\n const cacheWrite = num(usage.cache_creation_input_tokens)\n const reasoning = num(details?.thinking_tokens) ?? num(details?.reasoning_tokens)\n if (input !== undefined) r.input = input\n if (output !== undefined) r.output = output\n if (cacheRead !== undefined) r.cacheRead = cacheRead\n if (cacheWrite !== undefined) r.cacheWrite = cacheWrite\n if (reasoning !== undefined) r.reasoning = reasoning\n const key =\n typeof e.message?.id === \"string\"\n ? e.message.id\n : typeof e.requestId === \"string\"\n ? `req:${e.requestId}`\n : `anon:${state.anon++}`\n state.responses.set(key, r)\n}\n\nfunction newState(): FileState {\n return { offset: 0, responses: new Map(), anon: 0 }\n}\n\n/** Parse a whole transcript's text in one go. Exposed for tests + one-shot\n * callers; the incremental reader below folds lines through the same path. */\nexport function parseClaudeCodeTranscriptUsage(text: string): ClaudeCodeUsage | null {\n const state = newState()\n for (const line of text.split(\"\\n\")) foldLine(state, line)\n return sumResponses([state])\n}\n\nfunction sumResponses(states: readonly FileState[]): ClaudeCodeUsage | null {\n const out: ClaudeCodeUsage = {}\n let any = false\n const add = (k: keyof ClaudeCodeUsage, v: number | undefined): void => {\n if (v === undefined) return\n out[k] = (out[k] ?? 0) + v\n }\n for (const state of states) {\n for (const r of state.responses.values()) {\n any = true\n add(\"tokensIn\", r.input)\n add(\"tokensOut\", r.output)\n add(\"cacheReadTokens\", r.cacheRead)\n add(\"cacheWriteTokens\", r.cacheWrite)\n add(\"reasoningTokens\", r.reasoning)\n }\n }\n return any ? out : null\n}\n\n/** Incremental parse state, keyed by absolute file path. */\nconst fileStates = new Map<string, FileState>()\n\n/** Bring `path`'s state up to date with the file on disk. Returns undefined\n * when the file doesn't exist. */\nasync function refreshFile(path: string): Promise<FileState | undefined> {\n let size: number\n try {\n size = (await stat(path)).size\n } catch {\n fileStates.delete(path)\n return undefined\n }\n let state = fileStates.get(path)\n // Shrunk = rewritten (e.g. a resumed transcript), start over.\n if (!state || size < state.offset) {\n state = newState()\n fileStates.set(path, state)\n }\n if (size === state.offset) return state\n const start = state.offset\n const fh = await open(path, \"r\")\n try {\n const len = size - start\n const buf = Buffer.alloc(len)\n const { bytesRead } = await fh.read(buf, 0, len, start)\n // An overlapping call (turn-end read racing the live poller) already\n // consumed this range; folding is keyed so it'd be harmless, but the\n // offset must not advance twice.\n if (state.offset !== start || fileStates.get(path) !== state) return state\n // Only consume through the last newline: anything after it is a line\n // still being written, re-read whole on the next call (cutting on a\n // byte boundary could also split a multi-byte character).\n const end = buf.subarray(0, bytesRead).lastIndexOf(0x0a)\n if (end < 0) return state\n state.offset = start + end + 1\n for (const line of buf.subarray(0, end).toString(\"utf8\").split(\"\\n\")) {\n foldLine(state, line)\n }\n } finally {\n await fh.close()\n }\n return state\n}\n\n/** Transcript paths for `sessionId`: the main JSONL plus any Task\n * sub-agent transcripts beside it. */\nasync function transcriptPaths(projectDir: string, sessionId: string): Promise<string[]> {\n const paths = [join(projectDir, `${sessionId}.jsonl`)]\n const subDir = join(projectDir, sessionId, \"subagents\")\n try {\n for (const name of (await readdir(subDir)).sort()) {\n if (name.endsWith(\".jsonl\")) paths.push(join(subDir, name))\n }\n } catch {\n // no sub-agents\n }\n return paths\n}\n\n/** Claude Code's project-dir slug: every non-alphanumeric char → \"-\". */\nexport function claudeCodeProjectSlug(cwd: string): string {\n return cwd.replace(/[^a-zA-Z0-9]/g, \"-\")\n}\n\n/**\n * Best-effort cumulative usage for a claude-code session. Looks under the\n * session's isolated `configDir` first, then `~/.claude`. Returns null when\n * no transcript (or no usage in it) is found; never throws.\n */\nexport async function readClaudeCodeUsage(\n sessionId: string,\n ctx?: { cwd?: string; configDir?: string },\n): Promise<ClaudeCodeUsage | null> {\n try {\n if (!ctx?.cwd) return null\n const slug = claudeCodeProjectSlug(ctx.cwd)\n const bases = [\n ...(ctx.configDir ? [ctx.configDir] : []),\n resolve(homedir(), \".claude\"),\n ]\n for (const base of bases) {\n const projectDir = resolve(base, \"projects\", slug)\n const states: FileState[] = []\n for (const path of await transcriptPaths(projectDir, sessionId)) {\n const state = await refreshFile(path)\n if (state) states.push(state)\n }\n // The main transcript decides which base is the session's store.\n if (states.length > 0) return sumResponses(states)\n }\n return null\n } catch {\n return null\n }\n}\n\n/** Test hook: drop the incremental parse cache. */\nexport function resetClaudeCodeUsageCache(): void {\n fileStates.clear()\n}\n","/**\n * @agentproto/adapter-claude-code — AIP-45 adapter for Anthropic's\n * Claude Code via the @agentclientprotocol/claude-agent-acp wrapper.\n */\n\nimport {\n createAgentCliRuntime,\n defineAgentCli,\n type AgentCliHandle,\n type AgentCliRuntime,\n} from \"@agentproto/driver-agent-cli\"\nimport { ANTHROPIC_CORE_SCRUB_ENV } from \"@agentproto/provider-presets\"\nimport {\n listNativeModelIds,\n listOpencodeAnthropicModelRefs,\n} from \"@agentproto/model-catalog/llm\"\n\n// Cloud-provider redirect toggles that must be scrubbed alongside the core\n// ANTHROPIC_API_KEY whenever the claude binary is pointed at a non-Anthropic\n// gateway — a leftover toggle would override ANTHROPIC_BASE_URL and silently\n// route back to Bedrock/Vertex/etc. The core ANTHROPIC_API_KEY scrub itself\n// is sourced from @agentproto/provider-presets (the single source of truth for\n// gateway facts), so a new native-Anthropic credential env var added there is\n// picked up here automatically. Shared by the moonshot/openrouter modes and\n// the base_url option.\nconst CLAUDE_CODE_CLOUD_TOGGLES: string[] = [\n \"CLAUDE_CODE_USE_BEDROCK\",\n \"CLAUDE_CODE_USE_VERTEX\",\n \"CLAUDE_CODE_USE_FOUNDRY\",\n \"CLAUDE_CODE_USE_ANTHROPIC_AWS\",\n \"CLAUDE_CODE_USE_MANTLE\",\n \"CLAUDE_CODE_USE_GATEWAY\",\n]\nconst CLAUDE_CODE_GATEWAY_ENV_UNSET: string[] = [\n ...ANTHROPIC_CORE_SCRUB_ENV,\n ...CLAUDE_CODE_CLOUD_TOGGLES,\n]\n\n// Native-Anthropic model menu, derived from the catalog's own synced\n// `/v1/models` listing (see `listNativeModelIds` — never a hand-typed id\n// list, see agentproto#186 / the removal note below for why that used to\n// be one). An id landing here the moment Anthropic publishes it is the\n// whole point: no PR needed for the next model. Nothing is known to need\n// hiding today, so the denylist starts empty — it exists purely as the\n// one sanctioned manual override (a specific id we've vetted and want\n// OFF this adapter), never as a stand-in for a hand-typed allowlist.\nconst NATIVE_ANTHROPIC_DENYLIST = new Set<string>([])\nconst NATIVE_ANTHROPIC_MODELS = listNativeModelIds(\"anthropic\")\n .filter(id => !NATIVE_ANTHROPIC_DENYLIST.has(id))\n .map(id => ({ id, provider: \"anthropic\" as const }))\n\n// OpenCode Go / OpenCode Zen, both fronted through their Anthropic-compatible\n// gateway presets (`opencode-go` / `opencode` in @agentproto/provider-presets).\n// Derived, not hand-typed, and deliberately NOT the endpoints' full lineups:\n// each endpoint serves three wire surfaces behind one base URL and only the\n// `/v1/messages` subset is reachable from the claude binary, so the menu comes\n// from the catalog's generated per-model surface discriminator\n// (`listOpencodeAnthropicModelRefs`). Zen's subset is the entire Claude family\n// — the valuable path here, since it drives this very harness on real Claude\n// models against a Zen balance. Go's is four ids (minimax-m2.5/m2.7/m3,\n// qwen3.8-flash). The refs carry NO `@route` suffix: for these endpoints the\n// route IS the id's leading segment (`opencode/claude-sonnet-4-6`), which is\n// what the catalog keys and what `modelIdPrefixProvider` reads.\nconst OPENCODE_ANTHROPIC_MODELS = [\n ...listOpencodeAnthropicModelRefs(\"opencode-go\").map(id => ({\n id,\n provider: \"opencode-go\" as const,\n })),\n ...listOpencodeAnthropicModelRefs(\"opencode\").map(id => ({\n id,\n provider: \"opencode\" as const,\n })),\n]\n\nexport const claudeCode: AgentCliHandle = defineAgentCli({\n name: \"claude-code\",\n id: \"claude-code\",\n description:\n \"Anthropic's Claude Code wrapped as an ACP agent via @agentclientprotocol/claude-agent-acp. Spawned via `npx -y @agentclientprotocol/claude-agent-acp` and driven over stdio JSON-RPC.\",\n version: \"0.1.0\",\n bin: \"npx\",\n // Pinned for reproducibility. 0.81.2 bundles @anthropic-ai/claude-agent-sdk\n // 0.3.280 = Claude Code 2.1.280, the FLOOR for the current Opus generation:\n // the 0.75.1 pin shipped CC 2.1.257, which rejects `claude-opus-5-5` outright\n // (\"API Error: 400 … does not support this model; version 2.1.280 or newer is\n // required\") — a spawn-time failure, not a silent fallback. Nothing between\n // 0.75.1 and 0.81.2 breaks this adapter: the one ⚠ BREAKING entry (0.77.0,\n // `claudeCode.options.agent` no longer forwarded + the agent-picker exports\n // removed) is library-API surface for in-process consumers, and we drive the\n // wrapper as a spawned ACP server over stdio and never set that option. The\n // config options we DO apply (`model`, `effort`, `mode` via\n // `session/set_config_option`) and `session/new` are unchanged.\n bin_args: [\"-y\", \"@agentclientprotocol/claude-agent-acp@0.81.2\"],\n install: [\n {\n method: \"npm\",\n package: \"@agentclientprotocol/claude-agent-acp\",\n global: true,\n },\n ],\n version_check: {\n // PRESENCE probe — must be local, not a registry query. `npm view` would\n // succeed on every networked machine, installed or not, making `install`\n // report \"already installed\" forever on a virgin box. This probes exactly\n // what install[] creates (the global npm package): exit 1 when absent.\n // npx wrinkle: the adapter also runs via `npx -y …` without any global\n // install, but that path doesn't need this verb — and this probe can\n // never report \"installed\" when nothing is on the machine.\n cmd: \"npm ls -g @agentclientprotocol/claude-agent-acp --depth=0\",\n parse: \"(\\\\d+\\\\.\\\\d+\\\\.\\\\d+)\",\n range: \">=0.30.0\",\n timeout_ms: 15_000,\n },\n auth: {\n ref: \"./SECRETS.md\",\n state: { env: [\"ANTHROPIC_API_KEY\"] },\n },\n // Deterministic billing-auth (subscription vs api-key), resolved by the\n // runtime (@agentproto/runtime's resolveAuthSpec) and applied MECHANICALLY\n // by the driver. EXPLICIT credential selection, not scrub-by-absence: the\n // resolver SETS exactly one credential env var (from a named config/store\n // ref, never the ambient shell) and SCRUBS the conflicting one(s), so which\n // credential — and thus which billing — a spawn uses is *stated*, never\n // inferred from whatever the daemon's launching shell exported (the outage\n // this surface exists to prevent).\n //\n // provider \"anthropic\" ⇒ api-key mode SETS providerEnvVar(\"anthropic\") =\n // ANTHROPIC_API_KEY (derived from the catalog, not re-listed here) and\n // scrubs the subscription-family creds (CLAUDE_CODE_OAUTH_TOKEN +\n // ANTHROPIC_AUTH_TOKEN). authEnforce \"always\" preserves #312: claude-code\n // engages on EVERY spawn and fails fast with no credential.\n //\n // authSubscription: \"subscription\" SETS CLAUDE_CODE_OAUTH_TOKEN to a bearer\n // token minted via `claude setup-token` (bills Max/Pro, not API credits) —\n // the var Claude Code documents for that token and the ONLY one that yields\n // the clean native claude.ai-login path. (The same token as\n // ANTHROPIC_AUTH_TOKEN authenticates but is treated as a generic override\n // that disables connectors — the degraded path, so it's a `conflictEnv` to\n // scrub, never the setEnv.) `conflictEnv` (ANTHROPIC_AUTH_TOKEN) is scrubbed\n // in BOTH modes; `unsetEnvAdd` (cloud toggles + ANTHROPIC_BASE_URL) only in\n // subscription (native) mode — matching #312's exact byte-for-byte scrub set\n // in each mode (asserted by the regression snapshot test). ANTHROPIC_API_KEY\n // is NOT listed in unsetEnvAdd because it derives from providerEnvVar and is\n // scrubbed as the non-set credential automatically.\n provider: \"anthropic\",\n // A model's route is an independent choice here: the gateway modes\n // (moonshot/openrouter/…) re-point ANTHROPIC_BASE_URL, so the same model\n // can go direct-Anthropic or via any gateway → free route selection.\n routeSelection: \"free\",\n authEnforce: \"always\",\n authSubscription: {\n setEnv: \"CLAUDE_CODE_OAUTH_TOKEN\",\n conflictEnv: [\"ANTHROPIC_AUTH_TOKEN\"],\n unsetEnvAdd: [...CLAUDE_CODE_CLOUD_TOGGLES, \"ANTHROPIC_BASE_URL\"],\n },\n // How this adapter receives a GATEWAY-routed bearer credential (D4) —\n // ANTHROPIC_AUTH_TOKEN, the SAME var as the `auth_token` option below\n // (env: { ANTHROPIC_AUTH_TOKEN: \"{value}\" }) and the one the claude binary\n // actually sends as `Authorization: Bearer`. Distinct from a gateway\n // preset's own `keyEnv` (OPENROUTER_API_KEY, MOONSHOT_API_KEY, …) — that's\n // merely where the operator's providers.json stores the key; the runtime's\n // resolveAuthSpec now injects the resolved credential HERE for a gateway\n // route instead, so it lands in a var the claude binary actually reads.\n gatewayAuth: { setEnv: \"ANTHROPIC_AUTH_TOKEN\" },\n sandbox: \"./SANDBOX.md\",\n protocol: \"acp\",\n acp: \"./claude-code-acp.ACP.md\",\n session: {\n mode: \"persistent\",\n idle_timeout_ms: 1_800_000,\n context_carryover: true,\n },\n // Every id below is validated against the wrapper's live\n // `session/new` → configOptions[model] selector: the wrapper resolves\n // these (via its own `resolveModelPreference`) and rejects anything it\n // can't. That USED to be fatal — a rejected `session/set_config_option`\n // killed the whole spawn (agentproto#186) — which is why the native\n // Anthropic ids used to be a small hand-picked subset with stale entries\n // pruned by hand whenever the wrapper's own menu drifted. The apply is\n // now best-effort (see @agentproto/acp's `newSession`: a rejected model\n // is caught, logged, and recorded as `modelApplyRejection` — the session\n // continues on the agent's default rather than dying), so that risk is\n // gone and the native Anthropic ids below are derived from the catalog's\n // synced model list instead (`NATIVE_ANTHROPIC_MODELS`) — a model the\n // wrapper doesn't yet recognize just no-ops back to its default, it\n // doesn't take the spawn down with it.\n //\n // The gateway (Moonshot/OpenRouter/Requesty) models keep their `provider`\n // annotation but NO LONGER carry a `mode:` binding: the route to a gateway\n // is derived from the model catalog's `@route` route-identity, not an\n // adapter mode (SPEC §3.4a) — the gateway `modes[]` entries were deleted.\n // The claude binary still reaches those endpoints via the per-spawn\n // `base_url` / `auth_token` options (below) until the catalog route\n // apply-path lands.\n models: {\n default: \"claude-sonnet-5\",\n allowed: [\n // Native Anthropic — every id the catalog's own `/v1/models` sync\n // currently carries for this provider (see NATIVE_ANTHROPIC_MODELS\n // above), not a hand-typed subset.\n ...NATIVE_ANTHROPIC_MODELS,\n // Moonshot (Kimi) — route resolved from the catalog `@route`\n { id: \"kimi-k3\", provider: \"moonshot\" },\n { id: \"kimi-k2.7-code\", provider: \"moonshot\" },\n // OpenRouter — route resolved from the catalog `@route` route-identity\n // suffix (a bare 2-segment id resolves to the direct vendor route, which\n // is dead here; `@openrouter` pins the catalog join to the OpenRouter\n // gateway, reachable via ANTHROPIC_BASE_URL like moonshot).\n { id: \"z-ai/glm-5.2@openrouter\", provider: \"openrouter\" },\n { id: \"deepseek/deepseek-v4-pro@openrouter\", provider: \"openrouter\" },\n { id: \"moonshotai/kimi-k2@openrouter\", provider: \"openrouter\" },\n { id: \"x-ai/grok-4.5@openrouter\", provider: \"openrouter\" },\n { id: \"x-ai/grok-4.20@openrouter\", provider: \"openrouter\" },\n { id: \"x-ai/grok-4.3@openrouter\", provider: \"openrouter\" },\n { id: \"google/gemini-3.1-pro-preview@openrouter\", provider: \"openrouter\" },\n { id: \"google/gemini-3.5-flash@openrouter\", provider: \"openrouter\" },\n { id: \"google/gemini-2.5-flash@openrouter\", provider: \"openrouter\" },\n { id: \"google/gemini-2.5-pro@openrouter\", provider: \"openrouter\" },\n { id: \"moonshotai/kimi-k2.7-code@openrouter\", provider: \"openrouter\" },\n // OpenAI gpt-5.6 series via OpenRouter — reachable via ANTHROPIC_BASE_URL\n // + ANTHROPIC_AUTH_TOKEN (the gatewayAuth setEnv above) like the other\n // gateway rows. The `@openrouter` suffix pins the catalog join to the\n // OpenRouter gateway (the bare id would resolve to the direct-OpenAI\n // route, which this Anthropic client can't speak). These are real,\n // already-priced OpenRouter chat models, not invented specialist ids.\n { id: \"openai/gpt-5.6-luna@openrouter\", provider: \"openrouter\" },\n { id: \"openai/gpt-5.6-sol@openrouter\", provider: \"openrouter\" },\n // Requesty — route resolved from the catalog `@route`\n { id: \"sference/thinkingcap-qwen3.6-27b@requesty\", provider: \"requesty\" },\n { id: \"sference/glm-5.2@requesty\", provider: \"requesty\" },\n // OpenCode Go + OpenCode Zen — see OPENCODE_ANTHROPIC_MODELS above.\n ...OPENCODE_ANTHROPIC_MODELS,\n // Local llm-endpoint proxy — route resolved from the catalog `@route`\n // (registerBuiltinRoutes registers `llm-endpoint` → Anthropic surface at\n // localhost:18090). A SMALL curated set from the proxy's own `default`\n // pack (packages/llm-endpoint/src/packs.ts) — vendor prefix is the proxy's\n // transparent-provider name so the boundary-stripped `vendor/product`\n // upstream id (e.g. `moonshot/kimi-k2.7-code`) transparently routes.\n { id: \"moonshot/kimi-k3@llm-endpoint\", provider: \"llm-endpoint\" },\n { id: \"moonshot/kimi-k2.7-code@llm-endpoint\", provider: \"llm-endpoint\" },\n { id: \"moonshot/kimi-k2.6@llm-endpoint\", provider: \"llm-endpoint\" },\n { id: \"zai/glm-5.2@llm-endpoint\", provider: \"llm-endpoint\" },\n { id: \"openai/gpt-4.1@llm-endpoint\", provider: \"llm-endpoint\" },\n { id: \"openai/gpt-4o-mini@llm-endpoint\", provider: \"llm-endpoint\" },\n ],\n env: { anthropic: \"ANTHROPIC_API_KEY\" },\n },\n capabilities: {\n streaming: true,\n tool_calls: true,\n sub_agents: false,\n file_io: true,\n // ACP wrapper forwards `image` content blocks in user prompts\n // straight to Anthropic Messages API. Hosts SHOULD send images\n // inline (see CLAUDE-CODE.md) instead of passing paths and\n // hoping the model uses Read.\n multimodal: true,\n // The wrapper (@agentclientprotocol/claude-agent-acp >= 0.30)\n // advertises `loadSession: true` and exposes the full session\n // lifecycle (newSession / loadSession / resumeSession / forkSession)\n // over JSON-RPC. Pairs with `continuation.default: native-resume`\n // below — the host persists the sessionId and reattaches to the\n // existing session across cold starts (api restart, sandbox reap,\n // multi-machine).\n resumable: true,\n bidirectional: true,\n // Claude Code's Read tool can ingest any absolute path the host\n // surfaces via the prompt. Pair with the daemon's POST /files/upload\n // route + a host UI drag-drop handler: drop a file → daemon writes\n // to `cwd/.agentproto-attachments/<name>` → host pastes the path\n // into the terminal → Claude reads it natively. No protocol-level\n // multimodal round-trip needed; pure file-path injection.\n file_attach: true,\n // Claude Code has a verified native TUI resume path:\n // `claude --resume <conversation-id>`. Governs provider-native\n // terminal restart, distinct from ACP-level `resumable`.\n nativeTerminalResume: true,\n // Claude Code defers MCP tool schemas behind its own `ToolSearch`\n // tool (docs: code.claude.com/docs/en/mcp \"MCP Tool Search\"; modes\n // standard/tst/tst-auto in the pinned binary, see the `lean` mode below).\n // The daemon therefore mounts itself eager here — see\n // `resolveSpawnDeferredTools` (packages/runtime/src/deferred-tools.ts).\n nativeToolSearch: true,\n },\n // Only the `lean` context mode remains a manifest `modes[]` entry (SPEC\n // §3.4a). Posture (plan / accept-edits / bypass-permissions) and the gateway\n // routes (moonshot / openrouter / requesty / deepseek) were BOTH removed from\n // here:\n // - posture now comes from the harness's own ACP mode registry\n // (`SessionModeState.availableModes`) plus the daemon's canonical-posture\n // layer (step 2c). The `CLAUDE_CONFIG_DIR` ENFORCEMENT MECHANISM in the\n // driver (`resolveClaudeCodePermissionMode` in define-agent-cli.ts) is\n // unchanged — it still points a per-session `CLAUDE_CONFIG_DIR` at a\n // throwaway `settings.json` with `{\"permissions\":{\"defaultMode\":\n // \"<value>\"}}` (the ACP wrapper ignores `--permission-mode` on argv). But\n // its INPUT changed: it looks the value up in `modes[]` by `config.mode`,\n // and with the posture modes removed here that lookup no longer matches\n // for `plan`/`accept-edits`/`bypass-permissions` — so the `config.mode`-\n // driven path is now DORMANT (returns undefined) until step 2c re-sources\n // the requested posture from the canonical layer and feeds it in. The\n // known limitation still holds once it does: a target repo that commits\n // its own escalated `.claude/settings.json` `permissions.defaultMode`\n // defeats OUR requested mode in the same merge pass and the session falls\n // back to \"default\" (never the original silent-write bug).\n // - route now comes from the model catalog's `@route` route-identity; the\n // gateway endpoint is still reachable per-spawn via the `base_url` /\n // `auth_token` options (below), which carry the same ANTHROPIC_API_KEY +\n // cloud-toggle scrub via `env_unset`.\n modes: [\n {\n id: \"lean\",\n description:\n \"Drop Claude Code's bundled skills and workflows from context (built-in slash \" +\n \"commands stay typable but are hidden from the model), AND turn on Claude \" +\n \"Code's own native MCP tool-search (deferred tool-schema loading) so its \" +\n \"turn-0 tools/list payload — including whatever this session's own \" +\n \"`mcpServers` mount (e.g. the daemon self-mount) advertises — shrinks the \" +\n \"same way `tool_search` does on the daemon's gateway. Plugins, project \" +\n \"`.claude/skills/`, and `.claude/commands/` are unaffected. Both knobs are \" +\n \"env-only — the ACP wrapper exposes no CLI flag for either, and the \" +\n \"underlying claude binary reads them directly.\",\n // CLAUDE_CODE_DISABLE_BUNDLED_SKILLS: unchanged from before this mode existed.\n //\n // ENABLE_TOOL_SEARCH: UNDOCUMENTED — there is no public Anthropic reference\n // for it. Confirmed present and wired (not a guess) by extracting readable\n // strings from the EXACT pinned binary this adapter spawns\n // (`~/.local/share/claude/versions/2.1.280`, the build\n // `@agentclientprotocol/claude-agent-acp@0.81.2` bundles — see the pin\n // comment on `bin_args` above): `ENABLE_TOOL_SEARCH` appears in the CLI's\n // own recognized-env-var table (alongside `MCP_TIMEOUT`,\n // `MAX_MCP_OUTPUT_TOKENS`, etc.) and drives a real decision function\n // (minified as `Het()` in that build) that resolves to one of three modes:\n // `\"standard\"` (today's eager behaviour, the default when unset in most\n // cohorts), `\"tst\"` (tool-search-tool: MCP/tool schemas deferred behind a\n // native search tool — the ACTUAL feature this mirrors), or `\"tst-auto\"`\n // (auto-threshold via `auto:<N>`, `0 <= N <= 100`). The value parser\n // (minified `Co`/`De` in that build) accepts the literal strings\n // `\"1\"`/`\"true\"`/`\"yes\"`/`\"on\"` for on and `\"0\"`/`\"false\"`/`\"no\"`/`\"off\"`\n // for off — `\"1\"` here is a valid, intentional value, not a placeholder.\n // NOT independently verified against a live model turn in this\n // environment (no authenticated Claude Code login available when this\n // was investigated) — only that `claude -p` accepts the env var and\n // proceeds past argument parsing to the auth check without erroring on\n // it. If Anthropic ever removes or renames this (it is explicitly\n // unstable — the binary also guards it behind\n // `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS`), the worst case is a no-op:\n // an unrecognized env var the claude binary already ignores today.\n env: { CLAUDE_CODE_DISABLE_BUNDLED_SKILLS: \"1\", ENABLE_TOOL_SEARCH: \"1\" },\n kind: \"context\",\n },\n ],\n options: [\n {\n id: \"model\",\n // string (not enum) so any valid Anthropic model ID is accepted\n // without requiring a code change to expand the list. Applied via\n // ANTHROPIC_MODEL env var so the claude binary picks it up directly\n // — the claude-agent-acp wrapper only forwards CLI args when --cli\n // is passed, otherwise it runs in ACP mode and ignores argv.\n type: \"string\" as const,\n description:\n \"Anthropic model ID or wrapper alias (e.g. 'claude-opus-4-8', \" +\n \"'claude-sonnet-5', 'sonnet', 'opus'). Set via ANTHROPIC_MODEL env \" +\n \"var so the claude binary uses it directly. Omit to use the claude-code default.\",\n env: { ANTHROPIC_MODEL: \"{value}\" },\n },\n {\n id: \"effort\",\n type: \"enum\" as const,\n // Effort is model-dependent: the same label maps to different\n // underlying compute budgets across models, and the model's own\n // default differs (Sonnet 4.6 / Opus 4.8 default to \"high\";\n // Opus 4.7 defaults to \"xhigh\"). \"max\" and \"ultracode\" are\n // session-only — not valid in persisted settings. Omit to keep\n // the model's own default rather than hardcoding one here.\n enum: [\"low\", \"medium\", \"high\", \"xhigh\", \"max\", \"ultracode\"],\n description:\n \"Reasoning effort level. Model-dependent: the same label ≠ the same \" +\n \"compute budget across models, and defaults differ by model \" +\n \"(e.g. Sonnet 4.6 / Opus 4.8 default to 'high'; Opus 4.7 to 'xhigh'). \" +\n \"'max' and 'ultracode' are session-only. Omit to keep the model's own default.\",\n },\n {\n id: \"max_turns\",\n type: \"integer\" as const,\n min: 1,\n max: 200,\n description:\n \"Hard cap on tool-use turns within a single send. Claude Code stops after this many cycles.\",\n bin_args_template: [\"--max-turns\", \"{value}\"],\n },\n {\n id: \"tool_search\",\n // Same `ENABLE_TOOL_SEARCH` env var the `lean` mode sets (see the long\n // note there for where it's read and which values the binary accepts).\n // \"false\" is the one a workflow agent step with a declared `tools`\n // allowlist gets (sessions-registry-agent-host.ts): its gateway mount\n // is already scoped to a handful of tools, so deferring them behind\n // Claude Code's own search only costs the model ToolSearch round-trips\n // before it can call the tool it was told to call.\n type: \"enum\" as const,\n enum: [\"true\", \"false\", \"auto\"],\n description:\n \"Claude Code's own MCP tool search (deferred tool-schema loading), via \" +\n \"ENABLE_TOOL_SEARCH. 'false' loads every mounted MCP tool eagerly; 'true' \" +\n \"always defers; 'auto' defers past a size threshold. Omit to keep Claude \" +\n \"Code's default.\",\n env: { ENABLE_TOOL_SEARCH: \"{value}\" },\n },\n {\n id: \"base_url\",\n // Injected into the child env as ANTHROPIC_BASE_URL — the claude binary\n // honors it, so this fronts real Anthropic, Bedrock/Vertex/Azure, or an\n // Anthropic-compatible gateway (LiteLLM / claude-code-router / Moonshot\n // / OpenRouter). Auto-scrubs the ambient ANTHROPIC_API_KEY + cloud\n // redirect toggles the moment it's set (symmetric with the moonshot/\n // openrouter modes and with claude-sdk's buildQueryOptions scrub) so the\n // real Anthropic credential can never leak to a third-party host — pair\n // with `auth_token` to supply the gateway key. A base_url pointed at a\n // real-Anthropic mirror that still wants the ambient key is the one\n // shape this breaks; that's an acceptable trade for the default being\n // leak-safe (matches claude-sdk).\n type: \"string\" as const,\n description:\n \"Custom Anthropic base URL. Injected as ANTHROPIC_BASE_URL in the \" +\n \"child env — front real Anthropic, Bedrock/Vertex/Azure, or an \" +\n \"Anthropic-compatible gateway. Auto-scrubs the ambient \" +\n \"ANTHROPIC_API_KEY + cloud redirect toggles when set (so the real \" +\n \"key can't leak to a third-party host) — pair with `auth_token` to \" +\n \"supply the gateway credential. For Moonshot/OpenRouter the dedicated \" +\n \"modes pre-wire the URL too. Omit to use the default endpoint.\",\n env: { ANTHROPIC_BASE_URL: \"{value}\" },\n env_unset: CLAUDE_CODE_GATEWAY_ENV_UNSET,\n },\n {\n id: \"auth_token\",\n // Injected into the child env as ANTHROPIC_AUTH_TOKEN — the claude\n // binary sends it as `Authorization: Bearer <token>`, which\n // Anthropic-compatible gateways (Moonshot, OpenRouter) accept. Pair\n // with base_url (or a gateway mode) for a per-spawn key instead of the\n // ambient ANTHROPIC_API_KEY.\n type: \"string\" as const,\n description:\n \"Bearer token for the Anthropic API or a compatible gateway. Injected \" +\n \"as ANTHROPIC_AUTH_TOKEN in the child env (sent as `Authorization: \" +\n \"Bearer`). Pair with `base_url` (or a `moonshot`/`openrouter` mode) \" +\n \"to target a gateway with a per-spawn key instead of the ambient \" +\n \"ANTHROPIC_API_KEY. Omit to use ANTHROPIC_API_KEY from the environment.\",\n env: { ANTHROPIC_AUTH_TOKEN: \"{value}\" },\n },\n ],\n continuation: {\n // native-resume: each turn cold-spawns claude, then ACP `loadSession`\n // reattaches to the saved sessionId. Survives api restarts, sandbox\n // reaps, multi-machine — claude reads its own JSONL session store.\n // Requires the host to register `configureNativeResume({load, save})`\n // hooks; without them the strategy degrades to per-spawn behaviour\n // (no continuity).\n //\n // pinned-session is still supported as a fallback for hosts that\n // haven't wired the resume hooks yet — same warm-process semantics\n // as pre-AIP-45-extension behaviour.\n default: \"native-resume\",\n supported: [\"native-resume\", \"pinned-session\", \"transcript\", \"none\"],\n pinned_session: {\n idle_timeout_ms: 1_800_000,\n key_scope: [\"conversation\", \"operator\"],\n },\n },\n tags: [\"claude-code\", \"anthropic\", \"acp\", \"agent-runtime\", \"coding\"],\n metadata: {\n // Opts claude-code into `agentproto install skill/<slug>` fan-out (no\n // --target given). Claude Code skills install as a whole plugin\n // bundle, not per-skill drops — `unit: \"whole-pack\"` tells the\n // fan-out dispatcher to emit the pack once, not once per requested\n // skill slug. See\n // packages/cli/src/commands/skill-install/types.ts `AdapterSkillsTarget`.\n skills: {\n format: \"claude-plugin\",\n unit: \"whole-pack\",\n outDir: \"~/.claude/plugins/agentproto\",\n },\n },\n})\n\nexport function claudeCodeRuntime(): AgentCliRuntime {\n return createAgentCliRuntime(claudeCode)\n}\n\nexport {\n claudeCodeProjectSlug,\n parseClaudeCodeTranscriptUsage,\n readClaudeCodeUsage,\n resetClaudeCodeUsageCache,\n type ClaudeCodeUsage,\n} from \"./usage.js\"\n\nexport type { AgentCliHandle, AgentCliRuntime }\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentproto/adapter-claude-code",
3
- "version": "2.4.9",
3
+ "version": "2.5.0",
4
4
  "description": "@agentproto/adapter-claude-code — AIP-45 AGENT-CLI adapter for Anthropic's Claude Code via @agentclientprotocol/claude-agent-acp. Spawns the ACP wrapper and drives Claude Code as an agentproto agent CLI.",
5
5
  "keywords": [
6
6
  "agentproto",
@@ -41,9 +41,9 @@
41
41
  "access": "public"
42
42
  },
43
43
  "dependencies": {
44
- "@agentproto/provider-presets": "0.7.0",
45
- "@agentproto/driver-agent-cli": "2.7.1",
46
- "@agentproto/model-catalog": "0.11.3"
44
+ "@agentproto/driver-agent-cli": "2.8.0",
45
+ "@agentproto/model-catalog": "0.11.3",
46
+ "@agentproto/provider-presets": "0.7.0"
47
47
  },
48
48
  "devDependencies": {
49
49
  "@types/node": "^25.9.5",