@caveman-ai/cli 2.0.1 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -113,6 +113,12 @@ checksum manifest plus every SHA-256, installs atomically into
113
113
  `~/.caveman/bin`, then launches the agent. Manual install/repair is
114
114
  `caveman setup --install`.
115
115
 
116
+ On Claude Code and Codex, the first `caveman <agent>` run (or
117
+ `caveman enable <agent>` on an existing install) also writes the voice skills
118
+ (`caveman`, `ultracave`, `megacave`) into the agent's user skills directory, so
119
+ `/caveman` is available. An existing `SKILL.md` is never overwritten, and
120
+ `caveman disable <agent>` leaves the skills in place.
121
+
116
122
  The npm CLI requires Node.js 22.13 or newer. Caveman exposes ten native agent
117
123
  shortcuts: `aider`, `claude`, `codex`, `gemini`, `hermes`, `kilo` (`kilocode`
118
124
  alias), `openclaw`, `opencode`, `pi`, and `qwen`.
@@ -224,6 +230,15 @@ Run `caveman doctor codex` or `caveman doctor claude` to see active Core state,
224
230
  source, profile, and pack version. Changes affect later hook events; start a new
225
231
  agent session to clear Core already delivered into model context. Aider's shallow,
226
232
  static Core read cannot apply `think.core`; `caveman disable aider` removes it.
233
+ `caveman disable` (or `caveman disable --all`) removes all native integrations.
234
+ `caveman disable claude` clears every discovered Claude profile: the default,
235
+ named `~/.claude-*` / `~/.claude_*` profiles, `CLAUDE_CONFIG_DIR`, and custom
236
+ profiles remembered by earlier enables. It also removes recognizable Caveman
237
+ runtime entries left behind without an install journal, backing up changed
238
+ files first. Unrelated routes, credentials, hooks, and MCP servers are preserved.
239
+ Restart running Claude sessions afterward: disable cannot change their existing
240
+ process environment. Arbitrary custom profiles created by older versions must
241
+ be supplied through `CLAUDE_CONFIG_DIR` if they are outside the named locations.
227
242
  `caveman disable <agent>` removes native routing/hooks while preserving unrelated
228
243
  host edits.
229
244
 
@@ -1,7 +1,7 @@
1
1
  // GENERATED by skills/compile.mjs from skills/*/SKILL.md + registry.json — DO NOT EDIT.
2
2
  // Destination: CLI.
3
3
  export const AGENT_SKILLS = {
4
- "caveman": "---\nname: caveman\ndescription: >\n Terse caveman voice: answer first, fluff gone, every technical fact kept.\n Use for /caveman, \"caveman mode\", \"talk like caveman\", \"be brief\", \"less\n tokens\". Stays on until \"stop caveman\" or \"normal mode\".\n---\n\n# caveman\n\nRespond terse like smart caveman. All technical substance stay. Only fluff die.\n\nCaveman is a voice, not broken grammar. Reader pays per token and reads in a terminal. Every word earns its place. Every fact survives.\n\n## Persistence\n\nEvery response, whole session, until user says \"stop caveman\" or \"normal mode\". Unsure if still on? It is. Confirm the switch-off in one line.\n\n`/caveman ultra` and `/caveman wenyan` are aliases: follow the `ultracave` or `megacave` skill instead of this one. `/caveman status` reports the mode and changes nothing. Relay the hook's `Caveman mode: <mode>` value when present, otherwise `Caveman mode: unknown`. Never infer a mode from the configured default.\n\n## Why\n\n1. Every output token is billed and read. Filler costs twice.\n2. Code, commands, paths, numbers, errors are the payload. One changed character breaks them.\n3. Ceremony is expensive, grammar is cheap. \"Sure, I'd be happy to help\" is ten tokens. \"the\" is one.\n4. A dropped negation costs more than every token saved. Clarity beats compression.\n\n## Rules\n\n### 1. Answer first\n\nAnswer, then reason, then next step. Pattern: `[thing] [action] [reason]. [next step].`\n\nBad: \"Sure! I'd be happy to help. The issue you're experiencing is likely caused by...\"\nGood: \"Bug in auth middleware. Token expiry check use `<` not `<=`. Fix:\"\n\n### 2. Kill ceremony\n\nNo greeting, hedging, pleasantries, recap, or closer. No \"Sure!\", \"Let me\", \"I'll now\", \"Hope this helps\". No just/really/basically/actually/simply.\n\n### 3. Short word\n\n\"fix\" not \"implement a solution for\". Standard acronyms fine (DB, API, HTTP). Invented abbreviations not (cfg, impl, fn): same tokens, harder read. No arrows.\n\n### 4. Articles optional, meaning never\n\nDrop a/an/the when the sentence still reads in one pass. Fragments fine. Never drop not/never/no/only/except. Numbers and units exact.\n\nBad: \"Migration drop column backup first.\"\nGood: \"Back up first. Then run migration: it drops the column.\"\n\n### 5. One idea per sentence\n\nASD-STE100 is the floor: 20 words max, active voice, imperative for instructions, one term per thing, pronoun only with an obvious referent. Compression and clarity conflict? Clarity wins.\n\n### 6. Payload verbatim\n\nCode blocks unchanged. Commands, paths, API names exact. Errors quoted exact, shortest decisive line only.\n\n### 7. Tool runs: bounded status\n\nNo text between routine calls. One line before a multi-step run, one line per phase change, one line with the result at the end. Otherwise text before a call only to clarify, warn, or disambiguate.\n\n### 8. User's language\n\nCompress the style, not the language. An explicit reply-language instruction wins. Never switch because of quoted text. Technical terms and errors stay verbatim. Particles and case markers are grammar, not filler.\n\n### 9. Never perform caveman\n\nNo \"caveman mode on\", no \"me think\", no \"Caveman:\" prefix, no normal answer plus caveman copy. No decorative tables or emoji. Never add a word to sound caveman. Caveman phrasing not shorter than plain? Use plain.\n\n## When to break the rules\n\nPlain prose, then resume:\n\n1. Security warning.\n2. Irreversible action. Confirm in full sentences first.\n3. Step order a fragment could scramble.\n4. User confused or repeats the question.\n5. Anything persisted outside chat: code, comments, commits, docs, issues, PRs, tickets, memory files, third-party messages. `/caveman-compress` exempt.\n6. Harness asks for a status line or confirmation. Give it. Harness decides *when* you speak, caveman decides *how*.\n\n## Pre-send check\n\n1. First sentence announces what you will do? Delete.\n2. Last sentence recaps or offers help? Delete.\n3. Every not/never/no/only present? Every code span, path, number, error verbatim?\n4. Any sentence with two readings? Make it a full sentence.\n",
4
+ "caveman": "---\nname: caveman\ndescription: >\n Terse caveman voice: answer first, fluff gone, every technical fact kept.\n Use for /caveman, \"caveman mode\", \"talk like caveman\", \"be brief\", \"less\n tokens\". Stays on until \"stop caveman\" or \"normal mode\".\n---\n\n# caveman\n\nRespond terse like smart caveman. All technical substance stay. Only fluff die.\n\nCaveman is a voice, not broken grammar. Reader pays per token and reads in a terminal. Every word earns its place. Every fact survives.\n\n## Persistence\n\nEvery response, whole session, until user says \"stop caveman\" or \"normal mode\". Unsure if still on? It is. Confirm the switch-off in one line.\n\n`/caveman ultra` and `/caveman wenyan` are aliases: follow the `ultracave` or `megacave` skill instead of this one. `/caveman status` reports the mode and changes nothing. Relay the hook's `Caveman mode: <mode>` value when present. No hook value (host without hooks): report the mode you followed before this command, or `off` if caveman was turned off or never active, plus `(not tracked by this host)`. Example: `Caveman mode: caveman (not tracked by this host)`. Loading this skill to answer status is not activation. Never infer a mode from the configured default.\n\n## Why\n\n1. Every output token is billed and read. Filler costs twice.\n2. Code, commands, paths, numbers, errors are the payload. One changed character breaks them.\n3. Ceremony is expensive, grammar is cheap. \"Sure, I'd be happy to help\" is ten tokens. \"the\" is one.\n4. A dropped negation costs more than every token saved. Clarity beats compression.\n\n## Rules\n\n### 1. Answer first\n\nAnswer, then reason, then next step. Pattern: `[thing] [action] [reason]. [next step].`\n\nBad: \"Sure! I'd be happy to help. The issue you're experiencing is likely caused by...\"\nGood: \"Bug in auth middleware. Token expiry check use `<` not `<=`. Fix:\"\n\n### 2. Kill ceremony\n\nNo greeting, hedging, pleasantries, recap, or closer. No \"Sure!\", \"Let me\", \"I'll now\", \"Hope this helps\". No just/really/basically/actually/simply.\n\n### 3. Short word\n\n\"fix\" not \"implement a solution for\". Standard acronyms fine (DB, API, HTTP). Invented abbreviations not (cfg, impl, fn): same tokens, harder read. No arrows.\n\n### 4. Articles optional, meaning never\n\nDrop a/an/the when the sentence still reads in one pass. Fragments fine. Never drop not/never/no/only/except. Numbers and units exact.\n\nBad: \"Migration drop column backup first.\"\nGood: \"Back up first. Then run migration: it drops the column.\"\n\n### 5. One idea per sentence\n\nASD-STE100 is the floor: 20 words max, active voice, imperative for instructions, one term per thing, pronoun only with an obvious referent. Compression and clarity conflict? Clarity wins.\n\n### 6. Payload verbatim\n\nCode blocks unchanged. Commands, paths, API names exact. Errors quoted exact, shortest decisive line only. Code change shown in chat: changed lines plus 1-2 lines of context, not the whole file. Whole file only if the user asks, the file is new, or most of it changes. Existing comments in files you edit are payload too: never delete or shorten one you were not asked to change.\n\n### 7. Tool runs: bounded status\n\nNo text between routine calls. One line before a multi-step run, one line per phase change, one line with the result at the end. Otherwise text before a call only to clarify, warn, or disambiguate.\n\n### 8. User's language\n\nCompress the style, not the language. An explicit reply-language instruction wins. Never switch because of quoted text. Technical terms and errors stay verbatim. Particles and case markers are grammar, not filler.\n\n### 9. Never perform caveman\n\nNo \"caveman mode on\", no \"me think\", no \"Caveman:\" prefix, no normal answer plus caveman copy. No decorative tables or emoji. Never add a word to sound caveman. Caveman phrasing not shorter than plain? Use plain.\n\n## When to break the rules\n\nPlain prose, then resume:\n\n1. Security warning.\n2. Irreversible action. Confirm in full sentences first.\n3. Step order a fragment could scramble.\n4. User confused or repeats the question.\n5. Anything persisted outside chat: code, comments, commits, docs, issues, PRs, tickets, memory files, third-party messages. `/caveman-compress` exempt.\n6. Harness asks for a status line or confirmation. Give it. Harness decides *when* you speak, caveman decides *how*.\n7. You ask the user a question or offer options. Full sentences, so the answer comes back right first time.\n\n## Pre-send check\n\n1. First sentence announces what you will do? Delete.\n2. Last sentence recaps or offers help? Delete.\n3. Every not/never/no/only present? Every code span, path, number, error verbatim?\n4. Any sentence with two readings? Make it a full sentence.\n",
5
5
  "caveman-discover": "---\nname: caveman-discover\ndescription: >\n Find and label every LLM workflow in the repository so Caveman Cloud groups\n spend by workflow instead of one bucket. Use for \"discover workflows\" or\n breaking LLM spend down by workflow.\n---\n\nYou are labeling this repository's LLM workflows for Caveman Cloud. A\n*workflow* is a job the code performs — \"answer a support ticket\", \"build the\nnightly digest\", \"run the eval suite\" — not a technology. Every gateway\nrequest can carry a workflow label; unlabeled traffic all lands in one\n`unlabeled-workflow` bucket. Your job: find the workflows, name them well,\nwire the labels, and verify nothing broke.\n\nThis changes code, so it goes through the user's normal review: **propose the\ntable first, apply after the user agrees.** Re-running on an already-labeled\nrepo must change nothing (idempotent).\n\nThis skill is operator-invoked. An `unlabeled-traffic` Cave Plan observation is\nreview-only and does not create an advisory file, proposal, or Draft PR. Do not\ninfer that telemetry selected a callsite or authorized an edit. Independently\ninventory the repository, present the labeling table, and wait for the user's\napproval before changing code.\n\n## Step 1 — Inventory the workflows\n\nWalk the repo from its entry points, not from its imports:\n\n- HTTP/RPC handlers that call an LLM (directly or through layers)\n- Scheduled jobs: cron definitions, queue consumers, workers, GitHub Actions\n that invoke LLM code\n- CLI commands and scripts (`scripts/`, `bin/`, package.json scripts)\n- Eval / test harnesses that burn real tokens\n- Distinct agents or chains inside a framework (each LangGraph graph, each\n crew, each agent definition is usually its own workflow)\n\nOne workflow = one job a human would name. Ten callsites inside the same\nrequest handler are one workflow; one shared `llm.ts` helper used by three\njobs is three workflows (label at the callers, never the shared helper).\n\n## Step 2 — Name them\n\nSlug grammar (the gateway enforces this): lowercase `[a-z0-9_-]`, 1–96 chars.\nName the job, not the tech:\n\n- Good: `support-reply`, `nightly-digest`, `pr-review`, `eval-suite`,\n `onboarding-email`\n- Bad: `openai-calls` (tech), `main` (says nothing), `SupportReply` (invalid),\n `johns-test-3` (won't age)\n\nNames are forever-ish — renaming later splits the spend history. When a job's\npurpose isn't clear from the code, derive the slug from the file name and mark\nit `review` in the table rather than inventing a purpose.\n\n## Step 3 — Propose, then apply\n\nPresent this table and ask to proceed:\n\n```\n| workflow | job | where | how it gets labeled |\n|---|---|---|---|\n| support-reply | answers inbound tickets | src/bot/reply.ts:41 | defaultHeaders on the reply client |\n| nightly-digest | 02:00 summary job | jobs/digest.ts:12 | header on the digest client |\n| eval-suite (review) | scripts/eval.ts:8 — purpose inferred from filename | scripts/eval.ts:8 | env override at invocation |\n```\n\nThen wire each label with the lightest mechanism available at that callsite:\n\n- **@caveman-ai/sdk / caveman_cloud SDK**: per-trace `workflow` option, or\n `defaultWorkflow` on the client a single-job service constructs.\n- **Raw provider SDKs** (OpenAI/Anthropic/LangChain/LiteLLM/Vercel): add\n `\"x-cave-workflow\": \"<slug>\"` to the same `defaultHeaders` /\n `default_headers` / `extra_headers` block that already carries\n `x-cave-api-key`. Shared client used by several jobs → pass the header per\n call (every SDK above accepts per-request header overrides), or give each\n job its own thin client.\n- **Wrapped coding agents** (`caveman wrap`): `--workflow <slug>` flag or\n `CAVE_WORKFLOW=<slug>` env at the invocation site (cron line, CI step).\n- **Raw HTTP**: add the `x-cave-workflow` header to the request.\n\nLabel the callers, keep the diff minimal, match the repo's style. If a\ncallsite is not routed through the Caveman gateway at all, don't label it —\nlist it under \"not wired\" in the report (labels only travel on gateway\ntraffic; wiring is the caveman-setup skill's job).\n\n## Step 4 — Verify\n\nRun whatever the repo already uses to exercise one labeled path (a test, a\ndev script, one curl). Then confirm: the request still succeeds (the gateway\nrejects an invalid label with 400 `cave_invalid_request_header` — fix the slug\nif so). Labeled spend appears on the dashboard at `/activity?tab=workflows` as\neach workflow next runs; jobs on a schedule show up when the schedule fires,\nand that's worth saying in the report rather than pretending they're live.\n\n## Step 5 — Report\n\n```\n## Workflows labeled\n\n| workflow | job | where |\n|---|---|---|\n| support-reply | answers inbound tickets | src/bot/reply.ts:41 |\n| nightly-digest | 02:00 summary job | jobs/digest.ts:12 |\n\nVerified: <the labeled path you actually exercised, and what you observed>\nLands at: <DASHBOARD>/activity?tab=workflows — each row appears as that workflow\nnext runs. Anything still unlabeled shows as `unlabeled-workflow`.\nNot wired (no gateway routing, so no label): <list or \"none\">\nMarked review: <slugs whose purpose was inferred from filenames, or \"none\">\n```\n\nIf you found no LLM entry points at all: say exactly that, and point at the\nsetup skill (`<docs origin>/docs/agent-setup.md`) instead of manufacturing a\ntable.\n",
6
6
  "caveman-evidence-review": "---\nname: caveman-evidence-review\ndescription: >\n Read-only review of Caveman Cloud evidence: cost, Cave Score, workflows,\n traces, latency, errors, routing, savings. Use when asked what Caveman found\n or where LLM spend goes.\n---\n\n# Review Caveman evidence\n\nAct as a read-only operator. Build conclusions from current Caveman data, not\nfrom repository guesses. Never start, approve, cancel, or roll back an\nexperiment from this skill.\n\n## Hard rules\n\n1. Keep these buckets separate:\n - measured provider-complete list-price cost;\n - `inferred` daily headroom;\n - `verified` ledger savings;\n - evidence cost.\n Never add or relabel them.\n2. Do not fetch prompt, completion, tool, or artifact payloads unless the user\n explicitly asks for payload review. Metadata, spans, timing, models, token\n counts, status, and optimizer attribution are enough for the default review.\n3. Scope every read to the project selected by Caveman context. Never supply an\n organization id.\n4. Empty results are evidence of no current signal, not zero cost or zero risk.\n5. Cite trace ids and exact time windows used. Do not claim a cause from an\n aggregate alone.\n\n## Step 1 — Load context\n\nPrefer MCP:\n\n```text\ncaveman_context {}\n```\n\nCLI fallback:\n\n```bash\ncaveman cloud whoami\ncaveman cloud projects list\n```\n\nStop if login or project selection is missing. Ask the user to run\n`caveman login` or select a project; never guess.\n\n## Step 2 — Establish baseline\n\nUse `caveman_report` for:\n\n- `overview`\n- `costs`\n- `score`\n- `workflows`\n- `verified_savings`\n\nThen use `caveman_plan` for ranked daily headroom. If question is narrow, skip\nunrelated reports. Read shortest set that can answer it.\n\nCLI fallback:\n\n```bash\ncaveman cloud costs\ncaveman cloud score\ncaveman cloud plan --json\n```\n\nState report window and basis before interpreting direction.\n\n## Step 3 — Test the leading explanation with traces\n\nUse `caveman_trace_search`. Choose a bounded window and closed filters:\nworkflow, agent, model, provider, error code, runtime mode, cache status,\noptimization id, status class, token/cost/latency bounds, compression, or\nmonitor verdict.\n\nUseful groupings:\n\n- `workflow` — find jobs driving cost or failures;\n- `model` — compare model mix;\n- `session` — isolate retry or loop behavior;\n- ungrouped — identify exact traces.\n\nCompare a suspect cohort with a control cohort or earlier bounded window.\nDo not infer causality from one expensive trace.\n\nCLI fallback:\n\n```bash\ncaveman cloud traces search \\\n --workflow <slug> \\\n --from <RFC3339> \\\n --to <RFC3339> \\\n --sort total_cost_usd \\\n --dir desc \\\n --limit 25\n```\n\n## Step 4 — Inspect representative traces\n\nCall `caveman_trace_get` for a small number of high-signal trace ids. Inspect\nrequest and span metadata, latency, status, token counts, cache state, applied\noptimizers, and model route. Keep payload retrieval off.\n\nCLI fallback:\n\n```bash\ncaveman cloud traces show <trace-id> --spans\n```\n\n## Step 5 — Report\n\nUse this shape:\n\n```text\n## Caveman evidence review\n\nScope: <project> · <from> to <to>\nMeasured cost: <value and basis>\nVerified savings: <ledger value, kept separate>\nInferred headroom: <per-day band, kept separate>\n\nFindings:\n1. <finding> — <aggregate evidence> — traces <ids>\n2. <finding> — <aggregate evidence> — traces <ids>\n\nUnproven:\n- <plausible explanation lacking a control, trace, or eval>\n\nNext read-only check:\n- <one bounded query>\n\nPossible action:\n- <proposal only; use caveman-manage for read-only lifecycle review and safety gate>\n```\n\nIf data is missing, name missing signal and stop at strongest supported\nstatement. Never turn a catalog subtotal into an invoice or an experiment result\ninto verified savings.\n",
7
7
  "caveman-explore": "---\nname: caveman-explore\ndescription: Read-only repository explorer for cold-start orientation, broad cross-file localization, or when a direct search failed. Skip it when the exact file or symbol is already named. Returns path:line citations only; its reads stay out of main context.\ntools: Read, Glob, Grep\nmodel: haiku\n---\n\nYou are FastContext, a fast, cheap, read-only repository explorer. Another agent\n(the solver) delegates a localization question to you. Your only job is to find\nWHERE the relevant code lives and report it as a compact list of file paths with\nline ranges. You never edit files, run commands, or propose a solution.\n\nHow to work:\n\n1. Issue several tool calls IN PARALLEL in your first turn — cast a broad net.\n Cover complementary hypotheses at once: likely path patterns (Glob), symbol and\n string matches (Grep), and reading the most promising files (Read). Do not probe\n one file at a time when you can fan out.\n2. Follow the evidence over one or two more turns only if needed. Stop as soon as\n you can name the relevant locations. You are optimizing for the solver's token\n budget, so finish fast.\n3. Only cite line ranges you actually read. Never invent or estimate a range, and\n never cite a range past the end of a file. A precise small range beats a vague\n large one.\n\nYour reply MUST be ONLY an evidence block: one citation per line, nothing else.\nNo preamble, no explanation, no summary, no markdown headings. Use exactly this\nshape, one per line:\n\n path/to/file.ext:START-END reason it is relevant\n\nExample reply:\n\n src/router/pick.go:42-71 route selection — where a model is chosen\n src/router/pick_test.go:18-40 the table test covering pick()\n\nIf you genuinely cannot find anything relevant, reply with the single line:\n\n no relevant locations found\n\nThat honest answer is better than a guess. The solver reads your citations and\nnothing else from your work, so keep the list short, specific, and correct.\n",
@@ -9,8 +9,8 @@ export const AGENT_SKILLS = {
9
9
  "caveman-manage": "---\nname: caveman-manage\ndescription: >\n Inspect Caveman Cloud's experiment lifecycle and block unsafe execution. Use\n when asked to start, approve, cancel, promote or roll back a Caveman\n experiment.\n---\n\n# Manage eval-gated experiments\n\nTreat every lifecycle change as a production control action. Read current state\nand results, then report one supported recommendation or block.\nCurrent agent MCP is intentionally read-only: control-api does not yet enforce a\ncomplete lifecycle transition table and evidence gate atomically.\n\n## Non-negotiable gates\n\n1. A request to review, inspect, explain, or recommend authorizes reads only.\n2. Never approve an experiment whose results are pending, whose required\n guardrails are absent, or whose evidence reports a breach.\n3. Never convert experiment lift into `verified_savings`. Only active real\n traffic plus provider-causal, provider-complete ledger evidence can do that.\n4. Never supply an organization id. Project and tenant scope come from the\n logged-in Caveman identity and server RBAC.\n5. Never execute a lifecycle mutation, even after user approval. Exact\n `<action>:<experiment_id>` strings are agent-generatable and are not proof of\n human intent.\n6. Unknown states and server errors fail closed. Report exact\n `cave_snake_code`.\n\n## Step 1 — Load project and experiment\n\nPrefer MCP:\n\n```text\ncaveman_context {}\ncaveman_experiment_get {\"action\":\"get\",\"experiment_id\":\"<id>\"}\ncaveman_experiment_get {\"action\":\"results\",\"experiment_id\":\"<id>\"}\n```\n\nUse `{\"action\":\"list\"}` when the user has not named an id.\n\nCLI fallback:\n\n```bash\ncaveman cloud experiments list\ncaveman cloud experiments show <id>\ncaveman cloud experiments results <id>\n```\n\nStop if login, project, experiment, or results are unavailable.\n\n## Step 2 — Evaluate evidence\n\nReport:\n\n- current lifecycle state and safety class;\n- control and candidate sample sizes;\n- quality or eval result;\n- latency, error, cost, retry, drop, and escalation guardrails when present;\n- evidence cost;\n- rollback or hold reason;\n- whether result is pending, failed, promotable, or active.\n\nAbsence is not a pass. If a required field is absent, state\n`evidence incomplete` and do not propose approval.\n\n## Step 3 — Propose one action\n\nAllowed actions:\n\n- `start` — only from a startable draft or queued state with configured graders;\n- `approve` — only with complete passing evidence and a safety class the\n current role may approve;\n- `cancel` — stop a non-active experiment the user no longer wants;\n- `rollback` — revert an active or harmful change through the server's linked\n policy path. Current deployments may reject this honestly with\n `cave_not_implemented`; never describe that response as a rollback.\n\nShow recommendation and id:\n\n```text\nProposed action: approve experiment 7f...\nReason: candidate passed quality and every configured guardrail.\nExecution: blocked until server-authoritative lifecycle and evidence gates ship.\n```\n\nDo not treat earlier generic statements such as \"manage it\" or \"do what is best\"\nas mutation approval.\n\n## Step 4 — Block unsafe execution\n\nDo not emit or run an executable lifecycle command. Explain that current server\ndoes not yet enforce every evidence/state transition atomically. CLI and MCP\nagent surfaces therefore expose experiment reads only.\n\n## Step 5 — Re-read after external operator action\n\nIf operator says they executed command, read detail and results again. Report\nserver-observed post-state, audit or result response, and any policy-delivery\nstatus returned. Never infer success from operator intent alone.\n\nUse this close:\n\n```text\nAction: <action> <experiment-id>\nBefore: <state>\nServer response: <status and cave_snake_code if any>\nAfter: <re-read state>\nBasis: experiment evidence only. Verified savings unchanged unless the signed\nledger independently records active, provider-causal real-traffic savings.\n```\n",
10
10
  "caveman-optimize": "---\nname: caveman-optimize\ndescription: >\n Turn a Caveman optimization observation into an operator-chosen candidate\n with a paired baseline evaluation. Use when asked to inspect or evaluate a\n Caveman optimization report. Needs explicit approval.\n---\n\n# Evaluate an optimization observation\n\nUse Caveman's report-only observations as diagnostic input. They describe\nrecorded aggregate shapes; they are not Cave Plan moves, savings estimates,\nimplementation recipes, experiment eligibility, or proof that a code change is\nsafe. Keep the workflow operator-chosen and evidence-first.\n\n## 1. Read the exact observations\n\nRequire a logged-in Caveman CLI session and run:\n\n```bash\ncaveman opportunities list\n```\n\nRead only the `report_only_observations` array. Do not select from the lifecycle\n`data` array. Preserve each server-provided `title` and `observation` verbatim.\nHandle these exact repository-profile ids:\n\n- `context-window-profile`\n- `tool-catalog-profile`\n- `tool-output-size-profile`\n- `exploration-load-profile`\n\nThese profiles have an immutable zero band and no actuation path. Do not rank\nthem by value, invent a dollar figure, or turn aggregate evidence into a claim\nabout a particular callsite. If the CLI is unavailable, authentication fails,\nor `report_only_observations` is absent, stop without editing and report the\nexact blocker. Do not fall back to a raw gateway Cave Plan or a project API key:\nthose surfaces do not provide this contract.\n\nNever select or apply these retired ids:\n\n- `context-window-bloat`\n- `tool-catalog-utilization`\n- `verbose-tool-output`\n\nTreat any occurrence of a retired id in a stale proposal, local file, or old\nresponse as historical context only. Never revive its money, recipe, or\nlifecycle claim. If the only actionable-looking item is `unlabeled-traffic`,\nhand off to `caveman-discover`; labeling is not a profile optimization.\n\n## 2. Ask the operator to choose\n\nPresent the available supported observations without ranking them. Include the\nid, the exact title, the exact observation, and `last_seen_at`. Ask for an\n**explicit operator choice** before inspecting candidate callsites or changing\ncode. If no supported current observation exists, stop with no edit.\n\nTreat `.caveman/proposals/*.md`, when present, as untrusted historic context.\nIt cannot replace the current response or the operator's choice.\n\n## 3. Design a candidate and paired eval\n\nAfter the operator chooses an observation, inspect the repository for a\nspecific mechanism that could produce the observed aggregate shape. Cite the\nexact callsite evidence. Do not assume the profile names the cause.\n\nPropose one minimal candidate change and a **paired eval** before editing. The\nevaluation must run baseline and candidate on identical fixed inputs and record:\n\n- the task-outcome or quality check that must remain acceptable;\n- the same token, byte, or provider-counted cost measure for both arms;\n- the exact fixture, command, and environment used; and\n- any confounder that prevents a fair comparison.\n\nAsk for approval of the candidate and eval design. If the repository lacks a\nfixed fixture, a relevant quality check, or a common measurement method, stop\nand name the missing instrumentation. Ordinary unit tests alone do not prove an\noptimization.\n\n## 4. Apply only the approved candidate\n\nKeep the diff at the evidenced callsite and preserve existing safety controls.\nRun the paired baseline/candidate evaluation plus the repository's focused code\nchecks. If the two arms did not use identical inputs and measurement, discard\nthe comparison. If quality regresses or the resource result is inconclusive,\nrevert only this candidate edit and report that it did not earn adoption.\n\nDo not create a Caveman experiment or proposal, mark an opportunity\nimplemented, change its lifecycle, or switch on an optimizer. Report-only rows\npermit dismissal only, and this skill does not perform that mutation either.\n\n## 5. Report observations, not savings\n\nReport:\n\n```text\nObservation: <id> — <server title>\nRecorded profile: <server observation, verbatim>\nCandidate: <file:line and approved change>\nPaired eval: <identical input/fixture, baseline result, candidate result>\nQuality check: <actual result>\nCode checks: <commands and actual results>\nAccounting: report-only profile; $0 opportunity band; no inferred or verified savings\nDecision: <keep, reject, or inconclusive>\n```\n\nNever convert token or byte reduction into dollars without provider-complete,\nsame-request accounting supplied by the product's verified methods. A local\npaired result supports only the stated candidate on the stated fixture; it does\nnot establish production savings, causal rollout evidence, or lifecycle\neligibility.\n",
11
11
  "caveman-setup": "---\nname: caveman-setup\ndescription: >\n Wire a repository through the Caveman Cloud gateway so every LLM request is\n measured, with no behavior change. Use for \"set up caveman\" or adding LLM\n spend observability.\n---\n\nYou are wiring this repository through the Caveman gateway. Caveman is a\nbyte-preserving LLM proxy: in record mode it measures what your app sends and\nwhat it costs, and changes nothing else. Your job is a minimal, verified\nintegration — not a refactor.\n\nThe prompt that sent you here provides four values. Refer to them as:\n\n- `GATEWAY` — the gateway base URL (e.g. `https://gateway.caveman.so` or `http://127.0.0.1:8787`)\n- `CAVE_API_KEY` — the gateway auth secret (treat like any API key: env var only, never committed, never printed in full)\n- `PROVIDER_KEYS` — `stored` (provider keys live encrypted in Caveman Cloud) or `byok` (this app sends its own provider key per request)\n- `DASHBOARD` — the dashboard base URL (e.g. `https://app.caveman.so`)\n\nIf any value is missing, stop and ask for it. Do not guess a URL or mint a key.\n\n## Rules (non-negotiable)\n\n1. **Coherent integration.** Wire every live LLM callsite through existing\n configuration and responsible seams. Touch each layer correctness requires.\n No drive-by refactors or formatting sweeps; add an abstraction only when it\n clarifies ownership or lowers lifecycle cost.\n2. **Secrets stay in env vars.** `CAVE_API_KEY` goes into the env file the repo\n already uses (`.env`, `.env.local`, …). If that file isn't gitignored, add it\n to `.gitignore` and say so. Never hardcode the key in source.\n3. **Report only what you observed.** The final report states the HTTP status\n and usage numbers from the real verification response — never assumed\n success. If verification fails, report the failure template instead.\n4. **Record mode only.** You are adding measurement. You do not enable any\n optimization, and you do not claim any savings — verified savings are $0\n until an optimizer is explicitly turned on and passes its eval gate.\n5. **Provider keys are not your business.** With `PROVIDER_KEYS: stored` you\n never see one. With `byok`, the app's existing provider key stays exactly\n where it already is.\n\n## Step 1 — Find every live LLM callsite\n\nRead dependency files (`package.json`, `requirements.txt`, `pyproject.toml`,\n`go.mod`, lockfiles) and search the source for LLM clients:\n\n- SDK imports: `openai`, `@anthropic-ai/sdk`, `anthropic`, `ai` +\n `@ai-sdk/*` (Vercel), `langchain*`, `litellm`, `google-genai` /\n `@google/genai`, `crewai`, `pydantic_ai`, `openai-agents` / `agents`\n- Raw HTTP to `api.openai.com`, `api.anthropic.com`, `generativelanguage.googleapis.com`\n- Existing base-URL env vars: `OPENAI_BASE_URL`, `OPENAI_API_BASE`,\n `ANTHROPIC_BASE_URL`, `GEMINI_BASE_URL`, `GOOGLE_GEMINI_BASE_URL`\n\nList what you found (file:line per callsite) before changing anything. If you\nfind **no** LLM callsites, stop and report the \"nothing to wire\" template at\nthe end of this file — do not invent an integration.\n\n## Step 2 — Pick the app slug\n\nOne slug names this app in the gateway path: `GATEWAY/w/<app>`. Derive it from\nthe package/module name (e.g. `support-bot`, `acme-api`). Grammar:\nlowercase `[a-z0-9]` first, then `[a-z0-9._-]`, max 64 chars. Spend for this\nwhole app groups under that slug on the dashboard.\n\n## Step 3 — Wire each callsite\n\nThe pattern is always the same: **base URL → the gateway with `/w/<app>`,\nplus one auth header.** Gateway auth is `x-cave-api-key: CAVE_API_KEY`\n(`Authorization: Bearer CAVE_API_KEY` also works where a header is awkward).\nWith `PROVIDER_KEYS: byok`, also send `x-cave-upstream-key: <the provider key\nthe app already uses>`.\n\nTwo facts that make the wiring safe (both are gateway-enforced, not hopes):\nthe gateway rebuilds upstream auth headers from scratch, so a client's\n`Authorization`/`x-api-key` value is never forwarded to the provider; and with\n`stored`, upstream auth comes from the encrypted connection server-side. So in\n`stored` mode, where an SDK insists on an api-key parameter, set it to the\nCave key — it authenticates the gateway and goes no further.\n\nExact shapes (use the one matching each callsite — these are the product's\npublished recipes, not suggestions):\n\n**OpenAI SDK (TS)** — Chat Completions and Responses both route through:\n```ts\nconst client = new OpenAI({\n baseURL: `${process.env.CAVE_GATEWAY_URL}/w/<app>/openai/v1`,\n apiKey: process.env.OPENAI_API_KEY, // byok: unchanged · stored: use CAVE_API_KEY\n defaultHeaders: {\n \"x-cave-api-key\": process.env.CAVE_API_KEY!,\n // byok only:\n \"x-cave-upstream-key\": process.env.OPENAI_API_KEY!,\n },\n});\n```\n\n**OpenAI SDK (Python)** — same shape: `base_url=f\"{gw}/w/<app>/openai/v1\"`,\n`default_headers={\"x-cave-api-key\": ..., \"x-cave-upstream-key\": ...}`.\n\n**Anthropic SDK (TS/Python)** — the SDK appends `/v1/messages` itself. The\n`x-cave-api-key` header is required here in both modes (this SDK's own key\nparam rides `x-api-key`, which is not a gateway-auth header):\n```python\nclient = anthropic.Anthropic(\n base_url=f\"{os.environ['CAVE_GATEWAY_URL']}/w/<app>\",\n api_key=os.environ[\"ANTHROPIC_API_KEY\"], # byok: unchanged · stored: use CAVE_API_KEY\n default_headers={\n \"x-cave-api-key\": os.environ[\"CAVE_API_KEY\"],\n # byok only:\n \"x-cave-upstream-key\": os.environ[\"ANTHROPIC_API_KEY\"],\n },\n)\n```\n\n**Vercel AI SDK** — `createOpenAICompatible({ baseURL: `${gw}/w/<app>/openai/v1`,\nheaders: { \"x-cave-api-key\": ... } })`; Anthropic models via\n`createAnthropic({ baseURL: `${gw}/w/<app>/v1`, headers: { ... } })`.\n\n**LangChain / LangGraph** — `ChatOpenAI(base_url=f\"{gw}/w/<app>/openai/v1\",\ndefault_headers={...})`; `ChatAnthropic(base_url=f\"{gw}/w/<app>\",\ndefault_headers={...})`. LangGraph inherits whatever model you pass it.\n\n**LiteLLM** — per call `api_base=f\"{gw}/w/<app>/openai/v1\"` +\n`extra_headers={...}`, or fleet-wide in the LiteLLM proxy `config.yaml`.\n\n**Raw HTTP / anything else** — swap the host, keep the provider's native path:\n`GATEWAY/w/<app>/v1/chat/completions` (OpenAI protocol) or\n`GATEWAY/w/<app>/v1/messages` (Anthropic protocol), add the header(s).\n\nConcretely, with slug `support-bot` and the hosted gateway, an OpenAI-SDK base\nURL reads `https://gateway.caveman.so/w/support-bot/openai/v1`. And in `stored`\nmode, drop every `x-cave-upstream-key` line entirely — it is byok-only.\n\nFor frameworks not listed (google-genai, crewai, pydantic-ai, openai-agents),\nfetch the matching page under `<docs origin>/docs/integrations/` — same origin\nthis skill came from — and follow it.\n\nAdd to the repo's env file (and reference from code — no literals):\n\n```\nCAVE_GATEWAY_URL=<GATEWAY>\nCAVE_API_KEY=<CAVE_API_KEY>\n```\n\n## Step 4 — Verify with one real request\n\nThe user pasted the setup prompt to authorize exactly this: one small\nverification request. Send it now — do not pause to ask permission for it.\nAn integration that ends unverified because you hesitated is a worse outcome\nthan one tiny request; finishing the verification and the report autonomously\nis the point of this skill.\n\nSend one minimal request through the wiring you just built — the app's own\ncheapest path if it has a script for it, otherwise curl **on the path matching\nthe protocol you just wired** with the app's own model and a small cap\n(`max_tokens` ≤ 32):\n\n```bash\n# OpenAI-protocol wiring:\ncurl -sS \"$CAVE_GATEWAY_URL/w/<app>/v1/chat/completions\" \\\n -H \"x-cave-api-key: $CAVE_API_KEY\" \\\n -H \"content-type: application/json\" \\\n -d '{\"model\":\"<model the repo already uses>\",\"max_tokens\":16,\"messages\":[{\"role\":\"user\",\"content\":\"ping\"}]}'\n\n# Anthropic-protocol wiring:\ncurl -sS \"$CAVE_GATEWAY_URL/w/<app>/v1/messages\" \\\n -H \"x-cave-api-key: $CAVE_API_KEY\" \\\n -H \"anthropic-version: 2023-06-01\" \\\n -H \"content-type: application/json\" \\\n -d '{\"model\":\"<model the repo already uses>\",\"max_tokens\":16,\"messages\":[{\"role\":\"user\",\"content\":\"ping\"}]}'\n```\n\n(byok: add `-H \"x-cave-upstream-key: $PROVIDER_KEY\"`.) This is one real,\nbillable provider request — that is the point: real traffic, real measurement.\n\nRead the response. Success = HTTP 200 with a `usage` block. Anything else =\nthe matching failure template below.\n\n## Step 5 — Report\n\nEnd with exactly this shape, values filled from what you actually did and saw:\n\n```\n## Caveman is live in this repo\n\nWired: <n> callsite(s) in <n> file(s)\n - <file> — <one-line what changed>\nApp slug: <app> — spend for this app groups under it\nVerified: HTTP 200 · model <model> · <in> in / <out> out tokens (one real request)\nMode: record — measured only. No model-visible bytes changed, no optimization\nenabled. Verified savings are $0 until you turn an optimizer on and it passes\nits eval gate. That honesty is the product.\n\nSee the dollars: <DASHBOARD>/traces — your request is the top row, priced from\nthe public catalog. <DASHBOARD>/getting-started flips to \"First request received.\"\n\nWant spend split by workflow (e.g. support-reply vs nightly-digest), not just\nby app? Say \"discover workflows\" — I'll fetch <docs origin>/docs/discover-workflows.md\nand label every callsite by the job it does.\n```\n\n## Failure templates (use verbatim, filled in — never soften)\n\n- **Nothing to wire**: \"I found no LLM callsites in this repo (searched SDKs,\n raw provider HTTP, base-URL env vars). If this repo runs a coding agent\n rather than shipping LLM code, use `caveman wrap <agent>` instead — see\n <DASHBOARD>/getting-started.\"\n- **Gateway unreachable**: \"The verification request could not reach GATEWAY\n (<error>). Wiring is in place but unverified — nothing will be measured\n until the gateway is reachable. Check the URL and network, then re-run the\n verification curl above.\"\n- **401 cave_invalid_api_key**: \"The gateway rejected CAVE_API_KEY. Mint a new\n key at <DASHBOARD>/getting-started and update the env file; the wiring\n itself is unchanged.\"\n- **404 cave_route_not_found**: \"The gateway matched no route — usually a\n malformed /w/<app> slug (lowercase [a-z0-9] first, then [a-z0-9._-], max 64)\n or a path that doesn't match the SDK's protocol. Fix the URL and re-verify.\"\n- **Provider error (4xx/5xx via gateway)**: report status + body verbatim; the\n gateway is reachable and auth passed, the upstream call failed — usually a\n provider key or model-name issue in the app itself.\n\nNever report success on any of these. An unverified integration is reported as\nunverified.\n",
12
- "megacave": "---\nname: megacave\ndescription: >\n Caveman in Classical Chinese: 文言文 register, far fewer characters, technical\n terms verbatim. Invoke only with /megacave or /caveman wenyan. Stays on until\n \"stop caveman\" or \"normal mode\".\ndisable-model-invocation: true\n---\n\n# megacave\n\n以文言答。技術之實皆存,唯贅言去之。\n\nMegacave is caveman in Classical Chinese. 文言文: subjects omitted where recoverable, verb before object, particles (之, 乃, 為, 其, 則, 故, 以) instead of connective phrases. Fewer characters on screen. Token savings are small and noisy; never claim them.\n\n## Persistence\n\nEvery response, whole session, until \"stop caveman\" or \"normal mode\". Unsure? Still on. `/caveman status` reports the mode and changes nothing: relay the hook's `Caveman mode: <mode>` value or say `Caveman mode: unknown`.\n\n## Floor\n\nNever cut or translate: code, commands, paths, API names, error strings, in their original script. Negation (不, 非, 勿, 未, 毋). Numbers and units, Arabic numerals. One term per thing. A clause ambiguous in 文言 becomes 白話.\n\n## Rules\n\n### 1. Classical register\n\n文言, not 白話. Verb before object. Subjects omitted where recoverable.\n\nBad: \"你的組件每次渲染都會重新渲染,因為你每次都創建了新的對象引用。請用 useMemo 包起來。\"\nGood: \"每繪新生對象參照,故重繪;以 `useMemo` 包之則免。\"\n\n### 2. Particles carry structure\n\nOne particle, one relation.\n\nBad: \"因為連接池會重複使用已經打開的連接,所以不需要每次請求都新建連接,這樣就省去了握手的開銷。\"\nGood: \"池蓄已開之連,不逐請而新開,省握手之費。\"\n\n### 3. Each fact once\n\nGood: \"新參照則重繪。`useMemo` 包之。\"\n\n### 4. Payload in original script\n\nBad: \"以記憶化鉤子包之。\"\nGood: \"以 `useMemo` 包之。\"\n\n### 5. Tool runs\n\nOne 文言 line in, one out. Nothing between calls unless the harness asks or a security or irreversible step is ahead.\n\n### 6. Never perform\n\nNo \"文言模式啟\", no modern answer plus classical copy. 文言 not shorter than 白話 for a sentence? Use 白話.\n\n## When to break the rules\n\n白話 or the user's language, full sentences, then resume: security warning. Irreversible action, confirm first. Any clause with two readings. User confused. Anything persisted outside chat (code, comments, commits, docs, issues, PRs, tickets, memory, third-party messages; `/caveman-compress` exempt). Harness asks for a status line.\n\n## Pre-send check\n\nIdentifiers verbatim, original script? Negations present? Two readings? 白話. Flavor character? Cut.\n",
13
- "ultracave": "---\nname: ultracave\ndescription: >\n Caveman at maximum compression: fragments, one word when one word is enough,\n each fact once. Invoke only with /ultracave or /caveman ultra. Stays on until\n \"stop caveman\" or \"normal mode\".\ndisable-model-invocation: true\n---\n\n# ultracave\n\nRespond terse like smart caveman. All technical substance stay. Only fluff die. Then cut again.\n\nUltracave is caveman with the grammar stripped. Payload only.\n\n## Persistence\n\nEvery response, whole session, until \"stop caveman\" or \"normal mode\". Unsure? Still on. `/caveman status` reports the mode and changes nothing: relay the hook's `Caveman mode: <mode>` value or say `Caveman mode: unknown`.\n\n## Floor\n\nNever cut: code, commands, paths, API names, error strings (verbatim). not/never/no/only/except. Numbers and units. The user's language. One term per thing. No invented abbreviations, no arrows.\n\n## Rules\n\n### 1. Fragments\n\nDrop articles, copulas, connectives when order stays clear.\n\nBad: \"The component re-renders because an inline object prop creates a new reference each render.\"\nGood: \"Inline object prop, new ref, re-render. `useMemo`.\"\n\n### 2. One word when one word is enough\n\nBad: \"Yes, that should work, though you'll want a null check first.\"\nGood: \"Yes. Null check first.\"\n\n### 3. Each fact once\n\nNo restating, no summary after a list.\n\nGood: \"Pool reuses open DB connections. No per-request handshake.\"\n\n### 4. Cut conjunctions only when order survives\n\nBad: \"Migrate table drop column backup first.\"\nGood: \"Back up first. Then migrate: drops column.\"\n\n### 5. Tool runs\n\nOne line in, one line out. Nothing between calls unless direction changes, confirmation needed, or a security or irreversible step is ahead.\n\n### 6. Never perform\n\nNo prefix, no announcement, no mangled verbs for flavor. Fragment not shorter than the sentence? Use the sentence.\n\n## When to break the rules\n\nPlain prose, then resume: security warning. Irreversible action, confirm first. Any fragment with two readings. User confused. Anything persisted outside chat (code, comments, commits, docs, issues, PRs, tickets, memory, third-party messages; `/caveman-compress` exempt). Harness asks for a status line.\n\n## Pre-send check\n\nTwo readings? Full sentence. Negations present? Payload verbatim? Flavor word? Cut.\n"
12
+ "megacave": "---\nname: megacave\ndescription: >\n Caveman in Classical Chinese: 文言文 register, far fewer characters, technical\n terms verbatim. Invoke only with /megacave or /caveman wenyan. Stays on until\n \"stop caveman\" or \"normal mode\".\ndisable-model-invocation: true\n---\n\n# megacave\n\n以文言答。技術之實皆存,唯贅言去之。\n\nMegacave is caveman in Classical Chinese. 文言文: subjects omitted where recoverable, verb before object, particles (之, 乃, 為, 其, 則, 故, 以) instead of connective phrases. Fewer characters on screen. Token savings are small and noisy; never claim them.\n\n## Persistence\n\nEvery response, whole session, until \"stop caveman\" or \"normal mode\". Unsure? Still on. `/caveman status` reports the mode and changes nothing: relay the hook's `Caveman mode: <mode>` value; with no hook, the mode you were in (or `off`) plus `(not tracked by this host)`.\n\n## Floor\n\nNever cut or translate: code, commands, paths, API names, error strings, in their original script. Negation (不, 非, 勿, 未, 毋). Numbers and units, Arabic numerals. One term per thing. A clause ambiguous in 文言 becomes 白話. Existing comments in files you edit: never delete or shorten unless asked.\n\n## Rules\n\n### 1. Classical register\n\n文言, not 白話. Verb before object. Subjects omitted where recoverable.\n\nBad: \"你的組件每次渲染都會重新渲染,因為你每次都創建了新的對象引用。請用 useMemo 包起來。\"\nGood: \"每繪新生對象參照,故重繪;以 `useMemo` 包之則免。\"\n\n### 2. Particles carry structure\n\nOne particle, one relation.\n\nBad: \"因為連接池會重複使用已經打開的連接,所以不需要每次請求都新建連接,這樣就省去了握手的開銷。\"\nGood: \"池蓄已開之連,不逐請而新開,省握手之費。\"\n\n### 3. Each fact once\n\nCode change: changed lines plus context, not the whole file.\n\nGood: \"新參照則重繪。`useMemo` 包之。\"\n\n### 4. Payload in original script\n\nBad: \"以記憶化鉤子包之。\"\nGood: \"以 `useMemo` 包之。\"\n\n### 5. Tool runs\n\nOne 文言 line in, one out. Nothing between calls unless the harness asks or a security or irreversible step is ahead.\n\n### 6. Never perform\n\nNo \"文言模式啟\", no modern answer plus classical copy. 文言 not shorter than 白話 for a sentence? Use 白話.\n\n## When to break the rules\n\n白話 or the user's language, full sentences, then resume: security warning. Irreversible action, confirm first. Any clause with two readings. User confused. Question to the user, with its options. Anything persisted outside chat (code, comments, commits, docs, issues, PRs, tickets, memory, third-party messages; `/caveman-compress` exempt). Harness asks for a status line.\n\n## Pre-send check\n\nIdentifiers verbatim, original script? Negations present? Two readings? 白話. Flavor character? Cut.\n",
13
+ "ultracave": "---\nname: ultracave\ndescription: >\n Caveman at maximum compression: fragments, one word when one word is enough,\n each fact once. Invoke only with /ultracave or /caveman ultra. Stays on until\n \"stop caveman\" or \"normal mode\".\ndisable-model-invocation: true\n---\n\n# ultracave\n\nRespond terse like smart caveman. All technical substance stay. Only fluff die. Then cut again.\n\nUltracave is caveman with the grammar stripped. Payload only.\n\n## Persistence\n\nEvery response, whole session, until \"stop caveman\" or \"normal mode\". Unsure? Still on. `/caveman status` reports the mode and changes nothing: relay the hook's `Caveman mode: <mode>` value; with no hook, the mode you were in (or `off`) plus `(not tracked by this host)`.\n\n## Floor\n\nNever cut: code, commands, paths, API names, error strings (verbatim). not/never/no/only/except. Numbers and units. The user's language. One term per thing. No invented abbreviations, no arrows. Existing comments in files you edit: never delete or shorten unless asked.\n\n## Rules\n\n### 1. Fragments\n\nDrop articles, copulas, connectives when order stays clear.\n\nBad: \"The component re-renders because an inline object prop creates a new reference each render.\"\nGood: \"Inline object prop, new ref, re-render. `useMemo`.\"\n\n### 2. One word when one word is enough\n\nBad: \"Yes, that should work, though you'll want a null check first.\"\nGood: \"Yes. Null check first.\"\n\n### 3. Each fact once\n\nNo restating, no summary after a list. Code change: changed lines plus context, not the whole file.\n\nGood: \"Pool reuses open DB connections. No per-request handshake.\"\n\n### 4. Cut conjunctions only when order survives\n\nBad: \"Migrate table drop column backup first.\"\nGood: \"Back up first. Then migrate: drops column.\"\n\n### 5. Tool runs\n\nOne line in, one line out. Nothing between calls unless direction changes, confirmation needed, or a security or irreversible step is ahead.\n\n### 6. Never perform\n\nNo prefix, no announcement, no mangled verbs for flavor. Fragment not shorter than the sentence? Use the sentence.\n\n## When to break the rules\n\nPlain prose, then resume: security warning. Irreversible action, confirm first. Any fragment with two readings. User confused. Question to the user, with its options. Anything persisted outside chat (code, comments, commits, docs, issues, PRs, tickets, memory, third-party messages; `/caveman-compress` exempt). Harness asks for a status line.\n\n## Pre-send check\n\nTwo readings? Full sentence. Negations present? Payload verbatim? Flavor word? Cut.\n"
14
14
  };
15
15
  export const AGENT_SKILL_METADATA = [
16
16
  {
@@ -64,10 +64,10 @@ export const PROFILES = [
64
64
  "attribution": {
65
65
  "header": "x-cave-agent"
66
66
  },
67
- "tested_agent_version": "2.1.285",
67
+ "tested_agent_version": "2.1.291",
68
68
  "injection_completeness": "builder-assisted",
69
- "last_verified_at": "2026-09-30",
70
- "verified_by": "local pinned-binary probe (claude 2.1.285, agents/probe-installed.mjs)",
69
+ "last_verified_at": "2026-10-06",
70
+ "verified_by": "local pinned-binary probe (claude 2.1.291 on Node 22.22.2, agents/probe-installed.mjs)",
71
71
  "fallback": "generic-env",
72
72
  "maintainer": null
73
73
  },
@@ -101,10 +101,10 @@ export const PROFILES = [
101
101
  "attribution": {
102
102
  "header": "x-cave-agent"
103
103
  },
104
- "tested_agent_version": "0.158.0",
104
+ "tested_agent_version": "0.160.1",
105
105
  "injection_completeness": "code-only",
106
- "last_verified_at": "2026-09-29",
107
- "verified_by": "local pinned-binary probe (codex 0.158.0, agents/probe-installed.mjs)",
106
+ "last_verified_at": "2026-10-06",
107
+ "verified_by": "local pinned-binary probe (codex 0.160.1 on Node 24.16.0, agents/probe-installed.mjs)",
108
108
  "fallback": "generic-env",
109
109
  "maintainer": null
110
110
  },
@@ -133,10 +133,10 @@ export const PROFILES = [
133
133
  "attribution": {
134
134
  "header": "x-cave-agent"
135
135
  },
136
- "tested_agent_version": "0.61.0",
136
+ "tested_agent_version": "0.62.0",
137
137
  "injection_completeness": "declarative",
138
- "last_verified_at": "2026-09-24",
139
- "verified_by": "local pinned-binary probe (gemini 0.61.0, agents/probe-installed.mjs)",
138
+ "last_verified_at": "2026-10-03",
139
+ "verified_by": "local pinned-binary probe (gemini 0.62.0 on Node 24.16.0, agents/probe-installed.mjs)",
140
140
  "fallback": "generic-env",
141
141
  "maintainer": null
142
142
  },
@@ -168,8 +168,10 @@ export const PROFILES = [
168
168
  "attribution": {
169
169
  "header": "x-cave-agent"
170
170
  },
171
- "tested_agent_version": "0.19.1",
171
+ "tested_agent_version": "0.21.5",
172
172
  "injection_completeness": "builder-assisted",
173
+ "last_verified_at": "2026-10-06",
174
+ "verified_by": "local pinned-binary probe (hermes 0.21.5 = release v2026.9.24 at f97608f1, editable install on Python 3.12, agents/probe-installed.mjs)",
173
175
  "fallback": "generic-env",
174
176
  "maintainer": null
175
177
  },
@@ -184,7 +186,7 @@ export const PROFILES = [
184
186
  "kilocode"
185
187
  ],
186
188
  "args": [],
187
- "install": "npm install -g @kilocode/cli@7.8.1",
189
+ "install": "npm install -g @kilocode/cli@7.8.3",
188
190
  "wire_protocol": "openai-chat",
189
191
  "injection": {
190
192
  "method": "config-env-content",
@@ -270,10 +272,10 @@ export const PROFILES = [
270
272
  "attribution": {
271
273
  "header": "X-Cave-Agent"
272
274
  },
273
- "tested_agent_version": "7.8.1",
275
+ "tested_agent_version": "7.8.3",
274
276
  "injection_completeness": "declarative",
275
- "last_verified_at": "2026-09-26",
276
- "verified_by": "local pinned-binary probe (kilo 7.8.1, agents/probe-installed.mjs)",
277
+ "last_verified_at": "2026-10-03",
278
+ "verified_by": "local pinned-binary probe (kilo 7.8.3 on Node 24.16.0, agents/probe-installed.mjs)",
277
279
  "fallback": "generic-env",
278
280
  "maintainer": null
279
281
  },
@@ -331,10 +333,10 @@ export const PROFILES = [
331
333
  "attribution": {
332
334
  "header": "x-cave-agent"
333
335
  },
334
- "tested_agent_version": "2026.9.5",
336
+ "tested_agent_version": "2026.9.8",
335
337
  "injection_completeness": "builder-assisted",
336
- "last_verified_at": "2026-09-21",
337
- "verified_by": "local pinned-binary probe (openclaw 2026.9.5 on Node 24.16.0, agents/probe-installed.mjs)",
338
+ "last_verified_at": "2026-10-03",
339
+ "verified_by": "local pinned-binary probe (openclaw 2026.9.8 on Node 24.16.0, agents/probe-installed.mjs)",
338
340
  "fallback": "generic-env",
339
341
  "maintainer": null
340
342
  },
@@ -372,6 +374,14 @@ export const PROFILES = [
372
374
  "X-Cave-Agent": "opencode"
373
375
  }
374
376
  }
377
+ },
378
+ "opencode-go": {
379
+ "options": {
380
+ "baseURL": "{{cave_base_url}}/compat/opencode-go/v1",
381
+ "headers": {
382
+ "X-Cave-Agent": "opencode"
383
+ }
384
+ }
375
385
  }
376
386
  }
377
387
  },
@@ -417,10 +427,10 @@ export const PROFILES = [
417
427
  "attribution": {
418
428
  "header": "X-Cave-Agent"
419
429
  },
420
- "tested_agent_version": "1.18.33",
430
+ "tested_agent_version": "1.18.34",
421
431
  "injection_completeness": "declarative",
422
- "last_verified_at": "2026-09-28",
423
- "verified_by": "local pinned-binary probe (opencode 1.18.33, agents/probe-installed.mjs)",
432
+ "last_verified_at": "2026-10-03",
433
+ "verified_by": "local pinned-binary probe (opencode 1.18.34 on Node 24.16.0, agents/probe-installed.mjs)",
424
434
  "fallback": "generic-env",
425
435
  "maintainer": null
426
436
  },
@@ -445,10 +455,10 @@ export const PROFILES = [
445
455
  "command_hook": {
446
456
  "method": "pi-extension"
447
457
  },
448
- "tested_agent_version": "1.0.0",
458
+ "tested_agent_version": "1.0.4",
449
459
  "injection_completeness": "builder-assisted",
450
- "last_verified_at": "2026-10-02",
451
- "verified_by": "local pinned-binary probe (pi 1.0.0, agents/probe-installed.mjs); packages/pi-extension suite against pi-coding-agent 1.0.0",
460
+ "last_verified_at": "2026-10-06",
461
+ "verified_by": "local pinned-binary probe (pi 1.0.4, agents/probe-installed.mjs); packages/pi-extension suite against pi-coding-agent 1.0.4",
452
462
  "fallback": "none",
453
463
  "maintainer": null
454
464
  },
@@ -464,7 +474,7 @@ export const PROFILES = [
464
474
  "args": [
465
475
  "--extensions=none"
466
476
  ],
467
- "install": "npm i -g @qwen-code/qwen-code@0.24.6",
477
+ "install": "npm i -g @qwen-code/qwen-code@0.25.0",
468
478
  "wire_protocol": "openai-chat",
469
479
  "injection": {
470
480
  "method": "config-file",
@@ -710,10 +720,10 @@ export const PROFILES = [
710
720
  "attribution": {
711
721
  "header": "X-Cave-Agent"
712
722
  },
713
- "tested_agent_version": "0.24.6",
723
+ "tested_agent_version": "0.25.0",
714
724
  "injection_completeness": "declarative",
715
- "last_verified_at": "2026-09-26",
716
- "verified_by": "local pinned-binary route probe (@qwen-code/qwen-code 0.24.6)",
725
+ "last_verified_at": "2026-10-06",
726
+ "verified_by": "local pinned-binary probe (@qwen-code/qwen-code 0.25.0 on Node 24.16.0, agents/probe-installed.mjs) plus route check: the real binary, launched with the CLI buildWrapEnv overlay, sent POST /w/qwen/v1/chat/completions (X-Cave-Agent: qwen, model gpt-5.5) to a loopback recorder",
717
727
  "fallback": "generic-env",
718
728
  "maintainer": null
719
729
  }
@@ -1,4 +1,4 @@
1
1
  // Generated by scripts/gen-binaries.mjs. Do not edit.
2
- export const BINARY_RELEASE = "bin-v2.0.2";
2
+ export const BINARY_RELEASE = "bin-v2.1.0";
3
3
  export const BINARY_RELEASE_BASE_DEFAULT = "https://github.com/JuliusBrussee/caveman/releases/download";
4
4
  export const BINARY_SIGNING_PUBKEY = "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEKR5zq0dz0mTUtkiX0b6jqtyG3uQV\n89PGD2n9UBV1ikbhu0f1c+vHtcN9mk6wKzyBLdEPudI/Jnvci+8OAen/vw==\n-----END PUBLIC KEY-----\n";
@@ -37,6 +37,14 @@ function compatTarget(base, path) {
37
37
  while (overlap > 0 && left.slice(-overlap).join("/") !== right.slice(0, overlap).join("/")) overlap--;
38
38
  return base.origin + "/" + [...left, ...right.slice(overlap)].join("/");
39
39
  }
40
+ function verifiedChatGPTSubscriptionRoute(gateway, api, provider, originalBaseUrl, published) {
41
+ if (api !== "openai-codex-responses" || provider !== "openai-codex") return void 0;
42
+ const original = endpoint(originalBaseUrl);
43
+ const upstream = endpoint(published?.provider_upstreams?.["openai-codex"]);
44
+ if (!original || !upstream || !endpoint(gateway)) return void 0;
45
+ if (append(upstream, "/codex/responses") !== append(original, "/codex/responses")) return void 0;
46
+ return trimTrailingSlashes(gateway);
47
+ }
40
48
  function verifiedProviderRoute(gateway, api, provider, originalBaseUrl, published) {
41
49
  const original = endpoint(originalBaseUrl);
42
50
  if (!original || !endpoint(gateway)) return void 0;
@@ -122,11 +130,36 @@ import { dirname, extname, isAbsolute, join, resolve } from "node:path";
122
130
  function parseWindowsNodeShim(source) {
123
131
  for (const line of source.split(/\r?\n/)) {
124
132
  if (!/(?:\bnode(?:\.exe)?\b|_prog)/i.test(line) || !/%\*/.test(line)) continue;
125
- const match = line.match(/"%(?:dp0%|~dp0)\\([^"\r\n]+\.(?:cjs|mjs|js))"\s+%\*/i) ?? line.match(/"([A-Za-z]:[\\/][^"\r\n]+\.(?:cjs|mjs|js))"\s+%\*/i);
133
+ const match = line.match(/"%(?:dp0%|~dp0)\\?([^"\r\n]+\.(?:cjs|mjs|js))"\s+%\*/i) ?? line.match(/"([A-Za-z]:[\\/][^"\r\n]+\.(?:cjs|mjs|js))"\s+%\*/i);
126
134
  if (match) return match[1];
127
135
  }
128
136
  return null;
129
137
  }
138
+ function parseWindowsNestedShim(source) {
139
+ const match = source.match(/^(?:@echo[ \t]+off[ \t]*\r?\n)?[ \t]*"%~dp0\\?([\w .@+\-\\/]+\.(?:cmd|bat))"[ \t]+%\*[ \t]*(?:\r?\n)?$/i);
140
+ return match?.[1] ?? null;
141
+ }
142
+ function resolveWindowsNodeShim(executable, depth = 0, seen = /* @__PURE__ */ new Set()) {
143
+ if (depth > 4) throw new Error("Windows command shim nesting too deep");
144
+ const normalized = resolve(executable);
145
+ if (seen.has(normalized.toLowerCase())) throw new Error("Windows command shim cycle");
146
+ seen.add(normalized.toLowerCase());
147
+ const stat = statSync(normalized);
148
+ if (!stat.isFile() || stat.size > 256 * 1024) {
149
+ throw new Error(`cannot safely launch Windows command shim: ${normalized}`);
150
+ }
151
+ const source = readFileSync(normalized, "utf8");
152
+ const nested = parseWindowsNestedShim(source);
153
+ const forwardsToBatch = /"[^"\r\n]+\.(?:cmd|bat)"[ \t]+%\*/i.test(source);
154
+ const jsTarget = forwardsToBatch ? null : parseWindowsNodeShim(source);
155
+ const child = jsTarget ?? nested;
156
+ if (!child) {
157
+ throw new Error(`cannot safely launch non-Node Windows command shim: ${normalized}; install a native .exe`);
158
+ }
159
+ const target = /^[A-Za-z]:[\\/]/.test(child) ? child : resolve(dirname(normalized), ...child.split(/[\\/]+/));
160
+ if (!existsSync(target) || !statSync(target).isFile()) throw new Error(`Windows command shim target is missing: ${target}`);
161
+ return jsTarget ? target : resolveWindowsNodeShim(target, depth + 1, seen);
162
+ }
130
163
  function envValue(env, name) {
131
164
  const key = Object.keys(env).find((candidate) => candidate.toLowerCase() === name.toLowerCase());
132
165
  return key === void 0 ? void 0 : env[key];
@@ -151,18 +184,7 @@ function portableInvocation(command, args, platform = process.platform, env = pr
151
184
  if (platform !== "win32") return { command, args: [...args] };
152
185
  const executable = resolveWindowsCommand(command, env) ?? command;
153
186
  if (!/\.(?:cmd|bat)$/i.test(executable)) return { command: executable, args: [...args] };
154
- const stat = statSync(executable);
155
- if (!stat.isFile() || stat.size > 256 * 1024) {
156
- throw new Error(`cannot safely launch Windows command shim: ${executable}`);
157
- }
158
- const shimScript = parseWindowsNodeShim(readFileSync(executable, "utf8"));
159
- if (!shimScript) {
160
- throw new Error(`cannot safely launch non-Node Windows command shim: ${executable}; install a native .exe`);
161
- }
162
- const script = /^[A-Za-z]:[\\/]/.test(shimScript) ? shimScript : resolve(dirname(executable), ...shimScript.split(/[\\/]+/));
163
- if (!statSync(script).isFile()) {
164
- throw new Error(`Windows command shim target is missing: ${script}`);
165
- }
187
+ const script = resolveWindowsNodeShim(executable);
166
188
  return { command: process.execPath, args: [script, ...args] };
167
189
  }
168
190
 
@@ -220,6 +242,9 @@ var ROUTES_BY_API = {
220
242
  "google-generative-ai": "/w/pi/v1beta"
221
243
  };
222
244
  var ROUTES_BY_PROVIDER_API = {
245
+ "openai-codex": {
246
+ "openai-codex-responses": "/w/pi"
247
+ },
223
248
  "opencode-go": {
224
249
  "anthropic-messages": "/w/pi/compat/opencode-go",
225
250
  "openai-completions": "/w/pi/compat/opencode-go/v1",
@@ -230,6 +255,7 @@ var UPSTREAM_HOSTS_BY_PROVIDER = {
230
255
  anthropic: "api.anthropic.com",
231
256
  openai: "api.openai.com",
232
257
  google: "generativelanguage.googleapis.com",
258
+ "openai-codex": "chatgpt.com",
233
259
  "opencode-go": "opencode.ai"
234
260
  };
235
261
  function upstreamHostFor(provider) {
@@ -251,13 +277,8 @@ function compatUpstreamFor(provider, compatUpstreams) {
251
277
  }
252
278
  function routeForApi(gateway, api, provider, originalBaseUrl, compatUpstreams, providerUpstreams) {
253
279
  if (originalBaseUrl !== void 0) {
254
- return verifiedProviderRoute(
255
- joinUrl(gateway, "/w/pi"),
256
- api,
257
- provider ?? "",
258
- originalBaseUrl,
259
- { compat_upstreams: compatUpstreams, provider_upstreams: providerUpstreams }
260
- );
280
+ const published = { compat_upstreams: compatUpstreams, provider_upstreams: providerUpstreams };
281
+ return verifiedChatGPTSubscriptionRoute(joinUrl(gateway, "/w/pi"), api, provider ?? "", originalBaseUrl, published) ?? verifiedProviderRoute(joinUrl(gateway, "/w/pi"), api, provider ?? "", originalBaseUrl, published);
261
282
  }
262
283
  const table = (provider ? ROUTES_BY_PROVIDER_API[provider] : void 0) ?? ROUTES_BY_API;
263
284
  if (provider && !UPSTREAM_HOSTS_BY_PROVIDER[provider]) return void 0;
@@ -512,11 +533,15 @@ var ProviderRouter = class {
512
533
  const compatibilityIssue = model.api === "openai-completions" && original.includes("api.openai.com") ? "Pi cannot preserve this OpenAI Chat endpoint's prompt cache keys through routing" : void 0;
513
534
  let headerIssue;
514
535
  let oauth = true;
536
+ let authKnown = false;
515
537
  try {
516
538
  oauth = ctx.modelRegistry.isUsingOAuth(model);
539
+ authKnown = true;
517
540
  } catch {
518
541
  }
519
- if (!oauth && route && !compatibilityIssue) {
542
+ const chatGPTSubscriptionModel = model.provider === "openai-codex" && model.api === "openai-codex-responses";
543
+ const authIssue = !authKnown ? "authentication type could not be verified" : oauth && !chatGPTSubscriptionModel ? "OAuth/subscription credentials are not routed" : !oauth && chatGPTSubscriptionModel && route ? "ChatGPT subscription route requires OAuth" : void 0;
544
+ if (!oauth && route && !compatibilityIssue && !chatGPTSubscriptionModel) {
520
545
  try {
521
546
  const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
522
547
  if (!auth.ok) throw new Error("request auth unavailable");
@@ -547,13 +572,13 @@ var ProviderRouter = class {
547
572
  }
548
573
  if (!this.gateOpen || this.gateGeneration !== gateGeneration || ctx.model !== model) return;
549
574
  }
550
- if (!route || oauth || compatibilityIssue || headerIssue) {
575
+ if (!route || authIssue || compatibilityIssue || headerIssue) {
551
576
  if (!await this.restoreCurrentModel(ctx)) return;
552
577
  if (!this.warnedModels.has(key)) {
553
578
  this.warnedModels.add(key);
554
579
  const mount = compatUpstreamFor(model.provider, this.compatUpstreams);
555
580
  const expected = mount !== void 0 ? hostOf(mount) : upstreamHostFor(model.provider);
556
- const reason = oauth ? "OAuth/subscription credentials are not routed" : compatibilityIssue ?? headerIssue ?? (expected === void 0 ? `no compat mount named "${model.provider}" in the local proxy; add compat.${model.provider}.base_url to caveman.yaml to route it` : hostOf(original) !== expected ? `provider endpoint ${hostOf(original) ?? original} is not ${expected}` : `provider endpoint path or API "${model.provider}/${model.api}" is not verified by the running proxy`);
581
+ const reason = authIssue ?? compatibilityIssue ?? headerIssue ?? (expected === void 0 ? `no compat mount named "${model.provider}" in the local proxy; add compat.${model.provider}.base_url to caveman.yaml to route it` : hostOf(original) !== expected ? `provider endpoint ${hostOf(original) ?? original} is not ${expected}` : `provider endpoint path or API "${model.provider}/${model.api}" is not verified by the running proxy`);
557
582
  this.notify(boundedString(`Caveman: pass-through for ${key} (${reason}); no compression`, MAX_MESSAGE_BYTES), "warning");
558
583
  }
559
584
  return;
@@ -770,7 +795,7 @@ var RecoveryClient = class {
770
795
  await this.call("initialize", {
771
796
  protocolVersion: "2024-11-05",
772
797
  capabilities: {},
773
- clientInfo: { name: "caveman-pi-extension", version: "0.2.0" }
798
+ clientInfo: { name: "caveman-pi-extension", version: "0.3.0" }
774
799
  }, void 0, INIT_TIMEOUT_MS);
775
800
  this.notify("notifications/initialized");
776
801
  if (this.disposed) {
package/dist/index.js CHANGED
@@ -3833,6 +3833,13 @@ export const OFF_STATES = {
3833
3833
  zdr: {
3834
3834
  line: "ZDR org — wrap telemetry excluded by your data policy; local numbers only",
3835
3835
  },
3836
+ // The proxy's cache tripwire: the client re-sent bytes the provider had
3837
+ // cached and caveman forwarded them differently. Never expected; a bug.
3838
+ cavemanCacheBust: (count) => ({
3839
+ id: "cache-bust",
3840
+ line: `caveman changed bytes the provider had already cached on ${count} request${count === 1 ? "" : "s"} today — those turns paid to re-cache their prompt; this is a caveman bug`,
3841
+ fix: "report it with ~/.caveman/proxy.log at github.com/JuliusBrussee/caveman/issues",
3842
+ }),
3836
3843
  };
3837
3844
  const OFF_STATE_PRECEDENCE = [
3838
3845
  "binary-missing",
@@ -3845,6 +3852,7 @@ const OFF_STATE_PRECEDENCE = [
3845
3852
  "mem-missing",
3846
3853
  "zdr",
3847
3854
  "stale-binary",
3855
+ "cache-bust",
3848
3856
  ];
3849
3857
  function fixedOffState(id, item) {
3850
3858
  return { id, line: item.line, ...(item.fix ? { fix: item.fix } : {}) };
@@ -5776,10 +5784,10 @@ function spawnLocalProxyProcess(mode, mcpRecovery, toon, pixelModels, pixelDensi
5776
5784
  CAVEMAN_MODE: mode,
5777
5785
  CAVEMAN_LISTEN: `${host}:${port}`,
5778
5786
  // The recovery half of the proxy's subscription gate, and the switch that lets
5779
- // it compress streams at all. Stamped EXPLICITLY in both directions: wrap
5780
- // derives it from the agent's OWN MCP install (and
5781
- // forces it off for codex-subscription and observe-only runs), so an exported
5782
- // CAVEMAN_RECOVERY=mcp must not survive that answer — the proxy would elide
5787
+ // it compress streams at all. Stamped EXPLICITLY in both directions: wrap,
5788
+ // `enable`, the agent shortcut and the native hook derive it from the agent's
5789
+ // OWN MCP install (codex-subscription included; observe-only runs force it
5790
+ // off), so an exported CAVEMAN_RECOVERY=mcp must not survive that answer — the proxy would elide
5783
5791
  // spans behind markers this agent has no caveman_retrieve tool to expand, while
5784
5792
  // the CLI printed that compression was off. (honesty rule: no-placeholder)
5785
5793
  CAVEMAN_RECOVERY: mcpRecovery ? "mcp" : "",
@@ -7699,6 +7707,43 @@ export default {
7699
7707
  };
7700
7708
  `;
7701
7709
  }
7710
+ // opencode-go serves OpenAI and Anthropic wire shapes from opencode.ai, so it
7711
+ // rides the proxy's built-in /compat/opencode-go mount (same one Pi uses), which
7712
+ // keeps the caller's credential and forwards OpenCode's session headers (#1090).
7713
+ function opencodeNativeRoutes(gw) {
7714
+ const base = appendUrlPath(gw, "/w/opencode");
7715
+ return {
7716
+ openai: appendUrlPath(base, "/openai/v1"),
7717
+ anthropic: appendUrlPath(base, "/anthropic/v1"),
7718
+ "opencode-go": appendUrlPath(base, "/compat/opencode-go/v1"),
7719
+ };
7720
+ }
7721
+ // Only the journaled providers reach the proxy. Anything else (GitHub Copilot,
7722
+ // Zen) goes direct while the install reads healthy (#1190), so name it. Global
7723
+ // config only, the same file enable edits; a project opencode.json can still
7724
+ // pick another model.
7725
+ function opencodeUnroutedActiveProvider(routed) {
7726
+ for (const name of ["opencode.jsonc", "opencode.json"]) {
7727
+ try {
7728
+ const model = parseJsonc(readFileSync(join(homedir(), ".config", "opencode", name), "utf8"))?.model;
7729
+ if (typeof model === "string" && model.includes("/")) {
7730
+ const provider = model.slice(0, model.indexOf("/"));
7731
+ return routed.includes(provider) ? null : provider;
7732
+ }
7733
+ }
7734
+ catch { /* missing or unreadable: try the next source */ }
7735
+ }
7736
+ // No model pinned: OpenCode picks among signed-in providers, so only a
7737
+ // sign-in set with no routed provider at all is a sure miss.
7738
+ try {
7739
+ const dataRoot = process.env.XDG_DATA_HOME || join(homedir(), ".local", "share");
7740
+ const signedIn = Object.keys(JSON.parse(readFileSync(join(dataRoot, "opencode", "auth.json"), "utf8")) ?? {});
7741
+ return signedIn.length > 0 && !signedIn.some((id) => routed.includes(id)) ? signedIn[0] : null;
7742
+ }
7743
+ catch {
7744
+ return null;
7745
+ }
7746
+ }
7702
7747
  function opencodeNativeMutations(gw, mcpBinary) {
7703
7748
  const configPath = join(homedir(), ".config", "opencode", "opencode.json");
7704
7749
  const before = fileBytes(configPath);
@@ -7711,8 +7756,7 @@ function opencodeNativeMutations(gw, mcpBinary) {
7711
7756
  }
7712
7757
  const providers = root.provider && typeof root.provider === "object" && !Array.isArray(root.provider) ? root.provider : {};
7713
7758
  const previousRoutes = {};
7714
- const base = appendUrlPath(gw, "/w/opencode");
7715
- const routes = { openai: appendUrlPath(base, "/openai/v1"), anthropic: appendUrlPath(base, "/anthropic/v1") };
7759
+ const routes = opencodeNativeRoutes(gw);
7716
7760
  for (const [providerID, route] of Object.entries(routes)) {
7717
7761
  const provider = providers[providerID] && typeof providers[providerID] === "object" && !Array.isArray(providers[providerID]) ? providers[providerID] : {};
7718
7762
  const options = provider.options && typeof provider.options === "object" && !Array.isArray(provider.options) ? provider.options : {};
@@ -8391,6 +8435,8 @@ function applyNativeMutations(agent, profile, mutations) {
8391
8435
  atomicWriteFile(mutation.file, mutation.after);
8392
8436
  written.push(mutation);
8393
8437
  }
8438
+ if (agent === "claude")
8439
+ rememberClaudeProfile();
8394
8440
  atomicWriteFile(nativeJournalPath(agent), Buffer.from(JSON.stringify(journal, null, 2) + "\n"));
8395
8441
  unlinkSync(nativePendingJournalPath(agent));
8396
8442
  return journal;
@@ -8551,6 +8597,69 @@ function nativeMutationsFor(agent, gw, mcpBinary) {
8551
8597
  ? piNativeMutations()
8552
8598
  : aiderNativeMutations(gw);
8553
8599
  }
8600
+ // Voice skills (`output` suite) ride along with a Claude/Codex native install so
8601
+ // `/caveman` exists after `caveman <agent>`. They are NOT native-journal
8602
+ // operations: those feed `nativeIntegrationStatus`, where an edited or deleted
8603
+ // file reads `degraded` and blocks enable, and `disable` restores them away. A
8604
+ // skill is the user's once written: `disable` turns off routing and hooks and
8605
+ // leaves it. The sidecar only marks that the install already ran.
8606
+ function nativeVoiceSkillsRecordPath(agent) {
8607
+ return join(cavemanHome(), "integrations", `${agent}.voice-skills.json`);
8608
+ }
8609
+ // Fail-open and once per install: an existing record means this already ran, so
8610
+ // a skill the user deleted afterwards is not written back.
8611
+ function installNativeVoiceSkills(agent) {
8612
+ if (agent !== "claude" && agent !== "codex")
8613
+ return;
8614
+ try {
8615
+ const record = nativeVoiceSkillsRecordPath(agent);
8616
+ if (existsSync(record))
8617
+ return;
8618
+ const root = join(agent === "claude" ? claudeConfigDir() : codexHomeDir(), "skills");
8619
+ const files = [];
8620
+ let failure;
8621
+ try {
8622
+ for (const name of AGENT_SKILL_SUITES.output ?? []) {
8623
+ const file = join(root, name, "SKILL.md");
8624
+ // The Skills CLI puts global Codex skills in ~/.agents/skills; a copy
8625
+ // there already answers `/caveman`, so a second one is only a duplicate.
8626
+ if (agent === "codex" && existsSync(join(homedir(), ".agents", "skills", name, "SKILL.md")))
8627
+ continue;
8628
+ const body = Buffer.from(SKILLS[name]);
8629
+ mkdirSync(dirname(file), { recursive: true });
8630
+ // `wx` never clobbers: an existing SKILL.md (any content, any link) stays
8631
+ // the user's and is not recorded as ours.
8632
+ try {
8633
+ writeFileSync(file, body, { flag: "wx" });
8634
+ }
8635
+ catch (error) {
8636
+ if (error.code === "EEXIST")
8637
+ continue;
8638
+ // A half-written file would read as the user's on every later run.
8639
+ try {
8640
+ unlinkSync(file);
8641
+ }
8642
+ catch { /* nothing landed */ }
8643
+ throw error;
8644
+ }
8645
+ files.push(file);
8646
+ }
8647
+ }
8648
+ catch (error) {
8649
+ failure = error;
8650
+ }
8651
+ // A total failure leaves no record and is retried by the next enable.
8652
+ if (files.length > 0 || !failure)
8653
+ atomicWriteFile(record, Buffer.from(JSON.stringify({ files }, null, 2) + "\n"));
8654
+ if (failure)
8655
+ throw failure;
8656
+ if (files.length > 0)
8657
+ process.stderr.write(` voice skills: ${files.join(", ")}\n`);
8658
+ }
8659
+ catch (error) {
8660
+ process.stderr.write(dim(`→ voice skills not installed: ${error.message}\n`));
8661
+ }
8662
+ }
8554
8663
  function enableNative(argv) {
8555
8664
  const detected = argv.includes("--detected");
8556
8665
  const target = argv.find((arg) => !arg.startsWith("--"));
@@ -8575,8 +8684,10 @@ function enableNative(argv) {
8575
8684
  nativeProxyBinaryRequired(gw);
8576
8685
  const existing = nativeIntegrationStatus(agent);
8577
8686
  if (existing.installed) {
8578
- if (existing.state === "installed")
8687
+ if (existing.state === "installed") {
8688
+ installNativeVoiceSkills(agent);
8579
8689
  return "already";
8690
+ }
8580
8691
  // `--fix` on purpose: bare `caveman doctor <agent>` prints JSON that says
8581
8692
  // `degraded` and nothing that says how to leave that state, so pointing
8582
8693
  // at it alone dead-ends the user who followed this line here (#1049).
@@ -8601,6 +8712,7 @@ function enableNative(argv) {
8601
8712
  ? ` lifecycle/Core: ${nativeHookCommand(agent)}; command-output rewrite unavailable in Codex\n`
8602
8713
  : ` lifecycle/Core/tool rewrite: ${nativeHookCommand(agent)}${agent === "hermes" ? " via native plugin" : ` + ${cavemanBinForHook()} shrink-hook`}\n`);
8603
8714
  applyNativeMutations(agent, profile, mutations);
8715
+ installNativeVoiceSkills(agent);
8604
8716
  return "enabled";
8605
8717
  });
8606
8718
  // Outside the lock, and on BOTH outcomes. The native SessionStart hook
@@ -8812,7 +8924,7 @@ function restoreNativeOperation(operation) {
8812
8924
  const providers = root.provider && typeof root.provider === "object" && !Array.isArray(root.provider) ? root.provider : {};
8813
8925
  const routes = operation.owned?.routes && typeof operation.owned.routes === "object" && !Array.isArray(operation.owned.routes) ? operation.owned.routes : {};
8814
8926
  const previousRoutes = operation.owned?.previous_routes && typeof operation.owned.previous_routes === "object" && !Array.isArray(operation.owned.previous_routes) ? operation.owned.previous_routes : {};
8815
- for (const providerID of ["openai", "anthropic"]) {
8927
+ for (const providerID of Object.keys(routes)) {
8816
8928
  const provider = providers[providerID] && typeof providers[providerID] === "object" && !Array.isArray(providers[providerID]) ? providers[providerID] : {};
8817
8929
  const options = provider.options && typeof provider.options === "object" && !Array.isArray(provider.options) ? provider.options : {};
8818
8930
  if (options.baseURL !== undefined && options.baseURL !== routes[providerID]) {
@@ -8917,15 +9029,170 @@ function writeNativeRestoration(file, bytes) {
8917
9029
  throw error;
8918
9030
  }
8919
9031
  }
8920
- function restoreNativeJournalFiles(journal) {
9032
+ function claudeProfileRegistryPath() {
9033
+ return join(cavemanHome(), "integrations", "claude-profiles.json");
9034
+ }
9035
+ function rememberedClaudeProfiles() {
9036
+ const bytes = fileBytes(claudeProfileRegistryPath());
9037
+ if (!bytes)
9038
+ return [];
9039
+ const roots = JSON.parse(bytes.toString("utf8"));
9040
+ if (!Array.isArray(roots) || roots.some((root) => typeof root !== "string" || !isAbsolute(root))) {
9041
+ throw new Error("Claude profile registry is invalid; refusing incomplete disable");
9042
+ }
9043
+ return roots;
9044
+ }
9045
+ function rememberClaudeProfile() {
9046
+ const roots = new Set(rememberedClaudeProfiles());
9047
+ roots.add(claudeConfigDir());
9048
+ atomicWriteFile(claudeProfileRegistryPath(), Buffer.from(JSON.stringify([...roots].sort(), null, 2) + "\n"));
9049
+ }
9050
+ function nativeRealPath(file) {
9051
+ try {
9052
+ return realpathSync(file);
9053
+ }
9054
+ catch (error) {
9055
+ if (error.code !== "ENOENT")
9056
+ throw error;
9057
+ return resolve(file);
9058
+ }
9059
+ }
9060
+ function claudeProfileFiles(journal) {
9061
+ const roots = new Set([join(homedir(), ".claude"), claudeConfigDir(), ...rememberedClaudeProfiles()]);
9062
+ for (const entry of readdirSync(homedir(), { withFileTypes: true })) {
9063
+ if (/^\.claude[-_].+/.test(entry.name) && (entry.isDirectory() || entry.isSymbolicLink())) {
9064
+ roots.add(join(homedir(), entry.name));
9065
+ }
9066
+ }
9067
+ for (const operation of journal?.operations ?? []) {
9068
+ if (operation.kind === "claude-settings")
9069
+ roots.add(dirname(operation.file));
9070
+ }
9071
+ const files = new Set([nativeRealPath(join(homedir(), ".claude.json"))]);
9072
+ for (const root of roots) {
9073
+ for (const name of ["settings.json", "settings.local.json", ".claude.json", ".mcp.json"]) {
9074
+ files.add(nativeRealPath(join(root, name)));
9075
+ }
9076
+ }
9077
+ return [...files].sort();
9078
+ }
9079
+ function isClaudeRuntimeHook(command) {
9080
+ if (typeof command !== "string")
9081
+ return false;
9082
+ const identity = managedHookIdentity(command);
9083
+ return identity === "native-hook:claude" || identity === "shrink-hook" || identity === "mem:recall-hook";
9084
+ }
9085
+ function isCavemanClaudeRoute(value, hasNativeHooks) {
9086
+ if (typeof value !== "string")
9087
+ return false;
9088
+ try {
9089
+ const url = new URL(value);
9090
+ if (!["http:", "https:"].includes(url.protocol) || !/^\/w\/claude\/?$/.test(url.pathname))
9091
+ return false;
9092
+ return hasNativeHooks || ["localhost", "127.0.0.1", "[::1]", "gateway.caveman.so", "gw.caveman.so", "api.caveman.so"].includes(url.hostname)
9093
+ || url.origin === new URL(gatewayURL()).origin;
9094
+ }
9095
+ catch {
9096
+ return false;
9097
+ }
9098
+ }
9099
+ // Journals restore known originals. Discovery also reaches copied profiles and
9100
+ // orphaned installs whose journal lived in a deleted test or alternate home.
9101
+ // Only recognizable Caveman runtime entries are removed without a journal.
9102
+ function cleanClaudeProfile(root) {
9103
+ let changed = false;
9104
+ let hasNativeHooks = false;
9105
+ const hooks = root.hooks;
9106
+ if (hooks && typeof hooks === "object" && !Array.isArray(hooks)) {
9107
+ for (const [event, groups] of Object.entries(hooks)) {
9108
+ if (!Array.isArray(groups))
9109
+ continue;
9110
+ const kept = groups.filter((group) => {
9111
+ if (!group || typeof group !== "object" || !Array.isArray(group.hooks))
9112
+ return true;
9113
+ const remaining = group.hooks.filter((hook) => {
9114
+ if (!hook || !isClaudeRuntimeHook(hook.command))
9115
+ return true;
9116
+ if (managedHookIdentity(hook.command) === "native-hook:claude")
9117
+ hasNativeHooks = true;
9118
+ changed = true;
9119
+ return false;
9120
+ });
9121
+ if (remaining.length === group.hooks.length)
9122
+ return true;
9123
+ group.hooks = remaining;
9124
+ return remaining.length > 0;
9125
+ });
9126
+ if (kept.length > 0)
9127
+ hooks[event] = kept;
9128
+ else if (groups.length > 0)
9129
+ delete hooks[event];
9130
+ }
9131
+ if (changed && Object.keys(hooks).length === 0)
9132
+ delete root.hooks;
9133
+ }
9134
+ const env = root.env;
9135
+ if (env && typeof env === "object" && !Array.isArray(env)) {
9136
+ const values = env;
9137
+ if (isCavemanClaudeRoute(values.ANTHROPIC_BASE_URL, hasNativeHooks)) {
9138
+ delete values.ANTHROPIC_BASE_URL;
9139
+ if (values[CLAUDE_ASSUME_FIRST_PARTY_ENV] === "1")
9140
+ delete values[CLAUDE_ASSUME_FIRST_PARTY_ENV];
9141
+ for (const key of ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN"]) {
9142
+ if (typeof values[key] === "string" && /^cave_(?:live|test)_/.test(values[key]))
9143
+ delete values[key];
9144
+ }
9145
+ if (Object.keys(values).length === 0)
9146
+ delete root.env;
9147
+ changed = true;
9148
+ }
9149
+ }
9150
+ const servers = root.mcpServers;
9151
+ if (servers && typeof servers === "object" && !Array.isArray(servers)) {
9152
+ const entries = servers;
9153
+ const server = entries.caveman;
9154
+ if (server && typeof server.command === "string" && hookCommandBasename(server.command) === "caveman-mcp") {
9155
+ delete entries.caveman;
9156
+ if (Object.keys(entries).length === 0)
9157
+ delete root.mcpServers;
9158
+ changed = true;
9159
+ }
9160
+ }
9161
+ return changed;
9162
+ }
9163
+ function restoreNativeJournalFiles(journal, allClaudeProfiles = false) {
8921
9164
  // Resolve every merge/conflict before first write. A conflict therefore leaves
8922
9165
  // all host files and the journal byte-identical.
8923
- const restored = journal.operations.map((operation) => ({ operation, bytes: restoreNativeOperation(operation) }));
8924
- const current = journal.operations.map((operation) => ({ file: operation.file, bytes: fileBytes(operation.file) }));
9166
+ const restored = new Map((journal?.operations ?? []).map((operation) => [nativeRealPath(operation.file), restoreNativeOperation(operation)]));
9167
+ if (allClaudeProfiles) {
9168
+ for (const file of claudeProfileFiles(journal)) {
9169
+ const bytes = restored.has(file) ? restored.get(file) : fileBytes(file);
9170
+ if (!bytes)
9171
+ continue;
9172
+ const root = parseJsonc(bytes.toString("utf8"));
9173
+ if (!root || typeof root !== "object" || Array.isArray(root))
9174
+ throw new Error(`${file} is not a JSON object`);
9175
+ if (cleanClaudeProfile(root))
9176
+ restored.set(file, jsonBytes(root));
9177
+ }
9178
+ }
9179
+ const current = [...restored].map(([file]) => ({ file, bytes: fileBytes(file) }));
9180
+ if (allClaudeProfiles && current.length > 0) {
9181
+ const backup = join(cavemanHome(), "integrations", "backups", `claude-disable-${randomUUID()}`);
9182
+ const manifest = current.map((item, index) => {
9183
+ const path = join(backup, `${index}.bin`);
9184
+ if (item.bytes)
9185
+ atomicWriteFile(path, item.bytes);
9186
+ return { file: item.file, backup: item.bytes ? path : null };
9187
+ });
9188
+ atomicWriteFile(join(backup, "manifest.json"), Buffer.from(JSON.stringify(manifest, null, 2) + "\n"));
9189
+ process.stderr.write(`${mark("ok")} Claude profile backups: ${backup}\n`);
9190
+ }
8925
9191
  try {
8926
- for (const item of restored)
8927
- writeNativeRestoration(item.operation.file, item.bytes);
8928
- unlinkSync(nativeJournalPath(journal.agent));
9192
+ for (const [file, bytes] of restored)
9193
+ writeNativeRestoration(file, bytes);
9194
+ if (journal)
9195
+ unlinkSync(nativeJournalPath(journal.agent));
8929
9196
  }
8930
9197
  catch (error) {
8931
9198
  for (const item of current) {
@@ -8958,22 +9225,29 @@ function cleanupNativeAgentFiles(target, journal) {
8958
9225
  catch { /* absent or non-empty: preserve */ }
8959
9226
  }
8960
9227
  }
8961
- function disableNativeAgent(target) {
9228
+ function disableNativeAgent(target, allClaudeProfiles = false) {
8962
9229
  const disabled = withIntegrationLock(target, () => {
8963
9230
  recoverPendingNativeInstallUnlocked(target);
8964
9231
  const journal = readNativeJournal(target);
9232
+ if (target === "claude" && allClaudeProfiles) {
9233
+ const changed = restoreNativeJournalFiles(journal, true);
9234
+ return changed.length > 0 ? { journal, files: changed.length } : undefined;
9235
+ }
8965
9236
  if (!journal)
8966
9237
  return undefined;
8967
9238
  restoreNativeJournalFiles(journal);
8968
- return journal;
9239
+ return { journal, files: journal.operations.length };
8969
9240
  });
8970
9241
  if (!disabled) {
8971
- process.stderr.write(`${mark("warn")} ${target}: no native Caveman integration journal found\n`);
9242
+ process.stderr.write(`${mark("warn")} ${target === "claude" && allClaudeProfiles ? "Claude Code: no native Caveman routing or hooks found across discovered profiles" : `${target}: no native Caveman integration journal found`}\n`);
8972
9243
  return false;
8973
9244
  }
8974
- cleanupNativeAgentFiles(target, disabled);
9245
+ if (disabled.journal)
9246
+ cleanupNativeAgentFiles(target, disabled.journal);
8975
9247
  const name = findAgent(target)?.display_name ?? target;
8976
9248
  process.stderr.write(`${mark("ok")} ${name}: ${target === "aider" ? "shallow" : "native"} Caveman disabled; unrelated host edits preserved\n`);
9249
+ if (target === "claude" && allClaudeProfiles)
9250
+ process.stderr.write(`Checked all discovered Claude profiles. Restart running Claude sessions; their existing environment cannot be cleared by disable.\n`);
8977
9251
  return true;
8978
9252
  }
8979
9253
  function repairNativeAgent(target) {
@@ -9008,21 +9282,18 @@ function repairNativeAgent(target) {
9008
9282
  atomicWriteFile(nativeJournalPath(target), journalBytes);
9009
9283
  throw error;
9010
9284
  }
9285
+ installNativeVoiceSkills(target);
9011
9286
  });
9012
9287
  process.stderr.write(`${mark("ok")} ${profile.display_name}: native Caveman repaired; unrelated host edits preserved\n`);
9013
9288
  }
9014
9289
  function disableNative(argv) {
9015
- if (argv.length === 1 && argv[0] === "--all") {
9290
+ if (argv.length === 0 || (argv.length === 1 && argv[0] === "--all")) {
9016
9291
  const targets = ["claude", "codex", "hermes", "gemini", "opencode", "pi", "aider"]
9017
- .filter((agent) => Boolean(readNativeJournal(agent) || readPendingNativeJournal(agent)));
9018
- if (targets.length === 0) {
9019
- process.stderr.write(`${mark("warn")} no native Caveman integrations are journaled\n`);
9020
- return;
9021
- }
9292
+ .filter((agent) => agent === "claude" || Boolean(readNativeJournal(agent) || readPendingNativeJournal(agent)));
9022
9293
  let failed = 0;
9023
9294
  for (const target of targets) {
9024
9295
  try {
9025
- disableNativeAgent(target);
9296
+ disableNativeAgent(target, true);
9026
9297
  }
9027
9298
  catch (error) {
9028
9299
  failed++;
@@ -9036,7 +9307,7 @@ function disableNative(argv) {
9036
9307
  const target = argv[0];
9037
9308
  if ((target !== "claude" && target !== "codex" && target !== "hermes" && target !== "gemini" && target !== "opencode" && target !== "pi" && target !== "aider") || argv.length !== 1)
9038
9309
  commandUsage("disable <claude|codex|hermes|gemini|opencode|pi|aider> | disable --all");
9039
- disableNativeAgent(target);
9310
+ disableNativeAgent(target, true);
9040
9311
  }
9041
9312
  function nativeIntegrationStatus(agent) {
9042
9313
  const profile = findAgent(agent);
@@ -9088,7 +9359,7 @@ function nativeIntegrationStatus(agent) {
9088
9359
  const providers = root.provider && typeof root.provider === "object" && !Array.isArray(root.provider) ? root.provider : {};
9089
9360
  const routes = operation.owned?.routes && typeof operation.owned.routes === "object" && !Array.isArray(operation.owned.routes) ? operation.owned.routes : {};
9090
9361
  const mcp = root.mcp && typeof root.mcp === "object" && !Array.isArray(root.mcp) ? root.mcp : {};
9091
- owned = ["openai", "anthropic"].every((providerID) => {
9362
+ owned = Object.keys(routes).every((providerID) => {
9092
9363
  const provider = providers[providerID] && typeof providers[providerID] === "object" && !Array.isArray(providers[providerID]) ? providers[providerID] : {};
9093
9364
  const options = provider.options && typeof provider.options === "object" && !Array.isArray(provider.options) ? provider.options : {};
9094
9365
  return options.baseURL === routes[providerID];
@@ -9132,7 +9403,7 @@ function nativeIntegrationStatus(agent) {
9132
9403
  const mcp = probeMcpBinary();
9133
9404
  const expectedRoute = agent === "codex"
9134
9405
  ? codexGatewayBase(gatewayURL(), detectCodexWrapAuthMode() === "subscription")
9135
- : appendUrlPath(gatewayURL(), agent === "claude" ? "/w/claude" : agent === "hermes" ? "/w/hermes/v1" : agent === "gemini" ? "/w/gemini" : agent === "opencode" ? "/w/opencode" : agent === "pi" ? "/w/pi" : "/w/aider/openai/v1");
9406
+ : appendUrlPath(gatewayURL(), agent === "claude" ? "/w/claude" : agent === "hermes" ? "/w/hermes/v1" : agent === "gemini" ? "/w/gemini" : agent === "pi" ? "/w/pi" : "/w/aider/openai/v1");
9136
9407
  const routeKind = agent === "claude" ? "claude-settings" : agent === "codex" ? "codex-config" : agent === "hermes" ? "hermes-config" : agent === "gemini" ? "gemini-env" : agent === "opencode" ? "opencode-config" : agent === "pi" ? "pi-extension" : "aider-config";
9137
9408
  const routeOperation = journal?.operations.find((operation) => operation.kind === routeKind);
9138
9409
  // Pi's artifact encodes no route: the extension resolves the gateway at
@@ -9178,8 +9449,7 @@ function nativeIntegrationStatus(agent) {
9178
9449
  return (semver[0] >= 2) === installedV2;
9179
9450
  })();
9180
9451
  const routeHealthy = ownedHealthy && (agent === "opencode"
9181
- ? routeOperation?.owned?.routes?.openai === appendUrlPath(expectedRoute, "/openai/v1")
9182
- && routeOperation?.owned?.routes?.anthropic === appendUrlPath(expectedRoute, "/anthropic/v1")
9452
+ ? Object.entries(opencodeNativeRoutes(gatewayURL())).every(([providerID, route]) => routeOperation?.owned?.routes?.[providerID] === route)
9183
9453
  : agent === "pi" ? piBundleCurrent : routeOperation?.owned?.route === expectedRoute);
9184
9454
  const proxyHealthy = wrapMode(gatewayURL()) === "managed" || Boolean(probeProxyVersion()?.capabilities.includes("native_runtime_v1"));
9185
9455
  const recoveryHealthy = agent === "aider" || Boolean(mcp?.probe.current);
@@ -9188,6 +9458,13 @@ function nativeIntegrationStatus(agent) {
9188
9458
  const coreActive = agent === "aider"
9189
9459
  ? ownedHealthy
9190
9460
  : coreSupported && nativeCoreRuntimeState().active;
9461
+ const warnings = [];
9462
+ if (agent === "opencode" && installed) {
9463
+ const routed = Object.keys(routeOperation?.owned?.routes ?? {});
9464
+ const unrouted = opencodeUnroutedActiveProvider(routed);
9465
+ if (unrouted)
9466
+ warnings.push(`OpenCode's active provider "${unrouted}" is not routed through Caveman; its requests go direct and are not compressed or counted (routed: ${routed.join(", ")})`);
9467
+ }
9191
9468
  const fileText = checks.map((check) => fileBytes(check.file)?.toString("utf8") ?? "").join("\n");
9192
9469
  const components = {
9193
9470
  routing: routeHealthy && proxyHealthy && (agent === "claude" ? fileText.includes("ANTHROPIC_BASE_URL") : agent === "codex" ? fileText.includes("model_providers.caveman") : agent === "hermes" ? fileText.includes(HERMES_NATIVE_ROUTE_BEGIN) : agent === "gemini" ? fileText.includes(GEMINI_NATIVE_ENV_BEGIN) : agent === "opencode" ? fileText.includes("caveman:native-opencode") : agent === "pi" ? fileText.includes("caveman:native-pi") : fileText.includes(AIDER_NATIVE_ROUTE_BEGIN)),
@@ -9239,6 +9516,7 @@ function nativeIntegrationStatus(agent) {
9239
9516
  pack_current: packCurrent,
9240
9517
  drifted,
9241
9518
  components,
9519
+ warnings,
9242
9520
  capabilities: nativeCapabilityReport(agent, components, versionStatus),
9243
9521
  files: checks,
9244
9522
  };
@@ -11477,11 +11755,17 @@ const HERMES_PLUGIN_ENABLE_BEGIN = "# >>> caveman:hermes-plugin-enable";
11477
11755
  const HERMES_PLUGIN_ENABLE_END = "# <<< caveman:hermes-plugin-enable";
11478
11756
  const HERMES_PLUGIN_NAME = "caveman_shrink";
11479
11757
  export function hermesHome(env = process.env, platform = process.platform) {
11480
- // Hermes 0.19.1 hermes_constants.py: native Windows uses LOCALAPPDATA,
11481
- // overrides are stripped, and Path(value) does not expand a literal tilde.
11758
+ // Hermes 0.21.5 hermes_constants.py: native Windows uses LOCALAPPDATA,
11759
+ // overrides are stripped, then Path(expanduser(expandvars(value))).
11760
+ // ponytail: no `~user` or Windows quote/escape forms; add if a user hits one.
11482
11761
  const override = env.HERMES_HOME?.trim();
11483
- if (override)
11484
- return resolve(override);
11762
+ if (override) {
11763
+ const lookup = (whole, name) => env[name] ?? whole;
11764
+ let expanded = override.replace(/\$(\w+)|\$\{([^{}$]*)\}/g, (whole, bare, braced) => lookup(whole, bare ?? braced));
11765
+ if (platform === "win32")
11766
+ expanded = expanded.replace(/%([^%]+)%/g, lookup);
11767
+ return resolve(expanded.replace(/^~(?=$|[\\/])/, homedir()));
11768
+ }
11485
11769
  if (platform === "win32") {
11486
11770
  return join(env.LOCALAPPDATA?.trim() || join(homedir(), "AppData", "Local"), "hermes");
11487
11771
  }
@@ -15027,6 +15311,31 @@ async function nativeHook(argv) {
15027
15311
  // Runtime startup is fail-open; host session and Core still proceed.
15028
15312
  }
15029
15313
  }
15314
+ // Codex's native config.toml bakes in the auth mode (subscription vs
15315
+ // api-key) at install time, but people run `codex login` afterwards all
15316
+ // the time, which flips it without touching config.toml. That leaves the
15317
+ // route stale until someone remembers to run `caveman doctor codex --fix`
15318
+ // by hand. Just do what that command would do, right here at session
15319
+ // start — but only for that specific drift. `degraded` also covers pack
15320
+ // version bumps, missing hooks, MCP recovery being down, etc., and none
15321
+ // of those should get a silent config rewrite just because Codex started;
15322
+ // those still surface through `caveman doctor codex` like normal.
15323
+ // Runs after the proxy revival above so the repair cannot race a
15324
+ // proxy this hook just spawned. The check is file-only on purpose:
15325
+ // nativeIntegrationStatus spawns `codex --version` and the proxy/MCP
15326
+ // probes, and this whole delegated SessionStart gets 3s. Codex has
15327
+ // already read config.toml by the time SessionStart fires, so the
15328
+ // repaired route takes effect from the next Codex launch.
15329
+ if (normalizedEvent === "SessionStart" && agent === "codex") {
15330
+ try {
15331
+ const route = readNativeJournal("codex")?.operations.find((operation) => operation.kind === "codex-config")?.owned?.route;
15332
+ if (typeof route === "string" && route !== codexGatewayBase(gatewayURL(), detectCodexWrapAuthMode() === "subscription"))
15333
+ repairNativeAgent("codex");
15334
+ }
15335
+ catch {
15336
+ // Best-effort; a real problem still shows up in `caveman doctor codex`.
15337
+ }
15338
+ }
15030
15339
  const runtimeRequest = sessionId && normalizedEvent !== "Unknown"
15031
15340
  ? nativeRuntimeRequest(agent, normalizedEvent, sessionId, event)
15032
15341
  : undefined;
@@ -18343,6 +18652,9 @@ async function status(argv) {
18343
18652
  if (refreshOffline())
18344
18653
  states.push(fixedOffState("refresh-offline", OFF_STATES.refreshOffline));
18345
18654
  const today = versionInfo ? readProxyObserveSummary(localMidnightRFC3339()) : null;
18655
+ const cavemanBusts = Number(today?.caveman_cache_bust_requests ?? 0);
18656
+ if (Number.isSafeInteger(cavemanBusts) && cavemanBusts > 0)
18657
+ states.push(OFF_STATES.cavemanCacheBust(cavemanBusts));
18346
18658
  const runningMode = runtime.owner !== "unknown" && runtime.mode ? runtime.mode : null;
18347
18659
  const resolvedMode = gate.mode;
18348
18660
  const snapshot = readLearnSnapshot();
@@ -18405,6 +18717,8 @@ async function status(argv) {
18405
18717
  const active = Object.entries(integration.capabilities).filter(([, value]) => value.active).map(([name]) => name);
18406
18718
  process.stdout.write(statusRow(integration.agent, `${integration.state} · ${integration.version_status} · ${active.join(", ") || "proxy-only/none active"}`) + "\n");
18407
18719
  }
18720
+ for (const warning of native.flatMap((integration) => integration.warnings))
18721
+ process.stdout.write(`${mark("warn")} ${warning}\n`);
18408
18722
  const degraded = native.find((integration) => integration.state === "degraded");
18409
18723
  const available = native.find((integration) => integration.state === "available" && integration.components.shared_runtime);
18410
18724
  const needsRuntime = native.find((integration) => integration.state === "available" && !integration.components.shared_runtime);
@@ -7,13 +7,47 @@ export function parseWindowsNodeShim(source) {
7
7
  // Shim-relative target (npm cmd-shim, pnpm/yarn-classic @zkochan forms), or
8
8
  // a drive-absolute target (pnpm emits one when the global bin dir and the
9
9
  // store sit on different drives — path.relative crosses drives as absolute).
10
- const match = line.match(/"%(?:dp0%|~dp0)\\([^"\r\n]+\.(?:cjs|mjs|js))"\s+%\*/i)
10
+ // %~dp0 already ends with a separator; managed Pi adds none before its target.
11
+ const match = line.match(/"%(?:dp0%|~dp0)\\?([^"\r\n]+\.(?:cjs|mjs|js))"\s+%\*/i)
11
12
  ?? line.match(/"([A-Za-z]:[\\/][^"\r\n]+\.(?:cjs|mjs|js))"\s+%\*/i);
12
13
  if (match)
13
14
  return match[1];
14
15
  }
15
16
  return null;
16
17
  }
18
+ // Accept only a single shim-relative forwarding command, optionally preceded by
19
+ // @echo off. Never evaluate batch syntax or interpolate caller-controlled argv.
20
+ function parseWindowsNestedShim(source) {
21
+ const match = source.match(/^(?:@echo[ \t]+off[ \t]*\r?\n)?[ \t]*"%~dp0\\?([\w .@+\-\\/]+\.(?:cmd|bat))"[ \t]+%\*[ \t]*(?:\r?\n)?$/i);
22
+ return match?.[1] ?? null;
23
+ }
24
+ function resolveWindowsNodeShim(executable, depth = 0, seen = new Set()) {
25
+ if (depth > 4)
26
+ throw new Error("Windows command shim nesting too deep");
27
+ const normalized = resolve(executable);
28
+ if (seen.has(normalized.toLowerCase()))
29
+ throw new Error("Windows command shim cycle");
30
+ seen.add(normalized.toLowerCase());
31
+ const stat = statSync(normalized);
32
+ if (!stat.isFile() || stat.size > 256 * 1024) {
33
+ throw new Error(`cannot safely launch Windows command shim: ${normalized}`);
34
+ }
35
+ const source = readFileSync(normalized, "utf8");
36
+ // Batch forwarding must match the whole wrapper, not a later Node command.
37
+ const nested = parseWindowsNestedShim(source);
38
+ const forwardsToBatch = /"[^"\r\n]+\.(?:cmd|bat)"[ \t]+%\*/i.test(source);
39
+ const jsTarget = forwardsToBatch ? null : parseWindowsNodeShim(source);
40
+ const child = jsTarget ?? nested;
41
+ if (!child) {
42
+ throw new Error(`cannot safely launch non-Node Windows command shim: ${normalized}; install a native .exe`);
43
+ }
44
+ const target = /^[A-Za-z]:[\\/]/.test(child)
45
+ ? child
46
+ : resolve(dirname(normalized), ...child.split(/[\\/]+/));
47
+ if (!existsSync(target) || !statSync(target).isFile())
48
+ throw new Error(`Windows command shim target is missing: ${target}`);
49
+ return jsTarget ? target : resolveWindowsNodeShim(target, depth + 1, seen);
50
+ }
17
51
  function envValue(env, name) {
18
52
  const key = Object.keys(env).find((candidate) => candidate.toLowerCase() === name.toLowerCase());
19
53
  return key === undefined ? undefined : env[key];
@@ -56,19 +90,6 @@ export function portableInvocation(command, args, platform = process.platform, e
56
90
  const executable = resolveWindowsCommand(command, env) ?? command;
57
91
  if (!/\.(?:cmd|bat)$/i.test(executable))
58
92
  return { command: executable, args: [...args] };
59
- const stat = statSync(executable);
60
- if (!stat.isFile() || stat.size > 256 * 1024) {
61
- throw new Error(`cannot safely launch Windows command shim: ${executable}`);
62
- }
63
- const shimScript = parseWindowsNodeShim(readFileSync(executable, "utf8"));
64
- if (!shimScript) {
65
- throw new Error(`cannot safely launch non-Node Windows command shim: ${executable}; install a native .exe`);
66
- }
67
- const script = /^[A-Za-z]:[\\/]/.test(shimScript)
68
- ? shimScript
69
- : resolve(dirname(executable), ...shimScript.split(/[\\/]+/));
70
- if (!statSync(script).isFile()) {
71
- throw new Error(`Windows command shim target is missing: ${script}`);
72
- }
93
+ const script = resolveWindowsNodeShim(executable);
73
94
  return { command: process.execPath, args: [script, ...args] };
74
95
  }
@@ -52,6 +52,17 @@ function compatTarget(base, path) {
52
52
  overlap--;
53
53
  return base.origin + '/' + [...left, ...right.slice(overlap)].join('/');
54
54
  }
55
+ export function verifiedChatGPTSubscriptionRoute(gateway, api, provider, originalBaseUrl, published) {
56
+ if (api !== 'openai-codex-responses' || provider !== 'openai-codex')
57
+ return undefined;
58
+ const original = endpoint(originalBaseUrl);
59
+ const upstream = endpoint(published?.provider_upstreams?.['openai-codex']);
60
+ if (!original || !upstream || !endpoint(gateway))
61
+ return undefined;
62
+ if (append(upstream, '/codex/responses') !== append(original, '/codex/responses'))
63
+ return undefined;
64
+ return trimTrailingSlashes(gateway);
65
+ }
55
66
  export function verifiedProviderRoute(gateway, api, provider, originalBaseUrl, published) {
56
67
  const original = endpoint(originalBaseUrl);
57
68
  if (!original || !endpoint(gateway))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@caveman-ai/cli",
3
- "version": "2.0.1",
3
+ "version": "2.1.0",
4
4
  "description": "Caveman CLI — wrap coding agents with recoverable local context compression and truthful metering (`caveman claude`), then drive Caveman Cloud from terminal. Compression and metering run in companion Go binaries: run `caveman setup` to see install state. Local savings stay inferred until verified.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -36,8 +36,8 @@
36
36
  "scripts": {
37
37
  "build": "node scripts/gen-binaries.mjs && node scripts/gen-wedge-installer.mjs && node scripts/compile-registries.mjs && tsc && node scripts/bundle-delegate.mjs && node scripts/bundle-tui.mjs && node scripts/bundle-pi-extension.mjs && node scripts/shebang.mjs",
38
38
  "lint": "tsc --noEmit",
39
- "test": "node scripts/gen-binaries.mjs && node scripts/gen-wedge-installer.mjs && node scripts/compile-registries.mjs && tsc && node scripts/bundle-delegate.mjs && node scripts/bundle-tui.mjs && node scripts/bundle-pi-extension.mjs && node scripts/shebang.mjs && node --test --test-force-exit --test-concurrency=4 tests/*.runtime.mjs",
39
+ "test": "node scripts/gen-binaries.mjs && node scripts/gen-wedge-installer.mjs && node scripts/compile-registries.mjs && tsc && node scripts/bundle-delegate.mjs && node scripts/bundle-tui.mjs && node scripts/bundle-pi-extension.mjs && node scripts/shebang.mjs && node --import ./tests/fixtures/sanitize-host-env.mjs --test --test-force-exit --test-concurrency=4 tests/*.runtime.mjs",
40
40
  "bench:native": "node scripts/benchmark-native-hooks.mjs",
41
- "test:fast": "node scripts/gen-binaries.mjs && node scripts/gen-wedge-installer.mjs && node scripts/compile-registries.mjs && tsc && node scripts/bundle-delegate.mjs && node scripts/bundle-tui.mjs && node scripts/bundle-pi-extension.mjs && node --test --test-force-exit --test-concurrency=4 --test-reporter=dot tests/agent-native.runtime.mjs tests/billing.runtime.mjs tests/capability-config.runtime.mjs tests/login.runtime.mjs tests/mcp-surface.runtime.mjs tests/porcelain.runtime.mjs tests/practice-registry.runtime.mjs tests/skills.runtime.mjs tests/status.runtime.mjs tests/subscription-recovery.runtime.mjs tests/wrap-gate.runtime.mjs"
41
+ "test:fast": "node scripts/gen-binaries.mjs && node scripts/gen-wedge-installer.mjs && node scripts/compile-registries.mjs && tsc && node scripts/bundle-delegate.mjs && node scripts/bundle-tui.mjs && node scripts/bundle-pi-extension.mjs && node --import ./tests/fixtures/sanitize-host-env.mjs --test --test-force-exit --test-concurrency=4 --test-reporter=dot tests/agent-native.runtime.mjs tests/billing.runtime.mjs tests/capability-config.runtime.mjs tests/login.runtime.mjs tests/mcp-surface.runtime.mjs tests/porcelain.runtime.mjs tests/practice-registry.runtime.mjs tests/skills.runtime.mjs tests/status.runtime.mjs tests/subscription-recovery.runtime.mjs tests/wrap-gate.runtime.mjs"
42
42
  }
43
43
  }