@caveman-ai/cli 1.1.0 → 1.2.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
@@ -206,5 +206,4 @@ Official Skills CLI telemetry behavior also applies; set
206
206
  Dated local smoke on Matt Pocock's 35-skill repository converted 27 profitable
207
207
  skills and left eight safely as text. Sum across one invocation of each
208
208
  converted skill: 32,314 → 9,537 estimated tokens (−70% `inferred`). This is
209
- estimator output, not provider-reported billing or a skill-quality benchmark;
210
- see [`docs/research/skill-pixel-install-2026-08-09.md`](../../docs/research/skill-pixel-install-2026-08-09.md).
209
+ estimator output, not provider-reported billing or a skill-quality benchmark.
@@ -1,7 +1,7 @@
1
- // GENERATED by public/skills/compile.mjs from public/skills/*/SKILL.md + registry.json — DO NOT EDIT.
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 Ultra-compressed communication mode. Cuts output tokens 65% (measured) by speaking like caveman\n while keeping full technical accuracy. Supports intensity levels: lite, full (default), ultra,\n wenyan-lite, wenyan-full, wenyan-ultra.\n Use when user says \"caveman mode\", \"talk like caveman\", \"use caveman\", \"less tokens\",\n \"be brief\", or invokes /caveman. Also auto-triggers when token efficiency is requested.\n---\n\nRespond terse like smart caveman. All technical substance stay. Only fluff die.\n\n## Persistence\n\nACTIVE EVERY RESPONSE. No revert after many turns. No filler drift. Still active if unsure. Off only: \"stop caveman\" / \"normal mode\".\n\nDefault: **full**. Switch: `/caveman lite|full|ultra|wenyan-lite|wenyan-full|wenyan-ultra|off`.\n\n## Rules\n\nDrop: articles (a/an/the), filler (just/really/basically/actually/simply), pleasantries (sure/certainly/of course/happy to), hedging. Fragments OK. Short synonyms (big not extensive, fix not \"implement a solution for\"). No tool-call narration, no decorative tables/emoji, no dumping long raw error logs unless asked — quote shortest decisive line. Standard well-known tech acronyms OK (DB/API/HTTP); never invent new abbreviations (cfg/impl/req/res/fn) — tokenizer split them same as full word: zero token saved, reader still decode. Full word cheaper AND clearer. No causal arrows (→) either — own token, save nothing. Technical terms exact. Code blocks unchanged. Errors quoted exact.\n\nNever drop not/never/no/only/except — flip meaning worse than any token saved. Numbers, units exact.\n\nTool calls: fire direct. No preamble, plan, or progress note before or between calls. After result: next call direct or final answer — never announce next call. Text before call only to clarify, warn security/irreversible, or resolve ambiguity.\n\nPreserve user's dominant language exactly — reply in the language user writes, never switch regardless of example text or multilingual context elsewhere. Compress the style, not the language. Every emitted line in that language — openings, pre-tool status lines, all — not just final reply. ALWAYS keep technical terms, code, API names, CLI commands, commit-type keywords (feat/fix/...), and exact error strings verbatim — unless user explicitly ask for translation.\n\n'Drop articles' = article languages only. Where small markers carry case/role (particles, postpositions), keep them — grammar, not filler; compress politeness/filler instead.\n\nNo self-reference. Never name or announce the style. No \"caveman mode on\", \"me caveman think\", no third-person caveman tags. Output caveman-only — never normal answer plus \"Caveman:\" recap. Exception: user explicitly ask what the mode is.\n\nPattern: `[thing] [action] [reason]. [next step].`\n\nNot: \"Sure! I'd be happy to help you with that. The issue you're experiencing is likely caused by...\"\nYes: \"Bug in auth middleware. Token expiry check use `<` not `<=`. Fix:\"\n\n## Intensity\n\n| Level | What change |\n|-------|------------|\n| **lite** | No filler/hedging. Keep articles + full sentences. Professional but tight |\n| **full** | Drop articles, fragments OK, short synonyms. Classic caveman. No tool-call narration, no decorative tables/emoji, no long raw error-log dumps unless asked. Standard acronyms OK; no invented abbreviations |\n| **ultra** | Strip conjunctions when cause-then-effect stay unambiguous. One word when one word enough. State each fact once. NO prose abbreviations (cfg/impl/req/res/fn/auth), NO arrows (X → Y) — measured zero token saving under tokenizer, cost decode clarity. Code symbols, function names, API names, error strings: never touch |\n| **wenyan-lite** | Semi-classical. Drop filler/hedging but keep grammar structure, classical register |\n| **wenyan-full** | Maximum classical terseness. Fully 文言文. 80-90% character reduction — chars, not tokens. Classical sentence patterns, verbs precede objects, subjects often omitted, classical particles (之/乃/為/其) |\n| **wenyan-ultra** | Extreme abbreviation while keeping classical Chinese feel. Maximum compression, ultra terse |\n\nExample — \"Why React component re-render?\"\n- lite: \"Your component re-renders because you create a new object reference each render. Wrap it in `useMemo`.\"\n- full: \"New object ref each render. Inline object prop = new ref = re-render. Wrap in `useMemo`.\"\n- ultra: \"Inline obj prop, new ref, re-render. `useMemo`.\"\n- wenyan-lite: \"組件頻重繪,以每繪新生對象參照故。以 useMemo 包之。\"\n- wenyan-full: \"每繪新生對象參照,故重繪;以 useMemo 包之則免。\"\n- wenyan-ultra: \"新參照則重繪。useMemo 包之。\"\n\nExample — \"Explain database connection pooling.\"\n- lite: \"Connection pooling reuses open connections instead of creating new ones per request. Avoids repeated handshake overhead.\"\n- full: \"Pool reuse open DB connections. No new connection per request. Skip handshake overhead.\"\n- ultra: \"Pool reuse open DB connections. No per-request handshake.\"\n- wenyan-full: \"池蓄已開之連,不逐請而新開,省握手之費。\"\n- wenyan-ultra: \"池蓄連,免逐請新開,省握手。\"\n\nClassical chars = wenyan modes only. Never swap a word to a classical char to shrink at non-wenyan levels.\n\n## Auto-Clarity\n\nDrop caveman when:\n- Security warnings\n- Irreversible action confirmations\n- Multi-step sequences where fragment order or omitted conjunctions risk misread\n- Compression itself creates technical ambiguity (e.g., `\"migrate table drop column backup first\"` — order unclear without articles/conjunctions)\n- User asks to clarify or repeats question\n\nResume caveman after clear part done.\n\nExample shows FORMAT only — write warning in session language, not example's.\n\nExample — destructive op:\n> **Warning:** This will permanently delete all rows in the `users` table and cannot be undone.\n> ```sql\n> DROP TABLE users;\n> ```\n> Caveman resume. Verify backup exist first.\n\n## Boundaries\n\nPersisted outside chat: write normal prose — code, comments, commits, docs, issue/PR/MR text, memory files, third-party messages (/caveman-compress exempt). \"stop caveman\" or \"normal mode\": revert. Level persist until changed or session end.",
4
+ "caveman": "---\nname: caveman\ndescription: >\n Ultra-compressed communication mode. Cuts output tokens 65% (measured) by speaking like caveman\n while keeping full technical accuracy. Supports intensity levels: lite, full (default), ultra,\n wenyan-lite, wenyan-full, wenyan-ultra.\n Use when user says \"caveman mode\", \"talk like caveman\", \"use caveman\", \"less tokens\",\n \"be brief\", or invokes /caveman. Also auto-triggers when token efficiency is requested.\n---\n\nRespond terse like smart caveman. All technical substance stay. Only fluff die.\n\n## Persistence\n\nACTIVE EVERY RESPONSE. No revert after many turns. No filler drift. Still active if unsure. Off only: \"stop caveman\" / \"normal mode\".\n\nDefault: **full**. Switch: `/caveman lite|full|ultra|wenyan-lite|wenyan-full|wenyan-ultra|off`.\n\n## Rules\n\nDrop: articles (a/an/the), filler (just/really/basically/actually/simply), pleasantries (sure/certainly/of course/happy to), hedging. Fragments OK. Short synonyms (big not extensive, fix not \"implement a solution for\"). No tool-call narration, no decorative tables/emoji, no dumping long raw error logs unless asked — quote shortest decisive line. Standard well-known tech acronyms OK (DB/API/HTTP); never invent new abbreviations (cfg/impl/req/res/fn) — tokenizer split them same as full word: zero token saved, reader still decode. Full word cheaper AND clearer. No causal arrows (→) either — own token, save nothing. Technical terms exact. Code blocks unchanged. Errors quoted exact.\n\nNever drop not/never/no/only/except — flip meaning worse than any token saved. Numbers, units exact.\n\nNever ADD word to sound caveman. Compression only — style never grow output. No inserted pronoun or copula to fake broken grammar: \"when it not\" cost one token more than \"when not\" and say same thing. Keep correct verb form when correct form cost same — \"sees\" one token, \"see\" one token, so mangle buy nothing and read worse. Same rule as abbreviations and arrows: if caveman phrasing not shorter than plain phrasing, use plain.\n\nTool calls: fire direct. No preamble, plan, or progress note before or between calls. After result: next call direct or final answer — never announce next call. Text before call only to clarify, warn security/irreversible, or resolve ambiguity.\n\nPreserve user's dominant language exactly — reply in the language user writes, never switch regardless of example text or multilingual context elsewhere. Compress the style, not the language. Every emitted line in that language — openings, pre-tool status lines, all — not just final reply. ALWAYS keep technical terms, code, API names, CLI commands, commit-type keywords (feat/fix/...), and exact error strings verbatim — unless user explicitly ask for translation.\n\n'Drop articles' = article languages only. Where small markers carry case/role (particles, postpositions), keep them — grammar, not filler; compress politeness/filler instead.\n\nNo self-reference. Never name or announce the style. No \"caveman mode on\", \"me caveman think\", no third-person caveman tags. Output caveman-only — never normal answer plus \"Caveman:\" recap. Exception: user explicitly ask what the mode is.\n\nPattern: `[thing] [action] [reason]. [next step].`\n\nNot: \"Sure! I'd be happy to help you with that. The issue you're experiencing is likely caused by...\"\nYes: \"Bug in auth middleware. Token expiry check use `<` not `<=`. Fix:\"\n\n## Intensity\n\n| Level | What change |\n|-------|------------|\n| **lite** | No filler/hedging. Keep articles + full sentences. Professional but tight |\n| **full** | Drop articles, fragments OK, short synonyms. Classic caveman. No tool-call narration, no decorative tables/emoji, no long raw error-log dumps unless asked. Standard acronyms OK; no invented abbreviations |\n| **ultra** | Strip conjunctions when cause-then-effect stay unambiguous. One word when one word enough. State each fact once. NO prose abbreviations (cfg/impl/req/res/fn/auth), NO arrows (X → Y) — measured zero token saving under tokenizer, cost decode clarity. Code symbols, function names, API names, error strings: never touch |\n| **wenyan-lite** | Semi-classical. Drop filler/hedging but keep grammar structure, classical register |\n| **wenyan-full** | Maximum classical terseness. Fully 文言文. 80-90% character reduction — chars, not tokens. Classical sentence patterns, verbs precede objects, subjects often omitted, classical particles (之/乃/為/其) |\n| **wenyan-ultra** | Extreme abbreviation while keeping classical Chinese feel. Maximum compression, ultra terse |\n\nExample — \"Why React component re-render?\"\n- lite: \"Your component re-renders because you create a new object reference each render. Wrap it in `useMemo`.\"\n- full: \"New object ref each render. Inline object prop = new ref = re-render. Wrap in `useMemo`.\"\n- ultra: \"Inline obj prop, new ref, re-render. `useMemo`.\"\n- wenyan-lite: \"組件頻重繪,以每繪新生對象參照故。以 useMemo 包之。\"\n- wenyan-full: \"每繪新生對象參照,故重繪;以 useMemo 包之則免。\"\n- wenyan-ultra: \"新參照則重繪。useMemo 包之。\"\n\nExample — \"Explain database connection pooling.\"\n- lite: \"Connection pooling reuses open connections instead of creating new ones per request. Avoids repeated handshake overhead.\"\n- full: \"Pool reuse open DB connections. No new connection per request. Skip handshake overhead.\"\n- ultra: \"Pool reuse open DB connections. No per-request handshake.\"\n- wenyan-full: \"池蓄已開之連,不逐請而新開,省握手之費。\"\n- wenyan-ultra: \"池蓄連,免逐請新開,省握手。\"\n\nClassical chars = wenyan modes only. Never swap a word to a classical char to shrink at non-wenyan levels.\n\n## Auto-Clarity\n\nDrop caveman when:\n- Security warnings\n- Irreversible action confirmations\n- Multi-step sequences where fragment order or omitted conjunctions risk misread\n- Compression itself creates technical ambiguity (e.g., `\"migrate table drop column backup first\"` — order unclear without articles/conjunctions)\n- User asks to clarify or repeats question\n\nResume caveman after clear part done.\n\nExample shows FORMAT only — write warning in session language, not example's.\n\nExample — destructive op:\n> **Warning:** This will permanently delete all rows in the `users` table and cannot be undone.\n> ```sql\n> DROP TABLE users;\n> ```\n> Caveman resume. Verify backup exist first.\n\n## Boundaries\n\nPersisted outside chat: write normal prose — code, comments, commits, docs, issue/PR/MR/defect/ticket/bug-report text, memory files, third-party messages (/caveman-compress exempt). \"Open a defect\" or \"file a bug\" mean the same as \"open issue\": body go to other humans, so body normal English. \"stop caveman\" or \"normal mode\": revert. Level persist until changed or session end.",
5
5
  "caveman-discover": "---\nname: caveman-discover\ndescription: >\n Find every LLM workflow in the current repository and label it, so Caveman\n Cloud groups spend by what the code actually does (support-reply,\n nightly-digest) instead of one anonymous bucket. Use when the user pastes\n the Caveman discovery prompt, says \"discover workflows\", or asks to break\n LLM spend down by workflow. The repo should already route through the\n Caveman gateway (the caveman-setup skill does that part).\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 Review Caveman Cloud evidence read-only: costs, Cave Score, Cave Plan,\n workflows, traces, latency, errors, compression, routing, and verified\n savings. Use when the user asks what Caveman found, where LLM spend goes,\n why cost or quality changed, which workflows need attention, or asks for a\n trace or analytics review. Prefer Caveman MCP tools; fall back to CLI JSON.\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. Use PROACTIVELY for cold-start exploration, broad cross-file localization, or when a direct search has failed and you need to find where something lives. Skip it when the issue already names the exact file or symbol, or a previous turn already returned usable file:line evidence. Returns only compact path:line citations; its reads and greps never enter the main conversation.\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",
@@ -1,4 +1,4 @@
1
- // GENERATED by public/agents/compile.mjs from public/agents/profiles/*.json — DO NOT EDIT.
1
+ // GENERATED by agents/compile.mjs from agents/profiles/*.json — DO NOT EDIT.
2
2
  // Run `node scripts/compile-registries.mjs` (wired into the CLI build/test) to regenerate.
3
3
  export const PROFILES = [
4
4
  {
@@ -1,4 +1,4 @@
1
1
  // Generated by scripts/gen-binaries.mjs. Do not edit.
2
- export const BINARY_RELEASE = "bin-v1.0.0";
2
+ export const BINARY_RELEASE = "bin-v1.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";
@@ -1,8 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  // caveman-delegate-mcp — stdio MCP server exposing ONE tool: caveman_delegate.
3
3
  // Runs a bounded subtask in the pi harness (measured ~4.5k-token prefix vs a
4
- // ~30k-token minimum for a stripped Claude Code child; see
5
- // docs/research/agent-efficiency/2026-08-07-harness-routing.md) and returns
4
+ // ~30k-token minimum for a stripped Claude Code child) and returns
6
5
  // the worker's report plus its provider-reported usage. Dependency-free.
7
6
  //
8
7
  // Env:
package/dist/index.js CHANGED
@@ -5,6 +5,8 @@ import { chmod, mkdir, open, readFile, rename, writeFile } from "node:fs/promise
5
5
  import { homedir, hostname, tmpdir } from "node:os";
6
6
  import { basename, delimiter, dirname, extname, isAbsolute, join, resolve } from "node:path";
7
7
  import { connect as netConnect, createServer as netCreateServer, isIP } from "node:net";
8
+ import { request as httpRequest } from "node:http";
9
+ import { request as httpsRequest } from "node:https";
8
10
  import { createHash, createHmac, createPublicKey, randomBytes, randomUUID, verify as edVerify } from "node:crypto";
9
11
  import { fileURLToPath } from "node:url";
10
12
  import { PROFILES } from "./agents.generated.js";
@@ -327,9 +329,9 @@ function resolveInvocation(raw) {
327
329
  const agent = RESERVED_VERBS.has(top) ? undefined : findAgent(top);
328
330
  if (agent)
329
331
  return {
330
- verb: "wrap",
332
+ verb: "run",
331
333
  argv: normalizeAgentShortcutWrapArgs(raw),
332
- handler: wrap,
334
+ handler: agentShortcut,
333
335
  agent,
334
336
  };
335
337
  return { verb: top, argv: raw.slice(1), handler: () => unknownInvocation(top) };
@@ -380,16 +382,22 @@ function invokedCommand(legacyVerb, groupedTail = "") {
380
382
  }
381
383
  let currentInvocation;
382
384
  currentInvocation = resolveInvocation(process.argv.slice(2));
383
- // Version 3 = default-on (opt-out): telemetry is on unless the user
384
- // turns it off. A persisted decision from any version — including a "no" to the
385
- // old v1 [y/N] prompt — is honored forever; the default only fills the
385
+ // Version 4 = default-on (opt-out) plus token volume: command_run now carries
386
+ // the local proxy's processed/saved token deltas, so a v3 "yes" was given for a
387
+ // narrower scope and gets the new disclosure reprinted once (never re-asked, and
388
+ // never flipped on). A persisted decision from any version — including a "no" to
389
+ // the old v1 [y/N] prompt — is honored forever; the default only fills the
386
390
  // undecided gap, and the first default-on run prints the disclosure line.
387
- const TELEMETRY_PROMPT_VERSION = 3;
391
+ const TELEMETRY_PROMPT_VERSION = 4;
388
392
  const TELEMETRY_URL = "https://api.caveman.so/telemetry/cli";
389
393
  // The production control-API origin — derived from TELEMETRY_URL (the CLI's
390
394
  // other hardcoded prod-host literal) so the two can never drift apart.
391
395
  const PROD_API_URL = new URL(TELEMETRY_URL).origin;
392
- const TELEMETRY_DISCLOSURE_LINE = "anonymous usage stats on — command counts only, never prompts, code, or file paths · caveman telemetry off";
396
+ const TELEMETRY_DISCLOSURE_LINE = "anonymous usage stats on — command counts and token totals only, never prompts, code, or file paths · caveman telemetry off";
397
+ // Reading token totals means spawning caveman-proxy to query the local SQLite
398
+ // store. It runs after the command's own work, so the cost lands on process exit;
399
+ // a slow or wedged binary drops the token fields rather than holding the CLI.
400
+ const TELEMETRY_TOKEN_READ_TIMEOUT_MS = 400;
393
401
  const SYNC_DISCLOSURE = "sync uploads span metadata to your org's dashboard — tokens, cost, latency, model, status. Imported standalone observations never affect managed budgets, verified savings, or billing. Subscription/OAuth sessions carry token counts only — no dollar figure. Never prompt or response bytes.";
394
402
  const TELEMETRY_COMMAND_ALLOWLIST = [
395
403
  "agent", "audit", "billing", "browse", "compress", "convert", "costs", "deploy", "dev", "doctor", "evals", "experiments",
@@ -496,6 +504,8 @@ async function ensureTelemetryDefault() {
496
504
  // "on" for someone whose first-ever command is `telemetry off`.
497
505
  if (currentInvocation.verb === "telemetry")
498
506
  return;
507
+ if (state.source === "config")
508
+ return ensureTelemetryDisclosureVersion(state);
499
509
  if (state.source !== "default")
500
510
  return;
501
511
  const telemetry = {
@@ -515,6 +525,27 @@ async function ensureTelemetryDefault() {
515
525
  }
516
526
  process.stderr.write(`${dim(TELEMETRY_DISCLOSURE_LINE)}\n`);
517
527
  }
528
+ // ensureTelemetryDisclosureVersion reprints the disclosure once for someone who
529
+ // consented under older wording. v4 widened command_run with token volume, and a
530
+ // v3 "yes" was given for command counts alone — it stays a yes (re-asking would
531
+ // silently reset a decision the user already made), but it is never widened
532
+ // silently. Only reached with source "config", which already means interactive,
533
+ // not CI, and no env override in play. An opt-out is left completely untouched:
534
+ // no write, no line, no version bump.
535
+ async function ensureTelemetryDisclosureVersion(state) {
536
+ const cfg = state.config;
537
+ if (!cfg?.enabled || state.state !== "on")
538
+ return;
539
+ if (cfg.promptVersion >= TELEMETRY_PROMPT_VERSION)
540
+ return;
541
+ try {
542
+ await saveTelemetryConfig({ ...cfg, promptVersion: TELEMETRY_PROMPT_VERSION });
543
+ }
544
+ catch {
545
+ return;
546
+ }
547
+ process.stderr.write(`${dim(TELEMETRY_DISCLOSURE_LINE)}\n`);
548
+ }
518
549
  function isHelpLikeInvocation() {
519
550
  return currentInvocation.verb === "help"
520
551
  || currentInvocation.verb === "version"
@@ -602,6 +633,17 @@ async function telemetryOff() {
602
633
  promptVersion: TELEMETRY_PROMPT_VERSION,
603
634
  };
604
635
  await saveTelemetryConfig(telemetry);
636
+ // Drop the token watermark with the decision. Keeping it would make a later
637
+ // `telemetry on` report every token processed during the opt-out window as one
638
+ // delta — the seeding rule has to hold across the off/on boundary too.
639
+ try {
640
+ mutateRawConfig((out) => {
641
+ delete out.telemetryTokens;
642
+ });
643
+ }
644
+ catch {
645
+ /* best effort: the decision itself is already persisted */
646
+ }
605
647
  print({ telemetry: "off", anonymous_id: "none" });
606
648
  }
607
649
  function telemetryCommandName() {
@@ -653,6 +695,161 @@ function telemetryAnonymousId(state) {
653
695
  telemetryEphemeralId = randomUUID();
654
696
  return telemetryEphemeralId;
655
697
  }
698
+ // parseProxyStatsPayload pulls the stats object out of caveman-proxy's stdout.
699
+ // The binary points its JSON slog handler at stdout too, so a log line can land
700
+ // ahead of the payload and a plain JSON.parse of the whole stream would throw.
701
+ // Every candidate must carry a numeric tokens_in: without that check a stray log
702
+ // object parses "successfully" as zero tokens, which reads as a rewound store and
703
+ // replays the entire lifetime total as one delta.
704
+ function parseProxyStatsPayload(out) {
705
+ const attempt = (text) => {
706
+ try {
707
+ const parsed = JSON.parse(text);
708
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
709
+ return null;
710
+ const raw = parsed;
711
+ return typeof raw.tokens_in === "number" ? raw : null;
712
+ }
713
+ catch {
714
+ return null;
715
+ }
716
+ };
717
+ const trimmed = out.trim();
718
+ if (!trimmed)
719
+ return null;
720
+ const whole = attempt(trimmed);
721
+ if (whole)
722
+ return whole;
723
+ // Log lines can land on either side of the payload (a deferred Close() error
724
+ // prints after it), so scan candidate object bounds from the end rather than
725
+ // assuming the payload runs to EOF. Bounded: this output is a handful of lines,
726
+ // and the budget keeps a pathological one from costing real time.
727
+ const lines = trimmed.split("\n");
728
+ let budget = 64;
729
+ for (let start = lines.length - 1; start >= 0 && budget > 0; start--) {
730
+ if (!lines[start].startsWith("{"))
731
+ continue;
732
+ for (let end = lines.length; end > start && budget > 0; end--) {
733
+ budget--;
734
+ const candidate = attempt(lines.slice(start, end).join("\n"));
735
+ if (candidate)
736
+ return candidate;
737
+ }
738
+ }
739
+ return null;
740
+ }
741
+ // readProxyTokenTotals reads the local proxy's lifetime token aggregate. Every
742
+ // failure path — no store yet, no proxy binary, slow spawn, unparsable output —
743
+ // returns null and the event simply ships without token fields. Numbers only:
744
+ // `caveman-proxy stats --json` is an aggregate over the requests table, never a
745
+ // row, a prompt, a model name, or a path.
746
+ function readProxyTokenTotals() {
747
+ try {
748
+ const db = process.env.CAVEMAN_DB || join(cavemanHome(), "caveman.db");
749
+ if (!existsSync(db))
750
+ return null;
751
+ const bin = resolveGoBin("caveman-proxy", "CAVEMAN_PROXY_BIN");
752
+ if (!bin)
753
+ return null;
754
+ const out = execFileSync(bin, ["stats", "--json"], {
755
+ encoding: "utf8",
756
+ timeout: TELEMETRY_TOKEN_READ_TIMEOUT_MS,
757
+ stdio: ["ignore", "pipe", "ignore"],
758
+ });
759
+ const parsed = parseProxyStatsPayload(out);
760
+ if (!parsed)
761
+ return null;
762
+ const tokensIn = parsed.tokens_in;
763
+ const tokensSaved = typeof parsed.compression_tokens_saved === "number" ? parsed.compression_tokens_saved : 0;
764
+ if (!Number.isFinite(tokensIn) || !Number.isFinite(tokensSaved))
765
+ return null;
766
+ // Basis rides along because these are tokenizer estimates, not billed counts;
767
+ // the receiving side must never promote them to verified savings.
768
+ const basis = typeof parsed.basis === "string" && parsed.basis ? parsed.basis : "inferred";
769
+ return {
770
+ tokensIn: Math.max(0, Math.trunc(tokensIn)),
771
+ tokensSaved: Math.max(0, Math.trunc(tokensSaved)),
772
+ basis,
773
+ };
774
+ }
775
+ catch {
776
+ return null;
777
+ }
778
+ }
779
+ function parseTelemetryTokenWatermark(value) {
780
+ if (!value || typeof value !== "object" || Array.isArray(value))
781
+ return null;
782
+ const raw = value;
783
+ if (typeof raw.tokensIn !== "number" || typeof raw.tokensSaved !== "number")
784
+ return null;
785
+ if (!Number.isFinite(raw.tokensIn) || !Number.isFinite(raw.tokensSaved))
786
+ return null;
787
+ return {
788
+ tokensIn: Math.max(0, Math.trunc(raw.tokensIn)),
789
+ tokensSaved: Math.max(0, Math.trunc(raw.tokensSaved)),
790
+ at: typeof raw.at === "string" ? raw.at : "",
791
+ };
792
+ }
793
+ function telemetryTokenWatermarkFromDisk() {
794
+ try {
795
+ const parsed = JSON.parse(readFileSync(configPath(), "utf8"));
796
+ return parseTelemetryTokenWatermark(parsed.telemetryTokens);
797
+ }
798
+ catch {
799
+ return null;
800
+ }
801
+ }
802
+ // telemetryTokenDelta returns what to report for THIS event and advances the
803
+ // watermark to the totals it read. The send is fire-and-forget, so a dropped POST
804
+ // loses that delta rather than replaying it — undercounting beats double-counting
805
+ // a savings number.
806
+ //
807
+ // Two cases report nothing and only re-baseline. The first read on a machine
808
+ // seeds the watermark: the store can already hold traffic from before the user
809
+ // saw this disclosure, and telemetry starts at consent rather than reaching
810
+ // backwards through history. A store that rewound (db deleted, restored backup)
811
+ // re-baselines for the same reason — never a negative, never a second copy of
812
+ // history.
813
+ function telemetryTokenDelta() {
814
+ const totals = readProxyTokenTotals();
815
+ if (!totals)
816
+ return null;
817
+ const prior = telemetryTokenWatermarkFromDisk();
818
+ const rewound = prior !== null && (totals.tokensIn < prior.tokensIn || totals.tokensSaved < prior.tokensSaved);
819
+ const processed = prior && !rewound ? Math.max(0, totals.tokensIn - prior.tokensIn) : 0;
820
+ const saved = prior && !rewound ? Math.max(0, totals.tokensSaved - prior.tokensSaved) : 0;
821
+ const rebaselining = prior === null || rewound;
822
+ if (processed === 0 && saved === 0 && !rebaselining)
823
+ return null;
824
+ // Claim the delta optimistically: two CLI processes exiting together would
825
+ // otherwise read the same watermark and both report the same tokens, inflating
826
+ // a savings figure. Whoever writes second sees the watermark already moved and
827
+ // reports nothing.
828
+ let claimed = true;
829
+ try {
830
+ mutateRawConfig((out) => {
831
+ const current = parseTelemetryTokenWatermark(out.telemetryTokens);
832
+ if (current?.tokensIn !== prior?.tokensIn || current?.tokensSaved !== prior?.tokensSaved) {
833
+ claimed = false;
834
+ return;
835
+ }
836
+ out.telemetryTokens = {
837
+ tokensIn: totals.tokensIn,
838
+ tokensSaved: totals.tokensSaved,
839
+ at: new Date().toISOString(),
840
+ };
841
+ });
842
+ }
843
+ catch {
844
+ // Read-only home: report nothing rather than resend the same delta forever.
845
+ return null;
846
+ }
847
+ if (!claimed)
848
+ return null;
849
+ if (processed === 0 && saved === 0)
850
+ return null;
851
+ return { processed, saved, basis: totals.basis };
852
+ }
656
853
  function emitCommandRunOnce(exitClass, errorClass) {
657
854
  const event = commandRunEventOnce(exitClass, errorClass);
658
855
  return event ? emitTelemetryEvents([event]) : Promise.resolve();
@@ -685,6 +882,14 @@ function commandRunEventOnce(exitClass, errorClass) {
685
882
  event.agent = agent;
686
883
  if (exitClass === "error")
687
884
  event.error_class = errorClass ?? "other";
885
+ // Token volume rides on command_run only — runtime_bootstrap shares the same
886
+ // watermark and would race it into a double count.
887
+ const tokens = telemetryTokenDelta();
888
+ if (tokens) {
889
+ event.tokens_processed = tokens.processed;
890
+ event.tokens_saved = tokens.saved;
891
+ event.tokens_basis = tokens.basis;
892
+ }
688
893
  return event;
689
894
  }
690
895
  function emitConsentGranted(anonymousId) {
@@ -815,7 +1020,7 @@ function exploreUsage() {
815
1020
  function guardExploreAgent(agent) {
816
1021
  if (agent === "claude")
817
1022
  return;
818
- console.error(`caveman explore: only --agent claude is wired today (codex needs verified transcript isolation first — see docs/FASTCONTEXT_EXPLORER_SPEC.md). got: ${agent}`);
1023
+ console.error(`caveman explore: only --agent claude is wired today (codex needs verified transcript isolation first). got: ${agent}`);
819
1024
  process.exit(2);
820
1025
  }
821
1026
  // Unprinted compatibility alias. Canonical surface is:
@@ -1710,7 +1915,7 @@ async function start(argv = []) {
1710
1915
  if (!resolved)
1711
1916
  return startMissingProxyUI(bin, options);
1712
1917
  // `caveman start` is the sibling entry point to `caveman wrap`, so it resolves the
1713
- // SAME mode decision. Per ADR 0031 there is no account condition in it — the
1918
+ // SAME mode decision. There is no account condition in it — the
1714
1919
  // entitlement read is a label, not a permission. The mode this proxy actually runs
1715
1920
  // is CAVEMAN_MODE (the proxy itself falls back to record for anything unknown), so
1716
1921
  // a plain `caveman start` resolves to record; record never mutates bytes anyway.
@@ -1737,7 +1942,7 @@ async function start(argv = []) {
1737
1942
  };
1738
1943
  if (options.config)
1739
1944
  env.CAVEMAN_CONFIG = options.config;
1740
- // The account gate is gone (ADR 0031) and so is the variable that carried it. Strip
1945
+ // The account gate is gone and so is the variable that carried it. Strip
1741
1946
  // any inherited copy so a stray export can never re-enter the contract; a proxy
1742
1947
  // binary old enough to still read it is already reported by the stale-binary state.
1743
1948
  delete env.CAVEMAN_WRAP_ENTITLED;
@@ -2999,7 +3204,7 @@ const WRAP_GRACE_MS = 7 * 24 * 60 * 60 * 1000;
2999
3204
  // status prints every active row in OFF_STATE_PRECEDENCE order.
3000
3205
  //
3001
3206
  // Every row here is a TECHNICAL reason compression is off or degraded. Account
3002
- // state is NOT one of them (ADR 0031): being signed out, seat-walled, denied, or
3207
+ // state is NOT one of them: being signed out, seat-walled, denied, or
3003
3208
  // lapsed never turns local compression off, so none of those may appear here.
3004
3209
  const MCP_MARKER_ONLY_LINE = "MCP surface marker-only by your config — the engine MCP tools are not injected; streaming turns and Claude Pro/Max sessions pass through uncompressed (non-streaming API-key traffic still compresses)";
3005
3210
  export const OFF_STATES = {
@@ -3144,7 +3349,7 @@ function printRunBanner(options) {
3144
3349
  }
3145
3350
  // resolveWrapGate is the PURE mode decision (no IO) so it is unit-testable.
3146
3351
  // `requestedMode` is what the user asked for; the returned `mode` is what the local
3147
- // proxy actually runs. Per ADR 0031 the ENTITLEMENT NEVER CHANGES THE MODE — it only
3352
+ // proxy actually runs. The ENTITLEMENT NEVER CHANGES THE MODE — it only
3148
3353
  // labels the account state for the messaging layer:
3149
3354
  // - user asked for plain record (--off): stays plain record. `record` mode is
3150
3355
  // always pass-through, so this is the one thing that withholds compression here.
@@ -3171,7 +3376,7 @@ export function resolveWrapGate(entitlement, now, requestedMode) {
3171
3376
  return { mode: requestedMode, estimate: false, reason: "unentitled" };
3172
3377
  }
3173
3378
  // subscriptionCompressEnabled is the PURE decision behind subscription/OAuth
3174
- // coding-agent compression (Claude Pro/Max, Codex ChatGPT, …). Per ADR 0031 there
3379
+ // coding-agent compression (Claude Pro/Max, Codex ChatGPT, …). There
3175
3380
  // is NO account condition here — a Caveman entitlement is irrelevant. It is on:
3176
3381
  // - LOCALLY — this is the local wrap only; the managed gateway's lossless+stealth
3177
3382
  // rule for non-PAYG traffic is unchanged and is not configured from here;
@@ -3307,7 +3512,7 @@ function planLabel(plan) {
3307
3512
  return "Enterprise";
3308
3513
  }
3309
3514
  }
3310
- // planWeeklyAllowanceText mirrors cloud/web/lib/plan.ts PLAN_WEEKLY_ALLOWANCE — the
3515
+ // planWeeklyAllowanceText mirrors the web dashboard's weekly-allowance display — the
3311
3516
  // parenthetical shows only for the capped tiers (free 5M / indie 50M).
3312
3517
  function planWeeklyAllowanceText(plan) {
3313
3518
  if (plan === "free")
@@ -3367,7 +3572,7 @@ async function requestWrapEntitlement(baseURL, accessToken, wrappedRun = false)
3367
3572
  }
3368
3573
  // fetchAndStoreWrapEntitlement runs the login-time handshake. Login itself NEVER
3369
3574
  // fails for seats or a down entitlement service — and never for compression, which
3370
- // does not depend on it (ADR 0031). The worst case is no cloud sync.
3575
+ // does not depend on it. The worst case is no cloud sync.
3371
3576
  async function fetchAndStoreWrapEntitlement(baseURL, accessToken) {
3372
3577
  const result = await requestWrapEntitlement(baseURL, accessToken);
3373
3578
  switch (result.kind) {
@@ -3421,7 +3626,9 @@ function printSeatWall(body) {
3421
3626
  }
3422
3627
  // refreshWrapEntitlementInBackground silently re-fetches during offline grace so a
3423
3628
  // renewed plan lifts the notice next session. Fire-and-forget; failure stays in
3424
- // grace. On 401 it rotates through the CLI's refresh-token path, then retries once.
3629
+ // grace. Socket is explicitly unrefed so a stalled control plane cannot hold a
3630
+ // completed wrapped agent process open. A 401 is left for foreground auth paths
3631
+ // to refresh; credential rotation must not become hidden post-run work.
3425
3632
  function isoWeekKey(now = new Date()) {
3426
3633
  const d = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
3427
3634
  const day = d.getUTCDay() || 7;
@@ -3439,6 +3646,45 @@ function claimWeeklyRunRefresh(now = new Date()) {
3439
3646
  });
3440
3647
  return claimed;
3441
3648
  }
3649
+ function backgroundPostJSON(urlString, token, body) {
3650
+ return new Promise((resolve, reject) => {
3651
+ const url = new URL(urlString);
3652
+ const request = (url.protocol === "https:" ? httpsRequest : httpRequest)(url, {
3653
+ method: "POST",
3654
+ headers: {
3655
+ authorization: `Bearer ${token}`,
3656
+ "content-type": "application/json",
3657
+ "content-length": Buffer.byteLength(body),
3658
+ "x-cave-csrf": "cli",
3659
+ },
3660
+ }, (response) => {
3661
+ response.socket?.unref();
3662
+ const chunks = [];
3663
+ let bytes = 0;
3664
+ response.on("data", (chunk) => {
3665
+ bytes += chunk.length;
3666
+ if (bytes > 1 << 20) {
3667
+ request.destroy(new Error("wrap entitlement response exceeds 1 MiB"));
3668
+ return;
3669
+ }
3670
+ chunks.push(chunk);
3671
+ });
3672
+ response.on("end", () => {
3673
+ let parsed = null;
3674
+ try {
3675
+ parsed = JSON.parse(Buffer.concat(chunks).toString("utf8"));
3676
+ }
3677
+ catch { /* invalid response stays null */ }
3678
+ const status = response.statusCode ?? 0;
3679
+ resolve({ ok: status >= 200 && status < 300, status, body: parsed });
3680
+ });
3681
+ });
3682
+ request.on("socket", (socket) => socket.unref());
3683
+ request.on("error", reject);
3684
+ request.setTimeout(5000, () => request.destroy(new Error("wrap entitlement refresh timed out")));
3685
+ request.end(body);
3686
+ });
3687
+ }
3442
3688
  function refreshWrapEntitlementInBackground(options = {}) {
3443
3689
  if (wrapExternalWritesDisabled())
3444
3690
  return;
@@ -3447,7 +3693,7 @@ function refreshWrapEntitlementInBackground(options = {}) {
3447
3693
  return;
3448
3694
  void (async () => {
3449
3695
  try {
3450
- let cfg = await config();
3696
+ const cfg = await config();
3451
3697
  if (!cfg.token)
3452
3698
  return;
3453
3699
  const deviceId = ensureDeviceId();
@@ -3456,25 +3702,14 @@ function refreshWrapEntitlementInBackground(options = {}) {
3456
3702
  device_name: hostname(),
3457
3703
  ...(wrappedRun ? { wrapped_run: true } : {}),
3458
3704
  });
3459
- const doPost = (tok) => fetch(`${cfg.baseURL}/api/v1/me/wrap-entitlement`, {
3460
- method: "POST",
3461
- headers: { authorization: `Bearer ${tok}`, "content-type": "application/json", "x-cave-csrf": "cli" },
3462
- body,
3463
- signal: AbortSignal.timeout(5000),
3464
- });
3465
- let resp = await doPost(cfg.token);
3466
- if (resp.status === 401 && cfg.refreshToken) {
3467
- cfg = await refreshCLIConfig(cfg);
3468
- if (cfg.token)
3469
- resp = await doPost(cfg.token);
3470
- }
3705
+ const resp = await backgroundPostJSON(`${cfg.baseURL}/api/v1/me/wrap-entitlement`, cfg.token, body);
3471
3706
  if (!resp.ok) {
3472
3707
  mutateRawConfig((out) => {
3473
3708
  out.wrapEntitlementRefresh = { at: new Date().toISOString(), ok: false };
3474
3709
  });
3475
3710
  return;
3476
3711
  }
3477
- const ent = await resp.json().catch(() => null);
3712
+ const ent = resp.body;
3478
3713
  if (parseWrapEntitlement(ent)) {
3479
3714
  saveWrapEntitlement(ent);
3480
3715
  mutateRawConfig((out) => {
@@ -4274,6 +4509,107 @@ function normalizeAgentShortcutWrapArgs(input) {
4274
4509
  }
4275
4510
  return [...wrapFlags, agent, ...agentArgs];
4276
4511
  }
4512
+ // Aider is deliberately absent: it has no lifecycle hooks, so nothing on the
4513
+ // native path would ever start the proxy or apply routedAiderArgs — a direct
4514
+ // launch would point it at a dead endpoint. Aider keeps the wrap door.
4515
+ function nativeAgentId(id) {
4516
+ return id === "claude" || id === "codex" || id === "hermes" || id === "gemini" || id === "opencode" ? id : undefined;
4517
+ }
4518
+ // `caveman <agent>` — the default door. It persistently enables the native
4519
+ // integration (the same journaled user-scoped writes as `caveman enable <agent>`)
4520
+ // and then launches the host binary untouched: routing, Core, and proxy
4521
+ // autostart all live in the installed hooks, so plain `<agent>` stays caveman'd
4522
+ // in every later session too. Wrap-session flags, unsupported agents, or any
4523
+ // enable failure fall back to the ephemeral `wrap` door — the shortcut is
4524
+ // never worse than a session-only wrap.
4525
+ async function agentShortcut(rest) {
4526
+ // normalizeAgentShortcutWrapArgs hoists --off/--pixel/--workflow to the
4527
+ // front, so a leading flag means explicit session-only wrap intent.
4528
+ if (rest[0]?.startsWith("--"))
4529
+ return wrap(rest);
4530
+ const agent = findAgent(rest[0] ?? "");
4531
+ const native = agent ? nativeAgentId(agent.id) : undefined;
4532
+ if (!agent || !native)
4533
+ return wrap(rest);
4534
+ // A Cave Build lock is enforced at the wrap door (claudeCaveBuildEnv); the
4535
+ // native door applies none of its transforms, so a locked project must keep
4536
+ // routing through wrap or the lock would be silently unenforced.
4537
+ if (existsSync(join(process.cwd(), ".caveman", "agent.lock.json")))
4538
+ return wrap(rest);
4539
+ // First-run disclosure comes before the first persistent write, mirroring wrap.
4540
+ await firstRunExperience();
4541
+ try {
4542
+ // An existing journal means the machine-wide install already owns routing —
4543
+ // exactly what plain `<agent>` uses — so launch directly without re-probing
4544
+ // (status probes spawn three subprocesses); `caveman doctor <agent>` stays
4545
+ // the repair door for drifted installs.
4546
+ if (!readNativeJournal(native))
4547
+ enableNative([native]);
4548
+ }
4549
+ catch (error) {
4550
+ process.stderr.write(`${mark("warn")} native enable failed: ${error.message} — using session-only wrap for this run\n`);
4551
+ return wrap(rest);
4552
+ }
4553
+ const bin = which(binOf(agent));
4554
+ if (!bin) {
4555
+ wrapNotFoundUI(rest[0], agent);
4556
+ await emitCommandRunOnce("error", "usage");
4557
+ process.exit(127);
4558
+ }
4559
+ // The native SessionStart hook autostarts the proxy, but only after the host
4560
+ // has approved the installed hooks — start it here too so the first routed
4561
+ // request never hits a dead endpoint. Fail-open, same as the hook.
4562
+ try {
4563
+ const opts = defaultWrapOptions();
4564
+ const gw = gatewayURL();
4565
+ const { host, port } = gatewayHostPort(gw);
4566
+ if (wrapMode(gw) === "local" && !opts.noProxy && !(await portListening(host, port))) {
4567
+ const subscription = native === "codex" && detectCodexWrapAuthMode() === "subscription";
4568
+ const mode = subscription && opts.mode === "pixel" ? "record" : opts.mode;
4569
+ const recovery = Boolean(probeMcpBinary()?.probe.current);
4570
+ await startWrapProxy(mode, recovery, subscription ? false : opts.toon, opts.pixelModels, opts.pixelDensity, gw, subscription ? "codex-subscription" : "standard", false);
4571
+ }
4572
+ }
4573
+ catch { /* runtime startup is fail-open; the native hook retries at SessionStart */ }
4574
+ if (native === "hermes")
4575
+ maybeWarnHermesMissingKey(agent, gatewayURL());
4576
+ const code = await new Promise((resolve, reject) => {
4577
+ const invocation = portableInvocation(bin, [...agent.args, ...rest.slice(1)]);
4578
+ const child = spawn(invocation.command, invocation.args, { stdio: "inherit" });
4579
+ // tty-generated signals (Ctrl+C / Ctrl+\) already reach the child through
4580
+ // the shared foreground group — forwarding would double-deliver them. But
4581
+ // process-directed SIGTERM/SIGHUP (timeout(1), supervisors, pkill) only hit
4582
+ // this launcher, so those must be forwarded. Either way the launcher
4583
+ // re-raises on itself after the child exits so callers see a signal death,
4584
+ // not a clean exit.
4585
+ let fatal;
4586
+ for (const signal of ["SIGINT", "SIGQUIT"]) {
4587
+ process.on(signal, () => { fatal = signal; /* the tty delivered it to the child already */ });
4588
+ }
4589
+ for (const signal of ["SIGHUP", "SIGTERM"]) {
4590
+ process.on(signal, () => {
4591
+ fatal = signal;
4592
+ child.kill(signal);
4593
+ const grace = setTimeout(() => child.kill("SIGKILL"), 10_000);
4594
+ grace.unref();
4595
+ });
4596
+ }
4597
+ child.on("error", (error) => reject(new Error(`failed to exec ${bin}: ${error.message}`)));
4598
+ child.on("exit", (exitCode, signal) => {
4599
+ if (fatal) {
4600
+ process.removeAllListeners(fatal);
4601
+ process.kill(process.pid, fatal);
4602
+ return;
4603
+ }
4604
+ resolve(exitCode ?? signalExitCode(signal));
4605
+ });
4606
+ });
4607
+ const exitClass = code === 0 ? "ok" : "error";
4608
+ const event = commandRunEventOnce(exitClass, exitClass === "error" ? "other" : undefined);
4609
+ if (event)
4610
+ await emitTelemetryEvents([event]);
4611
+ process.exit(code);
4612
+ }
4277
4613
  // runWrapped execs the resolved command with the gateway injection applied. It
4278
4614
  // auto-starts the local proxy when routing to loopback, so `caveman wrap claude`
4279
4615
  // is the one-command compression path. If the proxy can't be reached, a TTY run
@@ -4354,7 +4690,7 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = f
4354
4690
  if (managedGeminiUnsupported) {
4355
4691
  process.stderr.write("caveman: managed Gemini CLI wrap is unsupported because Gemini CLI cannot send separate Caveman and upstream credentials; launching directly\n");
4356
4692
  }
4357
- // ADR 0031: the local proxy compresses with no account. When wrap runs the LOCAL
4693
+ // The local proxy compresses with no account. When wrap runs the LOCAL
4358
4694
  // proxy path we resolve the mode; managed gateway traffic is governed by the cloud
4359
4695
  // policy engine, so we never resolve it here.
4360
4696
  const gateApplies = local && !opts.noProxy;
@@ -4833,13 +5169,13 @@ async function startWrapProxy(mode, mcpRecovery, toon, pixelModels, pixelDensity
4833
5169
  // Observe-only estimate: record mode measures would-have-saved tokens without
4834
5170
  // ever mutating the forwarded request.
4835
5171
  ...(observeEstimate ? { CAVEMAN_OBSERVE_ESTIMATE: "1" } : {}),
4836
- // Nothing else is stamped for subscription/OAuth compression: per ADR 0031 it
5172
+ // Nothing else is stamped for subscription/OAuth compression: it
4837
5173
  // has no account condition. The operator off-switch (`subscription_compress:
4838
5174
  // off`) stays the operator's — we never override it from here.
4839
5175
  };
4840
5176
  // Same reason as `start`: the dead account variable never rides along inherited.
4841
5177
  delete env.CAVEMAN_WRAP_ENTITLED;
4842
- const child = spawn(resolved, [], { stdio: "ignore", env, detached: true });
5178
+ const child = spawn(resolved, [], { stdio: "ignore", env, detached: true, windowsHide: true });
4843
5179
  child.unref();
4844
5180
  for (let i = 0; i < 20; i++) {
4845
5181
  await sleep(100);
@@ -5289,6 +5625,31 @@ function readJsonObject(path) {
5289
5625
  return {};
5290
5626
  }
5291
5627
  }
5628
+ export function normalizeHookPath(path, platform = process.platform) {
5629
+ return platform === "win32" ? path.replace(/\\/g, "/") : path;
5630
+ }
5631
+ export function quoteHookPath(path, platform = process.platform) {
5632
+ const normalized = normalizeHookPath(path, platform);
5633
+ if (platform === "win32")
5634
+ return `'${normalized.replace(/'/g, "''")}'`;
5635
+ return `'${normalized.replace(/'/g, `'"'"'`)}'`;
5636
+ }
5637
+ export function nativeHookInvocation(executable, fastHook, agentId, executableIsProxy, platform = process.platform) {
5638
+ const executableInvocation = hookExecutableInvocation(executable, executableIsProxy ? undefined : fastHook, platform);
5639
+ const invocation = executableIsProxy
5640
+ ? `${executableInvocation} native-hook ${agentId} --adapter ${quoteHookPath(fastHook, platform)}`
5641
+ : `${executableInvocation} native-hook ${agentId}`;
5642
+ return invocation;
5643
+ }
5644
+ export function hookExecutableInvocation(executable, script, platform = process.platform) {
5645
+ const invocation = script
5646
+ ? `${quoteHookPath(executable, platform)} ${quoteHookPath(script, platform)}`
5647
+ : quoteHookPath(executable, platform);
5648
+ // Claude/Codex/Gemini dispatch command hooks through PowerShell on native
5649
+ // Windows. A quoted executable is only a string literal there; `&` is the
5650
+ // required invocation operator. POSIX hook commands keep their exact shape.
5651
+ return platform === "win32" ? `& ${invocation}` : invocation;
5652
+ }
5292
5653
  function nativeHookCommand(agentId) {
5293
5654
  const fastHook = join(dirname(fileURLToPath(import.meta.url)), "native-hook-fast.js");
5294
5655
  const explicitProxy = process.env.CAVEMAN_PROXY_BIN;
@@ -5296,10 +5657,10 @@ function nativeHookCommand(agentId) {
5296
5657
  const proxy = explicitProxy || which("caveman-proxy") || (isExecutable(localProxy) ? localProxy : undefined);
5297
5658
  const bridgeCurrent = proxy ? probeVersionedBinary(proxy, "native_hook_bridge_v1").current : false;
5298
5659
  if (proxy && bridgeCurrent && existsSync(fastHook)) {
5299
- return `${JSON.stringify(proxy)} native-hook ${agentId} --adapter ${JSON.stringify(fastHook)}`;
5660
+ return nativeHookInvocation(proxy, fastHook, agentId, true);
5300
5661
  }
5301
5662
  if (existsSync(fastHook)) {
5302
- return `${JSON.stringify(process.execPath)} ${JSON.stringify(fastHook)} native-hook ${agentId}`;
5663
+ return nativeHookInvocation(process.execPath, fastHook, agentId, false);
5303
5664
  }
5304
5665
  return `${cavemanBinForHook()} native-hook ${agentId}`;
5305
5666
  }
@@ -7798,7 +8159,7 @@ function openLoginBrowser(url) {
7798
8159
  process.stderr.write(` browser opener unavailable; open ${url}\n`);
7799
8160
  return;
7800
8161
  }
7801
- const child = spawn(opener.command, opener.args, { detached: true, stdio: "ignore" });
8162
+ const child = spawn(opener.command, opener.args, { detached: true, stdio: "ignore", windowsHide: true });
7802
8163
  child.once("error", () => process.stderr.write(` browser did not open; open ${url}\n`));
7803
8164
  child.unref();
7804
8165
  }
@@ -7939,7 +8300,7 @@ async function login(argv = []) {
7939
8300
  // until the control plane has recorded that this CLI stored the bundle.
7940
8301
  await acknowledgeDeviceGrant(baseURL, credentials.access_token, code.device_code, ackToken);
7941
8302
  }
7942
- // Mint/refresh the local-wrap entitlement for this device (ADR 0022). Best
8303
+ // Mint/refresh the local-wrap entitlement for this device. Best
7943
8304
  // effort: login never fails for seats or a down entitlement service.
7944
8305
  await fetchAndStoreWrapEntitlement(baseURL, credentials.access_token);
7945
8306
  if (gateway && wrapMode(gateway) === "managed") {
@@ -9694,7 +10055,10 @@ function shouldShrink(command) {
9694
10055
  // cavemanBinForHook is the invocation a Claude hook uses to call back into this
9695
10056
  // CLI, robust to PATH: a resolved `caveman`/`cave`, else this very script's node.
9696
10057
  function cavemanBinForHook() {
9697
- return which("caveman") ?? which("cave") ?? `${process.execPath} ${process.argv[1]}`;
10058
+ const command = which("caveman") ?? which("cave");
10059
+ return command
10060
+ ? hookExecutableInvocation(command, undefined)
10061
+ : hookExecutableInvocation(process.execPath, process.argv[1]);
9698
10062
  }
9699
10063
  // shrinkHook is the settings-hook callback for the agents whose harness can
9700
10064
  // deterministically rewrite a shell command before it runs: Claude Code (PreToolUse,
@@ -10981,11 +11345,15 @@ function opencodePluginPath() {
10981
11345
  // cavemanInvocation returns how to call back into THIS CLI from a generated plugin,
10982
11346
  // baked at install time so it is independent of the agent's PATH: a resolved
10983
11347
  // caveman/cave binary, else this script under node.
11348
+ export function generatedPluginInvocation(onPath, currentScript, platform = process.platform) {
11349
+ if (onPath) {
11350
+ const invocation = portableInvocation(onPath, [], platform);
11351
+ return { cmd: invocation.command, pre: invocation.args };
11352
+ }
11353
+ return { cmd: process.execPath, pre: [currentScript] };
11354
+ }
10984
11355
  function cavemanInvocation() {
10985
- const onPath = which("caveman") ?? which("cave");
10986
- if (onPath)
10987
- return { cmd: onPath, pre: [] };
10988
- return { cmd: process.execPath, pre: [process.argv[1] ?? ""] };
11356
+ return generatedPluginInvocation(which("caveman") ?? which("cave") ?? undefined, process.argv[1] ?? "");
10989
11357
  }
10990
11358
  function opencodePluginSource() {
10991
11359
  const { cmd, pre } = cavemanInvocation();
@@ -11409,7 +11777,7 @@ function hooksUsage() {
11409
11777
  }
11410
11778
  // hooksDirectiveCmd handles `caveman hooks install|uninstall --directive <id> [agent]`
11411
11779
  // (AUTOPILOT_SPEC §7.3): the same verb surface that removes a shrink note today,
11412
- // extended with a flag — never a new porcelain verb (ADR 0024 cap). Install
11780
+ // extended with a flag — never a new porcelain verb (capped). Install
11413
11781
  // announces itself and prints the undo command (§7 announce+undo).
11414
11782
  function hooksDirectiveCmd(sub, directiveId, target) {
11415
11783
  // Object.hasOwn: directiveId is user input; a truthiness read would let
@@ -11474,7 +11842,7 @@ function hooksDirectiveCmd(sub, directiveId, target) {
11474
11842
  }
11475
11843
  function hooksCmd(rest) {
11476
11844
  // --directive <id> (or --directive=<id>) routes to the wrap-directive
11477
- // surface (same verb, no new porcelain — ADR 0024). Any OTHER --flag is
11845
+ // surface (same verb, no new porcelain). Any OTHER --flag is
11478
11846
  // rejected loudly: silently ignoring `--directive=x` used to install the
11479
11847
  // shrink note and exit 0 while the user believed a directive was installed
11480
11848
  // (review C8).
@@ -12119,7 +12487,7 @@ function openLearnReport(report) {
12119
12487
  process.stderr.write(`cannot open visual report; open this file: ${report}\n`);
12120
12488
  return;
12121
12489
  }
12122
- const child = spawn(opener.command, opener.args, { detached: true, stdio: "ignore" });
12490
+ const child = spawn(opener.command, opener.args, { detached: true, stdio: "ignore", windowsHide: true });
12123
12491
  child.once("error", () => {
12124
12492
  process.stderr.write(`cannot open visual report; open this file: ${report}\n`);
12125
12493
  });
@@ -12740,8 +13108,8 @@ function proxyRuntimeMatches(runtime, mode, recoveryViaMCP) {
12740
13108
  && runtime.mode === mode
12741
13109
  && proxyRuntimeGateMatches(runtime, recoveryViaMCP);
12742
13110
  }
12743
- // The only cross-session gate input left is the recovery contract (ADR 0031 removed
12744
- // the account one): reusing a proxy that lacks the agent's caveman_retrieve tool
13111
+ // The only cross-session gate input left is the recovery contract (the account
13112
+ // one was removed): reusing a proxy that lacks the agent's caveman_retrieve tool
12745
13113
  // would elide bytes nothing can expand.
12746
13114
  function proxyRuntimeGateMatches(runtime, recoveryViaMCP) {
12747
13115
  return runtime.recovery_via_mcp === recoveryViaMCP;
@@ -14645,10 +15013,14 @@ export function commandHasPath(command) {
14645
15013
  export function executableCandidateNames(command, platform = process.platform, pathExt = process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD") {
14646
15014
  if (platform !== "win32" || extname(command))
14647
15015
  return [command];
14648
- const candidates = [command];
15016
+ const candidates = [];
14649
15017
  for (const extension of pathExt.split(";").map((value) => value.trim()).filter(Boolean)) {
14650
15018
  candidates.push(`${command}${extension.startsWith(".") ? extension : `.${extension}`}`);
14651
15019
  }
15020
+ // Windows cannot launch extensionless POSIX npm shims without a shell. Keep
15021
+ // the bare name as a fallback for real extensionless executables, but prefer
15022
+ // native executables and cmd/bat shims from PATHEXT.
15023
+ candidates.push(command);
14652
15024
  const seen = new Set();
14653
15025
  return candidates.filter((candidate) => {
14654
15026
  const key = candidate.toLowerCase();
@@ -1,4 +1,4 @@
1
- // GENERATED by public/skills/compile.mjs from native-core.md + native SKILL.md files — DO NOT EDIT.
1
+ // GENERATED by skills/compile.mjs from native-core.md + native SKILL.md files — DO NOT EDIT.
2
2
  export const NATIVE_PACK = {
3
3
  "schema": "caveman.native-pack.v1",
4
4
  "id": "caveman-local",
@@ -1,4 +1,4 @@
1
- // GENERATED by public/integrations/compile.mjs from public/integrations/recipes/*.json — DO NOT EDIT.
1
+ // GENERATED by integrations/compile.mjs from integrations/recipes/*.json — DO NOT EDIT.
2
2
  // Run `node scripts/compile-registries.mjs` (wired into the CLI build/test) to regenerate.
3
3
  export const RECIPES = [
4
4
  {
@@ -1,4 +1,4 @@
1
- // GENERATED by public/agents/compile.mjs from public/agents/reserved-verbs.json — DO NOT EDIT.
1
+ // GENERATED by agents/compile.mjs from agents/reserved-verbs.json — DO NOT EDIT.
2
2
  // Run `node scripts/compile-registries.mjs` (wired into CLI build/test) to regenerate.
3
3
  export const RESERVED_VERBS = new Set([
4
4
  "--help",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@caveman-ai/cli",
3
- "version": "1.1.0",
3
+ "version": "1.2.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": "MIT",
6
6
  "type": "module",