@caveman-ai/cli 1.0.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 +1 -2
- package/dist/agent-skills.generated.js +2 -2
- package/dist/agents.generated.js +1 -1
- package/dist/binaries.generated.js +1 -1
- package/dist/caveman-delegate-mcp.mjs +1 -2
- package/dist/index.js +514 -57
- package/dist/native-pack.generated.js +1 -1
- package/dist/recipes.generated.js +1 -1
- package/dist/reserved-verbs.generated.js +1 -1
- package/package.json +6 -2
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
|
|
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",
|
package/dist/agents.generated.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// GENERATED by
|
|
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.
|
|
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
|
|
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: "
|
|
332
|
+
verb: "run",
|
|
331
333
|
argv: normalizeAgentShortcutWrapArgs(raw),
|
|
332
|
-
handler:
|
|
334
|
+
handler: agentShortcut,
|
|
333
335
|
agent,
|
|
334
336
|
};
|
|
335
337
|
return { verb: top, argv: raw.slice(1), handler: () => unknownInvocation(top) };
|
|
@@ -380,13 +382,22 @@ function invokedCommand(legacyVerb, groupedTail = "") {
|
|
|
380
382
|
}
|
|
381
383
|
let currentInvocation;
|
|
382
384
|
currentInvocation = resolveInvocation(process.argv.slice(2));
|
|
383
|
-
// Version
|
|
384
|
-
//
|
|
385
|
-
|
|
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
|
|
390
|
+
// undecided gap, and the first default-on run prints the disclosure line.
|
|
391
|
+
const TELEMETRY_PROMPT_VERSION = 4;
|
|
386
392
|
const TELEMETRY_URL = "https://api.caveman.so/telemetry/cli";
|
|
387
393
|
// The production control-API origin — derived from TELEMETRY_URL (the CLI's
|
|
388
394
|
// other hardcoded prod-host literal) so the two can never drift apart.
|
|
389
395
|
const PROD_API_URL = new URL(TELEMETRY_URL).origin;
|
|
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;
|
|
390
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.";
|
|
391
402
|
const TELEMETRY_COMMAND_ALLOWLIST = [
|
|
392
403
|
"agent", "audit", "billing", "browse", "compress", "convert", "costs", "deploy", "dev", "doctor", "evals", "experiments",
|
|
@@ -404,6 +415,7 @@ const TELEMETRY_START_MS = Date.now();
|
|
|
404
415
|
let telemetryCommandSent = false;
|
|
405
416
|
let telemetryEphemeralId = "";
|
|
406
417
|
async function main() {
|
|
418
|
+
await ensureTelemetryDefault();
|
|
407
419
|
try {
|
|
408
420
|
await dispatch();
|
|
409
421
|
emitCommandRunOnce("ok");
|
|
@@ -432,9 +444,12 @@ function telemetryState() {
|
|
|
432
444
|
const cfg = telemetryConfigFromDisk();
|
|
433
445
|
if (cfg?.decidedAt)
|
|
434
446
|
return { state: cfg.enabled ? "on" : "off", source: "config", config: cfg };
|
|
435
|
-
// No decision on disk: default
|
|
436
|
-
//
|
|
437
|
-
|
|
447
|
+
// No decision on disk: default ON (opt-out); only reachable interactively —
|
|
448
|
+
// the CI/non-TTY branch above already returned off. NOTHING may send while
|
|
449
|
+
// source is still "default": telemetrySendable gates every emitter, so the
|
|
450
|
+
// first real send always follows ensureTelemetryDefault's persist (stable
|
|
451
|
+
// anonymous id) + printed disclosure.
|
|
452
|
+
return { state: "on", source: "default", config: undefined };
|
|
438
453
|
}
|
|
439
454
|
// telemetrySendable is the single choke point every emitter must pass: on, and
|
|
440
455
|
// never the un-persisted default (no silent sends, no ephemeral-id retention
|
|
@@ -476,6 +491,67 @@ function parseTelemetryConfig(value) {
|
|
|
476
491
|
out.anonymousId = raw.anonymousId;
|
|
477
492
|
return out;
|
|
478
493
|
}
|
|
494
|
+
// ensureTelemetryDefault persists the default-on decision (with a stable
|
|
495
|
+
// anonymous id — retention counting is useless on ephemeral ids) the first time
|
|
496
|
+
// a real command runs interactively, and prints the one-line disclosure so the
|
|
497
|
+
// default is never silent. Env kills (DO_NOT_TRACK / CAVEMAN_TELEMETRY=0) and
|
|
498
|
+
// any persisted decision — including a "no" to the old v1 prompt — win.
|
|
499
|
+
async function ensureTelemetryDefault() {
|
|
500
|
+
const state = telemetryState();
|
|
501
|
+
if (isHelpLikeInvocation())
|
|
502
|
+
return;
|
|
503
|
+
// `caveman telemetry …` manages the decision explicitly — don't pre-mint an
|
|
504
|
+
// "on" for someone whose first-ever command is `telemetry off`.
|
|
505
|
+
if (currentInvocation.verb === "telemetry")
|
|
506
|
+
return;
|
|
507
|
+
if (state.source === "config")
|
|
508
|
+
return ensureTelemetryDisclosureVersion(state);
|
|
509
|
+
if (state.source !== "default")
|
|
510
|
+
return;
|
|
511
|
+
const telemetry = {
|
|
512
|
+
enabled: true,
|
|
513
|
+
anonymousId: randomUUID(),
|
|
514
|
+
decidedAt: new Date().toISOString(),
|
|
515
|
+
promptVersion: TELEMETRY_PROMPT_VERSION,
|
|
516
|
+
};
|
|
517
|
+
// A failed persist must never block the command (read-only home, root-owned
|
|
518
|
+
// config). Nothing sends this run either way: source stays "default" until a
|
|
519
|
+
// persist succeeds, and telemetrySendable refuses un-persisted defaults.
|
|
520
|
+
try {
|
|
521
|
+
await saveTelemetryConfig(telemetry);
|
|
522
|
+
}
|
|
523
|
+
catch {
|
|
524
|
+
return;
|
|
525
|
+
}
|
|
526
|
+
process.stderr.write(`${dim(TELEMETRY_DISCLOSURE_LINE)}\n`);
|
|
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
|
+
}
|
|
549
|
+
function isHelpLikeInvocation() {
|
|
550
|
+
return currentInvocation.verb === "help"
|
|
551
|
+
|| currentInvocation.verb === "version"
|
|
552
|
+
|| currentInvocation.argv[0] === "--help"
|
|
553
|
+
|| currentInvocation.argv[0] === "-h";
|
|
554
|
+
}
|
|
479
555
|
// promptYesNo is the one line-buffered [y/N] reader. Ctrl-D / closed stdin
|
|
480
556
|
// resolves as the default No, never hangs the CLI.
|
|
481
557
|
function promptYesNo(question) {
|
|
@@ -557,6 +633,17 @@ async function telemetryOff() {
|
|
|
557
633
|
promptVersion: TELEMETRY_PROMPT_VERSION,
|
|
558
634
|
};
|
|
559
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
|
+
}
|
|
560
647
|
print({ telemetry: "off", anonymous_id: "none" });
|
|
561
648
|
}
|
|
562
649
|
function telemetryCommandName() {
|
|
@@ -608,6 +695,161 @@ function telemetryAnonymousId(state) {
|
|
|
608
695
|
telemetryEphemeralId = randomUUID();
|
|
609
696
|
return telemetryEphemeralId;
|
|
610
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
|
+
}
|
|
611
853
|
function emitCommandRunOnce(exitClass, errorClass) {
|
|
612
854
|
const event = commandRunEventOnce(exitClass, errorClass);
|
|
613
855
|
return event ? emitTelemetryEvents([event]) : Promise.resolve();
|
|
@@ -640,6 +882,14 @@ function commandRunEventOnce(exitClass, errorClass) {
|
|
|
640
882
|
event.agent = agent;
|
|
641
883
|
if (exitClass === "error")
|
|
642
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
|
+
}
|
|
643
893
|
return event;
|
|
644
894
|
}
|
|
645
895
|
function emitConsentGranted(anonymousId) {
|
|
@@ -770,7 +1020,7 @@ function exploreUsage() {
|
|
|
770
1020
|
function guardExploreAgent(agent) {
|
|
771
1021
|
if (agent === "claude")
|
|
772
1022
|
return;
|
|
773
|
-
console.error(`caveman explore: only --agent claude is wired today (codex needs verified transcript isolation first
|
|
1023
|
+
console.error(`caveman explore: only --agent claude is wired today (codex needs verified transcript isolation first). got: ${agent}`);
|
|
774
1024
|
process.exit(2);
|
|
775
1025
|
}
|
|
776
1026
|
// Unprinted compatibility alias. Canonical surface is:
|
|
@@ -1665,7 +1915,7 @@ async function start(argv = []) {
|
|
|
1665
1915
|
if (!resolved)
|
|
1666
1916
|
return startMissingProxyUI(bin, options);
|
|
1667
1917
|
// `caveman start` is the sibling entry point to `caveman wrap`, so it resolves the
|
|
1668
|
-
// SAME mode decision.
|
|
1918
|
+
// SAME mode decision. There is no account condition in it — the
|
|
1669
1919
|
// entitlement read is a label, not a permission. The mode this proxy actually runs
|
|
1670
1920
|
// is CAVEMAN_MODE (the proxy itself falls back to record for anything unknown), so
|
|
1671
1921
|
// a plain `caveman start` resolves to record; record never mutates bytes anyway.
|
|
@@ -1692,7 +1942,7 @@ async function start(argv = []) {
|
|
|
1692
1942
|
};
|
|
1693
1943
|
if (options.config)
|
|
1694
1944
|
env.CAVEMAN_CONFIG = options.config;
|
|
1695
|
-
// The account gate is gone
|
|
1945
|
+
// The account gate is gone and so is the variable that carried it. Strip
|
|
1696
1946
|
// any inherited copy so a stray export can never re-enter the contract; a proxy
|
|
1697
1947
|
// binary old enough to still read it is already reported by the stale-binary state.
|
|
1698
1948
|
delete env.CAVEMAN_WRAP_ENTITLED;
|
|
@@ -2029,8 +2279,8 @@ function printInstallResult(installed, platform, binDir, json, continuing = fals
|
|
|
2029
2279
|
async function setupInstall(json, options = {}) {
|
|
2030
2280
|
const platform = setupPlatform();
|
|
2031
2281
|
const timeoutSeconds = setupTimeoutSeconds();
|
|
2032
|
-
const binDir = join(
|
|
2033
|
-
mkdirSync(binDir, { recursive: true });
|
|
2282
|
+
const binDir = join(ensureCavemanHome(), "bin");
|
|
2283
|
+
mkdirSync(binDir, { recursive: true, mode: 0o700 });
|
|
2034
2284
|
const local = verifiedLocalInstall(binDir);
|
|
2035
2285
|
if (local) {
|
|
2036
2286
|
printInstallResult(local, platform, binDir, json, options.continuing);
|
|
@@ -2954,7 +3204,7 @@ const WRAP_GRACE_MS = 7 * 24 * 60 * 60 * 1000;
|
|
|
2954
3204
|
// status prints every active row in OFF_STATE_PRECEDENCE order.
|
|
2955
3205
|
//
|
|
2956
3206
|
// Every row here is a TECHNICAL reason compression is off or degraded. Account
|
|
2957
|
-
// state is NOT one of them
|
|
3207
|
+
// state is NOT one of them: being signed out, seat-walled, denied, or
|
|
2958
3208
|
// lapsed never turns local compression off, so none of those may appear here.
|
|
2959
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)";
|
|
2960
3210
|
export const OFF_STATES = {
|
|
@@ -3099,7 +3349,7 @@ function printRunBanner(options) {
|
|
|
3099
3349
|
}
|
|
3100
3350
|
// resolveWrapGate is the PURE mode decision (no IO) so it is unit-testable.
|
|
3101
3351
|
// `requestedMode` is what the user asked for; the returned `mode` is what the local
|
|
3102
|
-
// proxy actually runs.
|
|
3352
|
+
// proxy actually runs. The ENTITLEMENT NEVER CHANGES THE MODE — it only
|
|
3103
3353
|
// labels the account state for the messaging layer:
|
|
3104
3354
|
// - user asked for plain record (--off): stays plain record. `record` mode is
|
|
3105
3355
|
// always pass-through, so this is the one thing that withholds compression here.
|
|
@@ -3126,7 +3376,7 @@ export function resolveWrapGate(entitlement, now, requestedMode) {
|
|
|
3126
3376
|
return { mode: requestedMode, estimate: false, reason: "unentitled" };
|
|
3127
3377
|
}
|
|
3128
3378
|
// subscriptionCompressEnabled is the PURE decision behind subscription/OAuth
|
|
3129
|
-
// coding-agent compression (Claude Pro/Max, Codex ChatGPT, …).
|
|
3379
|
+
// coding-agent compression (Claude Pro/Max, Codex ChatGPT, …). There
|
|
3130
3380
|
// is NO account condition here — a Caveman entitlement is irrelevant. It is on:
|
|
3131
3381
|
// - LOCALLY — this is the local wrap only; the managed gateway's lossless+stealth
|
|
3132
3382
|
// rule for non-PAYG traffic is unchanged and is not configured from here;
|
|
@@ -3262,7 +3512,7 @@ function planLabel(plan) {
|
|
|
3262
3512
|
return "Enterprise";
|
|
3263
3513
|
}
|
|
3264
3514
|
}
|
|
3265
|
-
// planWeeklyAllowanceText mirrors
|
|
3515
|
+
// planWeeklyAllowanceText mirrors the web dashboard's weekly-allowance display — the
|
|
3266
3516
|
// parenthetical shows only for the capped tiers (free 5M / indie 50M).
|
|
3267
3517
|
function planWeeklyAllowanceText(plan) {
|
|
3268
3518
|
if (plan === "free")
|
|
@@ -3322,7 +3572,7 @@ async function requestWrapEntitlement(baseURL, accessToken, wrappedRun = false)
|
|
|
3322
3572
|
}
|
|
3323
3573
|
// fetchAndStoreWrapEntitlement runs the login-time handshake. Login itself NEVER
|
|
3324
3574
|
// fails for seats or a down entitlement service — and never for compression, which
|
|
3325
|
-
// does not depend on it
|
|
3575
|
+
// does not depend on it. The worst case is no cloud sync.
|
|
3326
3576
|
async function fetchAndStoreWrapEntitlement(baseURL, accessToken) {
|
|
3327
3577
|
const result = await requestWrapEntitlement(baseURL, accessToken);
|
|
3328
3578
|
switch (result.kind) {
|
|
@@ -3376,7 +3626,9 @@ function printSeatWall(body) {
|
|
|
3376
3626
|
}
|
|
3377
3627
|
// refreshWrapEntitlementInBackground silently re-fetches during offline grace so a
|
|
3378
3628
|
// renewed plan lifts the notice next session. Fire-and-forget; failure stays in
|
|
3379
|
-
// grace.
|
|
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.
|
|
3380
3632
|
function isoWeekKey(now = new Date()) {
|
|
3381
3633
|
const d = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
|
|
3382
3634
|
const day = d.getUTCDay() || 7;
|
|
@@ -3394,6 +3646,45 @@ function claimWeeklyRunRefresh(now = new Date()) {
|
|
|
3394
3646
|
});
|
|
3395
3647
|
return claimed;
|
|
3396
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
|
+
}
|
|
3397
3688
|
function refreshWrapEntitlementInBackground(options = {}) {
|
|
3398
3689
|
if (wrapExternalWritesDisabled())
|
|
3399
3690
|
return;
|
|
@@ -3402,7 +3693,7 @@ function refreshWrapEntitlementInBackground(options = {}) {
|
|
|
3402
3693
|
return;
|
|
3403
3694
|
void (async () => {
|
|
3404
3695
|
try {
|
|
3405
|
-
|
|
3696
|
+
const cfg = await config();
|
|
3406
3697
|
if (!cfg.token)
|
|
3407
3698
|
return;
|
|
3408
3699
|
const deviceId = ensureDeviceId();
|
|
@@ -3411,25 +3702,14 @@ function refreshWrapEntitlementInBackground(options = {}) {
|
|
|
3411
3702
|
device_name: hostname(),
|
|
3412
3703
|
...(wrappedRun ? { wrapped_run: true } : {}),
|
|
3413
3704
|
});
|
|
3414
|
-
const
|
|
3415
|
-
method: "POST",
|
|
3416
|
-
headers: { authorization: `Bearer ${tok}`, "content-type": "application/json", "x-cave-csrf": "cli" },
|
|
3417
|
-
body,
|
|
3418
|
-
signal: AbortSignal.timeout(5000),
|
|
3419
|
-
});
|
|
3420
|
-
let resp = await doPost(cfg.token);
|
|
3421
|
-
if (resp.status === 401 && cfg.refreshToken) {
|
|
3422
|
-
cfg = await refreshCLIConfig(cfg);
|
|
3423
|
-
if (cfg.token)
|
|
3424
|
-
resp = await doPost(cfg.token);
|
|
3425
|
-
}
|
|
3705
|
+
const resp = await backgroundPostJSON(`${cfg.baseURL}/api/v1/me/wrap-entitlement`, cfg.token, body);
|
|
3426
3706
|
if (!resp.ok) {
|
|
3427
3707
|
mutateRawConfig((out) => {
|
|
3428
3708
|
out.wrapEntitlementRefresh = { at: new Date().toISOString(), ok: false };
|
|
3429
3709
|
});
|
|
3430
3710
|
return;
|
|
3431
3711
|
}
|
|
3432
|
-
const ent =
|
|
3712
|
+
const ent = resp.body;
|
|
3433
3713
|
if (parseWrapEntitlement(ent)) {
|
|
3434
3714
|
saveWrapEntitlement(ent);
|
|
3435
3715
|
mutateRawConfig((out) => {
|
|
@@ -4229,6 +4509,107 @@ function normalizeAgentShortcutWrapArgs(input) {
|
|
|
4229
4509
|
}
|
|
4230
4510
|
return [...wrapFlags, agent, ...agentArgs];
|
|
4231
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
|
+
}
|
|
4232
4613
|
// runWrapped execs the resolved command with the gateway injection applied. It
|
|
4233
4614
|
// auto-starts the local proxy when routing to loopback, so `caveman wrap claude`
|
|
4234
4615
|
// is the one-command compression path. If the proxy can't be reached, a TTY run
|
|
@@ -4309,7 +4690,7 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = f
|
|
|
4309
4690
|
if (managedGeminiUnsupported) {
|
|
4310
4691
|
process.stderr.write("caveman: managed Gemini CLI wrap is unsupported because Gemini CLI cannot send separate Caveman and upstream credentials; launching directly\n");
|
|
4311
4692
|
}
|
|
4312
|
-
//
|
|
4693
|
+
// The local proxy compresses with no account. When wrap runs the LOCAL
|
|
4313
4694
|
// proxy path we resolve the mode; managed gateway traffic is governed by the cloud
|
|
4314
4695
|
// policy engine, so we never resolve it here.
|
|
4315
4696
|
const gateApplies = local && !opts.noProxy;
|
|
@@ -4597,13 +4978,39 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = f
|
|
|
4597
4978
|
for (const [signal, handler] of signalHandlers)
|
|
4598
4979
|
process.removeListener(signal, handler);
|
|
4599
4980
|
};
|
|
4600
|
-
|
|
4981
|
+
const wrapSignals = ["SIGHUP", "SIGINT", "SIGQUIT", "SIGTERM"];
|
|
4982
|
+
for (const signal of wrapSignals) {
|
|
4601
4983
|
const handler = () => {
|
|
4602
|
-
|
|
4603
|
-
|
|
4604
|
-
|
|
4984
|
+
// Forward the signal but defer cleanup and self-termination until the
|
|
4985
|
+
// child exits: deleting the wrap temp pack before the agent shuts down
|
|
4986
|
+
// races its SessionEnd hooks, which still read the plugin directory.
|
|
4605
4987
|
removeSignalHandlers();
|
|
4606
|
-
|
|
4988
|
+
const finish = () => {
|
|
4989
|
+
cleanupWrapTempDirs();
|
|
4990
|
+
removeProxySessionMarker(sessionMarker);
|
|
4991
|
+
process.kill(process.pid, signal);
|
|
4992
|
+
};
|
|
4993
|
+
// Escape hatch: a second signal, or a child that traps the first one,
|
|
4994
|
+
// must still clean up — the temp pack can hold copied agent
|
|
4995
|
+
// credentials (e.g. the Codex ephemeral home's auth.json), so dying
|
|
4996
|
+
// at default disposition without cleanup would strand them on disk.
|
|
4997
|
+
const escape = () => {
|
|
4998
|
+
removeSignalHandlers();
|
|
4999
|
+
child.kill("SIGKILL");
|
|
5000
|
+
finish();
|
|
5001
|
+
};
|
|
5002
|
+
for (const s of wrapSignals) {
|
|
5003
|
+
signalHandlers.set(s, escape);
|
|
5004
|
+
process.once(s, escape);
|
|
5005
|
+
}
|
|
5006
|
+
child.kill(signal);
|
|
5007
|
+
const grace = setTimeout(escape, 10_000);
|
|
5008
|
+
grace.unref();
|
|
5009
|
+
child.once("exit", () => {
|
|
5010
|
+
clearTimeout(grace);
|
|
5011
|
+
removeSignalHandlers();
|
|
5012
|
+
finish();
|
|
5013
|
+
});
|
|
4607
5014
|
};
|
|
4608
5015
|
signalHandlers.set(signal, handler);
|
|
4609
5016
|
process.once(signal, handler);
|
|
@@ -4762,13 +5169,13 @@ async function startWrapProxy(mode, mcpRecovery, toon, pixelModels, pixelDensity
|
|
|
4762
5169
|
// Observe-only estimate: record mode measures would-have-saved tokens without
|
|
4763
5170
|
// ever mutating the forwarded request.
|
|
4764
5171
|
...(observeEstimate ? { CAVEMAN_OBSERVE_ESTIMATE: "1" } : {}),
|
|
4765
|
-
// Nothing else is stamped for subscription/OAuth compression:
|
|
5172
|
+
// Nothing else is stamped for subscription/OAuth compression: it
|
|
4766
5173
|
// has no account condition. The operator off-switch (`subscription_compress:
|
|
4767
5174
|
// off`) stays the operator's — we never override it from here.
|
|
4768
5175
|
};
|
|
4769
5176
|
// Same reason as `start`: the dead account variable never rides along inherited.
|
|
4770
5177
|
delete env.CAVEMAN_WRAP_ENTITLED;
|
|
4771
|
-
const child = spawn(resolved, [], { stdio: "ignore", env, detached: true });
|
|
5178
|
+
const child = spawn(resolved, [], { stdio: "ignore", env, detached: true, windowsHide: true });
|
|
4772
5179
|
child.unref();
|
|
4773
5180
|
for (let i = 0; i < 20; i++) {
|
|
4774
5181
|
await sleep(100);
|
|
@@ -5218,6 +5625,31 @@ function readJsonObject(path) {
|
|
|
5218
5625
|
return {};
|
|
5219
5626
|
}
|
|
5220
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
|
+
}
|
|
5221
5653
|
function nativeHookCommand(agentId) {
|
|
5222
5654
|
const fastHook = join(dirname(fileURLToPath(import.meta.url)), "native-hook-fast.js");
|
|
5223
5655
|
const explicitProxy = process.env.CAVEMAN_PROXY_BIN;
|
|
@@ -5225,10 +5657,10 @@ function nativeHookCommand(agentId) {
|
|
|
5225
5657
|
const proxy = explicitProxy || which("caveman-proxy") || (isExecutable(localProxy) ? localProxy : undefined);
|
|
5226
5658
|
const bridgeCurrent = proxy ? probeVersionedBinary(proxy, "native_hook_bridge_v1").current : false;
|
|
5227
5659
|
if (proxy && bridgeCurrent && existsSync(fastHook)) {
|
|
5228
|
-
return
|
|
5660
|
+
return nativeHookInvocation(proxy, fastHook, agentId, true);
|
|
5229
5661
|
}
|
|
5230
5662
|
if (existsSync(fastHook)) {
|
|
5231
|
-
return
|
|
5663
|
+
return nativeHookInvocation(process.execPath, fastHook, agentId, false);
|
|
5232
5664
|
}
|
|
5233
5665
|
return `${cavemanBinForHook()} native-hook ${agentId}`;
|
|
5234
5666
|
}
|
|
@@ -7727,7 +8159,7 @@ function openLoginBrowser(url) {
|
|
|
7727
8159
|
process.stderr.write(` browser opener unavailable; open ${url}\n`);
|
|
7728
8160
|
return;
|
|
7729
8161
|
}
|
|
7730
|
-
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 });
|
|
7731
8163
|
child.once("error", () => process.stderr.write(` browser did not open; open ${url}\n`));
|
|
7732
8164
|
child.unref();
|
|
7733
8165
|
}
|
|
@@ -7868,7 +8300,7 @@ async function login(argv = []) {
|
|
|
7868
8300
|
// until the control plane has recorded that this CLI stored the bundle.
|
|
7869
8301
|
await acknowledgeDeviceGrant(baseURL, credentials.access_token, code.device_code, ackToken);
|
|
7870
8302
|
}
|
|
7871
|
-
// Mint/refresh the local-wrap entitlement for this device
|
|
8303
|
+
// Mint/refresh the local-wrap entitlement for this device. Best
|
|
7872
8304
|
// effort: login never fails for seats or a down entitlement service.
|
|
7873
8305
|
await fetchAndStoreWrapEntitlement(baseURL, credentials.access_token);
|
|
7874
8306
|
if (gateway && wrapMode(gateway) === "managed") {
|
|
@@ -8615,6 +9047,20 @@ export function wrapExternalWritesDisabled(env = process.env) {
|
|
|
8615
9047
|
function cavemanHome() {
|
|
8616
9048
|
return process.env.CAVEMAN_HOME ?? join(homedir(), ".caveman");
|
|
8617
9049
|
}
|
|
9050
|
+
// ensureCavemanHome creates ~/.caveman itself with owner-only perms and repairs
|
|
9051
|
+
// an existing permissive mode. The proxy refuses CCR (sqlite parent check) when
|
|
9052
|
+
// this directory is group/world writable, and recursive mkdir with a mode only
|
|
9053
|
+
// applies it to directories it creates — an earlier no-mode caller (login, mcp
|
|
9054
|
+
// install) would otherwise have already created it 0775 under umask 002.
|
|
9055
|
+
function ensureCavemanHome() {
|
|
9056
|
+
const home = cavemanHome();
|
|
9057
|
+
mkdirSync(home, { recursive: true, mode: 0o700 });
|
|
9058
|
+
try {
|
|
9059
|
+
chmodSync(home, 0o700);
|
|
9060
|
+
}
|
|
9061
|
+
catch { /* not ours / Windows */ }
|
|
9062
|
+
return home;
|
|
9063
|
+
}
|
|
8618
9064
|
// cavemanBin resolves one of caveman's own Go binaries (proxy/engine/mcp/browse):
|
|
8619
9065
|
// explicit env override first, then PATH, then ~/.caveman/bin — the directory the
|
|
8620
9066
|
// install script and the missing-binary panels tell users to build into, so
|
|
@@ -9609,7 +10055,10 @@ function shouldShrink(command) {
|
|
|
9609
10055
|
// cavemanBinForHook is the invocation a Claude hook uses to call back into this
|
|
9610
10056
|
// CLI, robust to PATH: a resolved `caveman`/`cave`, else this very script's node.
|
|
9611
10057
|
function cavemanBinForHook() {
|
|
9612
|
-
|
|
10058
|
+
const command = which("caveman") ?? which("cave");
|
|
10059
|
+
return command
|
|
10060
|
+
? hookExecutableInvocation(command, undefined)
|
|
10061
|
+
: hookExecutableInvocation(process.execPath, process.argv[1]);
|
|
9613
10062
|
}
|
|
9614
10063
|
// shrinkHook is the settings-hook callback for the agents whose harness can
|
|
9615
10064
|
// deterministically rewrite a shell command before it runs: Claude Code (PreToolUse,
|
|
@@ -10896,11 +11345,15 @@ function opencodePluginPath() {
|
|
|
10896
11345
|
// cavemanInvocation returns how to call back into THIS CLI from a generated plugin,
|
|
10897
11346
|
// baked at install time so it is independent of the agent's PATH: a resolved
|
|
10898
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
|
+
}
|
|
10899
11355
|
function cavemanInvocation() {
|
|
10900
|
-
|
|
10901
|
-
if (onPath)
|
|
10902
|
-
return { cmd: onPath, pre: [] };
|
|
10903
|
-
return { cmd: process.execPath, pre: [process.argv[1] ?? ""] };
|
|
11356
|
+
return generatedPluginInvocation(which("caveman") ?? which("cave") ?? undefined, process.argv[1] ?? "");
|
|
10904
11357
|
}
|
|
10905
11358
|
function opencodePluginSource() {
|
|
10906
11359
|
const { cmd, pre } = cavemanInvocation();
|
|
@@ -11324,7 +11777,7 @@ function hooksUsage() {
|
|
|
11324
11777
|
}
|
|
11325
11778
|
// hooksDirectiveCmd handles `caveman hooks install|uninstall --directive <id> [agent]`
|
|
11326
11779
|
// (AUTOPILOT_SPEC §7.3): the same verb surface that removes a shrink note today,
|
|
11327
|
-
// extended with a flag — never a new porcelain verb (
|
|
11780
|
+
// extended with a flag — never a new porcelain verb (capped). Install
|
|
11328
11781
|
// announces itself and prints the undo command (§7 announce+undo).
|
|
11329
11782
|
function hooksDirectiveCmd(sub, directiveId, target) {
|
|
11330
11783
|
// Object.hasOwn: directiveId is user input; a truthiness read would let
|
|
@@ -11389,7 +11842,7 @@ function hooksDirectiveCmd(sub, directiveId, target) {
|
|
|
11389
11842
|
}
|
|
11390
11843
|
function hooksCmd(rest) {
|
|
11391
11844
|
// --directive <id> (or --directive=<id>) routes to the wrap-directive
|
|
11392
|
-
// surface (same verb, no new porcelain
|
|
11845
|
+
// surface (same verb, no new porcelain). Any OTHER --flag is
|
|
11393
11846
|
// rejected loudly: silently ignoring `--directive=x` used to install the
|
|
11394
11847
|
// shrink note and exit 0 while the user believed a directive was installed
|
|
11395
11848
|
// (review C8).
|
|
@@ -12034,7 +12487,7 @@ function openLearnReport(report) {
|
|
|
12034
12487
|
process.stderr.write(`cannot open visual report; open this file: ${report}\n`);
|
|
12035
12488
|
return;
|
|
12036
12489
|
}
|
|
12037
|
-
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 });
|
|
12038
12491
|
child.once("error", () => {
|
|
12039
12492
|
process.stderr.write(`cannot open visual report; open this file: ${report}\n`);
|
|
12040
12493
|
});
|
|
@@ -12655,8 +13108,8 @@ function proxyRuntimeMatches(runtime, mode, recoveryViaMCP) {
|
|
|
12655
13108
|
&& runtime.mode === mode
|
|
12656
13109
|
&& proxyRuntimeGateMatches(runtime, recoveryViaMCP);
|
|
12657
13110
|
}
|
|
12658
|
-
// The only cross-session gate input left is the recovery contract (
|
|
12659
|
-
//
|
|
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
|
|
12660
13113
|
// would elide bytes nothing can expand.
|
|
12661
13114
|
function proxyRuntimeGateMatches(runtime, recoveryViaMCP) {
|
|
12662
13115
|
return runtime.recovery_via_mcp === recoveryViaMCP;
|
|
@@ -14293,7 +14746,7 @@ function credentialsPath() {
|
|
|
14293
14746
|
return join(caveHome(), "credentials");
|
|
14294
14747
|
}
|
|
14295
14748
|
function fileTokenSet(token) {
|
|
14296
|
-
|
|
14749
|
+
ensureCavemanHome();
|
|
14297
14750
|
try {
|
|
14298
14751
|
chmodSync(credentialsPath(), 0o600);
|
|
14299
14752
|
}
|
|
@@ -14560,10 +15013,14 @@ export function commandHasPath(command) {
|
|
|
14560
15013
|
export function executableCandidateNames(command, platform = process.platform, pathExt = process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD") {
|
|
14561
15014
|
if (platform !== "win32" || extname(command))
|
|
14562
15015
|
return [command];
|
|
14563
|
-
const candidates = [
|
|
15016
|
+
const candidates = [];
|
|
14564
15017
|
for (const extension of pathExt.split(";").map((value) => value.trim()).filter(Boolean)) {
|
|
14565
15018
|
candidates.push(`${command}${extension.startsWith(".") ? extension : `.${extension}`}`);
|
|
14566
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);
|
|
14567
15024
|
const seen = new Set();
|
|
14568
15025
|
return candidates.filter((candidate) => {
|
|
14569
15026
|
const key = candidate.toLowerCase();
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// GENERATED by
|
|
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
|
|
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
|
|
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.
|
|
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",
|
|
@@ -20,7 +20,11 @@
|
|
|
20
20
|
"caveman": "dist/index.js",
|
|
21
21
|
"cave": "dist/index.js"
|
|
22
22
|
},
|
|
23
|
-
"files": [
|
|
23
|
+
"files": [
|
|
24
|
+
"dist",
|
|
25
|
+
"README.md",
|
|
26
|
+
"LICENSE"
|
|
27
|
+
],
|
|
24
28
|
"scripts": {
|
|
25
29
|
"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/shebang.mjs",
|
|
26
30
|
"prepack": "npm run build",
|