@caveman-ai/cli 1.1.0 → 1.2.1
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 +3 -3
- 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 +710 -57
- package/dist/learn-tui.js +43 -43
- 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 +1 -1
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";
|
|
@@ -23,6 +25,11 @@ const wrapTempDirs = new Set();
|
|
|
23
25
|
// `caveman wrap` points agents at it.
|
|
24
26
|
const PROXY_ADDR = "127.0.0.1:8787";
|
|
25
27
|
const PROXY_URL = `http://${PROXY_ADDR}`;
|
|
28
|
+
// Restores Claude Code's tool search after we take over ANTHROPIC_BASE_URL.
|
|
29
|
+
// "auto" defers to Claude Code's own tool-catalog size threshold, so a user with
|
|
30
|
+
// two small MCP servers pays no extra round-trip while a heavy setup stops
|
|
31
|
+
// inlining every schema. "true" would force it on regardless.
|
|
32
|
+
const TOOL_SEARCH_DEFAULT = "auto";
|
|
26
33
|
// Gateway resolution is dynamic — resolved per invocation, never frozen at module
|
|
27
34
|
// load — so `caveman login` persisting a managed gateway URL flips `wrap` to the
|
|
28
35
|
// cloud with no env var (SIMPLICITY_SPEC §6.5, audit finding #3). `caveman start`
|
|
@@ -327,9 +334,9 @@ function resolveInvocation(raw) {
|
|
|
327
334
|
const agent = RESERVED_VERBS.has(top) ? undefined : findAgent(top);
|
|
328
335
|
if (agent)
|
|
329
336
|
return {
|
|
330
|
-
verb: "
|
|
337
|
+
verb: "run",
|
|
331
338
|
argv: normalizeAgentShortcutWrapArgs(raw),
|
|
332
|
-
handler:
|
|
339
|
+
handler: agentShortcut,
|
|
333
340
|
agent,
|
|
334
341
|
};
|
|
335
342
|
return { verb: top, argv: raw.slice(1), handler: () => unknownInvocation(top) };
|
|
@@ -380,16 +387,22 @@ function invokedCommand(legacyVerb, groupedTail = "") {
|
|
|
380
387
|
}
|
|
381
388
|
let currentInvocation;
|
|
382
389
|
currentInvocation = resolveInvocation(process.argv.slice(2));
|
|
383
|
-
// Version
|
|
384
|
-
//
|
|
385
|
-
//
|
|
390
|
+
// Version 4 = default-on (opt-out) plus token volume: command_run now carries
|
|
391
|
+
// the local proxy's processed/saved token deltas, so a v3 "yes" was given for a
|
|
392
|
+
// narrower scope and gets the new disclosure reprinted once (never re-asked, and
|
|
393
|
+
// never flipped on). A persisted decision from any version — including a "no" to
|
|
394
|
+
// the old v1 [y/N] prompt — is honored forever; the default only fills the
|
|
386
395
|
// undecided gap, and the first default-on run prints the disclosure line.
|
|
387
|
-
const TELEMETRY_PROMPT_VERSION =
|
|
396
|
+
const TELEMETRY_PROMPT_VERSION = 4;
|
|
388
397
|
const TELEMETRY_URL = "https://api.caveman.so/telemetry/cli";
|
|
389
398
|
// The production control-API origin — derived from TELEMETRY_URL (the CLI's
|
|
390
399
|
// other hardcoded prod-host literal) so the two can never drift apart.
|
|
391
400
|
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";
|
|
401
|
+
const TELEMETRY_DISCLOSURE_LINE = "anonymous usage stats on — command counts and token totals only, never prompts, code, or file paths · caveman telemetry off";
|
|
402
|
+
// Reading token totals means spawning caveman-proxy to query the local SQLite
|
|
403
|
+
// store. It runs after the command's own work, so the cost lands on process exit;
|
|
404
|
+
// a slow or wedged binary drops the token fields rather than holding the CLI.
|
|
405
|
+
const TELEMETRY_TOKEN_READ_TIMEOUT_MS = 400;
|
|
393
406
|
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
407
|
const TELEMETRY_COMMAND_ALLOWLIST = [
|
|
395
408
|
"agent", "audit", "billing", "browse", "compress", "convert", "costs", "deploy", "dev", "doctor", "evals", "experiments",
|
|
@@ -496,6 +509,8 @@ async function ensureTelemetryDefault() {
|
|
|
496
509
|
// "on" for someone whose first-ever command is `telemetry off`.
|
|
497
510
|
if (currentInvocation.verb === "telemetry")
|
|
498
511
|
return;
|
|
512
|
+
if (state.source === "config")
|
|
513
|
+
return ensureTelemetryDisclosureVersion(state);
|
|
499
514
|
if (state.source !== "default")
|
|
500
515
|
return;
|
|
501
516
|
const telemetry = {
|
|
@@ -515,6 +530,27 @@ async function ensureTelemetryDefault() {
|
|
|
515
530
|
}
|
|
516
531
|
process.stderr.write(`${dim(TELEMETRY_DISCLOSURE_LINE)}\n`);
|
|
517
532
|
}
|
|
533
|
+
// ensureTelemetryDisclosureVersion reprints the disclosure once for someone who
|
|
534
|
+
// consented under older wording. v4 widened command_run with token volume, and a
|
|
535
|
+
// v3 "yes" was given for command counts alone — it stays a yes (re-asking would
|
|
536
|
+
// silently reset a decision the user already made), but it is never widened
|
|
537
|
+
// silently. Only reached with source "config", which already means interactive,
|
|
538
|
+
// not CI, and no env override in play. An opt-out is left completely untouched:
|
|
539
|
+
// no write, no line, no version bump.
|
|
540
|
+
async function ensureTelemetryDisclosureVersion(state) {
|
|
541
|
+
const cfg = state.config;
|
|
542
|
+
if (!cfg?.enabled || state.state !== "on")
|
|
543
|
+
return;
|
|
544
|
+
if (cfg.promptVersion >= TELEMETRY_PROMPT_VERSION)
|
|
545
|
+
return;
|
|
546
|
+
try {
|
|
547
|
+
await saveTelemetryConfig({ ...cfg, promptVersion: TELEMETRY_PROMPT_VERSION });
|
|
548
|
+
}
|
|
549
|
+
catch {
|
|
550
|
+
return;
|
|
551
|
+
}
|
|
552
|
+
process.stderr.write(`${dim(TELEMETRY_DISCLOSURE_LINE)}\n`);
|
|
553
|
+
}
|
|
518
554
|
function isHelpLikeInvocation() {
|
|
519
555
|
return currentInvocation.verb === "help"
|
|
520
556
|
|| currentInvocation.verb === "version"
|
|
@@ -602,6 +638,17 @@ async function telemetryOff() {
|
|
|
602
638
|
promptVersion: TELEMETRY_PROMPT_VERSION,
|
|
603
639
|
};
|
|
604
640
|
await saveTelemetryConfig(telemetry);
|
|
641
|
+
// Drop the token watermark with the decision. Keeping it would make a later
|
|
642
|
+
// `telemetry on` report every token processed during the opt-out window as one
|
|
643
|
+
// delta — the seeding rule has to hold across the off/on boundary too.
|
|
644
|
+
try {
|
|
645
|
+
mutateRawConfig((out) => {
|
|
646
|
+
delete out.telemetryTokens;
|
|
647
|
+
});
|
|
648
|
+
}
|
|
649
|
+
catch {
|
|
650
|
+
/* best effort: the decision itself is already persisted */
|
|
651
|
+
}
|
|
605
652
|
print({ telemetry: "off", anonymous_id: "none" });
|
|
606
653
|
}
|
|
607
654
|
function telemetryCommandName() {
|
|
@@ -653,6 +700,161 @@ function telemetryAnonymousId(state) {
|
|
|
653
700
|
telemetryEphemeralId = randomUUID();
|
|
654
701
|
return telemetryEphemeralId;
|
|
655
702
|
}
|
|
703
|
+
// parseProxyStatsPayload pulls the stats object out of caveman-proxy's stdout.
|
|
704
|
+
// The binary points its JSON slog handler at stdout too, so a log line can land
|
|
705
|
+
// ahead of the payload and a plain JSON.parse of the whole stream would throw.
|
|
706
|
+
// Every candidate must carry a numeric tokens_in: without that check a stray log
|
|
707
|
+
// object parses "successfully" as zero tokens, which reads as a rewound store and
|
|
708
|
+
// replays the entire lifetime total as one delta.
|
|
709
|
+
function parseProxyStatsPayload(out) {
|
|
710
|
+
const attempt = (text) => {
|
|
711
|
+
try {
|
|
712
|
+
const parsed = JSON.parse(text);
|
|
713
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
714
|
+
return null;
|
|
715
|
+
const raw = parsed;
|
|
716
|
+
return typeof raw.tokens_in === "number" ? raw : null;
|
|
717
|
+
}
|
|
718
|
+
catch {
|
|
719
|
+
return null;
|
|
720
|
+
}
|
|
721
|
+
};
|
|
722
|
+
const trimmed = out.trim();
|
|
723
|
+
if (!trimmed)
|
|
724
|
+
return null;
|
|
725
|
+
const whole = attempt(trimmed);
|
|
726
|
+
if (whole)
|
|
727
|
+
return whole;
|
|
728
|
+
// Log lines can land on either side of the payload (a deferred Close() error
|
|
729
|
+
// prints after it), so scan candidate object bounds from the end rather than
|
|
730
|
+
// assuming the payload runs to EOF. Bounded: this output is a handful of lines,
|
|
731
|
+
// and the budget keeps a pathological one from costing real time.
|
|
732
|
+
const lines = trimmed.split("\n");
|
|
733
|
+
let budget = 64;
|
|
734
|
+
for (let start = lines.length - 1; start >= 0 && budget > 0; start--) {
|
|
735
|
+
if (!lines[start].startsWith("{"))
|
|
736
|
+
continue;
|
|
737
|
+
for (let end = lines.length; end > start && budget > 0; end--) {
|
|
738
|
+
budget--;
|
|
739
|
+
const candidate = attempt(lines.slice(start, end).join("\n"));
|
|
740
|
+
if (candidate)
|
|
741
|
+
return candidate;
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
return null;
|
|
745
|
+
}
|
|
746
|
+
// readProxyTokenTotals reads the local proxy's lifetime token aggregate. Every
|
|
747
|
+
// failure path — no store yet, no proxy binary, slow spawn, unparsable output —
|
|
748
|
+
// returns null and the event simply ships without token fields. Numbers only:
|
|
749
|
+
// `caveman-proxy stats --json` is an aggregate over the requests table, never a
|
|
750
|
+
// row, a prompt, a model name, or a path.
|
|
751
|
+
function readProxyTokenTotals() {
|
|
752
|
+
try {
|
|
753
|
+
const db = process.env.CAVEMAN_DB || join(cavemanHome(), "caveman.db");
|
|
754
|
+
if (!existsSync(db))
|
|
755
|
+
return null;
|
|
756
|
+
const bin = resolveGoBin("caveman-proxy", "CAVEMAN_PROXY_BIN");
|
|
757
|
+
if (!bin)
|
|
758
|
+
return null;
|
|
759
|
+
const out = execFileSync(bin, ["stats", "--json"], {
|
|
760
|
+
encoding: "utf8",
|
|
761
|
+
timeout: TELEMETRY_TOKEN_READ_TIMEOUT_MS,
|
|
762
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
763
|
+
});
|
|
764
|
+
const parsed = parseProxyStatsPayload(out);
|
|
765
|
+
if (!parsed)
|
|
766
|
+
return null;
|
|
767
|
+
const tokensIn = parsed.tokens_in;
|
|
768
|
+
const tokensSaved = typeof parsed.compression_tokens_saved === "number" ? parsed.compression_tokens_saved : 0;
|
|
769
|
+
if (!Number.isFinite(tokensIn) || !Number.isFinite(tokensSaved))
|
|
770
|
+
return null;
|
|
771
|
+
// Basis rides along because these are tokenizer estimates, not billed counts;
|
|
772
|
+
// the receiving side must never promote them to verified savings.
|
|
773
|
+
const basis = typeof parsed.basis === "string" && parsed.basis ? parsed.basis : "inferred";
|
|
774
|
+
return {
|
|
775
|
+
tokensIn: Math.max(0, Math.trunc(tokensIn)),
|
|
776
|
+
tokensSaved: Math.max(0, Math.trunc(tokensSaved)),
|
|
777
|
+
basis,
|
|
778
|
+
};
|
|
779
|
+
}
|
|
780
|
+
catch {
|
|
781
|
+
return null;
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
function parseTelemetryTokenWatermark(value) {
|
|
785
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
786
|
+
return null;
|
|
787
|
+
const raw = value;
|
|
788
|
+
if (typeof raw.tokensIn !== "number" || typeof raw.tokensSaved !== "number")
|
|
789
|
+
return null;
|
|
790
|
+
if (!Number.isFinite(raw.tokensIn) || !Number.isFinite(raw.tokensSaved))
|
|
791
|
+
return null;
|
|
792
|
+
return {
|
|
793
|
+
tokensIn: Math.max(0, Math.trunc(raw.tokensIn)),
|
|
794
|
+
tokensSaved: Math.max(0, Math.trunc(raw.tokensSaved)),
|
|
795
|
+
at: typeof raw.at === "string" ? raw.at : "",
|
|
796
|
+
};
|
|
797
|
+
}
|
|
798
|
+
function telemetryTokenWatermarkFromDisk() {
|
|
799
|
+
try {
|
|
800
|
+
const parsed = JSON.parse(readFileSync(configPath(), "utf8"));
|
|
801
|
+
return parseTelemetryTokenWatermark(parsed.telemetryTokens);
|
|
802
|
+
}
|
|
803
|
+
catch {
|
|
804
|
+
return null;
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
// telemetryTokenDelta returns what to report for THIS event and advances the
|
|
808
|
+
// watermark to the totals it read. The send is fire-and-forget, so a dropped POST
|
|
809
|
+
// loses that delta rather than replaying it — undercounting beats double-counting
|
|
810
|
+
// a savings number.
|
|
811
|
+
//
|
|
812
|
+
// Two cases report nothing and only re-baseline. The first read on a machine
|
|
813
|
+
// seeds the watermark: the store can already hold traffic from before the user
|
|
814
|
+
// saw this disclosure, and telemetry starts at consent rather than reaching
|
|
815
|
+
// backwards through history. A store that rewound (db deleted, restored backup)
|
|
816
|
+
// re-baselines for the same reason — never a negative, never a second copy of
|
|
817
|
+
// history.
|
|
818
|
+
function telemetryTokenDelta() {
|
|
819
|
+
const totals = readProxyTokenTotals();
|
|
820
|
+
if (!totals)
|
|
821
|
+
return null;
|
|
822
|
+
const prior = telemetryTokenWatermarkFromDisk();
|
|
823
|
+
const rewound = prior !== null && (totals.tokensIn < prior.tokensIn || totals.tokensSaved < prior.tokensSaved);
|
|
824
|
+
const processed = prior && !rewound ? Math.max(0, totals.tokensIn - prior.tokensIn) : 0;
|
|
825
|
+
const saved = prior && !rewound ? Math.max(0, totals.tokensSaved - prior.tokensSaved) : 0;
|
|
826
|
+
const rebaselining = prior === null || rewound;
|
|
827
|
+
if (processed === 0 && saved === 0 && !rebaselining)
|
|
828
|
+
return null;
|
|
829
|
+
// Claim the delta optimistically: two CLI processes exiting together would
|
|
830
|
+
// otherwise read the same watermark and both report the same tokens, inflating
|
|
831
|
+
// a savings figure. Whoever writes second sees the watermark already moved and
|
|
832
|
+
// reports nothing.
|
|
833
|
+
let claimed = true;
|
|
834
|
+
try {
|
|
835
|
+
mutateRawConfig((out) => {
|
|
836
|
+
const current = parseTelemetryTokenWatermark(out.telemetryTokens);
|
|
837
|
+
if (current?.tokensIn !== prior?.tokensIn || current?.tokensSaved !== prior?.tokensSaved) {
|
|
838
|
+
claimed = false;
|
|
839
|
+
return;
|
|
840
|
+
}
|
|
841
|
+
out.telemetryTokens = {
|
|
842
|
+
tokensIn: totals.tokensIn,
|
|
843
|
+
tokensSaved: totals.tokensSaved,
|
|
844
|
+
at: new Date().toISOString(),
|
|
845
|
+
};
|
|
846
|
+
});
|
|
847
|
+
}
|
|
848
|
+
catch {
|
|
849
|
+
// Read-only home: report nothing rather than resend the same delta forever.
|
|
850
|
+
return null;
|
|
851
|
+
}
|
|
852
|
+
if (!claimed)
|
|
853
|
+
return null;
|
|
854
|
+
if (processed === 0 && saved === 0)
|
|
855
|
+
return null;
|
|
856
|
+
return { processed, saved, basis: totals.basis };
|
|
857
|
+
}
|
|
656
858
|
function emitCommandRunOnce(exitClass, errorClass) {
|
|
657
859
|
const event = commandRunEventOnce(exitClass, errorClass);
|
|
658
860
|
return event ? emitTelemetryEvents([event]) : Promise.resolve();
|
|
@@ -685,6 +887,14 @@ function commandRunEventOnce(exitClass, errorClass) {
|
|
|
685
887
|
event.agent = agent;
|
|
686
888
|
if (exitClass === "error")
|
|
687
889
|
event.error_class = errorClass ?? "other";
|
|
890
|
+
// Token volume rides on command_run only — runtime_bootstrap shares the same
|
|
891
|
+
// watermark and would race it into a double count.
|
|
892
|
+
const tokens = telemetryTokenDelta();
|
|
893
|
+
if (tokens) {
|
|
894
|
+
event.tokens_processed = tokens.processed;
|
|
895
|
+
event.tokens_saved = tokens.saved;
|
|
896
|
+
event.tokens_basis = tokens.basis;
|
|
897
|
+
}
|
|
688
898
|
return event;
|
|
689
899
|
}
|
|
690
900
|
function emitConsentGranted(anonymousId) {
|
|
@@ -815,7 +1025,7 @@ function exploreUsage() {
|
|
|
815
1025
|
function guardExploreAgent(agent) {
|
|
816
1026
|
if (agent === "claude")
|
|
817
1027
|
return;
|
|
818
|
-
console.error(`caveman explore: only --agent claude is wired today (codex needs verified transcript isolation first
|
|
1028
|
+
console.error(`caveman explore: only --agent claude is wired today (codex needs verified transcript isolation first). got: ${agent}`);
|
|
819
1029
|
process.exit(2);
|
|
820
1030
|
}
|
|
821
1031
|
// Unprinted compatibility alias. Canonical surface is:
|
|
@@ -1710,7 +1920,7 @@ async function start(argv = []) {
|
|
|
1710
1920
|
if (!resolved)
|
|
1711
1921
|
return startMissingProxyUI(bin, options);
|
|
1712
1922
|
// `caveman start` is the sibling entry point to `caveman wrap`, so it resolves the
|
|
1713
|
-
// SAME mode decision.
|
|
1923
|
+
// SAME mode decision. There is no account condition in it — the
|
|
1714
1924
|
// entitlement read is a label, not a permission. The mode this proxy actually runs
|
|
1715
1925
|
// is CAVEMAN_MODE (the proxy itself falls back to record for anything unknown), so
|
|
1716
1926
|
// a plain `caveman start` resolves to record; record never mutates bytes anyway.
|
|
@@ -1737,7 +1947,7 @@ async function start(argv = []) {
|
|
|
1737
1947
|
};
|
|
1738
1948
|
if (options.config)
|
|
1739
1949
|
env.CAVEMAN_CONFIG = options.config;
|
|
1740
|
-
// The account gate is gone
|
|
1950
|
+
// The account gate is gone and so is the variable that carried it. Strip
|
|
1741
1951
|
// any inherited copy so a stray export can never re-enter the contract; a proxy
|
|
1742
1952
|
// binary old enough to still read it is already reported by the stale-binary state.
|
|
1743
1953
|
delete env.CAVEMAN_WRAP_ENTITLED;
|
|
@@ -2792,6 +3002,83 @@ function proxyYamlMode() {
|
|
|
2792
3002
|
return undefined;
|
|
2793
3003
|
}
|
|
2794
3004
|
}
|
|
3005
|
+
// Claude Code treats any ANTHROPIC_BASE_URL whose host is not api.anthropic.com
|
|
3006
|
+
// as a custom endpoint and withholds first-party-only capabilities — most
|
|
3007
|
+
// visibly the 1M-token context window, whose loss shrinks the auto-compact
|
|
3008
|
+
// window to the 200k default (#865). The local proxy is a byte-safe
|
|
3009
|
+
// pass-through whose anthropic upstream IS api.anthropic.com unless the
|
|
3010
|
+
// operator overrides providers.anthropic.base_url in caveman.yaml, so for the
|
|
3011
|
+
// default upstream the first-party assertion is truthful and we make it
|
|
3012
|
+
// through Claude Code's own escape hatch. Never overrides a value the user
|
|
3013
|
+
// already set, and never asserts when the upstream cannot be verified.
|
|
3014
|
+
const CLAUDE_ASSUME_FIRST_PARTY_ENV = "_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL";
|
|
3015
|
+
// yamlProviderBaseUrl scans an indentation-nested `providers.<name>.base_url`
|
|
3016
|
+
// key without a YAML dependency (the published CLI has zero runtime deps).
|
|
3017
|
+
// Returns the value when found, null when the providers/<name> block or key is
|
|
3018
|
+
// absent, and undefined when the document uses a shape the scan cannot follow
|
|
3019
|
+
// (flow-style `{...}` blocks) — callers must treat undefined as unverifiable.
|
|
3020
|
+
function yamlProviderBaseUrl(raw, provider) {
|
|
3021
|
+
const lines = raw.split(/\r?\n/);
|
|
3022
|
+
let providersIndent = -1;
|
|
3023
|
+
let providerIndent = -1;
|
|
3024
|
+
for (const line of lines) {
|
|
3025
|
+
const code = line.split("#", 1)[0];
|
|
3026
|
+
if (!code.trim())
|
|
3027
|
+
continue;
|
|
3028
|
+
const indent = code.length - code.trimStart().length;
|
|
3029
|
+
const keyMatch = code.trim().match(/^([A-Za-z0-9_-]+)\s*:\s*(.*)$/);
|
|
3030
|
+
if (providersIndent !== -1 && indent <= providersIndent)
|
|
3031
|
+
providersIndent = -1;
|
|
3032
|
+
if (providerIndent !== -1 && indent <= providerIndent)
|
|
3033
|
+
providerIndent = -1;
|
|
3034
|
+
if (!keyMatch)
|
|
3035
|
+
continue;
|
|
3036
|
+
const key = keyMatch[1];
|
|
3037
|
+
const rest = keyMatch[2] ?? "";
|
|
3038
|
+
if (rest.startsWith("{") || rest.startsWith("[")) {
|
|
3039
|
+
// Flow-style collections keep their children on this line; a providers
|
|
3040
|
+
// subtree written that way is beyond this scan, so report unverifiable.
|
|
3041
|
+
if (key === "providers" || providersIndent !== -1)
|
|
3042
|
+
return undefined;
|
|
3043
|
+
continue;
|
|
3044
|
+
}
|
|
3045
|
+
if (providerIndent !== -1 && key === "base_url") {
|
|
3046
|
+
const value = rest.replace(/^["']|["']\s*$/g, "").trim();
|
|
3047
|
+
return value || null;
|
|
3048
|
+
}
|
|
3049
|
+
if (providersIndent !== -1 && key === provider && providerIndent === -1)
|
|
3050
|
+
providerIndent = indent;
|
|
3051
|
+
else if (key === "providers" && providersIndent === -1 && providerIndent === -1 && indent === 0)
|
|
3052
|
+
providersIndent = indent;
|
|
3053
|
+
}
|
|
3054
|
+
return null;
|
|
3055
|
+
}
|
|
3056
|
+
// proxyAnthropicUpstreamIsFirstParty answers whether the local proxy's
|
|
3057
|
+
// anthropic upstream is verifiably api.anthropic.com: a missing caveman.yaml
|
|
3058
|
+
// means the compiled-in default upstream, an explicit override must name the
|
|
3059
|
+
// first-party host, and anything unverifiable (unreadable file, flow-style
|
|
3060
|
+
// YAML) refuses the assertion — withholding it only keeps today's behavior.
|
|
3061
|
+
function proxyAnthropicUpstreamIsFirstParty() {
|
|
3062
|
+
const path = process.env.CAVEMAN_CONFIG ?? join(cavemanHome(), "caveman.yaml");
|
|
3063
|
+
let raw;
|
|
3064
|
+
try {
|
|
3065
|
+
raw = readFileSync(path, "utf8");
|
|
3066
|
+
}
|
|
3067
|
+
catch (e) {
|
|
3068
|
+
return e?.code === "ENOENT";
|
|
3069
|
+
}
|
|
3070
|
+
const override = yamlProviderBaseUrl(raw, "anthropic");
|
|
3071
|
+
if (override === undefined)
|
|
3072
|
+
return false;
|
|
3073
|
+
if (override === null)
|
|
3074
|
+
return true;
|
|
3075
|
+
try {
|
|
3076
|
+
return new URL(override).host === "api.anthropic.com";
|
|
3077
|
+
}
|
|
3078
|
+
catch {
|
|
3079
|
+
return false;
|
|
3080
|
+
}
|
|
3081
|
+
}
|
|
2795
3082
|
function projectCapabilityDocument() {
|
|
2796
3083
|
try {
|
|
2797
3084
|
return objectValue(JSON.parse(readFileSync(join(process.cwd(), ".caveman", "config.json"), "utf8")));
|
|
@@ -2999,7 +3286,7 @@ const WRAP_GRACE_MS = 7 * 24 * 60 * 60 * 1000;
|
|
|
2999
3286
|
// status prints every active row in OFF_STATE_PRECEDENCE order.
|
|
3000
3287
|
//
|
|
3001
3288
|
// Every row here is a TECHNICAL reason compression is off or degraded. Account
|
|
3002
|
-
// state is NOT one of them
|
|
3289
|
+
// state is NOT one of them: being signed out, seat-walled, denied, or
|
|
3003
3290
|
// lapsed never turns local compression off, so none of those may appear here.
|
|
3004
3291
|
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
3292
|
export const OFF_STATES = {
|
|
@@ -3144,7 +3431,7 @@ function printRunBanner(options) {
|
|
|
3144
3431
|
}
|
|
3145
3432
|
// resolveWrapGate is the PURE mode decision (no IO) so it is unit-testable.
|
|
3146
3433
|
// `requestedMode` is what the user asked for; the returned `mode` is what the local
|
|
3147
|
-
// proxy actually runs.
|
|
3434
|
+
// proxy actually runs. The ENTITLEMENT NEVER CHANGES THE MODE — it only
|
|
3148
3435
|
// labels the account state for the messaging layer:
|
|
3149
3436
|
// - user asked for plain record (--off): stays plain record. `record` mode is
|
|
3150
3437
|
// always pass-through, so this is the one thing that withholds compression here.
|
|
@@ -3171,7 +3458,7 @@ export function resolveWrapGate(entitlement, now, requestedMode) {
|
|
|
3171
3458
|
return { mode: requestedMode, estimate: false, reason: "unentitled" };
|
|
3172
3459
|
}
|
|
3173
3460
|
// subscriptionCompressEnabled is the PURE decision behind subscription/OAuth
|
|
3174
|
-
// coding-agent compression (Claude Pro/Max, Codex ChatGPT, …).
|
|
3461
|
+
// coding-agent compression (Claude Pro/Max, Codex ChatGPT, …). There
|
|
3175
3462
|
// is NO account condition here — a Caveman entitlement is irrelevant. It is on:
|
|
3176
3463
|
// - LOCALLY — this is the local wrap only; the managed gateway's lossless+stealth
|
|
3177
3464
|
// rule for non-PAYG traffic is unchanged and is not configured from here;
|
|
@@ -3307,7 +3594,7 @@ function planLabel(plan) {
|
|
|
3307
3594
|
return "Enterprise";
|
|
3308
3595
|
}
|
|
3309
3596
|
}
|
|
3310
|
-
// planWeeklyAllowanceText mirrors
|
|
3597
|
+
// planWeeklyAllowanceText mirrors the web dashboard's weekly-allowance display — the
|
|
3311
3598
|
// parenthetical shows only for the capped tiers (free 5M / indie 50M).
|
|
3312
3599
|
function planWeeklyAllowanceText(plan) {
|
|
3313
3600
|
if (plan === "free")
|
|
@@ -3367,7 +3654,7 @@ async function requestWrapEntitlement(baseURL, accessToken, wrappedRun = false)
|
|
|
3367
3654
|
}
|
|
3368
3655
|
// fetchAndStoreWrapEntitlement runs the login-time handshake. Login itself NEVER
|
|
3369
3656
|
// fails for seats or a down entitlement service — and never for compression, which
|
|
3370
|
-
// does not depend on it
|
|
3657
|
+
// does not depend on it. The worst case is no cloud sync.
|
|
3371
3658
|
async function fetchAndStoreWrapEntitlement(baseURL, accessToken) {
|
|
3372
3659
|
const result = await requestWrapEntitlement(baseURL, accessToken);
|
|
3373
3660
|
switch (result.kind) {
|
|
@@ -3421,7 +3708,9 @@ function printSeatWall(body) {
|
|
|
3421
3708
|
}
|
|
3422
3709
|
// refreshWrapEntitlementInBackground silently re-fetches during offline grace so a
|
|
3423
3710
|
// renewed plan lifts the notice next session. Fire-and-forget; failure stays in
|
|
3424
|
-
// grace.
|
|
3711
|
+
// grace. Socket is explicitly unrefed so a stalled control plane cannot hold a
|
|
3712
|
+
// completed wrapped agent process open. A 401 is left for foreground auth paths
|
|
3713
|
+
// to refresh; credential rotation must not become hidden post-run work.
|
|
3425
3714
|
function isoWeekKey(now = new Date()) {
|
|
3426
3715
|
const d = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
|
|
3427
3716
|
const day = d.getUTCDay() || 7;
|
|
@@ -3439,6 +3728,45 @@ function claimWeeklyRunRefresh(now = new Date()) {
|
|
|
3439
3728
|
});
|
|
3440
3729
|
return claimed;
|
|
3441
3730
|
}
|
|
3731
|
+
function backgroundPostJSON(urlString, token, body) {
|
|
3732
|
+
return new Promise((resolve, reject) => {
|
|
3733
|
+
const url = new URL(urlString);
|
|
3734
|
+
const request = (url.protocol === "https:" ? httpsRequest : httpRequest)(url, {
|
|
3735
|
+
method: "POST",
|
|
3736
|
+
headers: {
|
|
3737
|
+
authorization: `Bearer ${token}`,
|
|
3738
|
+
"content-type": "application/json",
|
|
3739
|
+
"content-length": Buffer.byteLength(body),
|
|
3740
|
+
"x-cave-csrf": "cli",
|
|
3741
|
+
},
|
|
3742
|
+
}, (response) => {
|
|
3743
|
+
response.socket?.unref();
|
|
3744
|
+
const chunks = [];
|
|
3745
|
+
let bytes = 0;
|
|
3746
|
+
response.on("data", (chunk) => {
|
|
3747
|
+
bytes += chunk.length;
|
|
3748
|
+
if (bytes > 1 << 20) {
|
|
3749
|
+
request.destroy(new Error("wrap entitlement response exceeds 1 MiB"));
|
|
3750
|
+
return;
|
|
3751
|
+
}
|
|
3752
|
+
chunks.push(chunk);
|
|
3753
|
+
});
|
|
3754
|
+
response.on("end", () => {
|
|
3755
|
+
let parsed = null;
|
|
3756
|
+
try {
|
|
3757
|
+
parsed = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
3758
|
+
}
|
|
3759
|
+
catch { /* invalid response stays null */ }
|
|
3760
|
+
const status = response.statusCode ?? 0;
|
|
3761
|
+
resolve({ ok: status >= 200 && status < 300, status, body: parsed });
|
|
3762
|
+
});
|
|
3763
|
+
});
|
|
3764
|
+
request.on("socket", (socket) => socket.unref());
|
|
3765
|
+
request.on("error", reject);
|
|
3766
|
+
request.setTimeout(5000, () => request.destroy(new Error("wrap entitlement refresh timed out")));
|
|
3767
|
+
request.end(body);
|
|
3768
|
+
});
|
|
3769
|
+
}
|
|
3442
3770
|
function refreshWrapEntitlementInBackground(options = {}) {
|
|
3443
3771
|
if (wrapExternalWritesDisabled())
|
|
3444
3772
|
return;
|
|
@@ -3447,7 +3775,7 @@ function refreshWrapEntitlementInBackground(options = {}) {
|
|
|
3447
3775
|
return;
|
|
3448
3776
|
void (async () => {
|
|
3449
3777
|
try {
|
|
3450
|
-
|
|
3778
|
+
const cfg = await config();
|
|
3451
3779
|
if (!cfg.token)
|
|
3452
3780
|
return;
|
|
3453
3781
|
const deviceId = ensureDeviceId();
|
|
@@ -3456,25 +3784,14 @@ function refreshWrapEntitlementInBackground(options = {}) {
|
|
|
3456
3784
|
device_name: hostname(),
|
|
3457
3785
|
...(wrappedRun ? { wrapped_run: true } : {}),
|
|
3458
3786
|
});
|
|
3459
|
-
const
|
|
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
|
-
}
|
|
3787
|
+
const resp = await backgroundPostJSON(`${cfg.baseURL}/api/v1/me/wrap-entitlement`, cfg.token, body);
|
|
3471
3788
|
if (!resp.ok) {
|
|
3472
3789
|
mutateRawConfig((out) => {
|
|
3473
3790
|
out.wrapEntitlementRefresh = { at: new Date().toISOString(), ok: false };
|
|
3474
3791
|
});
|
|
3475
3792
|
return;
|
|
3476
3793
|
}
|
|
3477
|
-
const ent =
|
|
3794
|
+
const ent = resp.body;
|
|
3478
3795
|
if (parseWrapEntitlement(ent)) {
|
|
3479
3796
|
saveWrapEntitlement(ent);
|
|
3480
3797
|
mutateRawConfig((out) => {
|
|
@@ -4274,6 +4591,109 @@ function normalizeAgentShortcutWrapArgs(input) {
|
|
|
4274
4591
|
}
|
|
4275
4592
|
return [...wrapFlags, agent, ...agentArgs];
|
|
4276
4593
|
}
|
|
4594
|
+
// Aider is deliberately absent: it has no lifecycle hooks, so nothing on the
|
|
4595
|
+
// native path would ever start the proxy or apply routedAiderArgs — a direct
|
|
4596
|
+
// launch would point it at a dead endpoint. Aider keeps the wrap door.
|
|
4597
|
+
function nativeAgentId(id) {
|
|
4598
|
+
return id === "claude" || id === "codex" || id === "hermes" || id === "gemini" || id === "opencode" ? id : undefined;
|
|
4599
|
+
}
|
|
4600
|
+
// `caveman <agent>` — the default door. It persistently enables the native
|
|
4601
|
+
// integration (the same journaled user-scoped writes as `caveman enable <agent>`)
|
|
4602
|
+
// and then launches the host binary untouched: routing, Core, and proxy
|
|
4603
|
+
// autostart all live in the installed hooks, so plain `<agent>` stays caveman'd
|
|
4604
|
+
// in every later session too. Wrap-session flags, unsupported agents, or any
|
|
4605
|
+
// enable failure fall back to the ephemeral `wrap` door — the shortcut is
|
|
4606
|
+
// never worse than a session-only wrap.
|
|
4607
|
+
async function agentShortcut(rest) {
|
|
4608
|
+
// normalizeAgentShortcutWrapArgs hoists --off/--pixel/--workflow to the
|
|
4609
|
+
// front, so a leading flag means explicit session-only wrap intent.
|
|
4610
|
+
if (rest[0]?.startsWith("--"))
|
|
4611
|
+
return wrap(rest);
|
|
4612
|
+
const agent = findAgent(rest[0] ?? "");
|
|
4613
|
+
const native = agent ? nativeAgentId(agent.id) : undefined;
|
|
4614
|
+
if (!agent || !native)
|
|
4615
|
+
return wrap(rest);
|
|
4616
|
+
// A Cave Build lock is enforced at the wrap door (claudeCaveBuildEnv); the
|
|
4617
|
+
// native door applies none of its transforms, so a locked project must keep
|
|
4618
|
+
// routing through wrap or the lock would be silently unenforced.
|
|
4619
|
+
if (existsSync(join(process.cwd(), ".caveman", "agent.lock.json")))
|
|
4620
|
+
return wrap(rest);
|
|
4621
|
+
// First-run disclosure comes before the first persistent write, mirroring wrap.
|
|
4622
|
+
await firstRunExperience();
|
|
4623
|
+
try {
|
|
4624
|
+
// An existing journal means the machine-wide install already owns routing —
|
|
4625
|
+
// exactly what plain `<agent>` uses — so launch directly without re-probing
|
|
4626
|
+
// (status probes spawn three subprocesses); `caveman doctor <agent>` stays
|
|
4627
|
+
// the repair door for drifted installs.
|
|
4628
|
+
if (!readNativeJournal(native))
|
|
4629
|
+
enableNative([native]);
|
|
4630
|
+
}
|
|
4631
|
+
catch (error) {
|
|
4632
|
+
process.stderr.write(`${mark("warn")} native enable failed: ${error.message} — using session-only wrap for this run\n`);
|
|
4633
|
+
return wrap(rest);
|
|
4634
|
+
}
|
|
4635
|
+
const bin = which(binOf(agent));
|
|
4636
|
+
if (!bin) {
|
|
4637
|
+
wrapNotFoundUI(rest[0], agent);
|
|
4638
|
+
await emitCommandRunOnce("error", "usage");
|
|
4639
|
+
process.exit(127);
|
|
4640
|
+
}
|
|
4641
|
+
// The native SessionStart hook autostarts the proxy, but only after the host
|
|
4642
|
+
// has approved the installed hooks — start it here too so the first routed
|
|
4643
|
+
// request never hits a dead endpoint. Fail-open, same as the hook.
|
|
4644
|
+
try {
|
|
4645
|
+
const opts = defaultWrapOptions();
|
|
4646
|
+
const gw = gatewayURL();
|
|
4647
|
+
const { host, port } = gatewayHostPort(gw);
|
|
4648
|
+
if (wrapMode(gw) === "local" && !opts.noProxy && !(await portListening(host, port))) {
|
|
4649
|
+
const subscription = native === "codex" && detectCodexWrapAuthMode() === "subscription";
|
|
4650
|
+
const mode = subscription && opts.mode === "pixel" ? "record" : opts.mode;
|
|
4651
|
+
const recovery = Boolean(probeMcpBinary()?.probe.current);
|
|
4652
|
+
await startWrapProxy(mode, recovery, subscription ? false : opts.toon, opts.pixelModels, opts.pixelDensity, gw, subscription ? "codex-subscription" : "standard", false);
|
|
4653
|
+
}
|
|
4654
|
+
}
|
|
4655
|
+
catch { /* runtime startup is fail-open; the native hook retries at SessionStart */ }
|
|
4656
|
+
if (native === "hermes")
|
|
4657
|
+
maybeWarnHermesMissingKey(agent, gatewayURL());
|
|
4658
|
+
const stopProxyKeepalive = startProxyKeepalive();
|
|
4659
|
+
const code = await new Promise((resolve, reject) => {
|
|
4660
|
+
const invocation = portableInvocation(bin, [...agent.args, ...rest.slice(1)]);
|
|
4661
|
+
const child = spawn(invocation.command, invocation.args, { stdio: "inherit" });
|
|
4662
|
+
// tty-generated signals (Ctrl+C / Ctrl+\) already reach the child through
|
|
4663
|
+
// the shared foreground group — forwarding would double-deliver them. But
|
|
4664
|
+
// process-directed SIGTERM/SIGHUP (timeout(1), supervisors, pkill) only hit
|
|
4665
|
+
// this launcher, so those must be forwarded. Either way the launcher
|
|
4666
|
+
// re-raises on itself after the child exits so callers see a signal death,
|
|
4667
|
+
// not a clean exit.
|
|
4668
|
+
let fatal;
|
|
4669
|
+
for (const signal of ["SIGINT", "SIGQUIT"]) {
|
|
4670
|
+
process.on(signal, () => { fatal = signal; /* the tty delivered it to the child already */ });
|
|
4671
|
+
}
|
|
4672
|
+
for (const signal of ["SIGHUP", "SIGTERM"]) {
|
|
4673
|
+
process.on(signal, () => {
|
|
4674
|
+
fatal = signal;
|
|
4675
|
+
child.kill(signal);
|
|
4676
|
+
const grace = setTimeout(() => child.kill("SIGKILL"), 10_000);
|
|
4677
|
+
grace.unref();
|
|
4678
|
+
});
|
|
4679
|
+
}
|
|
4680
|
+
child.on("error", (error) => reject(new Error(`failed to exec ${bin}: ${error.message}`)));
|
|
4681
|
+
child.on("exit", (exitCode, signal) => {
|
|
4682
|
+
if (fatal) {
|
|
4683
|
+
process.removeAllListeners(fatal);
|
|
4684
|
+
process.kill(process.pid, fatal);
|
|
4685
|
+
return;
|
|
4686
|
+
}
|
|
4687
|
+
resolve(exitCode ?? signalExitCode(signal));
|
|
4688
|
+
});
|
|
4689
|
+
});
|
|
4690
|
+
stopProxyKeepalive();
|
|
4691
|
+
const exitClass = code === 0 ? "ok" : "error";
|
|
4692
|
+
const event = commandRunEventOnce(exitClass, exitClass === "error" ? "other" : undefined);
|
|
4693
|
+
if (event)
|
|
4694
|
+
await emitTelemetryEvents([event]);
|
|
4695
|
+
process.exit(code);
|
|
4696
|
+
}
|
|
4277
4697
|
// runWrapped execs the resolved command with the gateway injection applied. It
|
|
4278
4698
|
// auto-starts the local proxy when routing to loopback, so `caveman wrap claude`
|
|
4279
4699
|
// is the one-command compression path. If the proxy can't be reached, a TTY run
|
|
@@ -4354,7 +4774,7 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = f
|
|
|
4354
4774
|
if (managedGeminiUnsupported) {
|
|
4355
4775
|
process.stderr.write("caveman: managed Gemini CLI wrap is unsupported because Gemini CLI cannot send separate Caveman and upstream credentials; launching directly\n");
|
|
4356
4776
|
}
|
|
4357
|
-
//
|
|
4777
|
+
// The local proxy compresses with no account. When wrap runs the LOCAL
|
|
4358
4778
|
// proxy path we resolve the mode; managed gateway traffic is governed by the cloud
|
|
4359
4779
|
// policy engine, so we never resolve it here.
|
|
4360
4780
|
const gateApplies = local && !opts.noProxy;
|
|
@@ -4632,6 +5052,7 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = f
|
|
|
4632
5052
|
summaryKind = "compress";
|
|
4633
5053
|
}
|
|
4634
5054
|
const sessionStart = summaryKind ? new Date().toISOString() : undefined;
|
|
5055
|
+
const stopProxyKeepalive = !direct && local && !opts.noProxy ? startProxyKeepalive(gw) : () => { };
|
|
4635
5056
|
let code;
|
|
4636
5057
|
try {
|
|
4637
5058
|
code = await new Promise((resolve, reject) => {
|
|
@@ -4690,6 +5111,7 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = f
|
|
|
4690
5111
|
});
|
|
4691
5112
|
}
|
|
4692
5113
|
finally {
|
|
5114
|
+
stopProxyKeepalive();
|
|
4693
5115
|
cleanupWrapTempDirs();
|
|
4694
5116
|
removeProxySessionMarker(sessionMarker);
|
|
4695
5117
|
}
|
|
@@ -4833,13 +5255,13 @@ async function startWrapProxy(mode, mcpRecovery, toon, pixelModels, pixelDensity
|
|
|
4833
5255
|
// Observe-only estimate: record mode measures would-have-saved tokens without
|
|
4834
5256
|
// ever mutating the forwarded request.
|
|
4835
5257
|
...(observeEstimate ? { CAVEMAN_OBSERVE_ESTIMATE: "1" } : {}),
|
|
4836
|
-
// Nothing else is stamped for subscription/OAuth compression:
|
|
5258
|
+
// Nothing else is stamped for subscription/OAuth compression: it
|
|
4837
5259
|
// has no account condition. The operator off-switch (`subscription_compress:
|
|
4838
5260
|
// off`) stays the operator's — we never override it from here.
|
|
4839
5261
|
};
|
|
4840
5262
|
// Same reason as `start`: the dead account variable never rides along inherited.
|
|
4841
5263
|
delete env.CAVEMAN_WRAP_ENTITLED;
|
|
4842
|
-
const child = spawn(resolved, [], { stdio: "ignore", env, detached: true });
|
|
5264
|
+
const child = spawn(resolved, [], { stdio: "ignore", env, detached: true, windowsHide: true });
|
|
4843
5265
|
child.unref();
|
|
4844
5266
|
for (let i = 0; i < 20; i++) {
|
|
4845
5267
|
await sleep(100);
|
|
@@ -4851,6 +5273,25 @@ async function startWrapProxy(mode, mcpRecovery, toon, pixelModels, pixelDensity
|
|
|
4851
5273
|
process.stderr.write(`${mark("warn")} started ${bin}, but proxy did not become ready on ${host}:${port}\n`);
|
|
4852
5274
|
return false;
|
|
4853
5275
|
}
|
|
5276
|
+
// startProxyKeepalive heartbeats the local proxy while the wrapped agent process
|
|
5277
|
+
// is alive, so a wrap-owned proxy's idle exit cannot fire under an open-but-quiet
|
|
5278
|
+
// session whose ANTHROPIC_BASE_URL still points at it (#860). The proxy treats
|
|
5279
|
+
// the beat as activity only — nothing is recorded. No immediate beat: launching
|
|
5280
|
+
// is already activity, and short-lived runs should never touch the port. The
|
|
5281
|
+
// timer is unref'd and every failure is ignored (fail-open, like the hooks).
|
|
5282
|
+
function startProxyKeepalive(gw = gatewayURL()) {
|
|
5283
|
+
if (wrapMode(gw) !== "local")
|
|
5284
|
+
return () => { };
|
|
5285
|
+
const { host, port } = gatewayHostPort(gw);
|
|
5286
|
+
const timer = setInterval(() => {
|
|
5287
|
+
const req = httpRequest({ host, port, path: "/caveman/keepalive", method: "POST", timeout: 3000 }, (res) => res.resume());
|
|
5288
|
+
req.on("timeout", () => req.destroy());
|
|
5289
|
+
req.on("error", () => { });
|
|
5290
|
+
req.end();
|
|
5291
|
+
}, 5 * 60 * 1000);
|
|
5292
|
+
timer.unref();
|
|
5293
|
+
return () => clearInterval(timer);
|
|
5294
|
+
}
|
|
4854
5295
|
// wrapMode selects which injection variant to use: "managed" when traffic is aimed
|
|
4855
5296
|
// off-loopback (CAVE_GATEWAY_URL points at a hosted gateway), else "local". Keying
|
|
4856
5297
|
// off where the bytes actually go means `caveman start` (local proxy) and a hosted
|
|
@@ -5289,6 +5730,31 @@ function readJsonObject(path) {
|
|
|
5289
5730
|
return {};
|
|
5290
5731
|
}
|
|
5291
5732
|
}
|
|
5733
|
+
export function normalizeHookPath(path, platform = process.platform) {
|
|
5734
|
+
return platform === "win32" ? path.replace(/\\/g, "/") : path;
|
|
5735
|
+
}
|
|
5736
|
+
export function quoteHookPath(path, platform = process.platform) {
|
|
5737
|
+
const normalized = normalizeHookPath(path, platform);
|
|
5738
|
+
if (platform === "win32")
|
|
5739
|
+
return `'${normalized.replace(/'/g, "''")}'`;
|
|
5740
|
+
return `'${normalized.replace(/'/g, `'"'"'`)}'`;
|
|
5741
|
+
}
|
|
5742
|
+
export function nativeHookInvocation(executable, fastHook, agentId, executableIsProxy, platform = process.platform) {
|
|
5743
|
+
const executableInvocation = hookExecutableInvocation(executable, executableIsProxy ? undefined : fastHook, platform);
|
|
5744
|
+
const invocation = executableIsProxy
|
|
5745
|
+
? `${executableInvocation} native-hook ${agentId} --adapter ${quoteHookPath(fastHook, platform)}`
|
|
5746
|
+
: `${executableInvocation} native-hook ${agentId}`;
|
|
5747
|
+
return invocation;
|
|
5748
|
+
}
|
|
5749
|
+
export function hookExecutableInvocation(executable, script, platform = process.platform) {
|
|
5750
|
+
const invocation = script
|
|
5751
|
+
? `${quoteHookPath(executable, platform)} ${quoteHookPath(script, platform)}`
|
|
5752
|
+
: quoteHookPath(executable, platform);
|
|
5753
|
+
// Claude/Codex/Gemini dispatch command hooks through PowerShell on native
|
|
5754
|
+
// Windows. A quoted executable is only a string literal there; `&` is the
|
|
5755
|
+
// required invocation operator. POSIX hook commands keep their exact shape.
|
|
5756
|
+
return platform === "win32" ? `& ${invocation}` : invocation;
|
|
5757
|
+
}
|
|
5292
5758
|
function nativeHookCommand(agentId) {
|
|
5293
5759
|
const fastHook = join(dirname(fileURLToPath(import.meta.url)), "native-hook-fast.js");
|
|
5294
5760
|
const explicitProxy = process.env.CAVEMAN_PROXY_BIN;
|
|
@@ -5296,10 +5762,10 @@ function nativeHookCommand(agentId) {
|
|
|
5296
5762
|
const proxy = explicitProxy || which("caveman-proxy") || (isExecutable(localProxy) ? localProxy : undefined);
|
|
5297
5763
|
const bridgeCurrent = proxy ? probeVersionedBinary(proxy, "native_hook_bridge_v1").current : false;
|
|
5298
5764
|
if (proxy && bridgeCurrent && existsSync(fastHook)) {
|
|
5299
|
-
return
|
|
5765
|
+
return nativeHookInvocation(proxy, fastHook, agentId, true);
|
|
5300
5766
|
}
|
|
5301
5767
|
if (existsSync(fastHook)) {
|
|
5302
|
-
return
|
|
5768
|
+
return nativeHookInvocation(process.execPath, fastHook, agentId, false);
|
|
5303
5769
|
}
|
|
5304
5770
|
return `${cavemanBinForHook()} native-hook ${agentId}`;
|
|
5305
5771
|
}
|
|
@@ -5619,6 +6085,23 @@ function claudeNativeMutations(gw, mcpBinary) {
|
|
|
5619
6085
|
const route = appendUrlPath(gw, "/w/claude");
|
|
5620
6086
|
const previousRoute = env.ANTHROPIC_BASE_URL;
|
|
5621
6087
|
env.ANTHROPIC_BASE_URL = route;
|
|
6088
|
+
// Routing through the local proxy makes ANTHROPIC_BASE_URL non-first-party in
|
|
6089
|
+
// Claude Code's eyes, which silently drops the 1M context / ~600k
|
|
6090
|
+
// auto-compact window to 200k (#865). When the proxy's anthropic upstream is
|
|
6091
|
+
// verifiably api.anthropic.com, assert first-party through Claude Code's own
|
|
6092
|
+
// escape hatch. Never touches a value the user already carries in settings.
|
|
6093
|
+
const assumeFirstParty = env[CLAUDE_ASSUME_FIRST_PARTY_ENV] === undefined
|
|
6094
|
+
&& wrapMode(gw) === "local" && proxyAnthropicUpstreamIsFirstParty();
|
|
6095
|
+
if (assumeFirstParty)
|
|
6096
|
+
env[CLAUDE_ASSUME_FIRST_PARTY_ENV] = "1";
|
|
6097
|
+
// Claude Code turns tool search (progressive MCP tool disclosure) OFF as soon
|
|
6098
|
+
// as ANTHROPIC_BASE_URL is not a first-party Anthropic host, so pointing it at
|
|
6099
|
+
// caveman would otherwise force every MCP tool schema inline on every request
|
|
6100
|
+
// — measured at ~48k extra prompt tokens on a 4-server setup. The proxy
|
|
6101
|
+
// forwards tool_reference blocks byte-identically, which is the condition
|
|
6102
|
+
// Claude Code names for the override. Never clobber an explicit user value.
|
|
6103
|
+
if (env.ENABLE_TOOL_SEARCH === undefined)
|
|
6104
|
+
env.ENABLE_TOOL_SEARCH = TOOL_SEARCH_DEFAULT;
|
|
5622
6105
|
settings.env = env;
|
|
5623
6106
|
const withHooks = nativeHooksDocument("claude", true, settings);
|
|
5624
6107
|
const mcpPath = join(homedir(), ".claude.json");
|
|
@@ -5640,7 +6123,7 @@ function claudeNativeMutations(gw, mcpBinary) {
|
|
|
5640
6123
|
before: settingsBefore,
|
|
5641
6124
|
after: Buffer.from(JSON.stringify(withHooks, null, 2) + "\n"),
|
|
5642
6125
|
kind: "claude-settings",
|
|
5643
|
-
owned: { route, previous_route: previousRoute ?? null },
|
|
6126
|
+
owned: { route, previous_route: previousRoute ?? null, assume_first_party: assumeFirstParty ? "1" : null },
|
|
5644
6127
|
},
|
|
5645
6128
|
{
|
|
5646
6129
|
file: mcpPath,
|
|
@@ -6673,6 +7156,19 @@ function restoreNativeOperation(operation) {
|
|
|
6673
7156
|
else
|
|
6674
7157
|
currentEnv.ANTHROPIC_BASE_URL = beforeEnv.ANTHROPIC_BASE_URL;
|
|
6675
7158
|
}
|
|
7159
|
+
// The first-party assertion is only ever written when the user carried no
|
|
7160
|
+
// value of their own, so restore is a plain removal — but only while the
|
|
7161
|
+
// value is still exactly ours; a user's later edit outlives disable.
|
|
7162
|
+
const assume = operation.owned?.assume_first_party;
|
|
7163
|
+
if (typeof assume === "string" && currentEnv[CLAUDE_ASSUME_FIRST_PARTY_ENV] === assume) {
|
|
7164
|
+
delete currentEnv[CLAUDE_ASSUME_FIRST_PARTY_ENV];
|
|
7165
|
+
}
|
|
7166
|
+
// Symmetric to the enable-side ENABLE_TOOL_SEARCH write: only withdraw the
|
|
7167
|
+
// value we introduced ourselves and only while it is still untouched, so a
|
|
7168
|
+
// user who set their own afterwards keeps it.
|
|
7169
|
+
if (beforeEnv.ENABLE_TOOL_SEARCH === undefined && currentEnv.ENABLE_TOOL_SEARCH === TOOL_SEARCH_DEFAULT) {
|
|
7170
|
+
delete currentEnv.ENABLE_TOOL_SEARCH;
|
|
7171
|
+
}
|
|
6676
7172
|
if (Object.keys(currentEnv).length > 0)
|
|
6677
7173
|
currentRoot.env = currentEnv;
|
|
6678
7174
|
else
|
|
@@ -7488,6 +7984,12 @@ function wrapBaseUrlEnv(gw) {
|
|
|
7488
7984
|
const env = {};
|
|
7489
7985
|
for (const key of WRAP_BASE_URL_ENV_VARS)
|
|
7490
7986
|
env[key] = gw;
|
|
7987
|
+
// Same reason as the native-enable path: redirecting ANTHROPIC_BASE_URL makes
|
|
7988
|
+
// Claude Code drop tool search and inline every MCP tool schema. Inert for the
|
|
7989
|
+
// other wrappable agents, which never read this variable. A value already in
|
|
7990
|
+
// the environment is the user's choice and wins.
|
|
7991
|
+
if (process.env.ENABLE_TOOL_SEARCH === undefined)
|
|
7992
|
+
env.ENABLE_TOOL_SEARCH = TOOL_SEARCH_DEFAULT;
|
|
7491
7993
|
return env;
|
|
7492
7994
|
}
|
|
7493
7995
|
function attributedGatewayUrl(gw, agent) {
|
|
@@ -7642,6 +8144,13 @@ export function buildWrapEnv(agent, gw = gatewayURL(), mcpMode = "auto") {
|
|
|
7642
8144
|
}
|
|
7643
8145
|
if (agent.id === "hermes")
|
|
7644
8146
|
applyHermesAuthEnv(env, renderedGw, gw);
|
|
8147
|
+
if (agent.id === "claude" && wrapMode(gw) === "local" && env[CLAUDE_ASSUME_FIRST_PARTY_ENV] === undefined && proxyAnthropicUpstreamIsFirstParty()) {
|
|
8148
|
+
// Keep Claude Code's first-party capability set (1M context window /
|
|
8149
|
+
// ~600k auto-compact window) intact behind the local pass-through proxy
|
|
8150
|
+
// (#865). Local-mode only: a managed gateway upstream is not verifiable
|
|
8151
|
+
// from here, and a user-exported value always wins.
|
|
8152
|
+
env[CLAUDE_ASSUME_FIRST_PARTY_ENV] = "1";
|
|
8153
|
+
}
|
|
7645
8154
|
return env;
|
|
7646
8155
|
}
|
|
7647
8156
|
// orgIdFromConfigFile reads the (non-secret) organization id straight from
|
|
@@ -7798,7 +8307,7 @@ function openLoginBrowser(url) {
|
|
|
7798
8307
|
process.stderr.write(` browser opener unavailable; open ${url}\n`);
|
|
7799
8308
|
return;
|
|
7800
8309
|
}
|
|
7801
|
-
const child = spawn(opener.command, opener.args, { detached: true, stdio: "ignore" });
|
|
8310
|
+
const child = spawn(opener.command, opener.args, { detached: true, stdio: "ignore", windowsHide: true });
|
|
7802
8311
|
child.once("error", () => process.stderr.write(` browser did not open; open ${url}\n`));
|
|
7803
8312
|
child.unref();
|
|
7804
8313
|
}
|
|
@@ -7939,7 +8448,7 @@ async function login(argv = []) {
|
|
|
7939
8448
|
// until the control plane has recorded that this CLI stored the bundle.
|
|
7940
8449
|
await acknowledgeDeviceGrant(baseURL, credentials.access_token, code.device_code, ackToken);
|
|
7941
8450
|
}
|
|
7942
|
-
// Mint/refresh the local-wrap entitlement for this device
|
|
8451
|
+
// Mint/refresh the local-wrap entitlement for this device. Best
|
|
7943
8452
|
// effort: login never fails for seats or a down entitlement service.
|
|
7944
8453
|
await fetchAndStoreWrapEntitlement(baseURL, credentials.access_token);
|
|
7945
8454
|
if (gateway && wrapMode(gateway) === "managed") {
|
|
@@ -9694,7 +10203,10 @@ function shouldShrink(command) {
|
|
|
9694
10203
|
// cavemanBinForHook is the invocation a Claude hook uses to call back into this
|
|
9695
10204
|
// CLI, robust to PATH: a resolved `caveman`/`cave`, else this very script's node.
|
|
9696
10205
|
function cavemanBinForHook() {
|
|
9697
|
-
|
|
10206
|
+
const command = which("caveman") ?? which("cave");
|
|
10207
|
+
return command
|
|
10208
|
+
? hookExecutableInvocation(command, undefined)
|
|
10209
|
+
: hookExecutableInvocation(process.execPath, process.argv[1]);
|
|
9698
10210
|
}
|
|
9699
10211
|
// shrinkHook is the settings-hook callback for the agents whose harness can
|
|
9700
10212
|
// deterministically rewrite a shell command before it runs: Claude Code (PreToolUse,
|
|
@@ -10981,11 +11493,15 @@ function opencodePluginPath() {
|
|
|
10981
11493
|
// cavemanInvocation returns how to call back into THIS CLI from a generated plugin,
|
|
10982
11494
|
// baked at install time so it is independent of the agent's PATH: a resolved
|
|
10983
11495
|
// caveman/cave binary, else this script under node.
|
|
11496
|
+
export function generatedPluginInvocation(onPath, currentScript, platform = process.platform) {
|
|
11497
|
+
if (onPath) {
|
|
11498
|
+
const invocation = portableInvocation(onPath, [], platform);
|
|
11499
|
+
return { cmd: invocation.command, pre: invocation.args };
|
|
11500
|
+
}
|
|
11501
|
+
return { cmd: process.execPath, pre: [currentScript] };
|
|
11502
|
+
}
|
|
10984
11503
|
function cavemanInvocation() {
|
|
10985
|
-
|
|
10986
|
-
if (onPath)
|
|
10987
|
-
return { cmd: onPath, pre: [] };
|
|
10988
|
-
return { cmd: process.execPath, pre: [process.argv[1] ?? ""] };
|
|
11504
|
+
return generatedPluginInvocation(which("caveman") ?? which("cave") ?? undefined, process.argv[1] ?? "");
|
|
10989
11505
|
}
|
|
10990
11506
|
function opencodePluginSource() {
|
|
10991
11507
|
const { cmd, pre } = cavemanInvocation();
|
|
@@ -11409,7 +11925,7 @@ function hooksUsage() {
|
|
|
11409
11925
|
}
|
|
11410
11926
|
// hooksDirectiveCmd handles `caveman hooks install|uninstall --directive <id> [agent]`
|
|
11411
11927
|
// (AUTOPILOT_SPEC §7.3): the same verb surface that removes a shrink note today,
|
|
11412
|
-
// extended with a flag — never a new porcelain verb (
|
|
11928
|
+
// extended with a flag — never a new porcelain verb (capped). Install
|
|
11413
11929
|
// announces itself and prints the undo command (§7 announce+undo).
|
|
11414
11930
|
function hooksDirectiveCmd(sub, directiveId, target) {
|
|
11415
11931
|
// Object.hasOwn: directiveId is user input; a truthiness read would let
|
|
@@ -11474,7 +11990,7 @@ function hooksDirectiveCmd(sub, directiveId, target) {
|
|
|
11474
11990
|
}
|
|
11475
11991
|
function hooksCmd(rest) {
|
|
11476
11992
|
// --directive <id> (or --directive=<id>) routes to the wrap-directive
|
|
11477
|
-
// surface (same verb, no new porcelain
|
|
11993
|
+
// surface (same verb, no new porcelain). Any OTHER --flag is
|
|
11478
11994
|
// rejected loudly: silently ignoring `--directive=x` used to install the
|
|
11479
11995
|
// shrink note and exit 0 while the user believed a directive was installed
|
|
11480
11996
|
// (review C8).
|
|
@@ -11754,7 +12270,7 @@ async function trial(rest) {
|
|
|
11754
12270
|
if (learnHistory) {
|
|
11755
12271
|
proxyExecMaybe(["usage", "import", "codex", "--since", since]);
|
|
11756
12272
|
proxyExecMaybe(["usage", "import", "claude", "--since", since]);
|
|
11757
|
-
proxyExecMaybe(["learn", "scan", "--
|
|
12273
|
+
proxyExecMaybe(["learn", "scan", "--since", since]);
|
|
11758
12274
|
}
|
|
11759
12275
|
proxyExec(["trial", "analyze", "--trial-id", trialID], process.env, true);
|
|
11760
12276
|
proxyPassthrough(["trial", "report", "--trial-id", trialID]);
|
|
@@ -11768,6 +12284,11 @@ async function trial(rest) {
|
|
|
11768
12284
|
}
|
|
11769
12285
|
const LEARN_EMPTY = "no Claude Code or Codex sessions found in the last 30d — the plan needs a block repeated across ≥3 sessions; run `caveman claude` a few times, then `caveman learn`";
|
|
11770
12286
|
const LEARN_DETAILED_NEXT = "next: caveman tools skills install caveman-learn (review + apply, with consent) · preview one: caveman learn apply <sink_id> --dry-run";
|
|
12287
|
+
const LEARN_ALL_FOOTER = [
|
|
12288
|
+
"advanced: caveman learn applied <sink_id> [--fix-kind <kind>] [--note <text>] record an approved, re-measured fix",
|
|
12289
|
+
"simulate: caveman learn simulate <sink_id...> sum counterfactual scale over scanned history",
|
|
12290
|
+
"scope: caveman learn --repo <substring> filter sessions before analysis",
|
|
12291
|
+
];
|
|
11771
12292
|
const LEARN_SUMMARY_LIMIT = 3;
|
|
11772
12293
|
function learnReportPath() {
|
|
11773
12294
|
return join(cavemanHome(), "reports", "caveman-learn.html");
|
|
@@ -11795,7 +12316,11 @@ function renderLearnDetailedRows(plan, markdown) {
|
|
|
11795
12316
|
for (const [index, sink] of plan.sinks.entries()) {
|
|
11796
12317
|
const lead = markdown ? `${index + 1}. **${sink.title}**` : `${index + 1}. ${sink.title}`;
|
|
11797
12318
|
lines.push(`${lead} · ${sink.sink_id} · ${sink.class}`);
|
|
11798
|
-
|
|
12319
|
+
const observed = typeof sink.tokens_observed === "number" && sink.tokens_observed > 0
|
|
12320
|
+
? ` · ~${humanTokens(sink.tokens_observed)} tokens observed (historical)`
|
|
12321
|
+
: "";
|
|
12322
|
+
const prefix = learnMeasuredPrefixSuffix(sink);
|
|
12323
|
+
lines.push(` ~${humanTokens(sink.tokens_per_turn)} tokens/turn · ~${humanTokens(sink.tokens_per_day_rate)} tokens/day${observed} · basis: inferred${prefix}`);
|
|
11799
12324
|
if (KNOWN_PRACTICE_IDS.has(sink.practice_id)) {
|
|
11800
12325
|
lines.push(` practice: ${sink.practice_id} · unmeasured — verified nowhere yet`);
|
|
11801
12326
|
}
|
|
@@ -11808,6 +12333,14 @@ function learnEvidenceNumber(sink, key) {
|
|
|
11808
12333
|
const value = sink.evidence?.[key];
|
|
11809
12334
|
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined;
|
|
11810
12335
|
}
|
|
12336
|
+
function learnMeasuredPrefixSuffix(sink) {
|
|
12337
|
+
if (!sink || sink.sink_id !== "config_tax:baseline")
|
|
12338
|
+
return "";
|
|
12339
|
+
const measured = learnEvidenceNumber(sink, "measured_prefix_tokens");
|
|
12340
|
+
return measured && measured > 0
|
|
12341
|
+
? ` · provider-counted prefix ~${humanTokens(measured)} (turn-1 median)`
|
|
12342
|
+
: "";
|
|
12343
|
+
}
|
|
11811
12344
|
function compactLearnText(value, max = 108) {
|
|
11812
12345
|
const oneLine = value.replace(/\s+/g, " ").trim();
|
|
11813
12346
|
if (oneLine.length <= max)
|
|
@@ -11820,10 +12353,37 @@ function compactLearnText(value, max = 108) {
|
|
|
11820
12353
|
return `${prefix.slice(0, wordEnd > 0 ? wordEnd : prefix.length)}…`;
|
|
11821
12354
|
}
|
|
11822
12355
|
export function learnSummaryMoves(plan) {
|
|
11823
|
-
const recurring = plan.sinks.filter((sink) => sink.class === "recurring_context");
|
|
11824
12356
|
const moves = [];
|
|
12357
|
+
const best = plan.portfolio?.best_next_move;
|
|
12358
|
+
const represented = new Set(best?.sink_ids ?? []);
|
|
12359
|
+
if (best) {
|
|
12360
|
+
const confidenceLabels = {
|
|
12361
|
+
measured_usage: "measured",
|
|
12362
|
+
transcript_inferred: "transcript",
|
|
12363
|
+
static_estimate: "estimate",
|
|
12364
|
+
};
|
|
12365
|
+
const confidence = confidenceLabels[best.confidence] ?? best.confidence;
|
|
12366
|
+
const detail = [
|
|
12367
|
+
`sink: ${best.top_sink_id}`,
|
|
12368
|
+
best.combined_rate_per_day > 0
|
|
12369
|
+
? `~${humanTokens(best.combined_rate_per_day)} tokens/day`
|
|
12370
|
+
: "",
|
|
12371
|
+
best.combined_observed_in_window > 0
|
|
12372
|
+
? `~${humanTokens(best.combined_observed_in_window)} tokens observed`
|
|
12373
|
+
: "",
|
|
12374
|
+
confidence,
|
|
12375
|
+
].filter(Boolean);
|
|
12376
|
+
moves.push({
|
|
12377
|
+
title: best.top_sink_title,
|
|
12378
|
+
kind: best.fix_label,
|
|
12379
|
+
detail: detail.join(" · "),
|
|
12380
|
+
...(best.net_note ? { action: compactLearnText(best.net_note) } : {}),
|
|
12381
|
+
});
|
|
12382
|
+
}
|
|
12383
|
+
const remaining = plan.sinks.filter((sink) => !represented.has(sink.sink_id));
|
|
12384
|
+
const recurring = remaining.filter((sink) => sink.class === "recurring_context");
|
|
11825
12385
|
let recurringAdded = false;
|
|
11826
|
-
for (const sink of
|
|
12386
|
+
for (const sink of remaining) {
|
|
11827
12387
|
if (sink.class === "load_bearing")
|
|
11828
12388
|
continue;
|
|
11829
12389
|
if (sink.class === "recurring_context") {
|
|
@@ -11879,6 +12439,9 @@ function learnSourceLine(plan, sessions) {
|
|
|
11879
12439
|
const sourceBits = [
|
|
11880
12440
|
by.claude ? `Claude ${by.claude}` : "",
|
|
11881
12441
|
by.codex ? `Codex ${by.codex}` : "",
|
|
12442
|
+
by.gemini ? `Gemini ${by.gemini}` : "",
|
|
12443
|
+
by.opencode ? `opencode ${by.opencode}` : "",
|
|
12444
|
+
by.aider ? `aider ${by.aider}` : "",
|
|
11882
12445
|
].filter(Boolean);
|
|
11883
12446
|
return `${sessions} sessions${sourceBits.length ? ` · ${sourceBits.join(" · ")}` : ""}`;
|
|
11884
12447
|
}
|
|
@@ -11896,6 +12459,7 @@ export function buildLearnTuiModel(plan, options = {}) {
|
|
|
11896
12459
|
const sessions = Math.max(0, Number(plan.sessions_scanned ?? 0));
|
|
11897
12460
|
const recurring = plan.sinks.some((sink) => sink.class === "recurring_context");
|
|
11898
12461
|
const protectedSink = plan.sinks.find((sink) => sink.class === "load_bearing");
|
|
12462
|
+
const confirmed = plan.confirmed?.length ?? 0;
|
|
11899
12463
|
const diffText = learnDiffText(options.diff);
|
|
11900
12464
|
const status = sessions === 0
|
|
11901
12465
|
? LEARN_EMPTY
|
|
@@ -11910,8 +12474,9 @@ export function buildLearnTuiModel(plan, options = {}) {
|
|
|
11910
12474
|
...(status ? { status } : {}),
|
|
11911
12475
|
moves: learnSummaryMoves(plan),
|
|
11912
12476
|
...(protectedSink
|
|
11913
|
-
? { protected: `${protectedSink.title.replace(/^Your\s+/i, "")} · included in score, never auto-fixed` }
|
|
12477
|
+
? { protected: `${protectedSink.title.replace(/^Your\s+/i, "")} · included in score, never auto-fixed${learnMeasuredPrefixSuffix(protectedSink)}` }
|
|
11914
12478
|
: {}),
|
|
12479
|
+
...(confirmed > 0 ? { confirmed } : {}),
|
|
11915
12480
|
findings: plan.sinks.length,
|
|
11916
12481
|
report: options.report ?? learnReportPath(),
|
|
11917
12482
|
};
|
|
@@ -11923,14 +12488,19 @@ export function renderLearnPlan(plan, options = {}) {
|
|
|
11923
12488
|
const sessions = Math.max(0, Number(plan.sessions_scanned ?? 0));
|
|
11924
12489
|
const recurring = plan.sinks.some((sink) => sink.class === "recurring_context");
|
|
11925
12490
|
const lines = [];
|
|
12491
|
+
const confirmedLines = renderLearnConfirmed(plan.confirmed, markdown);
|
|
11926
12492
|
if (sessions === 0) {
|
|
11927
12493
|
lines.push(LEARN_EMPTY);
|
|
12494
|
+
if (confirmedLines.length > 0)
|
|
12495
|
+
lines.push("", ...confirmedLines);
|
|
11928
12496
|
}
|
|
11929
12497
|
else if (!recurring) {
|
|
11930
12498
|
if (plan.sinks.length > 0) {
|
|
11931
12499
|
lines.push(...(verbose ? renderLearnDetailedRows(plan, markdown) : ["top moves", ...renderLearnSummaryRows(plan)]), "");
|
|
11932
12500
|
}
|
|
11933
12501
|
lines.push(`${sessions} sessions scanned · no block repeated across ≥3 sessions yet — keep running \`caveman claude\`, then re-run \`caveman learn\``);
|
|
12502
|
+
if (confirmedLines.length > 0)
|
|
12503
|
+
lines.push("", ...confirmedLines);
|
|
11934
12504
|
}
|
|
11935
12505
|
else {
|
|
11936
12506
|
lines.push(markdown
|
|
@@ -11950,6 +12520,8 @@ export function renderLearnPlan(plan, options = {}) {
|
|
|
11950
12520
|
const diffText = learnDiffText(options.diff);
|
|
11951
12521
|
if (diffText)
|
|
11952
12522
|
lines.push(diffText);
|
|
12523
|
+
if (confirmedLines.length > 0)
|
|
12524
|
+
lines.push("", ...confirmedLines);
|
|
11953
12525
|
if (verbose) {
|
|
11954
12526
|
lines.push("", ...renderLearnDetailedRows(plan, markdown), "", LEARN_DETAILED_NEXT);
|
|
11955
12527
|
}
|
|
@@ -11958,14 +12530,65 @@ export function renderLearnPlan(plan, options = {}) {
|
|
|
11958
12530
|
lines.push("", "top moves", ...renderLearnSummaryRows(plan));
|
|
11959
12531
|
if (protectedSink) {
|
|
11960
12532
|
const title = protectedSink.title.replace(/^Your\s+/i, "");
|
|
11961
|
-
lines.push(`protected ${title} · included in score, never auto-fixed`);
|
|
12533
|
+
lines.push(`protected ${title} · included in score, never auto-fixed${learnMeasuredPrefixSuffix(protectedSink)}`);
|
|
11962
12534
|
}
|
|
11963
12535
|
lines.push("", `next: ${invokedAs()} learn implement fix with Claude Code or Codex; asks before every edit`, `details: ${invokedAs()} learn --all ${plan.sinks.length} findings`);
|
|
11964
12536
|
}
|
|
11965
12537
|
}
|
|
12538
|
+
if (options.all === true && (plan.repos?.length ?? 0) > 0) {
|
|
12539
|
+
lines.push("", markdown ? "### Per-repo" : "per-repo", ...renderLearnRepos(plan.repos, markdown));
|
|
12540
|
+
}
|
|
12541
|
+
if (options.all === true) {
|
|
12542
|
+
lines.push("", ...(markdown ? ["### Advanced", ...LEARN_ALL_FOOTER.map((line) => `- ${line}`)] : LEARN_ALL_FOOTER));
|
|
12543
|
+
}
|
|
11966
12544
|
lines.push("", `report: ${report}`);
|
|
11967
12545
|
return `${lines.join("\n")}\n`;
|
|
11968
12546
|
}
|
|
12547
|
+
function learnMeasureValue(value) {
|
|
12548
|
+
if (value === undefined || !Number.isFinite(value))
|
|
12549
|
+
return "?";
|
|
12550
|
+
if (Number.isInteger(value))
|
|
12551
|
+
return String(value);
|
|
12552
|
+
return value.toFixed(1).replace(/\.0$/, "");
|
|
12553
|
+
}
|
|
12554
|
+
function learnMeasureUnit(unit) {
|
|
12555
|
+
const labels = {
|
|
12556
|
+
config_tokens_per_turn: "config tokens/turn",
|
|
12557
|
+
turns_over_half_window_pct: "turns over half-window (%)",
|
|
12558
|
+
recurrence_present: "recurrence present",
|
|
12559
|
+
};
|
|
12560
|
+
return labels[unit] ?? unit.replaceAll("_", " ");
|
|
12561
|
+
}
|
|
12562
|
+
function learnAppliedDate(appliedAt) {
|
|
12563
|
+
return appliedAt.slice(0, 10);
|
|
12564
|
+
}
|
|
12565
|
+
function renderLearnConfirmed(confirmed, markdown) {
|
|
12566
|
+
if (!confirmed?.length)
|
|
12567
|
+
return [];
|
|
12568
|
+
const symbols = {
|
|
12569
|
+
improved: "✓",
|
|
12570
|
+
unchanged: "·",
|
|
12571
|
+
regressed: "!",
|
|
12572
|
+
insufficient_data: "·",
|
|
12573
|
+
};
|
|
12574
|
+
const rows = confirmed.flatMap((entry) => {
|
|
12575
|
+
const applied = learnAppliedDate(entry.applied_at);
|
|
12576
|
+
if (entry.verdict === "insufficient_data") {
|
|
12577
|
+
const line = `${symbols[entry.verdict]} ${entry.sink_id} — applied ${applied} · needs more post-fix sessions (${entry.sessions_after} sessions so far)`;
|
|
12578
|
+
return [markdown ? `- *${line}*` : line];
|
|
12579
|
+
}
|
|
12580
|
+
if (entry.after === undefined || !Number.isFinite(entry.after))
|
|
12581
|
+
return [];
|
|
12582
|
+
const line = `${symbols[entry.verdict]} ${entry.sink_id} — ${learnMeasureValue(entry.before)} → ${learnMeasureValue(entry.after)} ${learnMeasureUnit(entry.unit)} over ${entry.sessions_after} sessions (${entry.verdict}) · applied ${applied}`;
|
|
12583
|
+
return [markdown ? `- ${line}` : line];
|
|
12584
|
+
});
|
|
12585
|
+
if (rows.length === 0)
|
|
12586
|
+
return [];
|
|
12587
|
+
return [markdown ? "### Confirmed fixes" : "confirmed fixes", ...rows];
|
|
12588
|
+
}
|
|
12589
|
+
function renderLearnRepos(repos, markdown) {
|
|
12590
|
+
return repos.map((repo) => `${markdown ? "- " : ""}${repo.repo} · ${repo.sessions} sessions · dumbzone ${repo.dumbzone_pct}% · median context ~${humanTokens(repo.median_context)}`);
|
|
12591
|
+
}
|
|
11969
12592
|
function readLearnDiff(current) {
|
|
11970
12593
|
const dir = join(cavemanHome(), "reports");
|
|
11971
12594
|
let files;
|
|
@@ -12098,6 +12721,16 @@ function proxyExecLearnAsync(proxyArgs, onProgress) {
|
|
|
12098
12721
|
});
|
|
12099
12722
|
});
|
|
12100
12723
|
}
|
|
12724
|
+
export function formatLearnProxyJSON(raw, tty = !!process.stdout.isTTY) {
|
|
12725
|
+
if (!tty)
|
|
12726
|
+
return raw;
|
|
12727
|
+
try {
|
|
12728
|
+
return `${JSON.stringify(JSON.parse(raw), null, 2)}\n`;
|
|
12729
|
+
}
|
|
12730
|
+
catch {
|
|
12731
|
+
return raw;
|
|
12732
|
+
}
|
|
12733
|
+
}
|
|
12101
12734
|
export function learnReportOpener(report, platform = process.platform) {
|
|
12102
12735
|
if (platform === "darwin")
|
|
12103
12736
|
return { command: "open", args: [report] };
|
|
@@ -12119,7 +12752,7 @@ function openLearnReport(report) {
|
|
|
12119
12752
|
process.stderr.write(`cannot open visual report; open this file: ${report}\n`);
|
|
12120
12753
|
return;
|
|
12121
12754
|
}
|
|
12122
|
-
const child = spawn(opener.command, opener.args, { detached: true, stdio: "ignore" });
|
|
12755
|
+
const child = spawn(opener.command, opener.args, { detached: true, stdio: "ignore", windowsHide: true });
|
|
12123
12756
|
child.once("error", () => {
|
|
12124
12757
|
process.stderr.write(`cannot open visual report; open this file: ${report}\n`);
|
|
12125
12758
|
});
|
|
@@ -12151,13 +12784,21 @@ function renderLearnApply(raw, dryRun) {
|
|
|
12151
12784
|
return `${lines.join("\n")}\n`;
|
|
12152
12785
|
}
|
|
12153
12786
|
function learnUsage() {
|
|
12154
|
-
console.log(`${invokedAs()} learn [--all|--plain|--json|--md] [--since 30d] [--sources codex,
|
|
12787
|
+
console.log(`${invokedAs()} learn [--all|--plain|--json|--md] [--since 30d] [--sources claude,codex,gemini,opencode,aider]
|
|
12155
12788
|
default interactive setup score + grouped top moves
|
|
12156
12789
|
--plain compact text; no animation or keyboard menu
|
|
12157
12790
|
--all every finding, internal id, basis, and suggestion
|
|
12158
12791
|
--json|--md machine-readable or detailed Markdown output
|
|
12159
12792
|
implement open Claude Code or Codex to review and fix findings
|
|
12160
|
-
apply prepare one finding for consent-gated editing
|
|
12793
|
+
apply prepare one finding for consent-gated editing
|
|
12794
|
+
|
|
12795
|
+
advanced:
|
|
12796
|
+
applied <sink_id> [--fix-kind <kind>] [--note <text>]
|
|
12797
|
+
record an approved, re-measured fix
|
|
12798
|
+
simulate <sink_id...>
|
|
12799
|
+
sum counterfactual scale over scanned history
|
|
12800
|
+
--repo <substring>
|
|
12801
|
+
filter sessions before analysis`);
|
|
12161
12802
|
}
|
|
12162
12803
|
function learnImplementUsage() {
|
|
12163
12804
|
console.log(`${invokedAs()} learn implement [claude|codex] [--prompt "<focus>"]
|
|
@@ -12270,6 +12911,11 @@ async function learn(rest) {
|
|
|
12270
12911
|
return learnUsage();
|
|
12271
12912
|
if (sub === "implement")
|
|
12272
12913
|
return learnImplement(rest.slice(1));
|
|
12914
|
+
if (sub === "applied" || sub === "simulate") {
|
|
12915
|
+
const rawText = proxyExecLearn(["learn", ...rest], false);
|
|
12916
|
+
process.stdout.write(formatLearnProxyJSON(rawText));
|
|
12917
|
+
return;
|
|
12918
|
+
}
|
|
12273
12919
|
if (sub === "apply") {
|
|
12274
12920
|
const json = rest.includes("--json");
|
|
12275
12921
|
const rawText = proxyExecLearn(["learn", ...rest], false);
|
|
@@ -12286,6 +12932,7 @@ async function learn(rest) {
|
|
|
12286
12932
|
const json = rest.includes("--json");
|
|
12287
12933
|
const markdown = rest.includes("--md");
|
|
12288
12934
|
const verbose = rest.includes("--all") || rest.includes("--verbose");
|
|
12935
|
+
const all = rest.includes("--all");
|
|
12289
12936
|
const tui = learnTuiEnabled(rest);
|
|
12290
12937
|
const forwarded = rest.filter((arg) => !["--json", "--md", "--all", "--verbose", "--plain"].includes(arg));
|
|
12291
12938
|
const reportBefore = learnReportMtime();
|
|
@@ -12323,6 +12970,7 @@ async function learn(rest) {
|
|
|
12323
12970
|
process.stdout.write(renderLearnPlan(plan, {
|
|
12324
12971
|
report,
|
|
12325
12972
|
verbose: true,
|
|
12973
|
+
all: true,
|
|
12326
12974
|
...(diff ? { diff } : {}),
|
|
12327
12975
|
}));
|
|
12328
12976
|
return;
|
|
@@ -12349,6 +12997,7 @@ async function learn(rest) {
|
|
|
12349
12997
|
markdown,
|
|
12350
12998
|
report: learnReportPath(),
|
|
12351
12999
|
verbose,
|
|
13000
|
+
all,
|
|
12352
13001
|
...(diff ? { diff } : {}),
|
|
12353
13002
|
}));
|
|
12354
13003
|
}
|
|
@@ -12740,8 +13389,8 @@ function proxyRuntimeMatches(runtime, mode, recoveryViaMCP) {
|
|
|
12740
13389
|
&& runtime.mode === mode
|
|
12741
13390
|
&& proxyRuntimeGateMatches(runtime, recoveryViaMCP);
|
|
12742
13391
|
}
|
|
12743
|
-
// The only cross-session gate input left is the recovery contract (
|
|
12744
|
-
//
|
|
13392
|
+
// The only cross-session gate input left is the recovery contract (the account
|
|
13393
|
+
// one was removed): reusing a proxy that lacks the agent's caveman_retrieve tool
|
|
12745
13394
|
// would elide bytes nothing can expand.
|
|
12746
13395
|
function proxyRuntimeGateMatches(runtime, recoveryViaMCP) {
|
|
12747
13396
|
return runtime.recovery_via_mcp === recoveryViaMCP;
|
|
@@ -14645,10 +15294,14 @@ export function commandHasPath(command) {
|
|
|
14645
15294
|
export function executableCandidateNames(command, platform = process.platform, pathExt = process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD") {
|
|
14646
15295
|
if (platform !== "win32" || extname(command))
|
|
14647
15296
|
return [command];
|
|
14648
|
-
const candidates = [
|
|
15297
|
+
const candidates = [];
|
|
14649
15298
|
for (const extension of pathExt.split(";").map((value) => value.trim()).filter(Boolean)) {
|
|
14650
15299
|
candidates.push(`${command}${extension.startsWith(".") ? extension : `.${extension}`}`);
|
|
14651
15300
|
}
|
|
15301
|
+
// Windows cannot launch extensionless POSIX npm shims without a shell. Keep
|
|
15302
|
+
// the bare name as a fallback for real extensionless executables, but prefer
|
|
15303
|
+
// native executables and cmd/bat shims from PATHEXT.
|
|
15304
|
+
candidates.push(command);
|
|
14652
15305
|
const seen = new Set();
|
|
14653
15306
|
return candidates.filter((candidate) => {
|
|
14654
15307
|
const key = candidate.toLowerCase();
|