@caveman-ai/cli 1.3.3 → 2.0.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/LICENSE +202 -21
- package/NOTICE +66 -0
- package/README.md +30 -1
- package/dist/agent-skills.generated.js +2 -2
- package/dist/agents.generated.js +24 -24
- package/dist/binaries.generated.js +1 -1
- package/dist/caveman-delegate-mcp.mjs +0 -0
- package/dist/caveman-pi-extension.mjs +291 -104
- package/dist/index.js +1638 -383
- package/dist/learn-autopilot.js +447 -0
- package/dist/learn-trends.js +132 -0
- package/dist/learn-tui.js +31 -31
- package/dist/native-hook-fast.js +19 -6
- package/dist/native-pack.generated.js +1 -1
- package/dist/openclaw-provider-compat.js +111 -0
- package/dist/provider-routing.js +147 -0
- package/dist/stats-cli.js +105 -0
- package/package.json +12 -12
package/dist/index.js
CHANGED
|
@@ -11,8 +11,9 @@ import { createHash, createHmac, createPublicKey, randomBytes, randomUUID, verif
|
|
|
11
11
|
import { fileURLToPath } from "node:url";
|
|
12
12
|
import { parseEnv } from "node:util";
|
|
13
13
|
import { PROFILES } from "./agents.generated.js";
|
|
14
|
+
import { autopilotStatusText, claimLearnNudge, confirmLearnNudge, maybeSpawnAutopilot, runAutopilot } from "./learn-autopilot.js";
|
|
14
15
|
import { BINARY_RELEASE, BINARY_RELEASE_BASE_DEFAULT, BINARY_SIGNING_PUBKEY, } from "./binaries.generated.js";
|
|
15
|
-
import { installProxyAwareFetch } from "./proxy-fetch.js";
|
|
16
|
+
import { installProxyAwareFetch, resolveProxyUrl } from "./proxy-fetch.js";
|
|
16
17
|
import { RECIPES } from "./recipes.generated.js";
|
|
17
18
|
import { PRACTICE_REGISTRY } from "./practices.generated.js";
|
|
18
19
|
import { RESERVED_VERBS } from "./reserved-verbs.generated.js";
|
|
@@ -22,6 +23,10 @@ import { NATIVE_CORE, NATIVE_PACK, NATIVE_SKILL_INSTRUCTIONS } from "./native-pa
|
|
|
22
23
|
import { serveAgentMcp, } from "./agent-mcp.js";
|
|
23
24
|
import { portableInvocation } from "./portable-command.js";
|
|
24
25
|
import { hardenedGitArgs, hardenedGitEnv } from "./git-safe.js";
|
|
26
|
+
import { learnTrendLines, learnTrendTable } from "./learn-trends.js";
|
|
27
|
+
import { publishedForwardHeadersOf, publishedUpstreamsOf, trimTrailingSlashes, unforwardedProviderHeaders, verifiedProviderRoute } from "./provider-routing.js";
|
|
28
|
+
import { openClawRequestCompatibilityIssue, preserveOpenClawProviderCompat } from "./openclaw-provider-compat.js";
|
|
29
|
+
import { parseStatsOptions, renderStatsSummary, STATS_HELP, STATS_USAGE } from "./stats-cli.js";
|
|
25
30
|
export const overlayBuilders = {};
|
|
26
31
|
const wrapTempDirs = new Set();
|
|
27
32
|
// The standalone proxy listens here; `caveman start` launches it and
|
|
@@ -121,7 +126,7 @@ const CLOUD_DISCOVERY = [
|
|
|
121
126
|
{ heading: "governance", verbs: [
|
|
122
127
|
{ verb: "audit", description: "import or report audit evidence" },
|
|
123
128
|
{ verb: "sync", description: "sync local metadata to connected org" },
|
|
124
|
-
{ verb: "agent", description: "inspect
|
|
129
|
+
{ verb: "agent", description: "inspect agents and optimization proposals" },
|
|
125
130
|
] },
|
|
126
131
|
];
|
|
127
132
|
const TOOL_VERBS = new Set(TOOL_DISCOVERY.flatMap((group) => group.verbs.map((entry) => entry.verb)));
|
|
@@ -230,14 +235,22 @@ const CLOUD_HANDLERS = {
|
|
|
230
235
|
},
|
|
231
236
|
audit,
|
|
232
237
|
sync: () => sync(),
|
|
233
|
-
agent: (argv) => {
|
|
238
|
+
agent: async (argv) => {
|
|
239
|
+
if (argv[0] === "factory") {
|
|
240
|
+
if (argv[1] === "list" && argv.length === 2)
|
|
241
|
+
return get(`/api/v1/projects/${await projectId()}/agents`).then(print);
|
|
242
|
+
if (argv[1] === "show" && argv.length === 3 && /^[A-Za-z0-9_-]+$/.test(argv[2])) {
|
|
243
|
+
return get(`/api/v1/projects/${await projectId()}/agents/${argv[2]}`).then(print);
|
|
244
|
+
}
|
|
245
|
+
return commandUsage("agent factory list|show <id>");
|
|
246
|
+
}
|
|
234
247
|
if (argv[0] === "list")
|
|
235
248
|
return get("/api/v1/optimization-proposals").then(print);
|
|
236
249
|
if (argv[0] === "show")
|
|
237
250
|
return get(`/api/v1/optimization-proposals/${argv[1] ?? ""}`).then(print);
|
|
238
251
|
if (argv[0] === "run")
|
|
239
252
|
return post(`/api/v1/optimization-proposals/${argv[1] ?? ""}/run`, {}).then(print);
|
|
240
|
-
return commandUsage("agent list|show <id>|run <id>");
|
|
253
|
+
return commandUsage("agent list|show <id>|run <id> | agent factory list|show <id>");
|
|
241
254
|
},
|
|
242
255
|
};
|
|
243
256
|
const LEGACY_HANDLERS = {
|
|
@@ -400,18 +413,20 @@ function invokedCommand(legacyVerb, groupedTail = "") {
|
|
|
400
413
|
}
|
|
401
414
|
let currentInvocation;
|
|
402
415
|
currentInvocation = resolveInvocation(process.argv.slice(2));
|
|
403
|
-
// Version
|
|
404
|
-
//
|
|
405
|
-
//
|
|
406
|
-
//
|
|
407
|
-
//
|
|
408
|
-
//
|
|
409
|
-
|
|
410
|
-
const
|
|
411
|
-
//
|
|
412
|
-
|
|
413
|
-
const PROD_API_URL =
|
|
414
|
-
|
|
416
|
+
// Version 5 = the receiver stores the client IP address with each event. v4 was
|
|
417
|
+
// default-on (opt-out) plus token volume (command_run carries the local proxy's
|
|
418
|
+
// processed/saved token deltas). A stale-version "yes" was given for a narrower
|
|
419
|
+
// scope and gets the new disclosure reprinted once (never re-asked, and never
|
|
420
|
+
// flipped on). A persisted decision from any version — including a "no" to the
|
|
421
|
+
// old v1 [y/N] prompt — is honored forever; the default only fills the undecided
|
|
422
|
+
// gap, and the first default-on run prints the disclosure line.
|
|
423
|
+
const TELEMETRY_PROMPT_VERSION = 5;
|
|
424
|
+
// Supabase Edge Function; source and schema live in supabase/ at the repo root.
|
|
425
|
+
const TELEMETRY_URL = "https://xvfgtprkhzlvegvmeefq.supabase.co/functions/v1/cli-telemetry";
|
|
426
|
+
const PROD_API_URL = "https://api.caveman.so";
|
|
427
|
+
// Where `telemetry off` points someone who wants already-sent events deleted.
|
|
428
|
+
const TELEMETRY_DELETION_URL = "https://github.com/JuliusBrussee/caveman/blob/main/SECURITY.md#delete-sent-telemetry";
|
|
429
|
+
const TELEMETRY_DISCLOSURE_LINE = "usage stats on — commands, agent sessions, token totals, account and install type, timezone and language, and your IP address; never prompts, code, or file paths · caveman telemetry off";
|
|
415
430
|
// Reading token totals means spawning caveman-proxy to query the local SQLite
|
|
416
431
|
// store. It runs after the command's own work, so the cost lands on process exit;
|
|
417
432
|
// a slow or wedged binary drops the token fields rather than holding the CLI.
|
|
@@ -476,10 +491,25 @@ function telemetryState() {
|
|
|
476
491
|
}
|
|
477
492
|
// telemetrySendable is the single choke point every emitter must pass: on, and
|
|
478
493
|
// never the un-persisted default (no silent sends, no ephemeral-id retention
|
|
479
|
-
// noise from commands that skipped the disclosure).
|
|
494
|
+
// noise from commands that skipped the disclosure). A config-sourced yes given
|
|
495
|
+
// under older wording also waits until the current disclosure has printed —
|
|
496
|
+
// help-like and `telemetry …` invocations skip that reprint, so without this
|
|
497
|
+
// they would send the widened scope unseen.
|
|
480
498
|
function telemetrySendable(state) {
|
|
499
|
+
if (state.source === "config" && (state.config?.promptVersion ?? 0) < TELEMETRY_PROMPT_VERSION)
|
|
500
|
+
return false;
|
|
481
501
|
return state.state === "on" && state.source !== "default";
|
|
482
502
|
}
|
|
503
|
+
// Native agent sessions never have a TTY. A decision persisted by an
|
|
504
|
+
// interactive run (which printed the disclosure) still covers them; CI and the
|
|
505
|
+
// env kills still win, and no default is ever minted here.
|
|
506
|
+
function sessionTelemetryState() {
|
|
507
|
+
const state = telemetryState();
|
|
508
|
+
if (state.source !== "runtime" || envTruthy(process.env.CI))
|
|
509
|
+
return state;
|
|
510
|
+
const cfg = state.config;
|
|
511
|
+
return cfg?.decidedAt ? { state: cfg.enabled ? "on" : "off", source: "config", config: cfg } : state;
|
|
512
|
+
}
|
|
483
513
|
function envTruthy(v) {
|
|
484
514
|
return v !== undefined && v !== "" && v !== "0" && v.toLowerCase() !== "false";
|
|
485
515
|
}
|
|
@@ -521,6 +551,7 @@ function parseTelemetryConfig(value) {
|
|
|
521
551
|
// any persisted decision — including a "no" to the old v1 prompt — win.
|
|
522
552
|
async function ensureTelemetryDefault() {
|
|
523
553
|
const state = telemetryState();
|
|
554
|
+
await persistTelemetryEnvKill(state);
|
|
524
555
|
if (isHelpLikeInvocation())
|
|
525
556
|
return;
|
|
526
557
|
// `caveman telemetry …` manages the decision explicitly — don't pre-mint an
|
|
@@ -548,6 +579,28 @@ async function ensureTelemetryDefault() {
|
|
|
548
579
|
}
|
|
549
580
|
process.stderr.write(`${dim(TELEMETRY_DISCLOSURE_LINE)}\n`);
|
|
550
581
|
}
|
|
582
|
+
// persistTelemetryEnvKill turns DO_NOT_TRACK / CAVEMAN_TELEMETRY=0, seen by an
|
|
583
|
+
// interactive run, into a persisted opt-out. Native agent hooks run under hosts
|
|
584
|
+
// that often never read the shell rc (GUI apps, launchd/systemd services), so an
|
|
585
|
+
// env-only kill would not reach them while config still says yes.
|
|
586
|
+
async function persistTelemetryEnvKill(state) {
|
|
587
|
+
if (state.source !== "env" || state.state !== "off" || !state.config?.enabled || !interactive())
|
|
588
|
+
return;
|
|
589
|
+
try {
|
|
590
|
+
await saveTelemetryConfig({ enabled: false, decidedAt: new Date().toISOString(), promptVersion: TELEMETRY_PROMPT_VERSION });
|
|
591
|
+
mutateRawConfig((out) => {
|
|
592
|
+
delete out.telemetryTokens;
|
|
593
|
+
});
|
|
594
|
+
}
|
|
595
|
+
catch {
|
|
596
|
+
/* best effort: the env var still wins for this process */
|
|
597
|
+
return;
|
|
598
|
+
}
|
|
599
|
+
// The id is gone from disk now, and it is the only key to a deletion request.
|
|
600
|
+
if (state.config.anonymousId) {
|
|
601
|
+
process.stderr.write(`${dim(`telemetry off · old install id ${state.config.anonymousId} · delete what it sent: ${TELEMETRY_DELETION_URL}`)}\n`);
|
|
602
|
+
}
|
|
603
|
+
}
|
|
551
604
|
// ensureTelemetryDisclosureVersion reprints the disclosure once for someone who
|
|
552
605
|
// consented under older wording. v4 widened command_run with token volume, and a
|
|
553
606
|
// v3 "yes" was given for command counts alone — it stays a yes (re-asking would
|
|
@@ -618,12 +671,19 @@ async function telemetryCmd(argv) {
|
|
|
618
671
|
return telemetryOn();
|
|
619
672
|
if (sub === "off")
|
|
620
673
|
return telemetryOff();
|
|
674
|
+
// Unprinted: the detached children startSessionTelemetry and emitTelemetryEvents spawn.
|
|
675
|
+
if (sub === "session")
|
|
676
|
+
return telemetrySession(argv.slice(1));
|
|
677
|
+
if (sub === "send")
|
|
678
|
+
return telemetrySend();
|
|
621
679
|
emitCommandRunOnce("error", "usage");
|
|
622
680
|
console.error(`usage: ${invokedCommand("telemetry")} [status|on|off]`);
|
|
623
681
|
process.exit(2);
|
|
624
682
|
}
|
|
625
683
|
function telemetryStatus() {
|
|
626
|
-
|
|
684
|
+
// Session state, not command state: an agent or pipe running this has no TTY,
|
|
685
|
+
// yet native hooks still send under a persisted yes.
|
|
686
|
+
const state = sessionTelemetryState();
|
|
627
687
|
print({
|
|
628
688
|
enabled: state.state === "on",
|
|
629
689
|
state: state.state,
|
|
@@ -641,6 +701,8 @@ async function telemetryOn() {
|
|
|
641
701
|
promptVersion: TELEMETRY_PROMPT_VERSION,
|
|
642
702
|
};
|
|
643
703
|
await saveTelemetryConfig(telemetry);
|
|
704
|
+
// The stored version claims this wording was shown, so show it.
|
|
705
|
+
process.stderr.write(`${dim(TELEMETRY_DISCLOSURE_LINE)}\n`);
|
|
644
706
|
if (!(prior?.enabled && prior.anonymousId) && !telemetryEnvForcesOff())
|
|
645
707
|
emitConsentGranted(anonymousId);
|
|
646
708
|
if (telemetryEnvForcesOff()) {
|
|
@@ -650,6 +712,7 @@ async function telemetryOn() {
|
|
|
650
712
|
print({ telemetry: "on", anonymous_id: anonymousId });
|
|
651
713
|
}
|
|
652
714
|
async function telemetryOff() {
|
|
715
|
+
const prior = telemetryConfigFromDisk();
|
|
653
716
|
const telemetry = {
|
|
654
717
|
enabled: false,
|
|
655
718
|
decidedAt: new Date().toISOString(),
|
|
@@ -667,8 +730,96 @@ async function telemetryOff() {
|
|
|
667
730
|
catch {
|
|
668
731
|
/* best effort: the decision itself is already persisted */
|
|
669
732
|
}
|
|
733
|
+
// The id leaves the config here, and it is the only key to events already
|
|
734
|
+
// sent, so show it once with where to ask for their deletion.
|
|
735
|
+
if (prior?.anonymousId) {
|
|
736
|
+
print({ telemetry: "off", anonymous_id: "none", discarded_anonymous_id: prior.anonymousId, delete_sent_data: TELEMETRY_DELETION_URL });
|
|
737
|
+
return;
|
|
738
|
+
}
|
|
670
739
|
print({ telemetry: "off", anonymous_id: "none" });
|
|
671
740
|
}
|
|
741
|
+
// Native sessions are where installed users show up: after setup most people
|
|
742
|
+
// launch the agent directly and never run the CLI. The host waits on the
|
|
743
|
+
// SessionStart hook, so the send runs in a detached child and never delays the
|
|
744
|
+
// agent's start.
|
|
745
|
+
function startSessionTelemetry(agent, sessionId, source) {
|
|
746
|
+
if (!telemetrySendable(sessionTelemetryState()))
|
|
747
|
+
return;
|
|
748
|
+
// One event per host session: resumes, repeated SessionStart calls (the
|
|
749
|
+
// OpenCode V1 plugin re-asks on every model step when it gets no context) and
|
|
750
|
+
// hooks registered in two scopes would otherwise each count. Checked here so
|
|
751
|
+
// a repeat costs one failed file create, not a process spawn.
|
|
752
|
+
if (sessionId) {
|
|
753
|
+
const dir = join(cavemanHome(), "runtime", "telemetry-sessions");
|
|
754
|
+
try {
|
|
755
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
756
|
+
closeSync(openSync(join(dir, createHash("sha256").update(`${agent}\0${sessionId}`).digest("hex")), "wx", 0o600));
|
|
757
|
+
}
|
|
758
|
+
catch (error) {
|
|
759
|
+
if (error.code === "EEXIST")
|
|
760
|
+
return;
|
|
761
|
+
/* unwritable home: count it rather than lose it */
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
const sessionSource = source === "startup" || source === "resume" || source === "clear" ? source : "unknown";
|
|
765
|
+
try {
|
|
766
|
+
const child = spawn(process.execPath, [fileURLToPath(import.meta.url), "telemetry", "session", agent, sessionSource], {
|
|
767
|
+
detached: true,
|
|
768
|
+
stdio: "ignore",
|
|
769
|
+
windowsHide: true,
|
|
770
|
+
});
|
|
771
|
+
child.on("error", () => { });
|
|
772
|
+
child.unref();
|
|
773
|
+
}
|
|
774
|
+
catch {
|
|
775
|
+
/* telemetry never blocks a session */
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
async function telemetrySession(argv) {
|
|
779
|
+
// session_start stands in for this invocation's command_run.
|
|
780
|
+
telemetryCommandSent = true;
|
|
781
|
+
pruneSessionMarkers();
|
|
782
|
+
const agent = findAgent(argv[0] ?? "")?.id;
|
|
783
|
+
const state = sessionTelemetryState();
|
|
784
|
+
// No persisted id means every session would mint a fresh "user".
|
|
785
|
+
if (!agent || !telemetrySendable(state) || !state.config?.anonymousId)
|
|
786
|
+
return;
|
|
787
|
+
const event = {
|
|
788
|
+
schema: "cli/v1",
|
|
789
|
+
anonymous_id: state.config.anonymousId,
|
|
790
|
+
event: "session_start",
|
|
791
|
+
agent,
|
|
792
|
+
session_source: argv[1] === "startup" || argv[1] === "resume" || argv[1] === "clear" ? argv[1] : "unknown",
|
|
793
|
+
cli_version: cliVersion(),
|
|
794
|
+
os: process.platform,
|
|
795
|
+
arch: process.arch,
|
|
796
|
+
node_major: Number(process.versions.node.split(".")[0] ?? 0),
|
|
797
|
+
ts: new Date().toISOString(),
|
|
798
|
+
};
|
|
799
|
+
const tokens = telemetryTokenDelta();
|
|
800
|
+
if (tokens) {
|
|
801
|
+
event.tokens_processed = tokens.processed;
|
|
802
|
+
event.tokens_saved = tokens.saved;
|
|
803
|
+
event.tokens_basis = tokens.basis;
|
|
804
|
+
}
|
|
805
|
+
await postTelemetry(telemetryBody([event]), 10_000);
|
|
806
|
+
}
|
|
807
|
+
// Markers only need to outlive one session's repeated SessionStart calls; a
|
|
808
|
+
// resume the next day counts as a new session. Bounded per run.
|
|
809
|
+
function pruneSessionMarkers() {
|
|
810
|
+
const dir = join(cavemanHome(), "runtime", "telemetry-sessions");
|
|
811
|
+
try {
|
|
812
|
+
const cutoff = Date.now() - 24 * 60 * 60 * 1000;
|
|
813
|
+
for (const name of readdirSync(dir).slice(0, 500)) {
|
|
814
|
+
const path = join(dir, name);
|
|
815
|
+
if (statSync(path).mtimeMs < cutoff)
|
|
816
|
+
unlinkSync(path);
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
catch {
|
|
820
|
+
/* nothing to prune */
|
|
821
|
+
}
|
|
822
|
+
}
|
|
672
823
|
function telemetryCommandName() {
|
|
673
824
|
if (currentInvocation.verb === "mcp-serve")
|
|
674
825
|
return "mcp";
|
|
@@ -778,6 +929,8 @@ function readProxyTokenTotals() {
|
|
|
778
929
|
encoding: "utf8",
|
|
779
930
|
timeout: TELEMETRY_TOKEN_READ_TIMEOUT_MS,
|
|
780
931
|
stdio: ["ignore", "pipe", "ignore"],
|
|
932
|
+
// The detached session sender has no console; without this Windows opens one.
|
|
933
|
+
windowsHide: true,
|
|
781
934
|
});
|
|
782
935
|
const parsed = parseProxyStatsPayload(out);
|
|
783
936
|
if (!parsed)
|
|
@@ -905,8 +1058,8 @@ function commandRunEventOnce(exitClass, errorClass) {
|
|
|
905
1058
|
event.agent = agent;
|
|
906
1059
|
if (exitClass === "error")
|
|
907
1060
|
event.error_class = errorClass ?? "other";
|
|
908
|
-
// Token volume rides on command_run
|
|
909
|
-
//
|
|
1061
|
+
// Token volume rides on command_run and session_start only; the watermark
|
|
1062
|
+
// claim in telemetryTokenDelta keeps concurrent readers from double counting.
|
|
910
1063
|
const tokens = telemetryTokenDelta();
|
|
911
1064
|
if (tokens) {
|
|
912
1065
|
event.tokens_processed = tokens.processed;
|
|
@@ -952,15 +1105,90 @@ function emitRuntimeBootstrap(exitClass, durationMS, errorClass) {
|
|
|
952
1105
|
event.error_class = errorClass ?? "other";
|
|
953
1106
|
emitTelemetryEvents([event]);
|
|
954
1107
|
}
|
|
1108
|
+
// Fields every event carries. Cheap local reads only: no keychain lookup, no
|
|
1109
|
+
// network, and the install path never leaves the machine — only its channel.
|
|
1110
|
+
function telemetryContext() {
|
|
1111
|
+
let raw = {};
|
|
1112
|
+
try {
|
|
1113
|
+
raw = JSON.parse(readFileSync(configPath(), "utf8"));
|
|
1114
|
+
}
|
|
1115
|
+
catch {
|
|
1116
|
+
/* no config yet */
|
|
1117
|
+
}
|
|
1118
|
+
const connected = Boolean(process.env.CAVE_TOKEN || raw.tokenStore || raw.token);
|
|
1119
|
+
const out = {
|
|
1120
|
+
account: connected ? "connected" : "none",
|
|
1121
|
+
install_channel: telemetryInstallChannel(),
|
|
1122
|
+
};
|
|
1123
|
+
// Logout leaves the cached entitlement behind, so only a live account's
|
|
1124
|
+
// unexpired plan counts.
|
|
1125
|
+
const entitlement = connected ? parseWrapEntitlement(raw.wrapEntitlement) : null;
|
|
1126
|
+
if (entitlement?.plan && !(Date.parse(entitlement.expires_at) < Date.now()))
|
|
1127
|
+
out.plan = entitlement.plan;
|
|
1128
|
+
try {
|
|
1129
|
+
const { timeZone, locale } = Intl.DateTimeFormat().resolvedOptions();
|
|
1130
|
+
if (timeZone)
|
|
1131
|
+
out.timezone = timeZone;
|
|
1132
|
+
if (locale)
|
|
1133
|
+
out.locale = locale;
|
|
1134
|
+
}
|
|
1135
|
+
catch {
|
|
1136
|
+
/* runtime without Intl data */
|
|
1137
|
+
}
|
|
1138
|
+
return out;
|
|
1139
|
+
}
|
|
1140
|
+
function telemetryInstallChannel() {
|
|
1141
|
+
const path = fileURLToPath(import.meta.url).replace(/\\/g, "/");
|
|
1142
|
+
if (path.includes("/_npx/"))
|
|
1143
|
+
return "npx";
|
|
1144
|
+
if (path.includes("/.pnpm/"))
|
|
1145
|
+
return "pnpm";
|
|
1146
|
+
if (path.includes("/.bun/") || path.includes("/bunx-"))
|
|
1147
|
+
return "bun";
|
|
1148
|
+
if (path.includes("/node_modules/"))
|
|
1149
|
+
return "npm";
|
|
1150
|
+
return "source";
|
|
1151
|
+
}
|
|
1152
|
+
function telemetryBody(events) {
|
|
1153
|
+
const context = telemetryContext();
|
|
1154
|
+
return JSON.stringify(events.map((event) => ({ ...event, ...context })));
|
|
1155
|
+
}
|
|
1156
|
+
// Sends run in a detached child so no command waits on the network at exit.
|
|
1157
|
+
// The child has no user-facing deadline, so it can outwait a cold endpoint.
|
|
955
1158
|
function emitTelemetryEvents(events) {
|
|
1159
|
+
const body = telemetryBody(events);
|
|
1160
|
+
try {
|
|
1161
|
+
const child = spawn(process.execPath, [fileURLToPath(import.meta.url), "telemetry", "send"], {
|
|
1162
|
+
detached: true,
|
|
1163
|
+
stdio: "ignore",
|
|
1164
|
+
windowsHide: true,
|
|
1165
|
+
env: { ...process.env, CAVEMAN_TELEMETRY_PAYLOAD: body },
|
|
1166
|
+
});
|
|
1167
|
+
child.on("error", () => { });
|
|
1168
|
+
child.unref();
|
|
1169
|
+
return Promise.resolve();
|
|
1170
|
+
}
|
|
1171
|
+
catch {
|
|
1172
|
+
return postTelemetry(body, 1500);
|
|
1173
|
+
}
|
|
1174
|
+
}
|
|
1175
|
+
function postTelemetry(body, timeoutMs) {
|
|
956
1176
|
const url = process.env.CAVEMAN_TELEMETRY_URL || TELEMETRY_URL;
|
|
957
1177
|
return fetch(url, {
|
|
958
1178
|
method: "POST",
|
|
959
1179
|
headers: { "content-type": "application/json" },
|
|
960
|
-
body
|
|
961
|
-
signal: AbortSignal.timeout(
|
|
1180
|
+
body,
|
|
1181
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
962
1182
|
}).then(() => { }).catch(() => { });
|
|
963
1183
|
}
|
|
1184
|
+
// `caveman telemetry send` (unprinted): the detached child emitTelemetryEvents
|
|
1185
|
+
// spawns. Consent was checked by the emitter; this only delivers.
|
|
1186
|
+
async function telemetrySend() {
|
|
1187
|
+
telemetryCommandSent = true;
|
|
1188
|
+
const body = process.env.CAVEMAN_TELEMETRY_PAYLOAD;
|
|
1189
|
+
if (body)
|
|
1190
|
+
await postTelemetry(body, 10_000);
|
|
1191
|
+
}
|
|
964
1192
|
function classifyTelemetryError(error) {
|
|
965
1193
|
const message = error instanceof Error ? error.message : "";
|
|
966
1194
|
if (telemetryCommandName() === "unknown" || message.startsWith("unknown command:"))
|
|
@@ -1041,7 +1269,7 @@ function exploreUsage() {
|
|
|
1041
1269
|
console.error(`usage: ${invokedCommand("explore")} install [--agent claude] [--user] [--dir <path>]`);
|
|
1042
1270
|
console.error(" legacy alias for tools skills install caveman-explore");
|
|
1043
1271
|
console.error(" --agent claude target Claude Code (default; codex is not wired yet)");
|
|
1044
|
-
console.error(" --user install
|
|
1272
|
+
console.error(" --user install in the Claude profile's skills directory for all repos");
|
|
1045
1273
|
console.error(" --dir <path> write SKILL.md into <path>");
|
|
1046
1274
|
process.exit(2);
|
|
1047
1275
|
}
|
|
@@ -1206,7 +1434,7 @@ function discoverSkillTargets(rest) {
|
|
|
1206
1434
|
targets.push({ name: profile.id, dir: "", agent: profile.id });
|
|
1207
1435
|
continue;
|
|
1208
1436
|
}
|
|
1209
|
-
const roots =
|
|
1437
|
+
const roots = profile.skills.user_dirs.map((path) => resolveSkillRoot(agentUserPath(profile.id, path)));
|
|
1210
1438
|
if (rest.includes("--project"))
|
|
1211
1439
|
roots.push(...(profile.skills.project_dirs ?? []).map(resolveSkillRoot));
|
|
1212
1440
|
for (const root of roots)
|
|
@@ -1475,8 +1703,8 @@ function skillsUsage() {
|
|
|
1475
1703
|
console.error(" add <source> install any Git/URL/local source through the official Skills CLI, then pixelize new Claude Code/Codex skills");
|
|
1476
1704
|
console.error(" accepts npx skills add flags such as --skill, --agent, --global, --list, --yes, and --all");
|
|
1477
1705
|
console.error(" --agent claude Claude Code (default) — writes .claude/skills/<name>/SKILL.md");
|
|
1478
|
-
console.error(" --agent codex Codex — writes
|
|
1479
|
-
console.error(" --user install
|
|
1706
|
+
console.error(" --agent codex Codex — writes skills/<name>/SKILL.md inside CODEX_HOME (default ~/.codex)");
|
|
1707
|
+
console.error(" --user install in the Claude profile's skills directory for all repos");
|
|
1480
1708
|
console.error(" --dir <path> single: write SKILL.md there; suite: write <path>/<name>/SKILL.md");
|
|
1481
1709
|
console.error(" --density LEVEL pixel pack geometry (default balanced): conservative|balanced|max");
|
|
1482
1710
|
console.error(" --no-pixel install plain SKILL.md without pixel conversion");
|
|
@@ -1677,12 +1905,12 @@ function skillDestination(name, rest, multiple, agent) {
|
|
|
1677
1905
|
return join(directDir, ...(multiple ? [name, "SKILL.md"] : ["SKILL.md"]));
|
|
1678
1906
|
if (agent === "claude") {
|
|
1679
1907
|
const root = rest.includes("--user")
|
|
1680
|
-
? join(
|
|
1908
|
+
? join(claudeConfigDir(), "skills")
|
|
1681
1909
|
: join(process.cwd(), ".claude", "skills");
|
|
1682
1910
|
return join(root, name, "SKILL.md");
|
|
1683
1911
|
}
|
|
1684
1912
|
if (agent === "codex")
|
|
1685
|
-
return join(
|
|
1913
|
+
return join(codexHomeDir(), "skills", name, "SKILL.md");
|
|
1686
1914
|
console.error(`caveman skills: --agent must be claude or codex (got ${agent})`);
|
|
1687
1915
|
process.exit(2);
|
|
1688
1916
|
}
|
|
@@ -1690,9 +1918,9 @@ function externalSkillRoots(args) {
|
|
|
1690
1918
|
const global = args.includes("--global") || args.includes("-g");
|
|
1691
1919
|
if (global) {
|
|
1692
1920
|
return [
|
|
1693
|
-
{ root: join(
|
|
1921
|
+
{ root: join(claudeConfigDir(), "skills"), agent: "claude" },
|
|
1694
1922
|
{ root: join(homedir(), ".agents", "skills"), agent: "codex" },
|
|
1695
|
-
{ root: join(
|
|
1923
|
+
{ root: join(codexHomeDir(), "skills"), agent: "codex" },
|
|
1696
1924
|
];
|
|
1697
1925
|
}
|
|
1698
1926
|
return [
|
|
@@ -1755,7 +1983,9 @@ function runExternalSkillAdd(rest) {
|
|
|
1755
1983
|
const noPixel = rest.includes("--no-pixel");
|
|
1756
1984
|
const args = stripCavemanSkillAddOptions(rest);
|
|
1757
1985
|
const listOnly = args.includes("--list") || args.includes("-l");
|
|
1758
|
-
|
|
1986
|
+
// Listing and plain installation delegate all path decisions upstream.
|
|
1987
|
+
// Resolving unrelated profiles here can reject an otherwise valid command.
|
|
1988
|
+
const roots = noPixel || listOnly ? [] : externalSkillRoots(args);
|
|
1759
1989
|
const before = noPixel || listOnly ? new Map() : snapshotExternalSkills(roots);
|
|
1760
1990
|
if (!noPixel && !listOnly && !args.includes("--copy"))
|
|
1761
1991
|
args.push("--copy");
|
|
@@ -1867,7 +2097,7 @@ async function skills(rest) {
|
|
|
1867
2097
|
installed.push({ name, dest, pixelResult });
|
|
1868
2098
|
}
|
|
1869
2099
|
const note = agent === "codex"
|
|
1870
|
-
?
|
|
2100
|
+
? `Codex auto-loads skill directories from ${join(codexHomeDir(), "skills")}.`
|
|
1871
2101
|
: "Claude Code auto-loads this skill when its description matches.";
|
|
1872
2102
|
const lines = installed.flatMap(({ name, dest, pixelResult }) => [
|
|
1873
2103
|
`${mark("ok")} ${name}: ${cyan(dest)}`,
|
|
@@ -2079,7 +2309,12 @@ function probeVersionedBinary(binary, requiredCapability) {
|
|
|
2079
2309
|
return { ...cached, current: cached.capabilities.includes(requiredCapability) };
|
|
2080
2310
|
let result = { version: "pre-versioned", capabilities: [] };
|
|
2081
2311
|
try {
|
|
2082
|
-
|
|
2312
|
+
// An npm-installed caveman-mcp on Windows is a `.cmd` shim, which Node
|
|
2313
|
+
// refuses to execFile directly (CVE-2024-27980). Route through the same
|
|
2314
|
+
// shim-aware invocation every other launch site uses; a shim that cannot
|
|
2315
|
+
// be launched safely throws and lands in the fail-closed branch below.
|
|
2316
|
+
const invocation = portableInvocation(binary, ["version", "--json"]);
|
|
2317
|
+
const raw = execFileSync(invocation.command, invocation.args, {
|
|
2083
2318
|
encoding: "utf8",
|
|
2084
2319
|
env: process.env,
|
|
2085
2320
|
timeout: versionedBinaryProbeTimeoutMs(),
|
|
@@ -2163,7 +2398,22 @@ function verifiedLocalInstall(binDir) {
|
|
|
2163
2398
|
}
|
|
2164
2399
|
return installed;
|
|
2165
2400
|
}
|
|
2166
|
-
|
|
2401
|
+
// A signed manifest names its release through a `RELEASE` entry: the sha256 of
|
|
2402
|
+
// the release asset `RELEASE`, whose content is "<tag>\n". Without it, anyone
|
|
2403
|
+
// able to edit a release page could serve an older, validly signed manifest
|
|
2404
|
+
// and its binaries. It rides as an ordinary checksum line so the shipped
|
|
2405
|
+
// wedge installers' strict parsers keep accepting the manifest. Releases
|
|
2406
|
+
// before bin-v2.0.0 were signed without it, so it is required from there on.
|
|
2407
|
+
const FIRST_RELEASE_WITH_SIGNED_NAME = [2, 0, 0];
|
|
2408
|
+
function releaseRequiresSignedName(release) {
|
|
2409
|
+
const match = release.match(/^bin-v(\d+)\.(\d+)\.(\d+)/);
|
|
2410
|
+
if (!match)
|
|
2411
|
+
return true;
|
|
2412
|
+
const version = match.slice(1, 4).map(Number);
|
|
2413
|
+
const i = version.findIndex((part, index) => part !== FIRST_RELEASE_WITH_SIGNED_NAME[index]);
|
|
2414
|
+
return i === -1 || version[i] > FIRST_RELEASE_WITH_SIGNED_NAME[i];
|
|
2415
|
+
}
|
|
2416
|
+
export function parseSignedChecksums(raw, release = BINARY_RELEASE) {
|
|
2167
2417
|
const checksums = new Map();
|
|
2168
2418
|
for (const line of raw.split("\n")) {
|
|
2169
2419
|
if (!line)
|
|
@@ -2176,6 +2426,10 @@ function parseSignedChecksums(raw) {
|
|
|
2176
2426
|
throw new Error(`duplicate checksum manifest entry: ${filename}`);
|
|
2177
2427
|
checksums.set(filename, match[1]);
|
|
2178
2428
|
}
|
|
2429
|
+
const signedName = checksums.get("RELEASE");
|
|
2430
|
+
if (signedName === undefined ? releaseRequiresSignedName(release) : signedName !== createHash("sha256").update(`${release}\n`).digest("hex")) {
|
|
2431
|
+
throw new Error(`manifest is not signed for release ${release}`);
|
|
2432
|
+
}
|
|
2179
2433
|
return checksums;
|
|
2180
2434
|
}
|
|
2181
2435
|
function verifyChecksumSignature(checksums, signature) {
|
|
@@ -2316,7 +2570,7 @@ async function setupInstall(json, options = {}) {
|
|
|
2316
2570
|
printInstallResult(local, platform, binDir, json, options.continuing);
|
|
2317
2571
|
return;
|
|
2318
2572
|
}
|
|
2319
|
-
const base = (process.env.CAVE_BINARY_RELEASE_BASE ?? BINARY_RELEASE_BASE_DEFAULT)
|
|
2573
|
+
const base = trimTrailingSlashes(process.env.CAVE_BINARY_RELEASE_BASE ?? BINARY_RELEASE_BASE_DEFAULT);
|
|
2320
2574
|
const releaseBase = `${base}/${BINARY_RELEASE}`;
|
|
2321
2575
|
let checksumsRaw;
|
|
2322
2576
|
let signatureRaw;
|
|
@@ -2337,8 +2591,8 @@ async function setupInstall(json, options = {}) {
|
|
|
2337
2591
|
try {
|
|
2338
2592
|
checksums = parseSignedChecksums(checksumsRaw);
|
|
2339
2593
|
}
|
|
2340
|
-
catch {
|
|
2341
|
-
throw new Error(
|
|
2594
|
+
catch (error) {
|
|
2595
|
+
throw new Error(`signature check failed for checksums.txt (${error.message}) — refusing to install; partial download deleted`);
|
|
2342
2596
|
}
|
|
2343
2597
|
const installed = [];
|
|
2344
2598
|
const artifactDigests = {};
|
|
@@ -2397,7 +2651,7 @@ function cliVersionBehind(current, latest) {
|
|
|
2397
2651
|
return false;
|
|
2398
2652
|
}
|
|
2399
2653
|
async function latestPublishedCliVersion(timeoutSeconds) {
|
|
2400
|
-
const registry = (process.env.CAVEMAN_NPM_REGISTRY ?? "https://registry.npmjs.org")
|
|
2654
|
+
const registry = trimTrailingSlashes(process.env.CAVEMAN_NPM_REGISTRY ?? "https://registry.npmjs.org");
|
|
2401
2655
|
try {
|
|
2402
2656
|
const response = await fetch(`${registry}/@caveman-ai%2fcli`, {
|
|
2403
2657
|
headers: { accept: "application/vnd.npm.install-v1+json" },
|
|
@@ -2530,7 +2784,7 @@ function readMcpServerMarker(agent, serverName) {
|
|
|
2530
2784
|
}
|
|
2531
2785
|
}
|
|
2532
2786
|
function claudeMcpRegistration(serverName) {
|
|
2533
|
-
const path =
|
|
2787
|
+
const path = claudeGlobalConfigPath();
|
|
2534
2788
|
const bytes = fileBytes(path);
|
|
2535
2789
|
if (!bytes)
|
|
2536
2790
|
return { present: false, command: "", args: [], exact_shape: false };
|
|
@@ -2564,7 +2818,7 @@ function installAgentNativeCloudMcp(agent, mcp) {
|
|
|
2564
2818
|
return;
|
|
2565
2819
|
}
|
|
2566
2820
|
const installed = agent === "claude"
|
|
2567
|
-
? installMcpJson(
|
|
2821
|
+
? installMcpJson(claudeGlobalConfigPath(), ["mcpServers", "caveman-cloud"], { command: mcp.command, args: mcp.args })
|
|
2568
2822
|
: installMcpForAgent(findAgent(agent), mcp, "caveman-cloud");
|
|
2569
2823
|
if (!installed)
|
|
2570
2824
|
throw new Error(`could not install caveman-cloud MCP for ${agent}`);
|
|
@@ -2572,7 +2826,7 @@ function installAgentNativeCloudMcp(agent, mcp) {
|
|
|
2572
2826
|
}
|
|
2573
2827
|
function uninstallAgentNativeCloudMcp(agent) {
|
|
2574
2828
|
const removed = agent === "claude"
|
|
2575
|
-
? removeMcpJson(
|
|
2829
|
+
? removeMcpJson(claudeGlobalConfigPath(), ["mcpServers", "caveman-cloud"])
|
|
2576
2830
|
: uninstallMcpForAgent(findAgent(agent), "caveman-cloud");
|
|
2577
2831
|
if (!removed)
|
|
2578
2832
|
throw new Error(`could not remove caveman-cloud MCP for ${agent}`);
|
|
@@ -2586,7 +2840,7 @@ function uninstallAgentNativeCloudMcp(agent) {
|
|
|
2586
2840
|
}
|
|
2587
2841
|
function agentNativeSkillFiles(agent) {
|
|
2588
2842
|
const names = AGENT_SKILL_SUITES["agent-native"] ?? [];
|
|
2589
|
-
const root = agent === "claude" ? join(
|
|
2843
|
+
const root = agent === "claude" ? join(claudeConfigDir(), "skills") : join(codexHomeDir(), "skills");
|
|
2590
2844
|
return names.map((name) => ({ name, file: join(root, name, "SKILL.md"), body: SKILLS[name] }));
|
|
2591
2845
|
}
|
|
2592
2846
|
function restoreAgentNativeBundleSkills(skills) {
|
|
@@ -2658,7 +2912,7 @@ function skillMatchesBefore(skill) {
|
|
|
2658
2912
|
function agentNativeCloudMcpHostAbsent(agent) {
|
|
2659
2913
|
if (agent === "claude")
|
|
2660
2914
|
return !claudeMcpRegistration("caveman-cloud").present;
|
|
2661
|
-
const config = fileBytes(join(
|
|
2915
|
+
const config = fileBytes(join(codexHomeDir(), "config.toml"))?.toString("utf8") ?? "";
|
|
2662
2916
|
return !config.includes("[mcp_servers.caveman-cloud]");
|
|
2663
2917
|
}
|
|
2664
2918
|
function agentNativeCloudMcpAbsent(agent) {
|
|
@@ -2763,7 +3017,7 @@ function preflightAgentNativeBundleComponents(agent, existingBundle) {
|
|
|
2763
3017
|
}
|
|
2764
3018
|
return;
|
|
2765
3019
|
}
|
|
2766
|
-
const config = fileBytes(join(
|
|
3020
|
+
const config = fileBytes(join(codexHomeDir(), "config.toml"))?.toString("utf8") ?? "";
|
|
2767
3021
|
if (!config.includes("[mcp_servers.caveman-cloud]"))
|
|
2768
3022
|
return;
|
|
2769
3023
|
if (!readMcpServerMarker("codex", "caveman-cloud")) {
|
|
@@ -3424,23 +3678,13 @@ export const OFF_STATES = {
|
|
|
3424
3678
|
},
|
|
3425
3679
|
runningModeMismatch: (running, resolvedMode) => ({
|
|
3426
3680
|
id: "running-mode-mismatch",
|
|
3427
|
-
line: `a caveman proxy is already running in ${running} mode
|
|
3428
|
-
fix: "
|
|
3429
|
-
}),
|
|
3430
|
-
runningModeHeld: (running, resolvedMode) => ({
|
|
3431
|
-
id: "running-mode-mismatch",
|
|
3432
|
-
line: `a caveman proxy is already running in ${running} mode — another live session holds it, so this session keeps that mode instead of restarting to ${resolvedMode}`,
|
|
3433
|
-
fix: "caveman run -- <your agent>",
|
|
3681
|
+
line: `a caveman proxy is already running in ${running} mode; keeping it running to protect existing sessions instead of switching to ${resolvedMode}`,
|
|
3682
|
+
fix: "restart the proxy explicitly after existing sessions finish, then retry",
|
|
3434
3683
|
}),
|
|
3435
3684
|
runningGateMismatch: {
|
|
3436
3685
|
id: "running-gate-mismatch",
|
|
3437
3686
|
line: "running caveman proxy has stale recovery state — launching this agent direct to avoid unsafe compression",
|
|
3438
|
-
fix: "
|
|
3439
|
-
},
|
|
3440
|
-
runningGateHeld: {
|
|
3441
|
-
id: "running-gate-mismatch",
|
|
3442
|
-
line: "another live session holds a caveman proxy with different recovery state — launching this agent direct to avoid unsafe compression",
|
|
3443
|
-
fix: "stop other wrapped sessions, then run this command again",
|
|
3687
|
+
fix: "restart the proxy explicitly after existing sessions finish, then retry",
|
|
3444
3688
|
},
|
|
3445
3689
|
foreignProcess: (host, port) => ({
|
|
3446
3690
|
id: "foreign-process",
|
|
@@ -3650,14 +3894,28 @@ function mutateRawConfig(fn) {
|
|
|
3650
3894
|
}
|
|
3651
3895
|
fn(out);
|
|
3652
3896
|
mkdirSync(dirname(configPath()), { recursive: true });
|
|
3653
|
-
|
|
3897
|
+
const target = configWriteTarget();
|
|
3898
|
+
const tmp = `${target}.${process.pid}.tmp`;
|
|
3899
|
+
writeFileSync(tmp, JSON.stringify(out, null, 2), { mode: 0o600 });
|
|
3900
|
+
renameSync(tmp, target);
|
|
3654
3901
|
try {
|
|
3655
|
-
chmodSync(
|
|
3902
|
+
chmodSync(target, 0o600);
|
|
3656
3903
|
}
|
|
3657
3904
|
catch {
|
|
3658
3905
|
/* best effort */
|
|
3659
3906
|
}
|
|
3660
3907
|
}
|
|
3908
|
+
// Config writes go temp-file + rename so a concurrent reader (background
|
|
3909
|
+
// session senders) never sees a truncated file and rewrites it as {}. Resolves
|
|
3910
|
+
// a symlinked config.json so the rename replaces its target, not the link.
|
|
3911
|
+
function configWriteTarget() {
|
|
3912
|
+
try {
|
|
3913
|
+
return realpathSync(configPath());
|
|
3914
|
+
}
|
|
3915
|
+
catch {
|
|
3916
|
+
return configPath();
|
|
3917
|
+
}
|
|
3918
|
+
}
|
|
3661
3919
|
// ensureDeviceId returns a stable, opaque per-machine id, generated once and
|
|
3662
3920
|
// persisted in config.json. The entitlement device_hash is sha256(deviceId) — a
|
|
3663
3921
|
// random per-install id, NEVER derived from a hardware serial.
|
|
@@ -4843,7 +5101,7 @@ async function agentShortcut(rest) {
|
|
|
4843
5101
|
// is the one-command compression path. If the proxy can't be reached, a TTY run
|
|
4844
5102
|
// offers to launch the agent directly (no Caveman, no compression this run) rather
|
|
4845
5103
|
// than wire it to a dead endpoint; non-TTY runs warn and route through as before.
|
|
4846
|
-
async function runWrapped(bin, cmdArgs, agent, opts = { mode: "compress", noProxy: false, toon: true, noShrink: false, mcpMode: "auto", noBrowse: false, delegate: false, minimal: false, command: [] }, codexSubscription
|
|
5104
|
+
async function runWrapped(bin, cmdArgs, agent, opts = { mode: "compress", noProxy: false, toon: true, noShrink: false, mcpMode: "auto", noBrowse: false, delegate: false, minimal: false, command: [] }, codexSubscription, routeDecision) {
|
|
4847
5105
|
const result = await spawnWrapped(bin, cmdArgs, agent, opts, gatewayURL(), codexSubscription, routeDecision);
|
|
4848
5106
|
// Preflight route bypass is intentionally outside Caveman's lifecycle: no
|
|
4849
5107
|
// savings read, sync, telemetry, or other post-child mutation.
|
|
@@ -4909,7 +5167,21 @@ function routedAiderArgs(args) {
|
|
|
4909
5167
|
process.stderr.write(`caveman: aider model not set; routing with --model ${AIDER_ROUTED_DEFAULT_MODEL}\n`);
|
|
4910
5168
|
return ["--model", AIDER_ROUTED_DEFAULT_MODEL, ...args];
|
|
4911
5169
|
}
|
|
4912
|
-
async function spawnWrapped(bin, cmdArgs, agent, opts, gw,
|
|
5170
|
+
async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscriptionOverride, routeDecision) {
|
|
5171
|
+
// Which Codex route is correct is a fact about ~/.codex/auth.json, not about
|
|
5172
|
+
// the caller: a ChatGPT login must reach the `/chatgpt` mux handler, an api-key
|
|
5173
|
+
// login the attributed `/w/codex/v1`. This used to be a defaulted parameter, so
|
|
5174
|
+
// every caller had to remember to pass it. `wrap codex` did (it resolves the
|
|
5175
|
+
// mode for --pixel anyway); `trial` and the interactive picker did not, and
|
|
5176
|
+
// their `false` built an ephemeral CODEX_HOME pinning the api-key route. Codex
|
|
5177
|
+
// then sent the OAuth token to the platform Responses API, which rejects it
|
|
5178
|
+
// with "Missing scopes: api.responses.write", while the model refresh 404s
|
|
5179
|
+
// because `/w/codex/v1/models` is not in the openai adapter's closed
|
|
5180
|
+
// allowlist (#1092). Resolving it here fixes every caller that forgets; an
|
|
5181
|
+
// explicit override still wins, which is what `wrap` passes.
|
|
5182
|
+
const codexSubscription = agent?.id === "codex"
|
|
5183
|
+
? codexSubscriptionOverride ?? detectCodexWrapAuthMode() === "subscription"
|
|
5184
|
+
: false;
|
|
4913
5185
|
const { host, port } = gatewayHostPort(gw);
|
|
4914
5186
|
const local = wrapMode(gw) === "local";
|
|
4915
5187
|
let proxyStarted = false;
|
|
@@ -4986,67 +5258,18 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = f
|
|
|
4986
5258
|
: OFF_STATES.staleBinary("caveman-proxy", proxyVersion?.version ?? "unknown", cliVersion());
|
|
4987
5259
|
}
|
|
4988
5260
|
else if (!proxyRuntimeMatches(runtime, effectiveMode, desiredRecoveryViaMCP)) {
|
|
4989
|
-
|
|
4990
|
-
|
|
4991
|
-
|
|
4992
|
-
|
|
4993
|
-
|
|
4994
|
-
|
|
4995
|
-
|
|
4996
|
-
|
|
4997
|
-
|
|
4998
|
-
|
|
4999
|
-
|
|
5000
|
-
|
|
5001
|
-
process.kill(runtime.pid, "SIGTERM");
|
|
5002
|
-
const deadline = Date.now() + proxyRestartTimeoutMs();
|
|
5003
|
-
let successor = false;
|
|
5004
|
-
while (Date.now() < deadline) {
|
|
5005
|
-
await sleep(100);
|
|
5006
|
-
const generation = readRawProxyRunState(port);
|
|
5007
|
-
if (generation.owner !== "unknown" && generation.instance_token !== runtime.instance_token) {
|
|
5008
|
-
successor = true;
|
|
5009
|
-
break;
|
|
5010
|
-
}
|
|
5011
|
-
if (!(await portListening(host, port)))
|
|
5012
|
-
break;
|
|
5013
|
-
}
|
|
5014
|
-
proxyReady = await portListening(host, port);
|
|
5015
|
-
if (!proxyReady && !successor) {
|
|
5016
|
-
proxyStarted = await startWrapProxy(effectiveMode, desiredRecoveryViaMCP, codexSubscription ? false : observeEstimate ? false : opts.toon, opts.pixelModels, opts.pixelDensity, gw, codexSubscription ? "codex-subscription" : "standard", observeEstimate);
|
|
5017
|
-
proxyReady = await portListening(host, port);
|
|
5018
|
-
}
|
|
5019
|
-
runtime = proxyReady ? await awaitProxyRuntimeState(port, proxyVersion) : { owner: "unknown" };
|
|
5020
|
-
if (runtime.owner === "unknown" || !proxyRuntimeMatches(runtime, effectiveMode, desiredRecoveryViaMCP)) {
|
|
5021
|
-
runtimeState = runtime.owner === "unknown"
|
|
5022
|
-
? OFF_STATES.foreignProcess(host, port)
|
|
5023
|
-
: !proxyRuntimeGateMatches(runtime, desiredRecoveryViaMCP)
|
|
5024
|
-
? OFF_STATES.runningGateMismatch
|
|
5025
|
-
: OFF_STATES.runningModeMismatch(runtime.mode ?? "unknown", effectiveMode);
|
|
5026
|
-
}
|
|
5027
|
-
}
|
|
5028
|
-
catch {
|
|
5029
|
-
runtime = readProxyRuntimeState(port, proxyVersion);
|
|
5030
|
-
runtimeState = runtime.owner === "unknown"
|
|
5031
|
-
? OFF_STATES.foreignProcess(host, port)
|
|
5032
|
-
: !proxyRuntimeMatches(runtime, effectiveMode, desiredRecoveryViaMCP)
|
|
5033
|
-
? !proxyRuntimeGateMatches(runtime, desiredRecoveryViaMCP)
|
|
5034
|
-
? OFF_STATES.runningGateMismatch
|
|
5035
|
-
: OFF_STATES.runningModeMismatch(runtime.mode ?? "unknown", effectiveMode)
|
|
5036
|
-
: null;
|
|
5037
|
-
}
|
|
5038
|
-
}
|
|
5039
|
-
else {
|
|
5040
|
-
runtime = readProxyRuntimeState(port, proxyVersion);
|
|
5041
|
-
runtimeState = runtime.owner === "unknown"
|
|
5042
|
-
? OFF_STATES.foreignProcess(host, port)
|
|
5043
|
-
: !proxyRuntimeMatches(runtime, effectiveMode, desiredRecoveryViaMCP)
|
|
5044
|
-
? !proxyRuntimeGateMatches(runtime, desiredRecoveryViaMCP)
|
|
5045
|
-
? OFF_STATES.runningGateMismatch
|
|
5046
|
-
: OFF_STATES.runningModeMismatch(runtime.mode ?? "unknown", effectiveMode)
|
|
5047
|
-
: null;
|
|
5048
|
-
}
|
|
5049
|
-
}
|
|
5261
|
+
// A missing wrapper marker does not prove this listener is unused:
|
|
5262
|
+
// native hooks, IDEs, and resumed sessions retain its base URL. Never
|
|
5263
|
+
// signal a shared proxy to change this new session's mode or recovery.
|
|
5264
|
+
// Re-read once in case another operator already replaced the generation.
|
|
5265
|
+
runtime = readProxyRuntimeState(port, proxyVersion);
|
|
5266
|
+
runtimeState = runtime.owner === "unknown"
|
|
5267
|
+
? OFF_STATES.foreignProcess(host, port)
|
|
5268
|
+
: !proxyRuntimeMatches(runtime, effectiveMode, desiredRecoveryViaMCP)
|
|
5269
|
+
? !proxyRuntimeGateMatches(runtime, desiredRecoveryViaMCP)
|
|
5270
|
+
? OFF_STATES.runningGateMismatch
|
|
5271
|
+
: OFF_STATES.runningModeMismatch(runtime.mode ?? "unknown", effectiveMode)
|
|
5272
|
+
: null;
|
|
5050
5273
|
}
|
|
5051
5274
|
}
|
|
5052
5275
|
if (!proxyReady && !direct) {
|
|
@@ -5070,6 +5293,12 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = f
|
|
|
5070
5293
|
// Explicit proxy:false leaves subscription Codex in pass-through launch mode
|
|
5071
5294
|
// without extra status noise; useful for tests and managed launchers.
|
|
5072
5295
|
}
|
|
5296
|
+
else if (local && !opts.noProxy) {
|
|
5297
|
+
// A failed local optimization layer must not wire the agent to a dead
|
|
5298
|
+
// listener. Direct launch preserves the agent's own provider setup.
|
|
5299
|
+
direct = true;
|
|
5300
|
+
process.stderr.write(`${mark("warn")} Caveman proxy not reachable on ${host}:${port}; launching directly without compression or metering\n`);
|
|
5301
|
+
}
|
|
5073
5302
|
else if (interactive()) {
|
|
5074
5303
|
// The proxy is down and we couldn't bring it up. Launching the agent now
|
|
5075
5304
|
// would wire it to a dead endpoint (every request fails), so offer to run
|
|
@@ -5098,7 +5327,7 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = f
|
|
|
5098
5327
|
// A foreign listener on the proxy port is the same failure as a gate
|
|
5099
5328
|
// mismatch, with a worse consequence: launching routed would hand the
|
|
5100
5329
|
// operator's provider keys to a process caveman does not own (#945).
|
|
5101
|
-
if (runtimeState?.id === "running-gate-mismatch") {
|
|
5330
|
+
if (runtimeState?.id === "running-gate-mismatch" || runtimeState?.id === "running-mode-mismatch") {
|
|
5102
5331
|
process.stderr.write(`${mark("warn")} ${runtimeState.line}\n`);
|
|
5103
5332
|
direct = true;
|
|
5104
5333
|
}
|
|
@@ -5178,7 +5407,13 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = f
|
|
|
5178
5407
|
// Direct mode: inherit the shell env with NO profile injection, stripping only
|
|
5179
5408
|
// our own routing if it leaked in — so the agent talks straight to the provider
|
|
5180
5409
|
// with its own key. Any unrelated base URL the user set themselves stays put.
|
|
5181
|
-
|
|
5410
|
+
// Codex is excluded by design, and the README has said so all along: its runtime
|
|
5411
|
+
// rejects the rewrite (openai/codex#18491). No door actually implemented that, and
|
|
5412
|
+
// since #1037 shrinkHook declines every Codex tool event — so registering it here
|
|
5413
|
+
// bought nothing but a node spawn per tool call. The persistent `caveman enable
|
|
5414
|
+
// codex` door still writes the entry; removing it there needs a migration, since
|
|
5415
|
+
// nativeHookEntriesHealthy would read every existing install as degraded.
|
|
5416
|
+
const includeShrink = !opts.noShrink && wrapCompressEnabled(opts) && agent?.id !== "codex";
|
|
5182
5417
|
let childArgs = cmdArgs;
|
|
5183
5418
|
let env;
|
|
5184
5419
|
try {
|
|
@@ -5186,7 +5421,7 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = f
|
|
|
5186
5421
|
? { ...process.env }
|
|
5187
5422
|
: agent?.id === "codex"
|
|
5188
5423
|
? buildCodexEphemeralWrapEnv(gw, codexSubscription, ephemeralMcpBinary, includeShrink, ephemeralDelegateMcp)
|
|
5189
|
-
: buildWrapEnv(agent, gw, opts.mcpMode, cmdArgs);
|
|
5424
|
+
: buildWrapEnv(agent, gw, opts.mcpMode, cmdArgs, runtime.owner === "unknown" ? undefined : runtime);
|
|
5190
5425
|
if (!direct && agent?.id === "claude") {
|
|
5191
5426
|
const pluginDir = buildClaudeEphemeralPlugin(ephemeralMcpBinary, includeShrink, Boolean(opts.autoRecall), ephemeralDelegateMcp);
|
|
5192
5427
|
childArgs = ["--plugin-dir", pluginDir, ...cmdArgs];
|
|
@@ -5202,10 +5437,10 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = f
|
|
|
5202
5437
|
childArgs = cmdArgs;
|
|
5203
5438
|
process.stderr.write(`${mark("warn")} temporary native pack unavailable: ${error.message}; launching ${agent?.display_name ?? bin} directly\n`);
|
|
5204
5439
|
}
|
|
5205
|
-
//
|
|
5206
|
-
//
|
|
5207
|
-
//
|
|
5208
|
-
if (direct && agent?.id === "qwen"
|
|
5440
|
+
// Qwen's extension lock and Hermes's forced custom provider are routing
|
|
5441
|
+
// injection too. Remove them on direct fallback so the host keeps the user's
|
|
5442
|
+
// provider and policy. OpenClaw's `chat` is a command, not a routing override.
|
|
5443
|
+
if (direct && (agent?.id === "qwen" || agent?.id === "hermes")
|
|
5209
5444
|
&& agent.args.every((arg, index) => childArgs[index] === arg)) {
|
|
5210
5445
|
childArgs = childArgs.slice(agent.args.length);
|
|
5211
5446
|
}
|
|
@@ -5216,7 +5451,7 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = f
|
|
|
5216
5451
|
if (direct) {
|
|
5217
5452
|
// buildWrapEnv writes the agent-attributed `${gw}/w/<agent>` form, and an
|
|
5218
5453
|
// outer routed wrap may leak the bare form; a direct launch strips both.
|
|
5219
|
-
const gwPrefix = `${gw
|
|
5454
|
+
const gwPrefix = `${trimTrailingSlashes(gw)}/`;
|
|
5220
5455
|
for (const k of WRAP_BASE_URL_ENV_VARS) {
|
|
5221
5456
|
const value = env[k];
|
|
5222
5457
|
if (value !== undefined && (value === gw || value.startsWith(gwPrefix)))
|
|
@@ -5404,7 +5639,13 @@ function applyHermesAuthEnv(env, gw, modeGw = gw) {
|
|
|
5404
5639
|
if (key && name)
|
|
5405
5640
|
env[name] = key;
|
|
5406
5641
|
}
|
|
5407
|
-
|
|
5642
|
+
// spawnLocalProxyProcess resolves the proxy binary, builds its env, and spawns
|
|
5643
|
+
// it detached + unref'd — the part every caller needs identically. Split out
|
|
5644
|
+
// of startWrapProxy so a caller that only wants to kick the proxy off (never
|
|
5645
|
+
// waiting to confirm it came up) doesn't have to either duplicate this env
|
|
5646
|
+
// assembly or pay for the readiness-poll loop below, which holds this
|
|
5647
|
+
// process's event loop open via a non-unref'd sleep() timer.
|
|
5648
|
+
function spawnLocalProxyProcess(mode, mcpRecovery, toon, pixelModels, pixelDensity, gw, purpose, observeEstimate) {
|
|
5408
5649
|
const bin = cavemanBin("caveman-proxy", "CAVEMAN_PROXY_BIN");
|
|
5409
5650
|
const resolved = which(bin);
|
|
5410
5651
|
if (!resolved) {
|
|
@@ -5414,7 +5655,7 @@ async function startWrapProxy(mode, mcpRecovery, toon, pixelModels, pixelDensity
|
|
|
5414
5655
|
else {
|
|
5415
5656
|
process.stderr.write(`${mark("warn")} ${bin} not found; wrap will still launch, but no local compression/metering will run — run ${cyan("caveman setup")} to see what's missing\n`);
|
|
5416
5657
|
}
|
|
5417
|
-
return
|
|
5658
|
+
return null;
|
|
5418
5659
|
}
|
|
5419
5660
|
const { host, port } = gatewayHostPort(gw);
|
|
5420
5661
|
const env = {
|
|
@@ -5462,19 +5703,64 @@ async function startWrapProxy(mode, mcpRecovery, toon, pixelModels, pixelDensity
|
|
|
5462
5703
|
process.stderr.write(`${mark("warn")} could not start ${bin}: ${error.message}\n`);
|
|
5463
5704
|
});
|
|
5464
5705
|
child.unref();
|
|
5706
|
+
return { host, port };
|
|
5707
|
+
}
|
|
5708
|
+
// Best-effort "there should be a proxy on this port now" for the `enable` door.
|
|
5709
|
+
// Fire-and-forget: the caller never waits, so `enable` returns at its own pace.
|
|
5710
|
+
//
|
|
5711
|
+
// Deliberately not startWrapProxy: that readiness poll's sleep() timer is not
|
|
5712
|
+
// unref'd, so awaiting it would hold this command's process open for up to two
|
|
5713
|
+
// seconds on every enable where nothing is listening yet — the common case this
|
|
5714
|
+
// exists to cover. Probe first (one fast TCP connect, not the retry loop) so a
|
|
5715
|
+
// second enable against a live proxy spawns nothing; the redundant process that
|
|
5716
|
+
// skipping the probe would create is harmless, since run state is only written
|
|
5717
|
+
// once the listener binds, but free beats harmless.
|
|
5718
|
+
//
|
|
5719
|
+
// aider is excluded on purpose. It is the one native agent installed without an
|
|
5720
|
+
// MCP binary (see nativeMcpBinaryRequired's aider branch), so the recovery flag
|
|
5721
|
+
// derived below would stamp CAVEMAN_RECOVERY=mcp onto a proxy with no retrieve
|
|
5722
|
+
// tool to back it — the exact leak the explicit stamping elsewhere exists to
|
|
5723
|
+
// prevent. Giving aider a proxy needs recovery pinned off and its own coverage;
|
|
5724
|
+
// until then it keeps the pre-existing behaviour, no better and no worse.
|
|
5725
|
+
function ensureLocalProxyForNative(agent, gw) {
|
|
5726
|
+
if (agent === "aider" || wrapMode(gw) !== "local")
|
|
5727
|
+
return;
|
|
5728
|
+
void (async () => {
|
|
5729
|
+
try {
|
|
5730
|
+
const opts = defaultWrapOptions();
|
|
5731
|
+
// Every other spawn site gates on this (agentShortcut, the native hook).
|
|
5732
|
+
// Without it, `enable` starts a proxy the user's config switched off.
|
|
5733
|
+
if (opts.noProxy)
|
|
5734
|
+
return;
|
|
5735
|
+
const { host, port } = gatewayHostPort(gw);
|
|
5736
|
+
if (await portListening(host, port))
|
|
5737
|
+
return;
|
|
5738
|
+
const subscription = agent === "codex" && detectCodexWrapAuthMode() === "subscription";
|
|
5739
|
+
const mode = subscription && opts.mode === "pixel" ? "record" : opts.mode;
|
|
5740
|
+
const recovery = Boolean(probeMcpBinary()?.probe.current);
|
|
5741
|
+
spawnLocalProxyProcess(mode, recovery, subscription ? false : opts.toon, opts.pixelModels, opts.pixelDensity, gw, subscription ? "codex-subscription" : "standard", false);
|
|
5742
|
+
}
|
|
5743
|
+
catch { /* fail-open, same as the SessionStart hook and the shortcut door */ }
|
|
5744
|
+
})();
|
|
5745
|
+
}
|
|
5746
|
+
async function startWrapProxy(mode, mcpRecovery, toon, pixelModels, pixelDensity, gw = gatewayURL(), purpose = "standard", observeEstimate = false) {
|
|
5747
|
+
const spawned = spawnLocalProxyProcess(mode, mcpRecovery, toon, pixelModels, pixelDensity, gw, purpose, observeEstimate);
|
|
5748
|
+
if (!spawned)
|
|
5749
|
+
return false;
|
|
5750
|
+
const { host, port } = spawned;
|
|
5465
5751
|
for (let i = 0; i < 20; i++) {
|
|
5466
5752
|
await sleep(100);
|
|
5467
5753
|
if (await portListening(host, port)) {
|
|
5468
|
-
process.stderr.write(dim(`→ started Caveman proxy on ${host}:${port} (${
|
|
5754
|
+
process.stderr.write(dim(`→ started Caveman proxy on ${host}:${port} (${mode})\n`));
|
|
5469
5755
|
return true;
|
|
5470
5756
|
}
|
|
5471
5757
|
}
|
|
5472
|
-
process.stderr.write(`${mark("warn")} started ${
|
|
5758
|
+
process.stderr.write(`${mark("warn")} started ${cavemanBin("caveman-proxy", "CAVEMAN_PROXY_BIN")}, but proxy did not become ready on ${host}:${port}\n`);
|
|
5473
5759
|
return false;
|
|
5474
5760
|
}
|
|
5475
5761
|
// startProxyKeepalive heartbeats the local proxy while the wrapped agent process
|
|
5476
|
-
// is alive,
|
|
5477
|
-
//
|
|
5762
|
+
// is alive, for compatibility with older proxies that still idle-exit (#860).
|
|
5763
|
+
// Current proxy versions never idle-exit. The proxy treats
|
|
5478
5764
|
// the beat as activity only — nothing is recorded. No immediate beat: launching
|
|
5479
5765
|
// is already activity, and short-lived runs should never touch the port. The
|
|
5480
5766
|
// timer is unref'd and every failure is ignored (fail-open, like the hooks).
|
|
@@ -5631,8 +5917,7 @@ function stripTrailingCommas(s) {
|
|
|
5631
5917
|
}
|
|
5632
5918
|
return out;
|
|
5633
5919
|
}
|
|
5634
|
-
|
|
5635
|
-
const raw = readFileSync(path, "utf8");
|
|
5920
|
+
function parseJsonc(raw) {
|
|
5636
5921
|
try {
|
|
5637
5922
|
return JSON.parse(raw);
|
|
5638
5923
|
}
|
|
@@ -5640,6 +5925,9 @@ export function readJson5Lenient(path) {
|
|
|
5640
5925
|
return JSON.parse(stripTrailingCommas(stripJson5Comments(raw)));
|
|
5641
5926
|
}
|
|
5642
5927
|
}
|
|
5928
|
+
export function readJson5Lenient(path) {
|
|
5929
|
+
return parseJsonc(readFileSync(path, "utf8"));
|
|
5930
|
+
}
|
|
5643
5931
|
function isPlainObject(v) {
|
|
5644
5932
|
if (!v || typeof v !== "object" || Array.isArray(v))
|
|
5645
5933
|
return false;
|
|
@@ -5721,9 +6009,9 @@ const OPENCLAW_API_BASE_PATH = {
|
|
|
5721
6009
|
"google-generative-ai": "/v1beta",
|
|
5722
6010
|
};
|
|
5723
6011
|
const OPENCLAW_WELL_KNOWN_PROVIDERS = {
|
|
5724
|
-
openai: { api: "openai-responses", apiKey: "${OPENAI_API_KEY}" },
|
|
5725
|
-
anthropic: { api: "anthropic-messages", apiKey: "${ANTHROPIC_API_KEY}" },
|
|
5726
|
-
google: { api: "google-generative-ai", apiKey: "${GEMINI_API_KEY}" },
|
|
6012
|
+
openai: { baseUrl: "https://api.openai.com/v1", api: "openai-responses", apiKey: "${OPENAI_API_KEY}" },
|
|
6013
|
+
anthropic: { baseUrl: "https://api.anthropic.com", api: "anthropic-messages", apiKey: "${ANTHROPIC_API_KEY}" },
|
|
6014
|
+
google: { baseUrl: "https://generativelanguage.googleapis.com/v1beta", api: "google-generative-ai", apiKey: "${GEMINI_API_KEY}" },
|
|
5727
6015
|
"openai-codex": { api: "openai-chatgpt-responses", auth: "oauth" },
|
|
5728
6016
|
};
|
|
5729
6017
|
const OPENCLAW_MODEL_DEFAULTS = {
|
|
@@ -5829,6 +6117,11 @@ function openClawProviderApi(providerId, provider, model) {
|
|
|
5829
6117
|
: undefined;
|
|
5830
6118
|
return modelApi || providerApi || wellKnownApi;
|
|
5831
6119
|
}
|
|
6120
|
+
function openClawEffectiveBaseUrl(api, baseUrl) {
|
|
6121
|
+
// OpenClaw normalizeModelCompat removes /v1 before the Anthropic SDK appends
|
|
6122
|
+
// /v1/messages. Pi passes its model base URL to that SDK unchanged.
|
|
6123
|
+
return api === "anthropic-messages" ? baseUrl?.replace(/\/v1\/?$/, "") : baseUrl;
|
|
6124
|
+
}
|
|
5832
6125
|
function openClawProviderModel(provider, modelId) {
|
|
5833
6126
|
const models = Array.isArray(provider.models) ? provider.models : [];
|
|
5834
6127
|
for (const item of models) {
|
|
@@ -5863,10 +6156,53 @@ function freshOpenClawModelRef(ctx) {
|
|
|
5863
6156
|
return { provider: "openai", model: OPENCLAW_FRESH_MODEL, raw: `openai/${OPENCLAW_FRESH_MODEL}` };
|
|
5864
6157
|
}
|
|
5865
6158
|
function appendUrlPath(base, path) {
|
|
5866
|
-
return `${base
|
|
5867
|
-
}
|
|
5868
|
-
function
|
|
5869
|
-
return join(homedir(), ".
|
|
6159
|
+
return `${trimTrailingSlashes(base)}${path}`;
|
|
6160
|
+
}
|
|
6161
|
+
export function claudeConfigDir(env = process.env) {
|
|
6162
|
+
return env.CLAUDE_CONFIG_DIR ? resolve(env.CLAUDE_CONFIG_DIR) : join(homedir(), ".claude");
|
|
6163
|
+
}
|
|
6164
|
+
export function claudeGlobalConfigPath(env = process.env) {
|
|
6165
|
+
// Claude keeps its default global/MCP config beside ~/.claude, but moves
|
|
6166
|
+
// that file inside a nonempty CLAUDE_CONFIG_DIR override.
|
|
6167
|
+
return env.CLAUDE_CONFIG_DIR ? join(claudeConfigDir(env), ".claude.json") : join(homedir(), ".claude.json");
|
|
6168
|
+
}
|
|
6169
|
+
export function geminiConfigDir(env = process.env) {
|
|
6170
|
+
// GEMINI_CLI_HOME replaces the home directory, not the .gemini directory.
|
|
6171
|
+
return resolve(env.GEMINI_CLI_HOME || homedir(), ".gemini");
|
|
6172
|
+
}
|
|
6173
|
+
function agentUserPath(agent, path) {
|
|
6174
|
+
const prefix = agent === "claude" ? "~/.claude/" : agent === "codex" ? "~/.codex/" : undefined;
|
|
6175
|
+
if (!prefix || !path.startsWith(prefix))
|
|
6176
|
+
return path;
|
|
6177
|
+
const root = agent === "claude" ? claudeConfigDir() : codexHomeDir();
|
|
6178
|
+
return join(root, path.slice(prefix.length));
|
|
6179
|
+
}
|
|
6180
|
+
export function codexHomeDir(env = process.env) {
|
|
6181
|
+
const configured = env.CODEX_HOME;
|
|
6182
|
+
if (!configured)
|
|
6183
|
+
return join(homedir(), ".codex");
|
|
6184
|
+
// Match Codex's own home resolver: a nonempty override may be relative, but
|
|
6185
|
+
// must already be a directory and is canonicalized before use. Never fall
|
|
6186
|
+
// back to another account's default home when the override is invalid.
|
|
6187
|
+
let metadata;
|
|
6188
|
+
try {
|
|
6189
|
+
metadata = statSync(configured);
|
|
6190
|
+
}
|
|
6191
|
+
catch (error) {
|
|
6192
|
+
if (error.code === "ENOENT") {
|
|
6193
|
+
throw new Error(`CODEX_HOME points to ${JSON.stringify(configured)}, but that path does not exist`);
|
|
6194
|
+
}
|
|
6195
|
+
throw new Error(`failed to read CODEX_HOME ${JSON.stringify(configured)}: ${error.message}`);
|
|
6196
|
+
}
|
|
6197
|
+
if (!metadata.isDirectory()) {
|
|
6198
|
+
throw new Error(`CODEX_HOME points to ${JSON.stringify(configured)}, but that path is not a directory`);
|
|
6199
|
+
}
|
|
6200
|
+
try {
|
|
6201
|
+
return realpathSync(configured);
|
|
6202
|
+
}
|
|
6203
|
+
catch (error) {
|
|
6204
|
+
throw new Error(`failed to canonicalize CODEX_HOME ${JSON.stringify(configured)}: ${error.message}`);
|
|
6205
|
+
}
|
|
5870
6206
|
}
|
|
5871
6207
|
function codexAuthPath() {
|
|
5872
6208
|
return join(codexHomeDir(), "auth.json");
|
|
@@ -5936,12 +6272,32 @@ function stripCodexCavemanProviderToml(text) {
|
|
|
5936
6272
|
}
|
|
5937
6273
|
return out.join("\n").trimEnd();
|
|
5938
6274
|
}
|
|
6275
|
+
// The api-key Codex route, in ONE place: the provider TOML writes it, the
|
|
6276
|
+
// install journal records it, and the doctor compares against it, and a route
|
|
6277
|
+
// only three of those four agree on reads as permanently degraded.
|
|
6278
|
+
const CODEX_PAYG_ROUTE = "/w/codex/v1";
|
|
6279
|
+
function codexGatewayBase(gw, subscription) {
|
|
6280
|
+
// Codex's OpenAI-Responses client appends "/responses" onto base_url itself,
|
|
6281
|
+
// exactly as it does against the real api.openai.com, so what the proxy
|
|
6282
|
+
// receives is `<this path>/responses`. The openai adapter's Routes are a
|
|
6283
|
+
// closed, exact allowlist holding "/v1/responses" and never "/responses", so
|
|
6284
|
+
// the api-key route needs the "/v1" or every api-key Codex session 404s with
|
|
6285
|
+
// cave_route_not_found before one request reaches OpenAI (#1045). Same
|
|
6286
|
+
// convention aider already uses (`/w/aider/openai/v1`). The subscription
|
|
6287
|
+
// route is a different mux handler (`/chatgpt/`) that takes the suffix
|
|
6288
|
+
// verbatim, so it must NOT gain a "/v1".
|
|
6289
|
+
return appendUrlPath(gw, subscription ? "/chatgpt" : CODEX_PAYG_ROUTE);
|
|
6290
|
+
}
|
|
6291
|
+
// Codex clears the stdio MCP environment, including these non-secret store
|
|
6292
|
+
// selectors. Forward their names so the proxy and recovery server share the
|
|
6293
|
+
// current launch's store without persisting provider credentials or stale paths.
|
|
6294
|
+
const CODEX_RECOVERY_ENV = 'env_vars = ["CAVEMAN_HOME", "CAVEMAN_CCR_DB"]';
|
|
5939
6295
|
function codexCavemanProviderToml(gw, subscription = true) {
|
|
5940
6296
|
return [
|
|
5941
6297
|
`model_provider = "caveman"`,
|
|
5942
6298
|
`[model_providers.caveman]`,
|
|
5943
6299
|
`name = "Caveman"`,
|
|
5944
|
-
`base_url = ${JSON.stringify(
|
|
6300
|
+
`base_url = ${JSON.stringify(codexGatewayBase(gw, subscription))}`,
|
|
5945
6301
|
`wire_api = "responses"`,
|
|
5946
6302
|
`requires_openai_auth = true`,
|
|
5947
6303
|
].join("\n");
|
|
@@ -6134,6 +6490,16 @@ function canonicalManagedHookEntry(entry) {
|
|
|
6134
6490
|
hooks[0].command = identity;
|
|
6135
6491
|
return JSON.stringify(clone);
|
|
6136
6492
|
}
|
|
6493
|
+
// Why: `think.shrink` (and its `CAVEMAN_SHRINK` env form) is the persisted
|
|
6494
|
+
// switch for the command-output rewrite, but only the ephemeral launcher ever
|
|
6495
|
+
// read it — every native writer passed a literal `true`, so `caveman enable` /
|
|
6496
|
+
// `doctor --fix` / `repairNativeAgent` reinstated `shrink-hook` no matter what
|
|
6497
|
+
// the config said and there was no persistent way to run the native
|
|
6498
|
+
// integration without it (#1049). Read in ONE place so the writers and the
|
|
6499
|
+
// health check that judges them cannot disagree about what is expected.
|
|
6500
|
+
function nativeShrinkEnabled() {
|
|
6501
|
+
return resolveCapabilities().values["think.shrink"].value;
|
|
6502
|
+
}
|
|
6137
6503
|
function nativeHooksDocument(agentId, includeShrink, base = {}, includeRecall = false) {
|
|
6138
6504
|
const root = JSON.parse(JSON.stringify(base));
|
|
6139
6505
|
const hooks = root.hooks && typeof root.hooks === "object" && !Array.isArray(root.hooks)
|
|
@@ -6157,23 +6523,34 @@ function nativeHooksDocument(agentId, includeShrink, base = {}, includeRecall =
|
|
|
6157
6523
|
list.push(nativeHookEntry(command, agentId));
|
|
6158
6524
|
hooks[event] = list;
|
|
6159
6525
|
}
|
|
6160
|
-
|
|
6526
|
+
{
|
|
6161
6527
|
const shrinkEvent = agentId === "gemini" ? "BeforeTool" : "PreToolUse";
|
|
6162
6528
|
const list = Array.isArray(hooks[shrinkEvent]) ? hooks[shrinkEvent] : [];
|
|
6163
6529
|
const shrinkCommand = `${cavemanBinForHook()} shrink-hook`;
|
|
6164
6530
|
// Same replace-not-accumulate rule as the native hook: a shrink-hook entry
|
|
6165
|
-
// under another caveman path is ours.
|
|
6531
|
+
// under another caveman path is ours. When the switch is OFF the rule has
|
|
6532
|
+
// to reach OUR path too (#1049): `base` is the host's live file, so a
|
|
6533
|
+
// standalone install, or any caveman old enough to predate the switch,
|
|
6534
|
+
// leaves an entry here that honoring the switch only on the entries we ADD
|
|
6535
|
+
// would merge straight through — the rewrite stays live on exactly the
|
|
6536
|
+
// machines that asked for it off, and the install is born degraded because
|
|
6537
|
+
// nativeHookEntriesHealthy rejects a managed entry the expected document
|
|
6538
|
+
// lacks. Withdrawing ours is not a claim on the user's other hooks:
|
|
6539
|
+
// managedHookIdentity only matches a caveman binary.
|
|
6166
6540
|
for (let i = list.length - 1; i >= 0; i--) {
|
|
6167
6541
|
const entry = list[i];
|
|
6168
6542
|
const existing = entry ? hookEntryCommand(entry) : undefined;
|
|
6169
|
-
if (existing
|
|
6543
|
+
if (existing === undefined || managedHookIdentity(existing) !== "shrink-hook")
|
|
6544
|
+
continue;
|
|
6545
|
+
if (!includeShrink || existing !== shrinkCommand)
|
|
6170
6546
|
list.splice(i, 1);
|
|
6171
6547
|
}
|
|
6172
|
-
if (!list.some((entry) => hookEntryCommand(entry) === shrinkCommand)) {
|
|
6548
|
+
if (includeShrink && !list.some((entry) => hookEntryCommand(entry) === shrinkCommand)) {
|
|
6173
6549
|
list.push(agentId === "gemini"
|
|
6174
6550
|
? { matcher: "run_shell_command", ...nativeHookEntry(shrinkCommand, agentId) }
|
|
6175
6551
|
: nativeHookEntry(shrinkCommand, agentId));
|
|
6176
6552
|
}
|
|
6553
|
+
// The lifecycle loop above always writes this event, so the key exists either way.
|
|
6177
6554
|
hooks[shrinkEvent] = list;
|
|
6178
6555
|
}
|
|
6179
6556
|
if (agentId === "claude" && includeRecall) {
|
|
@@ -6194,6 +6571,8 @@ function assertNativeHooksShape(path, root, agentId) {
|
|
|
6194
6571
|
const hooks = root.hooks;
|
|
6195
6572
|
if (!hooks)
|
|
6196
6573
|
return;
|
|
6574
|
+
// `true` on purpose, unlike the writers: this only reads the event NAMES to
|
|
6575
|
+
// refuse a non-array, so the superset is the safer set to check.
|
|
6197
6576
|
const expected = nativeHooksDocument(agentId, true).hooks;
|
|
6198
6577
|
for (const event of Object.keys(expected)) {
|
|
6199
6578
|
if (hooks[event] !== undefined && !Array.isArray(hooks[event])) {
|
|
@@ -6207,7 +6586,7 @@ function nativeHookEntriesHealthy(root, agentId) {
|
|
|
6207
6586
|
: undefined;
|
|
6208
6587
|
if (!hooks)
|
|
6209
6588
|
return false;
|
|
6210
|
-
const expected = nativeHooksDocument(agentId,
|
|
6589
|
+
const expected = nativeHooksDocument(agentId, nativeShrinkEnabled()).hooks;
|
|
6211
6590
|
const required = Object.entries(expected).every(([event, expectedRaw]) => {
|
|
6212
6591
|
const actual = Array.isArray(hooks[event]) ? hooks[event] : [];
|
|
6213
6592
|
const actualEntries = new Set(actual.map(canonicalManagedHookEntry).filter(Boolean));
|
|
@@ -6251,7 +6630,7 @@ function buildCodexEphemeralHome(gw, subscription, mcpBinary, includeShrink, del
|
|
|
6251
6630
|
const providerRoot = providerLines.shift();
|
|
6252
6631
|
const providerTables = providerLines.join("\n");
|
|
6253
6632
|
const mcp = mcpBinary
|
|
6254
|
-
? `\n\n[mcp_servers.caveman]\ncommand = ${JSON.stringify(mcpBinary)}\n`
|
|
6633
|
+
? `\n\n[mcp_servers.caveman]\ncommand = ${JSON.stringify(mcpBinary)}\n${CODEX_RECOVERY_ENV}\n`
|
|
6255
6634
|
: "\n";
|
|
6256
6635
|
const delegateArgs = delegateMcp?.args.length
|
|
6257
6636
|
? `\nargs = [${delegateMcp.args.map((arg) => JSON.stringify(arg)).join(", ")}]`
|
|
@@ -6270,6 +6649,9 @@ function buildCodexEphemeralWrapEnv(gw, subscription, mcpBinary, includeShrink,
|
|
|
6270
6649
|
const env = { ...process.env };
|
|
6271
6650
|
for (const key of WRAP_BASE_URL_ENV_VARS)
|
|
6272
6651
|
delete env[key];
|
|
6652
|
+
// The ephemeral CODEX_HOME points Codex at the same loopback gateway, so it
|
|
6653
|
+
// needs the same proxy exemption the base-url wrap path gets.
|
|
6654
|
+
Object.assign(env, gatewayNoProxyEnv(gw));
|
|
6273
6655
|
env.CODEX_HOME = buildCodexEphemeralHome(gw, subscription, mcpBinary, includeShrink, delegateMcp);
|
|
6274
6656
|
return env;
|
|
6275
6657
|
}
|
|
@@ -6601,6 +6983,13 @@ function claudeNativeMutations(gw, mcpBinary) {
|
|
|
6601
6983
|
&& wrapMode(gw) === "local" && proxyAnthropicUpstreamIsFirstParty();
|
|
6602
6984
|
if (assumeFirstParty)
|
|
6603
6985
|
env[CLAUDE_ASSUME_FIRST_PARTY_ENV] = "1";
|
|
6986
|
+
// Native routing points every later turn at the same loopback gateway, so it
|
|
6987
|
+
// needs the wrap path's proxy exemption too (#1001). Never clobber a value the
|
|
6988
|
+
// user already carries in settings.
|
|
6989
|
+
for (const [key, value] of Object.entries(gatewayNoProxyEnv(gw))) {
|
|
6990
|
+
if (env[key] === undefined)
|
|
6991
|
+
env[key] = value;
|
|
6992
|
+
}
|
|
6604
6993
|
// Claude Code turns tool search (progressive MCP tool disclosure) OFF as soon
|
|
6605
6994
|
// as ANTHROPIC_BASE_URL is not a first-party Anthropic host, so pointing it at
|
|
6606
6995
|
// caveman would otherwise force every MCP tool schema inline on every request
|
|
@@ -6610,8 +6999,8 @@ function claudeNativeMutations(gw, mcpBinary) {
|
|
|
6610
6999
|
if (env.ENABLE_TOOL_SEARCH === undefined)
|
|
6611
7000
|
env.ENABLE_TOOL_SEARCH = TOOL_SEARCH_DEFAULT;
|
|
6612
7001
|
settings.env = env;
|
|
6613
|
-
const withHooks = nativeHooksDocument("claude",
|
|
6614
|
-
const mcpPath =
|
|
7002
|
+
const withHooks = nativeHooksDocument("claude", nativeShrinkEnabled(), settings);
|
|
7003
|
+
const mcpPath = claudeGlobalConfigPath();
|
|
6615
7004
|
const mcpBefore = fileBytes(mcpPath);
|
|
6616
7005
|
const mcpRoot = parseJsonFileObject(mcpPath, mcpBefore);
|
|
6617
7006
|
if (mcpRoot.mcpServers !== undefined && (typeof mcpRoot.mcpServers !== "object" || mcpRoot.mcpServers === null || Array.isArray(mcpRoot.mcpServers))) {
|
|
@@ -6677,8 +7066,8 @@ function geminiNativeMutations(gw, mcpBinary) {
|
|
|
6677
7066
|
const installedMcp = { command: mcpBinary, args: [] };
|
|
6678
7067
|
servers.caveman = installedMcp;
|
|
6679
7068
|
settings.mcpServers = servers;
|
|
6680
|
-
const withHooks = nativeHooksDocument("gemini",
|
|
6681
|
-
const envPath = join(
|
|
7069
|
+
const withHooks = nativeHooksDocument("gemini", nativeShrinkEnabled(), settings);
|
|
7070
|
+
const envPath = join(geminiConfigDir(), ".env");
|
|
6682
7071
|
const envBefore = fileBytes(envPath);
|
|
6683
7072
|
const route = appendUrlPath(gw, "/w/gemini");
|
|
6684
7073
|
const nativeEnv = geminiNativeEnv(envBefore?.toString("utf8") ?? "", route);
|
|
@@ -6702,7 +7091,30 @@ function geminiNativeMutations(gw, mcpBinary) {
|
|
|
6702
7091
|
function opencodeNativePluginPath() {
|
|
6703
7092
|
return join(homedir(), ".config", "opencode", "plugins", "caveman-native.js");
|
|
6704
7093
|
}
|
|
7094
|
+
function opencodePluginMajor() {
|
|
7095
|
+
const profile = AGENTS.find((agent) => agent.id === "opencode");
|
|
7096
|
+
const semver = parsedSemver(profile ? detectedAgentVersion(profile) : null);
|
|
7097
|
+
return semver ? semver[0] : null;
|
|
7098
|
+
}
|
|
6705
7099
|
function opencodeNativePluginSource() {
|
|
7100
|
+
// OpenCode 2 replaced the plugin API: a V1 hook map no longer loads
|
|
7101
|
+
// (PluginModule.LoadError, missing "default"). Emit the implementation
|
|
7102
|
+
// matching the detected host major. See #1083.
|
|
7103
|
+
//
|
|
7104
|
+
// An unreadable version keeps V1, the status quo. nativeHostProbe returns
|
|
7105
|
+
// version: null for an empty/non-zero/unspawnable `opencode --version`
|
|
7106
|
+
// ("version_probe_failed"), and #1081 records exactly that state on a live
|
|
7107
|
+
// OpenCode 1.18.31 host — so "unknown" is not evidence of "new". Defaulting
|
|
7108
|
+
// it to V2 would break a 1.x user whose probe merely flaked, turning a
|
|
7109
|
+
// working install into one whose plugin the host refuses to load; a 2.x user
|
|
7110
|
+
// in the same state is no worse off than before this gate existed. Only a
|
|
7111
|
+
// version that positively reads as major >= 2 opts into the V2 API.
|
|
7112
|
+
const major = opencodePluginMajor();
|
|
7113
|
+
if (major === null || major < 2)
|
|
7114
|
+
return opencodeNativePluginSourceV1();
|
|
7115
|
+
return opencodeNativePluginSourceV2();
|
|
7116
|
+
}
|
|
7117
|
+
function opencodeNativePluginSourceV1() {
|
|
6706
7118
|
const { cmd, pre } = cavemanInvocation();
|
|
6707
7119
|
return `// caveman:native-opencode — GENERATED by \`caveman enable opencode\`.
|
|
6708
7120
|
// Contract: @opencode-ai/plugin 1.17.8 Hooks (installed local type source).
|
|
@@ -6873,6 +7285,211 @@ export const CavemanNative = async () => ({
|
|
|
6873
7285
|
});
|
|
6874
7286
|
`;
|
|
6875
7287
|
}
|
|
7288
|
+
function opencodeNativePluginSourceV2() {
|
|
7289
|
+
const { cmd, pre } = cavemanInvocation();
|
|
7290
|
+
return `// caveman:native-opencode — GENERATED by \`caveman enable opencode\`.
|
|
7291
|
+
// Contract: OpenCode 2 plugin API — default export { id, setup }
|
|
7292
|
+
// (https://opencode.ai/v2/docs/build/plugins/migrate-v1).
|
|
7293
|
+
import { execFileSync } from "node:child_process";
|
|
7294
|
+
import { createHash } from "node:crypto";
|
|
7295
|
+
|
|
7296
|
+
const command = ${JSON.stringify(cmd)};
|
|
7297
|
+
const prefix = ${JSON.stringify(pre)};
|
|
7298
|
+
|
|
7299
|
+
function call(event, payload = {}) {
|
|
7300
|
+
try {
|
|
7301
|
+
const raw = execFileSync(command, [...prefix, "native-hook", "opencode", event], {
|
|
7302
|
+
input: JSON.stringify({ event_name: event, ...payload }),
|
|
7303
|
+
encoding: "utf8",
|
|
7304
|
+
timeout: 2000,
|
|
7305
|
+
maxBuffer: 2 * 1024 * 1024,
|
|
7306
|
+
});
|
|
7307
|
+
if (!raw.trim()) return undefined;
|
|
7308
|
+
const value = JSON.parse(raw);
|
|
7309
|
+
return value && typeof value === "object" ? value : undefined;
|
|
7310
|
+
} catch { return undefined; }
|
|
7311
|
+
}
|
|
7312
|
+
|
|
7313
|
+
function digest(value) {
|
|
7314
|
+
try {
|
|
7315
|
+
const raw = JSON.stringify(value);
|
|
7316
|
+
return { bytes: Buffer.byteLength(raw), sha256: "sha256:" + createHash("sha256").update(raw).digest("hex") };
|
|
7317
|
+
} catch { return undefined; }
|
|
7318
|
+
}
|
|
7319
|
+
|
|
7320
|
+
function taskType(value) {
|
|
7321
|
+
let text;
|
|
7322
|
+
try { text = JSON.stringify(value).toLowerCase(); } catch { return "general"; }
|
|
7323
|
+
const has = (...terms) => terms.some((term) => text.includes(term));
|
|
7324
|
+
if (has("migration", "migrate", "schema change", "backfill", "rollback")) return "migration";
|
|
7325
|
+
if (has("bug", "fix", "broken", "regression", "crash", "error", "incorrect")) return "bugfix";
|
|
7326
|
+
if (has("investigate", "diagnose", "root cause", "why does", "trace")) return "investigation";
|
|
7327
|
+
if (has("refactor", "restructure", "reorganize", "cleanup")) return "refactor";
|
|
7328
|
+
if (has("review", "audit", "critique", "assess")) return "review";
|
|
7329
|
+
if (has("verify", "verification", "prove", "validate", "check that")) return "verification";
|
|
7330
|
+
if (has("build", "implement", "add", "create", "ship", "feature")) return "feature";
|
|
7331
|
+
return "general";
|
|
7332
|
+
}
|
|
7333
|
+
|
|
7334
|
+
function taskTerms(value) {
|
|
7335
|
+
let text;
|
|
7336
|
+
try { text = JSON.stringify(value); } catch { return []; }
|
|
7337
|
+
const stop = new Set(["about", "after", "agent", "before", "build", "change", "code", "create", "from", "have", "help", "implement", "into", "make", "please", "project", "repository", "should", "spec", "task", "that", "then", "there", "these", "they", "this", "through", "user", "want", "what", "when", "where", "which", "with", "would", "your"]);
|
|
7338
|
+
const out = [];
|
|
7339
|
+
const seen = new Set();
|
|
7340
|
+
for (const raw of text.match(/[A-Za-z][A-Za-z0-9_./-]{2,63}/g) ?? []) {
|
|
7341
|
+
const term = raw.toLowerCase().replace(/^[-./]+|[-./]+$/g, "");
|
|
7342
|
+
if (!term || term.includes("..") || stop.has(term) || seen.has(term) || /^(?:sk|pk|rk|ghp|github_pat|xox[baprs]|akia)[-_]/i.test(term) || /^[a-z0-9_-]{40,}$/i.test(term)) continue;
|
|
7343
|
+
seen.add(term);
|
|
7344
|
+
out.push(term);
|
|
7345
|
+
if (out.length === 12) break;
|
|
7346
|
+
}
|
|
7347
|
+
return out;
|
|
7348
|
+
}
|
|
7349
|
+
|
|
7350
|
+
function taskContinuation(value) {
|
|
7351
|
+
const visit = (item) => {
|
|
7352
|
+
if (typeof item === "string") return item;
|
|
7353
|
+
if (Array.isArray(item)) return item.map(visit).filter(Boolean).join(" ");
|
|
7354
|
+
if (!item || typeof item !== "object") return "";
|
|
7355
|
+
return visit(item.text ?? item.content ?? item.message ?? "");
|
|
7356
|
+
};
|
|
7357
|
+
const prompt = visit(value).trim().toLowerCase();
|
|
7358
|
+
if (!prompt || prompt.length > 160 || prompt.split(/\\s+/).length > 14) return false;
|
|
7359
|
+
return /^(?:please\\s+)?(?:continue|go ahead|keep going|proceed|do (?:it|that)|fix (?:it|that)|retry|try again|explain (?:it|that)|what do you mean|yes|yep|yeah|why\\??|how\\??)[.!?\\s]*$/.test(prompt);
|
|
7360
|
+
}
|
|
7361
|
+
|
|
7362
|
+
export default {
|
|
7363
|
+
id: "caveman-native",
|
|
7364
|
+
async setup(ctx) {
|
|
7365
|
+
// Per-plugin-instance state: one setup() runs per location, so two
|
|
7366
|
+
// projects never share session context through module scope.
|
|
7367
|
+
const contexts = new Map();
|
|
7368
|
+
const pending = new Map();
|
|
7369
|
+
|
|
7370
|
+
function sessionContext(sessionID) {
|
|
7371
|
+
if (!contexts.has(sessionID)) {
|
|
7372
|
+
const out = call("SessionStart", { session_id: sessionID, surface: "cli" });
|
|
7373
|
+
const context = out?.hookSpecificOutput?.additionalContext;
|
|
7374
|
+
contexts.set(sessionID, typeof context === "string" ? context : "");
|
|
7375
|
+
}
|
|
7376
|
+
return contexts.get(sessionID);
|
|
7377
|
+
}
|
|
7378
|
+
|
|
7379
|
+
const controller = new AbortController();
|
|
7380
|
+
const events = (async () => {
|
|
7381
|
+
for await (const event of ctx.event.subscribe({ signal: controller.signal })) {
|
|
7382
|
+
handleEvent(event);
|
|
7383
|
+
}
|
|
7384
|
+
})().catch(() => {
|
|
7385
|
+
if (!controller.signal.aborted) console.warn("[caveman-native] Event subscription failed");
|
|
7386
|
+
});
|
|
7387
|
+
|
|
7388
|
+
function sameLocation(event) {
|
|
7389
|
+
return event.location?.directory === ctx.location.directory &&
|
|
7390
|
+
event.location?.workspaceID === ctx.location.workspaceID;
|
|
7391
|
+
}
|
|
7392
|
+
|
|
7393
|
+
function handleEvent(event) {
|
|
7394
|
+
if (!sameLocation(event)) return;
|
|
7395
|
+
const type = event.type;
|
|
7396
|
+
const sessionID = event.data?.sessionID;
|
|
7397
|
+
if (typeof sessionID !== "string" || !sessionID) return;
|
|
7398
|
+
if (type === "session.created") sessionContext(sessionID);
|
|
7399
|
+
if (type === "session.idle") call("Stop", { session_id: sessionID });
|
|
7400
|
+
// "session.compacted" is the V1 event name; V2 reports compaction
|
|
7401
|
+
// through "session.compaction.ended". Handle both.
|
|
7402
|
+
if (type === "session.compaction.ended" || type === "session.compacted") {
|
|
7403
|
+
const out = call("PostCompact", { session_id: sessionID });
|
|
7404
|
+
const context = out?.hookSpecificOutput?.additionalContext;
|
|
7405
|
+
if (typeof context === "string" && context) contexts.set(sessionID, context);
|
|
7406
|
+
}
|
|
7407
|
+
if (type === "session.deleted") {
|
|
7408
|
+
call("SessionEnd", { session_id: sessionID });
|
|
7409
|
+
contexts.delete(sessionID);
|
|
7410
|
+
pending.delete(sessionID);
|
|
7411
|
+
}
|
|
7412
|
+
}
|
|
7413
|
+
|
|
7414
|
+
await ctx.session.hook("prompt", (event) => {
|
|
7415
|
+
const prompt = event.prompt ?? {};
|
|
7416
|
+
const decision = call("UserPromptSubmit", {
|
|
7417
|
+
session_id: event.sessionID,
|
|
7418
|
+
prompt: digest(prompt),
|
|
7419
|
+
task_type: taskType(prompt),
|
|
7420
|
+
task_terms: taskTerms(prompt),
|
|
7421
|
+
task_continuation: taskContinuation(prompt),
|
|
7422
|
+
});
|
|
7423
|
+
const dynamic = decision?.hookSpecificOutput?.additionalContext;
|
|
7424
|
+
if (typeof dynamic === "string" && dynamic) pending.set(event.sessionID, dynamic);
|
|
7425
|
+
});
|
|
7426
|
+
|
|
7427
|
+
await ctx.session.hook("context", (event) => {
|
|
7428
|
+
const stable = sessionContext(event.sessionID);
|
|
7429
|
+
if (stable) event.system.push({ type: "text", text: stable });
|
|
7430
|
+
const hint = pending.get(event.sessionID);
|
|
7431
|
+
if (hint) {
|
|
7432
|
+
event.system.push({ type: "text", text: hint });
|
|
7433
|
+
pending.delete(event.sessionID);
|
|
7434
|
+
}
|
|
7435
|
+
});
|
|
7436
|
+
|
|
7437
|
+
await ctx.session.hook("compaction", (event) => {
|
|
7438
|
+
call("PreCompact", { session_id: event.sessionID });
|
|
7439
|
+
const stable = sessionContext(event.sessionID);
|
|
7440
|
+
if (stable) event.system.push({ type: "text", text: stable });
|
|
7441
|
+
});
|
|
7442
|
+
|
|
7443
|
+
await ctx.tool.hook("execute.before", (event) => {
|
|
7444
|
+
const decision = call("PreToolUse", {
|
|
7445
|
+
session_id: event.sessionID,
|
|
7446
|
+
tool_name: event.tool,
|
|
7447
|
+
tool_input: event.input,
|
|
7448
|
+
});
|
|
7449
|
+
if (typeof decision?.hookSpecificOutput?.additionalContext === "string") {
|
|
7450
|
+
pending.set(event.sessionID, decision.hookSpecificOutput.additionalContext);
|
|
7451
|
+
}
|
|
7452
|
+
// V1 named this tool "bash"; V2 renamed the permission action to
|
|
7453
|
+
// "shell". Accept both so the rewrite survives either host.
|
|
7454
|
+
const input = event.input;
|
|
7455
|
+
if ((event.tool === "bash" || event.tool === "shell") &&
|
|
7456
|
+
input && typeof input === "object" && typeof input.command === "string") {
|
|
7457
|
+
try {
|
|
7458
|
+
const raw = execFileSync(command, [...prefix, "shrink-hook"], {
|
|
7459
|
+
input: JSON.stringify({ tool_name: "Bash", tool_input: { command: input.command } }),
|
|
7460
|
+
encoding: "utf8",
|
|
7461
|
+
timeout: 750,
|
|
7462
|
+
});
|
|
7463
|
+
const rewritten = JSON.parse(raw)?.hookSpecificOutput?.updatedInput?.command;
|
|
7464
|
+
if (typeof rewritten === "string" && rewritten) input.command = rewritten;
|
|
7465
|
+
} catch {}
|
|
7466
|
+
}
|
|
7467
|
+
});
|
|
7468
|
+
|
|
7469
|
+
await ctx.tool.hook("execute.after", (event) => {
|
|
7470
|
+
if (event.status !== "completed") return;
|
|
7471
|
+
const decision = call("PostToolUse", {
|
|
7472
|
+
session_id: event.sessionID,
|
|
7473
|
+
tool_name: event.tool,
|
|
7474
|
+
tool_input: event.input,
|
|
7475
|
+
tool_output: event.result,
|
|
7476
|
+
});
|
|
7477
|
+
const replacement = decision?.hookSpecificOutput?.updatedToolOutput ?? decision?.output_replacement;
|
|
7478
|
+
if (typeof replacement === "string") {
|
|
7479
|
+
event.result = { ...event.result, content: replacement };
|
|
7480
|
+
}
|
|
7481
|
+
});
|
|
7482
|
+
|
|
7483
|
+
return () => {
|
|
7484
|
+
controller.abort();
|
|
7485
|
+
for (const sessionID of contexts.keys()) call("SessionEnd", { session_id: sessionID });
|
|
7486
|
+
contexts.clear();
|
|
7487
|
+
pending.clear();
|
|
7488
|
+
};
|
|
7489
|
+
},
|
|
7490
|
+
};
|
|
7491
|
+
`;
|
|
7492
|
+
}
|
|
6876
7493
|
function opencodeNativeMutations(gw, mcpBinary) {
|
|
6877
7494
|
const configPath = join(homedir(), ".config", "opencode", "opencode.json");
|
|
6878
7495
|
const before = fileBytes(configPath);
|
|
@@ -7052,6 +7669,7 @@ function codexNativeConfig(source, gw, subscription, mcpBinary) {
|
|
|
7052
7669
|
"",
|
|
7053
7670
|
"[mcp_servers.caveman]",
|
|
7054
7671
|
`command = ${JSON.stringify(mcpBinary)}`,
|
|
7672
|
+
CODEX_RECOVERY_ENV,
|
|
7055
7673
|
CODEX_NATIVE_TABLES_END,
|
|
7056
7674
|
].join("\n");
|
|
7057
7675
|
const middle = stripped ? `\n\n${stripped}` : "";
|
|
@@ -7062,12 +7680,12 @@ function codexNativeMutations(gw, mcpBinary) {
|
|
|
7062
7680
|
const hooksBefore = fileBytes(hooksPath);
|
|
7063
7681
|
const hooksRoot = parseJsonFileObject(hooksPath, hooksBefore);
|
|
7064
7682
|
assertNativeHooksShape(hooksPath, hooksRoot, "codex");
|
|
7065
|
-
const hooks = nativeHooksDocument("codex",
|
|
7683
|
+
const hooks = nativeHooksDocument("codex", nativeShrinkEnabled(), hooksRoot);
|
|
7066
7684
|
const configPath = join(codexHomeDir(), "config.toml");
|
|
7067
7685
|
const configBefore = fileBytes(configPath);
|
|
7068
7686
|
const subscription = detectCodexWrapAuthMode() === "subscription";
|
|
7069
7687
|
const native = codexNativeConfig(configBefore?.toString("utf8") ?? "", gw, subscription, mcpBinary);
|
|
7070
|
-
const route =
|
|
7688
|
+
const route = codexGatewayBase(gw, subscription);
|
|
7071
7689
|
return [
|
|
7072
7690
|
{ file: hooksPath, before: hooksBefore, after: Buffer.from(JSON.stringify(hooks, null, 2) + "\n"), kind: "codex-hooks" },
|
|
7073
7691
|
{
|
|
@@ -7296,7 +7914,7 @@ function hermesNativeConfig(source, gw, mcpBinary) {
|
|
|
7296
7914
|
const routeBlock = [
|
|
7297
7915
|
` ${HERMES_NATIVE_ROUTE_BEGIN}`,
|
|
7298
7916
|
' provider: "custom"',
|
|
7299
|
-
` base_url: ${yamlQuote(appendUrlPath(gw, "/w/hermes"))}`,
|
|
7917
|
+
` base_url: ${yamlQuote(appendUrlPath(gw, "/w/hermes/v1"))}`,
|
|
7300
7918
|
` ${HERMES_NATIVE_ROUTE_END}`,
|
|
7301
7919
|
];
|
|
7302
7920
|
lines.splice(insertAt, 0, ...routeBlock);
|
|
@@ -7343,7 +7961,7 @@ function hermesNativeConfig(source, gw, mcpBinary) {
|
|
|
7343
7961
|
return {
|
|
7344
7962
|
text: yamlText(lines),
|
|
7345
7963
|
owned: {
|
|
7346
|
-
route: appendUrlPath(gw, "/w/hermes"),
|
|
7964
|
+
route: appendUrlPath(gw, "/w/hermes/v1"),
|
|
7347
7965
|
route_block: routeBlock.join("\n"),
|
|
7348
7966
|
previous_route_lines: previousRouteLines,
|
|
7349
7967
|
plugin_block: pluginBlock,
|
|
@@ -7604,6 +8222,69 @@ function readNativeJournal(agent) {
|
|
|
7604
8222
|
function readPendingNativeJournal(agent) {
|
|
7605
8223
|
return readNativeJournalAt(nativePendingJournalPath(agent), agent);
|
|
7606
8224
|
}
|
|
8225
|
+
// nativeRoutePinnedFor reports the config file that pins this agent's base URL,
|
|
8226
|
+
// when native routing is installed for it, or null when nothing is pinned.
|
|
8227
|
+
//
|
|
8228
|
+
// It reads the install journal rather than re-deriving per-agent config shapes,
|
|
8229
|
+
// so it covers every native host by construction: claude's settings.json env
|
|
8230
|
+
// block, codex's config.toml model_provider, hermes/gemini/aider's marker
|
|
8231
|
+
// fences, opencode's routes map, pi's bundle. A caller that needs to point an
|
|
8232
|
+
// agent somewhere else for one run has to know that any of these outranks the
|
|
8233
|
+
// environment it is about to set.
|
|
8234
|
+
//
|
|
8235
|
+
// Deliberately journal-only and file-cheap: unlike nativeIntegrationStatus this
|
|
8236
|
+
// probes no binary, proxy or MCP server, because the question is only "is a
|
|
8237
|
+
// route pinned on disk", not "is the whole integration healthy".
|
|
8238
|
+
//
|
|
8239
|
+
// The PENDING journal has to be consulted too, and the two are read differently.
|
|
8240
|
+
// installNativeAgent writes the pending journal first, then each host file, and
|
|
8241
|
+
// publishes the committed journal LAST. So a process death between those leaves
|
|
8242
|
+
// a fully applied, fully readable pinned route on disk with only the pending
|
|
8243
|
+
// journal to show for it — which is exactly the state this guard exists to
|
|
8244
|
+
// catch, reached by a crash instead of a successful install.
|
|
8245
|
+
//
|
|
8246
|
+
// A committed journal is taken at its word: enable finished, the route is
|
|
8247
|
+
// pinned. A pending one is genuinely ambiguous — the mutation may or may not
|
|
8248
|
+
// have landed before the process died — so it is resolved against the file
|
|
8249
|
+
// itself using the after_sha256 the journal already records. That is
|
|
8250
|
+
// agent-agnostic (no per-host config shapes here) and avoids refusing a trial
|
|
8251
|
+
// over a stale pending journal whose writes never happened.
|
|
8252
|
+
function nativeRoutePinnedFor(agent) {
|
|
8253
|
+
const routeIn = (owned) => {
|
|
8254
|
+
if (!owned)
|
|
8255
|
+
return null;
|
|
8256
|
+
if (typeof owned.route === "string" && owned.route)
|
|
8257
|
+
return owned.route;
|
|
8258
|
+
// opencode pins one route per protocol instead of a single base URL.
|
|
8259
|
+
const routes = owned.routes;
|
|
8260
|
+
if (routes && typeof routes === "object" && !Array.isArray(routes)) {
|
|
8261
|
+
for (const value of Object.values(routes)) {
|
|
8262
|
+
if (typeof value === "string" && value)
|
|
8263
|
+
return value;
|
|
8264
|
+
}
|
|
8265
|
+
}
|
|
8266
|
+
return null;
|
|
8267
|
+
};
|
|
8268
|
+
const committed = readNativeJournal(agent);
|
|
8269
|
+
for (const operation of committed?.operations ?? []) {
|
|
8270
|
+
const route = routeIn(operation.owned);
|
|
8271
|
+
if (route)
|
|
8272
|
+
return { file: operation.file, route, pending: false };
|
|
8273
|
+
}
|
|
8274
|
+
const pending = readPendingNativeJournal(agent);
|
|
8275
|
+
for (const operation of pending?.operations ?? []) {
|
|
8276
|
+
const route = routeIn(operation.owned);
|
|
8277
|
+
if (!route)
|
|
8278
|
+
continue;
|
|
8279
|
+
const current = fileBytes(operation.file);
|
|
8280
|
+
// No file, or contents that are not what this operation would have written,
|
|
8281
|
+
// means the interrupted install never got as far as pinning this route.
|
|
8282
|
+
if (current && bytesHash(current) === operation.after_sha256) {
|
|
8283
|
+
return { file: operation.file, route, pending: true };
|
|
8284
|
+
}
|
|
8285
|
+
}
|
|
8286
|
+
return null;
|
|
8287
|
+
}
|
|
7607
8288
|
function recoverPendingNativeInstallUnlocked(agent) {
|
|
7608
8289
|
const pending = readPendingNativeJournal(agent);
|
|
7609
8290
|
if (!pending)
|
|
@@ -7687,7 +8368,10 @@ function enableNative(argv) {
|
|
|
7687
8368
|
if (existing.installed) {
|
|
7688
8369
|
if (existing.state === "installed")
|
|
7689
8370
|
return "already";
|
|
7690
|
-
|
|
8371
|
+
// `--fix` on purpose: bare `caveman doctor <agent>` prints JSON that says
|
|
8372
|
+
// `degraded` and nothing that says how to leave that state, so pointing
|
|
8373
|
+
// at it alone dead-ends the user who followed this line here (#1049).
|
|
8374
|
+
throw new Error(`${profile.display_name} integration is degraded; run \`caveman doctor ${agent} --fix\` before changing it`);
|
|
7691
8375
|
}
|
|
7692
8376
|
const mutations = nativeMutationsFor(agent, gw, mcpBinary);
|
|
7693
8377
|
const route = mutations.find((item) => typeof item.owned?.route === "string")?.owned?.route;
|
|
@@ -7701,10 +8385,31 @@ function enableNative(argv) {
|
|
|
7701
8385
|
? ` Core: read-only ${aiderCorePath()}; lifecycle/tool interception unavailable; Ledger observational\n`
|
|
7702
8386
|
: agent === "pi"
|
|
7703
8387
|
? ` lifecycle/Core/tool rewrite: bundled Pi extension -> ${nativeHookCommand(agent)}\n`
|
|
7704
|
-
|
|
8388
|
+
// Codex gets the lifecycle line without the "tool rewrite" claim: since
|
|
8389
|
+
// #1037 shrink-hook declines every Codex tool event, so promising one here
|
|
8390
|
+
// would be the same false claim `doctor` used to report.
|
|
8391
|
+
: agent === "codex"
|
|
8392
|
+
? ` lifecycle/Core: ${nativeHookCommand(agent)}; command-output rewrite unavailable in Codex\n`
|
|
8393
|
+
: ` lifecycle/Core/tool rewrite: ${nativeHookCommand(agent)}${agent === "hermes" ? " via native plugin" : ` + ${cavemanBinForHook()} shrink-hook`}\n`);
|
|
7705
8394
|
applyNativeMutations(agent, profile, mutations);
|
|
7706
8395
|
return "enabled";
|
|
7707
8396
|
});
|
|
8397
|
+
// Outside the lock, and on BOTH outcomes. The native SessionStart hook
|
|
8398
|
+
// autostarts the proxy, but only once the host has approved the installed
|
|
8399
|
+
// hooks (Codex gates this behind /hooks), and `enable` run on its own —
|
|
8400
|
+
// outside the `caveman <agent>` shortcut, which has its own blocking
|
|
8401
|
+
// pre-start at its call site — otherwise leaves that window open
|
|
8402
|
+
// indefinitely: config.toml/settings route every request through a proxy
|
|
8403
|
+
// nothing has confirmed is listening, which is what turns a fresh Codex
|
|
8404
|
+
// session into a mid-stream disconnect rather than a connection error.
|
|
8405
|
+
//
|
|
8406
|
+
// "already" has to run it too. Re-running `enable` is exactly what someone
|
|
8407
|
+
// does when the route is dead, and the installed-state branch returns
|
|
8408
|
+
// before any of this; gating on a fresh install would make proxy startup an
|
|
8409
|
+
// accidental side effect of the first install rather than something the
|
|
8410
|
+
// command does. The integration lock is for file mutations — a liveness
|
|
8411
|
+
// probe and a detached spawn need no part of it.
|
|
8412
|
+
ensureLocalProxyForNative(agent, gw);
|
|
7708
8413
|
if (outcome === "already") {
|
|
7709
8414
|
process.stderr.write(`${mark("ok")} ${profile.display_name}: ${agent === "aider" ? "shallow" : "native"} Caveman already enabled\n`);
|
|
7710
8415
|
continue;
|
|
@@ -7738,6 +8443,8 @@ function removeNativeHookEntries(root, agent) {
|
|
|
7738
8443
|
: undefined;
|
|
7739
8444
|
if (!hooks)
|
|
7740
8445
|
return root;
|
|
8446
|
+
// `true` on purpose, unlike the writers: disable must withdraw a shrink entry
|
|
8447
|
+
// an earlier install wrote, whatever the config says now.
|
|
7741
8448
|
const expected = nativeHooksDocument(agent, true).hooks;
|
|
7742
8449
|
const allowedManaged = new Set(Object.values(expected)
|
|
7743
8450
|
.flatMap((raw) => Array.isArray(raw) ? raw : [])
|
|
@@ -8212,7 +8919,9 @@ function nativeIntegrationStatus(agent) {
|
|
|
8212
8919
|
const coreResolution = runtimeConfig.resolution.values["think.core"];
|
|
8213
8920
|
const coreConfigured = coreResolution.value === true;
|
|
8214
8921
|
const mcp = probeMcpBinary();
|
|
8215
|
-
const expectedRoute =
|
|
8922
|
+
const expectedRoute = agent === "codex"
|
|
8923
|
+
? codexGatewayBase(gatewayURL(), detectCodexWrapAuthMode() === "subscription")
|
|
8924
|
+
: appendUrlPath(gatewayURL(), agent === "claude" ? "/w/claude" : agent === "hermes" ? "/w/hermes/v1" : agent === "gemini" ? "/w/gemini" : agent === "opencode" ? "/w/opencode" : agent === "pi" ? "/w/pi" : "/w/aider/openai/v1");
|
|
8216
8925
|
const routeKind = agent === "claude" ? "claude-settings" : agent === "codex" ? "codex-config" : agent === "hermes" ? "hermes-config" : agent === "gemini" ? "gemini-env" : agent === "opencode" ? "opencode-config" : agent === "pi" ? "pi-extension" : "aider-config";
|
|
8217
8926
|
const routeOperation = journal?.operations.find((operation) => operation.kind === routeKind);
|
|
8218
8927
|
// Pi's artifact encodes no route: the extension resolves the gateway at
|
|
@@ -8232,13 +8941,38 @@ function nativeIntegrationStatus(agent) {
|
|
|
8232
8941
|
return false;
|
|
8233
8942
|
}
|
|
8234
8943
|
})();
|
|
8944
|
+
// Same class as piBundleCurrent above, one step removed: opencode's plugin API
|
|
8945
|
+
// is chosen when the mutations are built, so an install made against OpenCode
|
|
8946
|
+
// 1.x keeps its V1 hook map after the host upgrades to 2.x — which that host
|
|
8947
|
+
// refuses to load (#1083). Nothing else drifts on that upgrade: same journal,
|
|
8948
|
+
// same bytes, so packCurrent and ownedHealthy both still pass and doctor called
|
|
8949
|
+
// an unloadable plugin "installed". `caveman opencode` deliberately skips
|
|
8950
|
+
// enableNative whenever a journal exists (status probes spawn subprocesses),
|
|
8951
|
+
// which is exactly why that skip's own comment names doctor as the repair door
|
|
8952
|
+
// for drifted installs — so the drift has to be visible here to be repairable.
|
|
8953
|
+
// An unreadable version yields no judgement, matching opencodeNativePluginSource:
|
|
8954
|
+
// "unknown" is not evidence of a new host, so it must not degrade a good install.
|
|
8955
|
+
const opencodePluginApiCurrent = agent !== "opencode" || (() => {
|
|
8956
|
+
const operation = journal?.operations.find((item) => item.kind === "opencode-plugin");
|
|
8957
|
+
const current = operation ? fileBytes(operation.file)?.toString("utf8") : null;
|
|
8958
|
+
if (!current)
|
|
8959
|
+
return true;
|
|
8960
|
+
const installedV2 = current.includes("async setup(ctx)");
|
|
8961
|
+
const installedV1 = current.includes("export const CavemanNative");
|
|
8962
|
+
if (installedV1 === installedV2)
|
|
8963
|
+
return true;
|
|
8964
|
+
const semver = parsedSemver(host.version);
|
|
8965
|
+
if (!semver)
|
|
8966
|
+
return true;
|
|
8967
|
+
return (semver[0] >= 2) === installedV2;
|
|
8968
|
+
})();
|
|
8235
8969
|
const routeHealthy = ownedHealthy && (agent === "opencode"
|
|
8236
8970
|
? routeOperation?.owned?.routes?.openai === appendUrlPath(expectedRoute, "/openai/v1")
|
|
8237
8971
|
&& routeOperation?.owned?.routes?.anthropic === appendUrlPath(expectedRoute, "/anthropic/v1")
|
|
8238
8972
|
: agent === "pi" ? piBundleCurrent : routeOperation?.owned?.route === expectedRoute);
|
|
8239
8973
|
const proxyHealthy = wrapMode(gatewayURL()) === "managed" || Boolean(probeProxyVersion()?.capabilities.includes("native_runtime_v1"));
|
|
8240
8974
|
const recoveryHealthy = agent === "aider" || Boolean(mcp?.probe.current);
|
|
8241
|
-
const state = !available ? "unavailable" : transactionPending ? "degraded" : !installed ? "available" : !packCurrent || !ownedHealthy || !routeHealthy || !proxyHealthy || !recoveryHealthy ? "degraded" : "installed";
|
|
8975
|
+
const state = !available ? "unavailable" : transactionPending ? "degraded" : !installed ? "available" : !packCurrent || !ownedHealthy || !routeHealthy || !proxyHealthy || !recoveryHealthy || !opencodePluginApiCurrent ? "degraded" : "installed";
|
|
8242
8976
|
const coreSupported = agent === "aider" ? ownedHealthy : ownedHealthy && Boolean(NATIVE_PACK.core);
|
|
8243
8977
|
const coreActive = agent === "aider"
|
|
8244
8978
|
? ownedHealthy
|
|
@@ -8246,10 +8980,17 @@ function nativeIntegrationStatus(agent) {
|
|
|
8246
8980
|
const fileText = checks.map((check) => fileBytes(check.file)?.toString("utf8") ?? "").join("\n");
|
|
8247
8981
|
const components = {
|
|
8248
8982
|
routing: routeHealthy && proxyHealthy && (agent === "claude" ? fileText.includes("ANTHROPIC_BASE_URL") : agent === "codex" ? fileText.includes("model_providers.caveman") : agent === "hermes" ? fileText.includes(HERMES_NATIVE_ROUTE_BEGIN) : agent === "gemini" ? fileText.includes(GEMINI_NATIVE_ENV_BEGIN) : agent === "opencode" ? fileText.includes("caveman:native-opencode") : agent === "pi" ? fileText.includes("caveman:native-pi") : fileText.includes(AIDER_NATIVE_ROUTE_BEGIN)),
|
|
8249
|
-
|
|
8983
|
+
// A plugin the host cannot load runs no hooks, whatever its bytes hash to.
|
|
8984
|
+
lifecycle_hooks: agent !== "aider" && ownedHealthy && opencodePluginApiCurrent,
|
|
8250
8985
|
core: coreActive,
|
|
8251
8986
|
mcp_recovery: agent !== "aider" && ownedHealthy && Boolean(mcp?.probe.current),
|
|
8252
|
-
|
|
8987
|
+
// Codex is false for the same reason hermes is: no command rewrite happens. The
|
|
8988
|
+
// shrink-hook entry is still written into ~/.codex/hooks.json (removing it from
|
|
8989
|
+
// nativeHooksDocument would make every existing install read as degraded, since
|
|
8990
|
+
// nativeHookEntriesHealthy rejects a managed entry the expected document lacks),
|
|
8991
|
+
// but since #1037 shrinkHook declines every Codex tool event, so the presence of
|
|
8992
|
+
// that entry no longer evidences a rewrite. Report the behavior, not the file.
|
|
8993
|
+
tool_rewrite: agent !== "aider" && ownedHealthy && (agent === "hermes" || agent === "codex" ? false : agent === "pi" ? fileText.includes("caveman:native-pi") : fileText.includes("shrink-hook")),
|
|
8253
8994
|
shared_runtime: proxyHealthy,
|
|
8254
8995
|
};
|
|
8255
8996
|
const versionStatus = nativeVersionStatus(host.version, profile.tested_agent_version);
|
|
@@ -8550,9 +9291,6 @@ function buildOpenClawOverlay(_agent, baseConfig, ctx) {
|
|
|
8550
9291
|
const configuredRef = resolveOpenClawPrimaryRef(baseConfig);
|
|
8551
9292
|
const ref = configuredRef ?? freshOpenClawModelRef(ctx);
|
|
8552
9293
|
const synthesized = configuredRef === undefined;
|
|
8553
|
-
if (synthesized) {
|
|
8554
|
-
process.stderr.write(`caveman: openclaw primary model not found; routing fresh config through caveman/${ref.model}\n`);
|
|
8555
|
-
}
|
|
8556
9294
|
const provider = resolveOpenClawProvider(baseConfig, ref.provider);
|
|
8557
9295
|
if (!provider) {
|
|
8558
9296
|
process.stderr.write(`caveman: openclaw provider "${ref.provider}" not found; leaving primary model unchanged\n`);
|
|
@@ -8569,11 +9307,74 @@ function buildOpenClawOverlay(_agent, baseConfig, ctx) {
|
|
|
8569
9307
|
process.stderr.write(`caveman: openclaw provider "${ref.provider}" has no API adapter; leaving primary model unchanged\n`);
|
|
8570
9308
|
return overlay;
|
|
8571
9309
|
}
|
|
8572
|
-
const
|
|
9310
|
+
const originalBaseUrl = getString(provider, ["baseUrl"]) ?? getString(OPENCLAW_WELL_KNOWN_PROVIDERS[ref.provider], ["baseUrl"]);
|
|
9311
|
+
// A fresh managed setup has no original provider endpoint to preserve. An
|
|
9312
|
+
// existing setup needs the actual listener's routing map, unavailable from a
|
|
9313
|
+
// managed gateway. Preserve it until that endpoint proof exists.
|
|
9314
|
+
const baseUrl = synthesized && ctx.mode === "managed"
|
|
9315
|
+
? openClawProxyBaseUrl(api, ctx.gatewayUrl)
|
|
9316
|
+
: ctx.mode === "local" ? verifiedProviderRoute(ctx.gatewayUrl, api, ref.provider, openClawEffectiveBaseUrl(api, originalBaseUrl), ctx.upstreams) : undefined;
|
|
8573
9317
|
if (!baseUrl) {
|
|
8574
|
-
process.stderr.write(`caveman: openclaw provider
|
|
9318
|
+
process.stderr.write(`caveman: openclaw provider "${ref.provider}" endpoint is not verified by the running proxy; leaving primary model unchanged\n`);
|
|
8575
9319
|
return overlay;
|
|
8576
9320
|
}
|
|
9321
|
+
if (ctx.mode === "local") {
|
|
9322
|
+
// baseUrl is provider-wide in OpenClaw. A fallback or later model switch
|
|
9323
|
+
// must retain its own API, and every model sharing this override must map
|
|
9324
|
+
// to the same verified SDK base URL.
|
|
9325
|
+
const catalog = Array.isArray(provider.models) ? provider.models : [];
|
|
9326
|
+
const providerApi = openClawProviderApi(ref.provider, provider);
|
|
9327
|
+
const modelApis = [providerApi, ...catalog.map(model => openClawProviderApi(ref.provider, provider, asJsonObject(model)))].filter((value) => value !== undefined);
|
|
9328
|
+
if (modelApis.some(modelApi => verifiedProviderRoute(ctx.gatewayUrl, modelApi, ref.provider, openClawEffectiveBaseUrl(modelApi, originalBaseUrl), ctx.upstreams) !== baseUrl)) {
|
|
9329
|
+
process.stderr.write(`caveman: openclaw provider "${ref.provider}" uses model APIs with different routes; leaving provider unchanged\n`);
|
|
9330
|
+
return overlay;
|
|
9331
|
+
}
|
|
9332
|
+
const request = asJsonObject(provider.request);
|
|
9333
|
+
const requestIssue = openClawRequestCompatibilityIssue(provider.request);
|
|
9334
|
+
if (requestIssue) {
|
|
9335
|
+
process.stderr.write(`caveman: openclaw provider "${ref.provider}" stays direct because ${requestIssue}; proxy compression is off for this provider\n`);
|
|
9336
|
+
return overlay;
|
|
9337
|
+
}
|
|
9338
|
+
const headerRequirements = [{ api: providerApi ?? api, headers: { ...asJsonObject(provider.headers), ...asJsonObject(request?.headers) } }, ...catalog.map(model => ({
|
|
9339
|
+
api: openClawProviderApi(ref.provider, provider, asJsonObject(model)),
|
|
9340
|
+
headers: { ...asJsonObject(provider.headers), ...asJsonObject(asJsonObject(model)?.headers), ...asJsonObject(request?.headers) },
|
|
9341
|
+
}))];
|
|
9342
|
+
const missingHeaders = uniqueStrings(headerRequirements.flatMap(requirement => unforwardedProviderHeaders(requirement.api, ref.provider, requirement.headers, ctx.upstreams)));
|
|
9343
|
+
if (missingHeaders.length) {
|
|
9344
|
+
const remedy = missingHeaders.some(name => ["authorization", "x-api-key", "x-goog-api-key"].includes(name.toLowerCase()))
|
|
9345
|
+
? "the proxy cannot preserve this authentication override; keep the provider direct"
|
|
9346
|
+
: `configure compat.${ref.provider}.forward_headers or keep the provider direct`;
|
|
9347
|
+
process.stderr.write(`caveman: openclaw provider "${ref.provider}" requires headers not preserved by the running proxy (${missingHeaders.join(", ")}); ${remedy}\n`);
|
|
9348
|
+
return overlay;
|
|
9349
|
+
}
|
|
9350
|
+
const routedModels = [];
|
|
9351
|
+
for (const rawModel of catalog.length ? catalog : [openClawMirroredModel(ref, provider, providerModel)]) {
|
|
9352
|
+
const model = asJsonObject(rawModel);
|
|
9353
|
+
const modelApi = openClawProviderApi(ref.provider, provider, model);
|
|
9354
|
+
if (!model || typeof model.id !== "string" || !modelApi || !originalBaseUrl) {
|
|
9355
|
+
process.stderr.write(`caveman: openclaw provider "${ref.provider}" has an unresolved model catalog; leaving provider unchanged\n`);
|
|
9356
|
+
return overlay;
|
|
9357
|
+
}
|
|
9358
|
+
const preserved = preserveOpenClawProviderCompat({ provider: ref.provider, id: model.id, api: modelApi, baseUrl: originalBaseUrl, compat: model.compat });
|
|
9359
|
+
if (!preserved.ok) {
|
|
9360
|
+
process.stderr.write(`caveman: openclaw provider "${ref.provider}" stays direct because ${preserved.reason}; proxy compression is off for this provider\n`);
|
|
9361
|
+
return overlay;
|
|
9362
|
+
}
|
|
9363
|
+
routedModels.push({ ...model, ...(preserved.compat ? { compat: preserved.compat } : {}) });
|
|
9364
|
+
}
|
|
9365
|
+
const headers = { ...asJsonObject(provider.headers), [OPENCLAW_AGENT_HEADER]: "openclaw" };
|
|
9366
|
+
const workflowSlug = normalizeWorkflowSlug(process.env["CAVE_WORKFLOW"]);
|
|
9367
|
+
if (workflowSlug)
|
|
9368
|
+
headers["x-cave-workflow"] = workflowSlug;
|
|
9369
|
+
const routedProvider = { ...provider, baseUrl, ...(providerApi ? { api: providerApi } : {}), headers,
|
|
9370
|
+
models: routedModels };
|
|
9371
|
+
return deepMerge(overlay, {
|
|
9372
|
+
models: { mode: "merge", providers: { [ref.provider]: routedProvider } },
|
|
9373
|
+
...(synthesized ? { agents: { defaults: { model: { primary: ref.raw } } } } : {}),
|
|
9374
|
+
});
|
|
9375
|
+
}
|
|
9376
|
+
if (synthesized)
|
|
9377
|
+
process.stderr.write(`caveman: openclaw primary model not found; routing fresh config through caveman/${ref.model}\n`);
|
|
8577
9378
|
const sourceApiKey = openClawResolvedProviderApiKey(ref.provider, provider);
|
|
8578
9379
|
const headers = { [OPENCLAW_AGENT_HEADER]: "openclaw" };
|
|
8579
9380
|
const workflowSlug = normalizeWorkflowSlug(process.env["CAVE_WORKFLOW"]);
|
|
@@ -8630,7 +9431,7 @@ function withoutCavemanMcpServer(overlay) {
|
|
|
8630
9431
|
delete next["mcp"];
|
|
8631
9432
|
return next;
|
|
8632
9433
|
}
|
|
8633
|
-
function applyConfigFileInjection(env, agent, inj, gw, modeGw = gw, mcpMode = "auto", agentArgs = []) {
|
|
9434
|
+
function applyConfigFileInjection(env, agent, inj, gw, modeGw = gw, mcpMode = "auto", agentArgs = [], upstreams) {
|
|
8634
9435
|
const baseConfig = readBaseConfig(inj);
|
|
8635
9436
|
const mode = wrapMode(modeGw);
|
|
8636
9437
|
const staticOverlay = mode === "managed" && inj.config_overlay.managed !== undefined ? inj.config_overlay.managed : inj.config_overlay.local;
|
|
@@ -8642,7 +9443,7 @@ function applyConfigFileInjection(env, agent, inj, gw, modeGw = gw, mcpMode = "a
|
|
|
8642
9443
|
throw new Error("cannot safely resolve Qwen's effective OPENAI_API_KEY");
|
|
8643
9444
|
renderOptions.optionalOpenAIKeyEnvAvailable = available;
|
|
8644
9445
|
}
|
|
8645
|
-
let rawOverlay = renderDeep(builder ? builder(agent, baseConfig, { mode, gatewayUrl: gw, env }) : staticOverlay, gw, env, renderOptions);
|
|
9446
|
+
let rawOverlay = renderDeep(builder ? builder(agent, baseConfig, { mode, gatewayUrl: gw, env, upstreams }) : staticOverlay, gw, env, renderOptions);
|
|
8646
9447
|
if (agent.id === "qwen" && mcpMode === "auto") {
|
|
8647
9448
|
const ownedMcp = ownedMcpRegistration(agent.id, agentArgs);
|
|
8648
9449
|
if (ownedMcp) {
|
|
@@ -8700,10 +9501,46 @@ function cleanupWrapTempDirs() {
|
|
|
8700
9501
|
}
|
|
8701
9502
|
}
|
|
8702
9503
|
const WRAP_BASE_URL_ENV_VARS = ["ANTHROPIC_BASE_URL", "OPENAI_BASE_URL", "OPENAI_API_BASE", "GOOGLE_GEMINI_BASE_URL"];
|
|
9504
|
+
// A corporate HTTP(S)_PROXY in the operator's shell applies to the wrapped agent
|
|
9505
|
+
// too, so the agent's own hop to caveman's loopback listener gets handed to that
|
|
9506
|
+
// proxy and times out — #1001's symptom, one layer above the proxy's own
|
|
9507
|
+
// upstream_proxy support. Exempt exactly the gateway host, appending to whatever
|
|
9508
|
+
// NO_PROXY the operator already set and using the spelling they already use.
|
|
9509
|
+
// resolveProxyUrl returns null both when no proxy applies and when NO_PROXY
|
|
9510
|
+
// already covers the gateway, which are precisely the cases needing no change.
|
|
9511
|
+
function gatewayNoProxyEnv(gw, env = process.env) {
|
|
9512
|
+
let target;
|
|
9513
|
+
try {
|
|
9514
|
+
target = new URL(gw);
|
|
9515
|
+
}
|
|
9516
|
+
catch {
|
|
9517
|
+
return {};
|
|
9518
|
+
}
|
|
9519
|
+
// Only a loopback listener needs the exemption. A managed gateway is a public
|
|
9520
|
+
// host that the operator's proxy is supposed to carry; exempting it there
|
|
9521
|
+
// sends the agent straight at a firewall that drops direct egress.
|
|
9522
|
+
if (wrapMode(gw) !== "local")
|
|
9523
|
+
return {};
|
|
9524
|
+
if (!resolveProxyUrl(target, env))
|
|
9525
|
+
return {};
|
|
9526
|
+
// Append to each spelling the operator actually set, reading the value from
|
|
9527
|
+
// the same variable it is written back to. Choosing the name by definedness
|
|
9528
|
+
// and the value with ?? dropped the other spelling's entries.
|
|
9529
|
+
const names = env.NO_PROXY === undefined && env.no_proxy !== undefined ? ["no_proxy"] : ["NO_PROXY"];
|
|
9530
|
+
if (env.NO_PROXY !== undefined && env.no_proxy !== undefined)
|
|
9531
|
+
names.push("no_proxy");
|
|
9532
|
+
const out = {};
|
|
9533
|
+
for (const name of names) {
|
|
9534
|
+
const current = (env[name] ?? "").trim();
|
|
9535
|
+
out[name] = current ? `${current},${target.hostname}` : target.hostname;
|
|
9536
|
+
}
|
|
9537
|
+
return out;
|
|
9538
|
+
}
|
|
8703
9539
|
function wrapBaseUrlEnv(gw) {
|
|
8704
9540
|
const env = {};
|
|
8705
9541
|
for (const key of WRAP_BASE_URL_ENV_VARS)
|
|
8706
9542
|
env[key] = gw;
|
|
9543
|
+
Object.assign(env, gatewayNoProxyEnv(gw));
|
|
8707
9544
|
// Same reason as the native-enable path: redirecting ANTHROPIC_BASE_URL makes
|
|
8708
9545
|
// Claude Code drop tool search and inline every MCP tool schema. Inert for the
|
|
8709
9546
|
// other wrappable agents, which never read this variable. A value already in
|
|
@@ -8712,6 +9549,70 @@ function wrapBaseUrlEnv(gw) {
|
|
|
8712
9549
|
env.ENABLE_TOOL_SEARCH = TOOL_SEARCH_DEFAULT;
|
|
8713
9550
|
return env;
|
|
8714
9551
|
}
|
|
9552
|
+
// wrapWorkTags names the repository and branch a wrapped session is launched
|
|
9553
|
+
// in, as the managed gateway's x-cave-tags value ("repo=owner/name,branch=…").
|
|
9554
|
+
// Delivery joins coding-agent spend to merged changes on exactly these two
|
|
9555
|
+
// keys, and nothing else in the request carries them. Read once at spawn with
|
|
9556
|
+
// hardened git (git-safe.ts); a launch outside a repository, without an origin,
|
|
9557
|
+
// or on a detached HEAD yields the tags it can and never fails the wrap.
|
|
9558
|
+
// The value is fixed for the process: a branch switch mid-session is picked up
|
|
9559
|
+
// by the next launch, not this one.
|
|
9560
|
+
//
|
|
9561
|
+
// Only github.com remotes are tagged: Cloud joins tags['repo'] to the GitHub
|
|
9562
|
+
// pull requests it imported, keyed owner/name, so a same-named fork on another
|
|
9563
|
+
// host would collide with the wrong repository. Values are printable ASCII
|
|
9564
|
+
// without comma or equals — a header value must be a ByteString, and the tag
|
|
9565
|
+
// list is comma/equals delimited — anything else drops the tag, never the wrap.
|
|
9566
|
+
export function wrapWorkTags(cwd = process.cwd()) {
|
|
9567
|
+
const read = (...args) => {
|
|
9568
|
+
try {
|
|
9569
|
+
return execFileSync("git", hardenedGitArgs(cwd, ...args), {
|
|
9570
|
+
encoding: "utf8", env: hardenedGitEnv(), stdio: ["ignore", "pipe", "ignore"], timeout: 2000,
|
|
9571
|
+
}).trim();
|
|
9572
|
+
}
|
|
9573
|
+
catch {
|
|
9574
|
+
return "";
|
|
9575
|
+
}
|
|
9576
|
+
};
|
|
9577
|
+
const parts = [];
|
|
9578
|
+
const repo = repoSlugFromRemote(read("remote", "get-url", "origin"));
|
|
9579
|
+
if (repo)
|
|
9580
|
+
parts.push(`repo=${repo}`);
|
|
9581
|
+
const branch = read("branch", "--show-current");
|
|
9582
|
+
if (branch && branch.length <= 255 && workTagValueSafe(branch))
|
|
9583
|
+
parts.push(`branch=${branch}`);
|
|
9584
|
+
return parts.join(",");
|
|
9585
|
+
}
|
|
9586
|
+
// workTagValueSafe: printable ASCII (0x21–0x7E) with no comma or equals.
|
|
9587
|
+
export function workTagValueSafe(value) {
|
|
9588
|
+
return /^[\x21-\x2B\x2D-\x3C\x3E-\x7E]+$/.test(value);
|
|
9589
|
+
}
|
|
9590
|
+
// repoSlugFromRemote reduces a github.com remote URL to owner/name — the form
|
|
9591
|
+
// Cloud's Delivery join and its imported pull requests use — or "" when the
|
|
9592
|
+
// remote is on any other host or has no such shape. Never the URL itself: a
|
|
9593
|
+
// remote can embed a credential.
|
|
9594
|
+
export function repoSlugFromRemote(remote) {
|
|
9595
|
+
const cleaned = trimTrailingSlashes(remote.trim()).replace(/\.git$/i, "");
|
|
9596
|
+
let host = "";
|
|
9597
|
+
let path = "";
|
|
9598
|
+
const url = /^[a-z][a-z0-9+.-]*:\/\/([^/]+)\/(.*)$/i.exec(cleaned);
|
|
9599
|
+
const scp = /^(?:[^@/:]+@)?([^/:]+):(.*)$/.exec(cleaned);
|
|
9600
|
+
if (url) {
|
|
9601
|
+
host = url[1].replace(/^[^@]*@/, "").replace(/:\d+$/, "");
|
|
9602
|
+
path = url[2];
|
|
9603
|
+
}
|
|
9604
|
+
else if (scp) {
|
|
9605
|
+
host = scp[1];
|
|
9606
|
+
path = scp[2];
|
|
9607
|
+
}
|
|
9608
|
+
else {
|
|
9609
|
+
return "";
|
|
9610
|
+
}
|
|
9611
|
+
if (host.toLowerCase() !== "github.com")
|
|
9612
|
+
return "";
|
|
9613
|
+
const match = /^([A-Za-z0-9._-]+)\/([A-Za-z0-9._-]+)$/.exec(path);
|
|
9614
|
+
return match ? `${match[1]}/${match[2]}` : "";
|
|
9615
|
+
}
|
|
8715
9616
|
function attributedGatewayUrl(gw, agent) {
|
|
8716
9617
|
return appendUrlPath(gw, `/w/${agent.id}`);
|
|
8717
9618
|
}
|
|
@@ -8733,6 +9634,22 @@ function mergeAnthropicCustomHeader(raw, name, value) {
|
|
|
8733
9634
|
kept.push(`${name}: ${value}`);
|
|
8734
9635
|
return kept.join("\n");
|
|
8735
9636
|
}
|
|
9637
|
+
// existingCustomHeader returns the value of one header inside the newline-
|
|
9638
|
+
// separated ANTHROPIC_CUSTOM_HEADERS block ("" when present but empty), or
|
|
9639
|
+
// undefined when absent.
|
|
9640
|
+
function existingCustomHeader(raw, name) {
|
|
9641
|
+
const target = name.toLowerCase();
|
|
9642
|
+
for (const line of (raw ?? "").split(/\r\n|\n|\r/)) {
|
|
9643
|
+
const colon = line.indexOf(":");
|
|
9644
|
+
if (colon > 0 && line.slice(0, colon).trim().toLowerCase() === target)
|
|
9645
|
+
return line.slice(colon + 1).trim();
|
|
9646
|
+
}
|
|
9647
|
+
return undefined;
|
|
9648
|
+
}
|
|
9649
|
+
// workTagsOff: CAVEMAN_WORK_TAGS=0 (or false/off/no) stops the repo/branch tags.
|
|
9650
|
+
export function workTagsOff(value) {
|
|
9651
|
+
return /^(0|false|off|no)$/i.test((value ?? "").trim());
|
|
9652
|
+
}
|
|
8736
9653
|
function bedrockCredentialEnvValue(env, name) {
|
|
8737
9654
|
const raw = env[name];
|
|
8738
9655
|
if (typeof raw !== "string" || !raw.trim())
|
|
@@ -8821,7 +9738,7 @@ function applyClaudeBedrockWrap(env, agent, renderedGw, modeGw) {
|
|
|
8821
9738
|
// one production caller passes the SAME opts.mcpMode that wrapMcpRecoveryAvailable
|
|
8822
9739
|
// reads, which is what keeps "what we inject" and "what we tell the proxy" from
|
|
8823
9740
|
// ever disagreeing.
|
|
8824
|
-
export function buildWrapEnv(agent, gw = gatewayURL(), mcpMode = "auto", agentArgs = []) {
|
|
9741
|
+
export function buildWrapEnv(agent, gw = gatewayURL(), mcpMode = "auto", agentArgs = [], upstreams) {
|
|
8825
9742
|
if (agent?.id === "gemini" && wrapMode(gw) === "managed") {
|
|
8826
9743
|
throw new Error("managed Gemini CLI routing is unsupported because Gemini CLI cannot send separate Caveman and upstream credentials");
|
|
8827
9744
|
}
|
|
@@ -8880,11 +9797,27 @@ export function buildWrapEnv(agent, gw = gatewayURL(), mcpMode = "auto", agentAr
|
|
|
8880
9797
|
rendered = deepMerge(rendered, { mcp: { caveman: kiloMcpEntry(ownedMcp) } });
|
|
8881
9798
|
}
|
|
8882
9799
|
}
|
|
9800
|
+
if (agent.id === "opencode" && process.env[inj.env_var]) {
|
|
9801
|
+
// OpenCode treats inline JSONC as its own configuration layer. Replacing
|
|
9802
|
+
// that layer loses the user's model, account, permissions and MCP servers.
|
|
9803
|
+
// Preserve native {env:...}/{file:...} references for OpenCode to resolve
|
|
9804
|
+
// in the same context; only our routing fields take precedence.
|
|
9805
|
+
let original;
|
|
9806
|
+
try {
|
|
9807
|
+
original = parseJsonc(process.env[inj.env_var]);
|
|
9808
|
+
}
|
|
9809
|
+
catch {
|
|
9810
|
+
throw new Error("cannot preserve opencode inline configuration; launching with the original configuration is required");
|
|
9811
|
+
}
|
|
9812
|
+
if (!isPlainObject(original))
|
|
9813
|
+
throw new Error("opencode inline configuration must be a JSON object");
|
|
9814
|
+
rendered = deepMerge(original, rendered);
|
|
9815
|
+
}
|
|
8883
9816
|
env[inj.env_var] = JSON.stringify(rendered);
|
|
8884
9817
|
}
|
|
8885
9818
|
else if (inj.method === "config-file") {
|
|
8886
9819
|
try {
|
|
8887
|
-
applyConfigFileInjection(env, agent, inj, renderedGw, gw, mcpMode, agentArgs);
|
|
9820
|
+
applyConfigFileInjection(env, agent, inj, renderedGw, gw, mcpMode, agentArgs, upstreams);
|
|
8888
9821
|
}
|
|
8889
9822
|
catch (e) {
|
|
8890
9823
|
// OpenClaw ignores the generic base-URL union. Config injection is its only
|
|
@@ -8905,6 +9838,16 @@ export function buildWrapEnv(agent, gw = gatewayURL(), mcpMode = "auto", agentAr
|
|
|
8905
9838
|
}
|
|
8906
9839
|
if (agent.id === "hermes")
|
|
8907
9840
|
applyHermesAuthEnv(env, renderedGw, gw);
|
|
9841
|
+
if (agent.id === "claude" && wrapMode(gw) === "managed") {
|
|
9842
|
+
// Repository and branch ride every request as x-cave-tags so the managed
|
|
9843
|
+
// gateway can join this session's spend to the change it ships. A user's
|
|
9844
|
+
// own x-cave-tags is sent exactly as set (even empty), and CAVEMAN_WORK_TAGS=0 sends none.
|
|
9845
|
+
const tags = workTagsOff(env.CAVEMAN_WORK_TAGS) || existingCustomHeader(env.ANTHROPIC_CUSTOM_HEADERS, "x-cave-tags") !== undefined
|
|
9846
|
+
? ""
|
|
9847
|
+
: wrapWorkTags();
|
|
9848
|
+
if (tags)
|
|
9849
|
+
env.ANTHROPIC_CUSTOM_HEADERS = mergeAnthropicCustomHeader(env.ANTHROPIC_CUSTOM_HEADERS, "x-cave-tags", tags);
|
|
9850
|
+
}
|
|
8908
9851
|
if (agent.id === "claude" && wrapMode(gw) === "local" && env[CLAUDE_ASSUME_FIRST_PARTY_ENV] === undefined && proxyAnthropicUpstreamIsFirstParty()) {
|
|
8909
9852
|
// Keep Claude Code's first-party capability set (1M context window /
|
|
8910
9853
|
// ~600k auto-compact window) intact behind the local pass-through proxy
|
|
@@ -9039,28 +9982,59 @@ export function shouldOpenLoginBrowser(noBrowser, interactive = Boolean(process.
|
|
|
9039
9982
|
}
|
|
9040
9983
|
function validateLoginArgs(argv) {
|
|
9041
9984
|
let noBrowser = false;
|
|
9985
|
+
const values = new Map();
|
|
9986
|
+
const usage = "login [--no-browser] [--instance <https-origin> | --base-url <url> [--gateway-url <url>]]";
|
|
9042
9987
|
for (let index = 0; index < argv.length; index++) {
|
|
9043
9988
|
const arg = argv[index];
|
|
9044
9989
|
if (arg === "--no-browser") {
|
|
9045
9990
|
if (noBrowser)
|
|
9046
|
-
commandUsage(
|
|
9991
|
+
commandUsage(usage);
|
|
9047
9992
|
noBrowser = true;
|
|
9048
9993
|
continue;
|
|
9049
9994
|
}
|
|
9050
|
-
|
|
9051
|
-
|
|
9052
|
-
|
|
9053
|
-
|
|
9995
|
+
const flag = arg.split("=", 1)[0];
|
|
9996
|
+
if (["--instance", "--base-url", "--gateway-url"].includes(flag)) {
|
|
9997
|
+
const value = arg.includes("=") ? arg.slice(arg.indexOf("=") + 1) : argv[++index];
|
|
9998
|
+
if (!value || value.startsWith("-") || values.has(flag))
|
|
9999
|
+
commandUsage(usage);
|
|
10000
|
+
values.set(flag, value);
|
|
9054
10001
|
continue;
|
|
9055
10002
|
}
|
|
9056
|
-
|
|
9057
|
-
|
|
9058
|
-
|
|
9059
|
-
|
|
9060
|
-
}
|
|
9061
|
-
|
|
10003
|
+
commandUsage(usage);
|
|
10004
|
+
}
|
|
10005
|
+
const instance = values.get("--instance");
|
|
10006
|
+
if (instance === undefined)
|
|
10007
|
+
return { noBrowser };
|
|
10008
|
+
if (values.has("--base-url") || values.has("--gateway-url"))
|
|
10009
|
+
commandUsage(usage);
|
|
10010
|
+
const url = new URL(instance);
|
|
10011
|
+
if (!secureLoginURL(url) || url.pathname !== "/" || url.search || url.hash || url.hostname.replace(/\.$/, "") === new URL(PROD_API_URL).hostname) {
|
|
10012
|
+
throw new Error("--instance requires a private HTTPS origin (HTTP loopback is allowed for local development)");
|
|
10013
|
+
}
|
|
10014
|
+
return { noBrowser, instance: url.origin };
|
|
10015
|
+
}
|
|
10016
|
+
function secureLoginURL(url, allowLoopback = true) {
|
|
10017
|
+
return !url.username && !url.password && (url.protocol === "https:" ||
|
|
10018
|
+
(allowLoopback && url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)));
|
|
10019
|
+
}
|
|
10020
|
+
function privateVerificationURL(code, instance) {
|
|
10021
|
+
if (typeof code.device_code !== "string" || !code.device_code || code.device_code.length > 4096 ||
|
|
10022
|
+
typeof code.user_code !== "string" || !/^[A-HJ-NP-Z2-9]{4}-[A-HJ-NP-Z2-9]{4}$/.test(code.user_code) ||
|
|
10023
|
+
typeof code.expires_in !== "number" || !Number.isFinite(code.expires_in) || code.expires_in <= 0 || code.expires_in > 3600 ||
|
|
10024
|
+
(code.interval !== undefined && (typeof code.interval !== "number" || !Number.isFinite(code.interval) || code.interval < 0 || code.interval > 60))) {
|
|
10025
|
+
throw new Error("private device authorization returned an invalid code response");
|
|
10026
|
+
}
|
|
10027
|
+
const value = code.verification_uri_complete ?? code.verification_uri;
|
|
10028
|
+
if (typeof value !== "string")
|
|
10029
|
+
throw new Error("private device authorization omitted its browser URL");
|
|
10030
|
+
const url = new URL(value);
|
|
10031
|
+
if (!secureLoginURL(url, new URL(instance).protocol === "http:") || url.hash) {
|
|
10032
|
+
throw new Error("private device authorization returned an unsafe browser URL");
|
|
9062
10033
|
}
|
|
9063
|
-
|
|
10034
|
+
url.searchParams.set("user_code", code.user_code);
|
|
10035
|
+
url.searchParams.set("connection", "mcp");
|
|
10036
|
+
url.searchParams.set("client_name", "Caveman CLI");
|
|
10037
|
+
return url.href;
|
|
9064
10038
|
}
|
|
9065
10039
|
function openLoginBrowser(url) {
|
|
9066
10040
|
const opener = loginBrowserOpener(url);
|
|
@@ -9083,6 +10057,7 @@ async function acknowledgeDeviceGrant(baseURL, accessToken, deviceCode, ackToken
|
|
|
9083
10057
|
try {
|
|
9084
10058
|
const response = await fetch(`${baseURL}/api/v1/auth/device/ack`, {
|
|
9085
10059
|
method: "POST",
|
|
10060
|
+
redirect: "manual",
|
|
9086
10061
|
headers: {
|
|
9087
10062
|
authorization: `Bearer ${accessToken}`,
|
|
9088
10063
|
"content-type": "application/json",
|
|
@@ -9111,17 +10086,18 @@ async function acknowledgeDeviceGrant(baseURL, accessToken, deviceCode, ackToken
|
|
|
9111
10086
|
}
|
|
9112
10087
|
// 0600 credentials file) — never in plaintext config. organization_id is bound
|
|
9113
10088
|
// from the returned token, never from any local input.
|
|
9114
|
-
//
|
|
9115
|
-
// runs before argument parsing, network requests, browser launch, or local writes.
|
|
10089
|
+
// Hosted login remains gated; explicit private instances use project access.
|
|
9116
10090
|
function blockCloudLoginWhileBeta() {
|
|
9117
10091
|
throw new Error("Caveman Cloud platform is still in beta.");
|
|
9118
10092
|
}
|
|
9119
10093
|
async function login(argv = []) {
|
|
9120
|
-
|
|
9121
|
-
|
|
9122
|
-
const
|
|
10094
|
+
if (!argv.some((arg) => arg === "--instance" || arg.startsWith("--instance=")))
|
|
10095
|
+
blockCloudLoginWhileBeta();
|
|
10096
|
+
const { noBrowser, instance } = validateLoginArgs(argv);
|
|
10097
|
+
const baseURL = instance ?? resolveLoginBaseUrl(argv);
|
|
9123
10098
|
const codeResp = await fetch(`${baseURL}/api/v1/auth/device/code`, {
|
|
9124
10099
|
method: "POST",
|
|
10100
|
+
redirect: "error",
|
|
9125
10101
|
headers: { "content-type": "application/json" },
|
|
9126
10102
|
body: "{}",
|
|
9127
10103
|
signal: AbortSignal.timeout(5000),
|
|
@@ -9130,8 +10106,8 @@ async function login(argv = []) {
|
|
|
9130
10106
|
throw new Error(`device authorization failed: HTTP ${codeResp.status}`);
|
|
9131
10107
|
const code = await codeResp.json();
|
|
9132
10108
|
if (!code.device_code)
|
|
9133
|
-
throw new Error(
|
|
9134
|
-
const verificationURL = code.verification_uri_complete ?? code.verification_uri;
|
|
10109
|
+
throw new Error("device authorization failed: missing device code");
|
|
10110
|
+
const verificationURL = instance ? privateVerificationURL(code, instance) : code.verification_uri_complete ?? code.verification_uri;
|
|
9135
10111
|
console.error(`\n Authorize this device in your browser:`);
|
|
9136
10112
|
console.error(` ${verificationURL}`);
|
|
9137
10113
|
console.error(` code: ${code.user_code}\n`);
|
|
@@ -9146,6 +10122,7 @@ async function login(argv = []) {
|
|
|
9146
10122
|
try {
|
|
9147
10123
|
const tokResp = await fetch(`${baseURL}/api/v1/auth/device/token`, {
|
|
9148
10124
|
method: "POST",
|
|
10125
|
+
redirect: "manual",
|
|
9149
10126
|
headers: { "content-type": "application/json" },
|
|
9150
10127
|
body: JSON.stringify({ device_code: code.device_code }),
|
|
9151
10128
|
signal: AbortSignal.timeout(5000),
|
|
@@ -9157,7 +10134,7 @@ async function login(argv = []) {
|
|
|
9157
10134
|
if (Number.isFinite(seconds) && seconds >= 0)
|
|
9158
10135
|
retryAfterMs = seconds * 1000;
|
|
9159
10136
|
}
|
|
9160
|
-
tok = await tokResp.json();
|
|
10137
|
+
tok = tokenStatus >= 300 && tokenStatus < 400 ? {} : await tokResp.json();
|
|
9161
10138
|
}
|
|
9162
10139
|
catch (error) {
|
|
9163
10140
|
// RFC 8628 polling is retryable: a dropped connection or malformed
|
|
@@ -9170,6 +10147,8 @@ async function login(argv = []) {
|
|
|
9170
10147
|
await sleep(Math.max(intervalMs, retryAfterMs, 200));
|
|
9171
10148
|
continue;
|
|
9172
10149
|
}
|
|
10150
|
+
if (tokenStatus >= 300 && tokenStatus < 400)
|
|
10151
|
+
throw new Error("device login refused a redirected token endpoint");
|
|
9173
10152
|
if (tokenStatus === 429) {
|
|
9174
10153
|
// rateLimitAuth returns a nested cave error envelope rather than the RFC
|
|
9175
10154
|
// `error` string. Status is the authoritative retry signal here.
|
|
@@ -9178,6 +10157,13 @@ async function login(argv = []) {
|
|
|
9178
10157
|
}
|
|
9179
10158
|
const accessToken = typeof tok.access_token === "string" ? tok.access_token : "";
|
|
9180
10159
|
if (accessToken) {
|
|
10160
|
+
if (instance && (tokenStatus < 200 || tokenStatus >= 300 || tok.credential_kind !== "none" ||
|
|
10161
|
+
["gateway_api_key", "gateway_key_id", "gateway_url"].some((key) => tok[key] != null) ||
|
|
10162
|
+
typeof tok.refresh_token !== "string" || !tok.refresh_token || typeof tok.project_id !== "string" || !tok.project_id ||
|
|
10163
|
+
typeof tok.delivery_ack_token !== "string" || !tok.delivery_ack_token || typeof tok.scope !== "string" || !tok.scope ||
|
|
10164
|
+
tok.scope.split(/\s+/).some((scope) => scope === "proxy:write" || scope === "sdk:write"))) {
|
|
10165
|
+
throw new Error("private device login requires a keyless project grant with a refresh token and delivery acknowledgement");
|
|
10166
|
+
}
|
|
9181
10167
|
const credentials = {
|
|
9182
10168
|
access_token: accessToken,
|
|
9183
10169
|
...(typeof tok.refresh_token === "string" && tok.refresh_token ? { refresh_token: tok.refresh_token } : {}),
|
|
@@ -9187,7 +10173,7 @@ async function login(argv = []) {
|
|
|
9187
10173
|
};
|
|
9188
10174
|
const tokenStore = storeCredentials(credentials);
|
|
9189
10175
|
const organizationId = orgFromToken(accessToken);
|
|
9190
|
-
const gateway = resolveLoginGatewayUrl(baseURL, tok, code, argv);
|
|
10176
|
+
const gateway = instance ? "" : resolveLoginGatewayUrl(baseURL, tok, code, argv);
|
|
9191
10177
|
const saved = { baseURL, token: "", tokenStore };
|
|
9192
10178
|
if (organizationId)
|
|
9193
10179
|
saved.organizationId = organizationId;
|
|
@@ -9209,6 +10195,10 @@ async function login(argv = []) {
|
|
|
9209
10195
|
// until the control plane has recorded that this CLI stored the bundle.
|
|
9210
10196
|
await acknowledgeDeviceGrant(baseURL, credentials.access_token, code.device_code, ackToken);
|
|
9211
10197
|
}
|
|
10198
|
+
if (instance) {
|
|
10199
|
+
print({ authenticated: true, baseURL, organization_id: organizationId ?? null, project_id: credentials.project_id, scope: tok.scope, credential_kind: "none", token_store: tokenStore });
|
|
10200
|
+
return;
|
|
10201
|
+
}
|
|
9212
10202
|
// Mint/refresh the local-wrap entitlement for this device. Best
|
|
9213
10203
|
// effort: login never fails for seats or a down entitlement service.
|
|
9214
10204
|
await fetchAndStoreWrapEntitlement(baseURL, credentials.access_token);
|
|
@@ -9266,6 +10256,7 @@ async function logout() {
|
|
|
9266
10256
|
};
|
|
9267
10257
|
const request = {
|
|
9268
10258
|
method: "POST",
|
|
10259
|
+
redirect: "manual",
|
|
9269
10260
|
headers,
|
|
9270
10261
|
signal: AbortSignal.timeout(5000),
|
|
9271
10262
|
};
|
|
@@ -9603,7 +10594,7 @@ function localScanSyncLine(out) {
|
|
|
9603
10594
|
return `synced 30-day local scan · inferred token summary · separate from gateway spend and verified savings${destination}`;
|
|
9604
10595
|
}
|
|
9605
10596
|
// syncRequestSpan converts one local `requests` row into a caveman-jsonl span
|
|
9606
|
-
// line (public/shared/platform/importers Span shape; timestamps are already in
|
|
10597
|
+
// line (Caveman-Cloud public/shared/platform/importers Span shape; timestamps are already in
|
|
9607
10598
|
// the ClickHouse layout because the proxy writes them that way). The basis and
|
|
9608
10599
|
// per-row inferred savings ride in attributes — the spans schema has no savings
|
|
9609
10600
|
// column, and imported rows must never look like verified ledger entries.
|
|
@@ -10176,8 +11167,16 @@ const HERMES_MCP_END = "# <<< caveman:mcp";
|
|
|
10176
11167
|
const HERMES_PLUGIN_ENABLE_BEGIN = "# >>> caveman:hermes-plugin-enable";
|
|
10177
11168
|
const HERMES_PLUGIN_ENABLE_END = "# <<< caveman:hermes-plugin-enable";
|
|
10178
11169
|
const HERMES_PLUGIN_NAME = "caveman_shrink";
|
|
10179
|
-
function hermesHome() {
|
|
10180
|
-
|
|
11170
|
+
export function hermesHome(env = process.env, platform = process.platform) {
|
|
11171
|
+
// Hermes 0.19.1 hermes_constants.py: native Windows uses LOCALAPPDATA,
|
|
11172
|
+
// overrides are stripped, and Path(value) does not expand a literal tilde.
|
|
11173
|
+
const override = env.HERMES_HOME?.trim();
|
|
11174
|
+
if (override)
|
|
11175
|
+
return resolve(override);
|
|
11176
|
+
if (platform === "win32") {
|
|
11177
|
+
return join(env.LOCALAPPDATA?.trim() || join(homedir(), "AppData", "Local"), "hermes");
|
|
11178
|
+
}
|
|
11179
|
+
return join(homedir(), ".hermes");
|
|
10181
11180
|
}
|
|
10182
11181
|
function hermesConfigPath() {
|
|
10183
11182
|
return join(hermesHome(), "config.yaml");
|
|
@@ -10400,7 +11399,7 @@ function uninstallMcpForAgent(a, serverName = "caveman") {
|
|
|
10400
11399
|
case "qwen":
|
|
10401
11400
|
throw new Error(`${a.display_name} MCP changes require the ownership transaction`);
|
|
10402
11401
|
case "gemini":
|
|
10403
|
-
return removeMcpJson(
|
|
11402
|
+
return removeMcpJson(geminiSettingsPath(), ["mcpServers", serverName]);
|
|
10404
11403
|
case "hermes":
|
|
10405
11404
|
return removeMcpHermesYaml(serverName);
|
|
10406
11405
|
case "openclaw":
|
|
@@ -10412,7 +11411,7 @@ function uninstallMcpForAgent(a, serverName = "caveman") {
|
|
|
10412
11411
|
// removeMcpCodexToml drops the exact [mcp_servers.<name>] block mcpInstall wrote
|
|
10413
11412
|
// (header + its command/args lines, up to the next section or EOF).
|
|
10414
11413
|
function removeMcpCodexToml(serverName = "caveman") {
|
|
10415
|
-
const path = join(
|
|
11414
|
+
const path = join(codexHomeDir(), "config.toml");
|
|
10416
11415
|
let existing = "";
|
|
10417
11416
|
try {
|
|
10418
11417
|
existing = readFileSync(path, "utf8");
|
|
@@ -10974,6 +11973,10 @@ function qwenStringList(root, path, fallback) {
|
|
|
10974
11973
|
return null;
|
|
10975
11974
|
return resolved;
|
|
10976
11975
|
}
|
|
11976
|
+
// Through qwenCavemanToolDenied below: ported, with changes, from Qwen Code
|
|
11977
|
+
// 0.22.3 (https://github.com/QwenLM/qwen-code), Copyright 2025 Google LLC and
|
|
11978
|
+
// Copyright 2025 Qwen, Apache License 2.0. See NOTICE.
|
|
11979
|
+
//
|
|
10977
11980
|
// Exact wildcard matcher used by Qwen 0.22 for mcp.allowed/mcp.excluded:
|
|
10978
11981
|
// `*` spans any run, `?` spans one character, everything else is literal.
|
|
10979
11982
|
function qwenMcpServerPatternMatches(name, pattern) {
|
|
@@ -12476,7 +13479,7 @@ function installMcpForAgent(a, mcp, serverName = "caveman") {
|
|
|
12476
13479
|
case "qwen":
|
|
12477
13480
|
throw new Error(`${a.display_name} MCP changes require the ownership transaction`);
|
|
12478
13481
|
case "gemini":
|
|
12479
|
-
return installMcpJson(
|
|
13482
|
+
return installMcpJson(geminiSettingsPath(), ["mcpServers", serverName], {
|
|
12480
13483
|
command: mcp.command,
|
|
12481
13484
|
args: mcp.args,
|
|
12482
13485
|
});
|
|
@@ -12557,7 +13560,7 @@ function installMcpClaude(mcp, serverName = "caveman") {
|
|
|
12557
13560
|
}
|
|
12558
13561
|
}
|
|
12559
13562
|
function installMcpCodexToml(mcp, serverName = "caveman") {
|
|
12560
|
-
const path = join(
|
|
13563
|
+
const path = join(codexHomeDir(), "config.toml");
|
|
12561
13564
|
let existing = "";
|
|
12562
13565
|
try {
|
|
12563
13566
|
existing = readFileSync(path, "utf8");
|
|
@@ -12570,7 +13573,8 @@ function installMcpCodexToml(mcp, serverName = "caveman") {
|
|
|
12570
13573
|
}
|
|
12571
13574
|
const header = `[mcp_servers.${serverName}]`;
|
|
12572
13575
|
const argsLine = mcp.args.length ? `\nargs = [${mcp.args.map((s) => JSON.stringify(s)).join(", ")}]` : "";
|
|
12573
|
-
const
|
|
13576
|
+
const recoveryEnv = serverName === "caveman" ? `\n${CODEX_RECOVERY_ENV}` : "";
|
|
13577
|
+
const expectedBlock = `${header}\ncommand = ${JSON.stringify(mcp.command)}${argsLine}${recoveryEnv}\n`;
|
|
12574
13578
|
if (existing.includes(header)) {
|
|
12575
13579
|
const headerMatch = new RegExp(`(^|\\n)[ \\t]*\\[mcp_servers\\.${escapeRegExp(serverName)}\\][ \\t]*(?:\\r?\\n|$)`, "m").exec(existing);
|
|
12576
13580
|
if (!headerMatch) {
|
|
@@ -12607,7 +13611,7 @@ function installMcpCodexToml(mcp, serverName = "caveman") {
|
|
|
12607
13611
|
}
|
|
12608
13612
|
}
|
|
12609
13613
|
function codexMcpRegistrationMatches(serverName, mcp) {
|
|
12610
|
-
const path = join(
|
|
13614
|
+
const path = join(codexHomeDir(), "config.toml");
|
|
12611
13615
|
let existing = "";
|
|
12612
13616
|
try {
|
|
12613
13617
|
existing = readFileSync(path, "utf8");
|
|
@@ -12623,7 +13627,8 @@ function codexMcpRegistrationMatches(serverName, mcp) {
|
|
|
12623
13627
|
const nextHeaderOffset = existing.slice(contentStart).search(/^[ \\t]*\[/m);
|
|
12624
13628
|
const blockEnd = nextHeaderOffset === -1 ? existing.length : contentStart + nextHeaderOffset;
|
|
12625
13629
|
const argsLine = mcp.args.length ? `\nargs = [${mcp.args.map((arg) => JSON.stringify(arg)).join(", ")}]` : "";
|
|
12626
|
-
const
|
|
13630
|
+
const recoveryEnv = serverName === "caveman" ? `\n${CODEX_RECOVERY_ENV}` : "";
|
|
13631
|
+
const expected = `[mcp_servers.${serverName}]\ncommand = ${JSON.stringify(mcp.command)}${argsLine}${recoveryEnv}`;
|
|
12627
13632
|
return existing.slice(blockStart, blockEnd).trim() === expected.trim();
|
|
12628
13633
|
}
|
|
12629
13634
|
// installMcpJson merges a value at a nested key into an agent's JSON config without
|
|
@@ -12969,7 +13974,18 @@ function cavemanBinForHook(powershell = process.platform === "win32") {
|
|
|
12969
13974
|
// CLI (BeforeTool, tool "run_shell_command"). It reads the tool event on stdin and,
|
|
12970
13975
|
// for a noisy command, rewrites it to run through `caveman shrink`. Anything it won't
|
|
12971
13976
|
// safely shrink it passes through: exit 0 with NO stdout = "no rewrite, run as-is".
|
|
13977
|
+
//
|
|
13978
|
+
// Codex is deliberately NOT in that list, and re-adding it is the #1037 regression:
|
|
13979
|
+
// Codex matches a saved approval against the command text itself (`prefix_rule`), so
|
|
13980
|
+
// any rewrite makes an already-approved command look new and re-prompts the user —
|
|
13981
|
+
// and the rewrite leads with the resolved caveman/node path, which differs per
|
|
13982
|
+
// machine, so no rule the user writes can cover it either. The old Codex branch also
|
|
13983
|
+
// answered the host's approval question with permissionDecision:"allow" against an
|
|
13984
|
+
// unverified contract; if Codex ever honors that, caveman silently auto-approves a
|
|
13985
|
+
// command the user's `approval_policy` meant to gate. Both ends fail closed instead.
|
|
12972
13986
|
async function shrinkHook() {
|
|
13987
|
+
// Host hooks never report command_run: the POST would hold the host's turn.
|
|
13988
|
+
telemetryCommandSent = true;
|
|
12973
13989
|
if (nativePolicyMode() === "record" || !new Set(["full-safe", "full-max"]).has(nativeProfile()))
|
|
12974
13990
|
process.exit(0);
|
|
12975
13991
|
let raw;
|
|
@@ -12989,8 +14005,9 @@ async function shrinkHook() {
|
|
|
12989
14005
|
const tool = evt?.tool_name;
|
|
12990
14006
|
const isGemini = tool === "run_shell_command"; // Gemini CLI's shell tool
|
|
12991
14007
|
const isBash = tool === "Bash"; // Claude Code + the opencode plugin
|
|
12992
|
-
|
|
12993
|
-
|
|
14008
|
+
// Every other tool name — Codex's shell/shell_command/exec_command included — runs
|
|
14009
|
+
// as the host received it. See the #1037 note above before widening this.
|
|
14010
|
+
if (!isGemini && !isBash)
|
|
12994
14011
|
process.exit(0);
|
|
12995
14012
|
const command = evt.tool_input?.command;
|
|
12996
14013
|
if (typeof command !== "string" || !shouldShrink(command))
|
|
@@ -12998,9 +14015,8 @@ async function shrinkHook() {
|
|
|
12998
14015
|
// updatedInput.command executes in host shell (Git Bash on Claude Windows),
|
|
12999
14016
|
// not hook's explicit PowerShell shell. Never leak PowerShell `&` into it.
|
|
13000
14017
|
const rewritten = `${cavemanBinForHook(false)} shrink -- ${command.trim()}`;
|
|
13001
|
-
//
|
|
13002
|
-
// hookSpecificOutput.
|
|
13003
|
-
// via hookSpecificOutput.updatedInput (camelCase + hookEventName). Emit the right one.
|
|
14018
|
+
// Gemini merges hookSpecificOutput.tool_input (snake_case, no event discriminator);
|
|
14019
|
+
// Claude replaces via hookSpecificOutput.updatedInput (camelCase + hookEventName).
|
|
13004
14020
|
const out = isGemini
|
|
13005
14021
|
? { hookSpecificOutput: { tool_input: { command: rewritten } } }
|
|
13006
14022
|
: { hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "allow", updatedInput: { command: rewritten } } };
|
|
@@ -13245,7 +14261,7 @@ function nativeRepositoryState(cwd) {
|
|
|
13245
14261
|
try {
|
|
13246
14262
|
const status = execFileSync("git", hardenedGitArgs(cwd, "status", "--porcelain=v1", "-z", "--branch", "--untracked-files=all"), {
|
|
13247
14263
|
env: hardenedGitEnv(),
|
|
13248
|
-
timeout:
|
|
14264
|
+
timeout: 500, // same budget as nativehook.repositoryStatusBudget; 100ms emptied the state under load
|
|
13249
14265
|
maxBuffer: 8 * 1024 * 1024,
|
|
13250
14266
|
encoding: "buffer",
|
|
13251
14267
|
stdio: ["ignore", "pipe", "ignore"],
|
|
@@ -13568,6 +14584,8 @@ function nativeWhy(argv) {
|
|
|
13568
14584
|
// never cross the adapter boundary. Any malformed input/write failure stays
|
|
13569
14585
|
// fail-open and emits no blocking decision.
|
|
13570
14586
|
async function nativeHook(argv) {
|
|
14587
|
+
// Host hooks never report command_run: the POST would hold the host's turn.
|
|
14588
|
+
telemetryCommandSent = true;
|
|
13571
14589
|
const agent = argv[0] === "claude" || argv[0] === "codex" || argv[0] === "hermes" || argv[0] === "gemini" || argv[0] === "opencode" || argv[0] === "pi" ? argv[0] : undefined;
|
|
13572
14590
|
if (!agent)
|
|
13573
14591
|
process.exit(0);
|
|
@@ -13602,6 +14620,9 @@ async function nativeHook(argv) {
|
|
|
13602
14620
|
}[rawEventName] ?? rawEventName : rawEventName;
|
|
13603
14621
|
const normalizedEvent = eventName && NATIVE_EVENT_NAMES.has(eventName) ? eventName : "Unknown";
|
|
13604
14622
|
const sessionId = boundedHookString(event.session_id ?? event.sessionId);
|
|
14623
|
+
// A compaction re-fires SessionStart inside the same session; count real starts.
|
|
14624
|
+
if (normalizedEvent === "SessionStart" && event.source !== "compact")
|
|
14625
|
+
startSessionTelemetry(agent, sessionId, event.source);
|
|
13605
14626
|
const toolName = boundedHookString(event.tool_name ?? event.toolName);
|
|
13606
14627
|
const cwd = boundedHookString(event.cwd, 4096);
|
|
13607
14628
|
const entry = {
|
|
@@ -13618,11 +14639,13 @@ async function nativeHook(argv) {
|
|
|
13618
14639
|
entry.tool_name = toolName;
|
|
13619
14640
|
if (cwd)
|
|
13620
14641
|
entry.cwd_sha256 = `sha256:${createHash("sha256").update(cwd).digest("hex")}`;
|
|
14642
|
+
if (normalizedEvent === "SessionEnd")
|
|
14643
|
+
maybeSpawnAutopilot();
|
|
13621
14644
|
// SessionStart revives a missing local proxy, but native routing points every
|
|
13622
|
-
// LATER turn of the session at that proxy too
|
|
13623
|
-
//
|
|
13624
|
-
//
|
|
13625
|
-
//
|
|
14645
|
+
// LATER turn of the session at that proxy too. Current proxies never expire,
|
|
14646
|
+
// but crashes and older binaries can still leave a dead base URL. A plain
|
|
14647
|
+
// session needs prompt-time recovery as well. The port check makes revival
|
|
14648
|
+
// idempotent, so run
|
|
13626
14649
|
// it for the mid-session events that reach the full CLI as well.
|
|
13627
14650
|
if (normalizedEvent === "SessionStart" || normalizedEvent === "UserPromptSubmit" || normalizedEvent === "PostCompact") {
|
|
13628
14651
|
try {
|
|
@@ -13669,10 +14692,23 @@ async function nativeHook(argv) {
|
|
|
13669
14692
|
// it before provider forwarding. Generated structure/order are byte-stable.
|
|
13670
14693
|
const stableContext = [coreContext, marker].filter(Boolean).join("\n");
|
|
13671
14694
|
const compactContext = [coreContext, runtimeContext, marker].filter(Boolean).join("\n");
|
|
13672
|
-
|
|
14695
|
+
// systemMessage is the user-visible channel on Claude/Codex/Gemini SessionStart;
|
|
14696
|
+
// additionalContext would put the nudge in model context instead.
|
|
14697
|
+
// Under the fast hook the parent owns the token and confirms after relaying
|
|
14698
|
+
// our stdout, since it may still drop the output on its own timeout.
|
|
14699
|
+
const relayedToken = boundedHookString(process.env.CAVEMAN_LEARN_NUDGE_TOKEN);
|
|
14700
|
+
const learnNudgeToken = relayedToken || randomUUID();
|
|
14701
|
+
const learnNudge = normalizedEvent === "SessionStart" && (agent === "claude" || agent === "codex" || agent === "gemini")
|
|
14702
|
+
? claimLearnNudge(boundedHookString(event.source), learnNudgeToken)
|
|
14703
|
+
: undefined;
|
|
14704
|
+
if (normalizedEvent === "SessionStart" && agent !== "hermes" && (stableContext || learnNudge)) {
|
|
13673
14705
|
process.stdout.write(JSON.stringify({
|
|
13674
|
-
|
|
13675
|
-
|
|
14706
|
+
...(learnNudge ? { systemMessage: learnNudge } : {}),
|
|
14707
|
+
...(stableContext ? { hookSpecificOutput: { hookEventName: normalizedEvent, additionalContext: stableContext } } : {}),
|
|
14708
|
+
}), () => {
|
|
14709
|
+
if (learnNudge && !relayedToken)
|
|
14710
|
+
confirmLearnNudge(learnNudgeToken);
|
|
14711
|
+
});
|
|
13676
14712
|
}
|
|
13677
14713
|
else if (normalizedEvent === "PostCompact" && agent !== "hermes" && compactContext) {
|
|
13678
14714
|
process.stdout.write(JSON.stringify({
|
|
@@ -13704,13 +14740,13 @@ async function nativeHook(argv) {
|
|
|
13704
14740
|
}
|
|
13705
14741
|
}
|
|
13706
14742
|
function claudeSettingsPath() {
|
|
13707
|
-
return join(
|
|
14743
|
+
return join(claudeConfigDir(), "settings.json");
|
|
13708
14744
|
}
|
|
13709
14745
|
function geminiSettingsPath() {
|
|
13710
|
-
return join(
|
|
14746
|
+
return join(geminiConfigDir(), "settings.json");
|
|
13711
14747
|
}
|
|
13712
14748
|
function codexHooksPath() {
|
|
13713
|
-
return join(
|
|
14749
|
+
return join(codexHomeDir(), "hooks.json");
|
|
13714
14750
|
}
|
|
13715
14751
|
// installSettingsHook registers a command-output shrink hook in a settings.json that
|
|
13716
14752
|
// follows the Claude/Gemini shape — root.hooks[<event>] is an array of
|
|
@@ -13833,7 +14869,7 @@ function commandHookKind(a) {
|
|
|
13833
14869
|
}
|
|
13834
14870
|
function instructionFileForAgent(a) {
|
|
13835
14871
|
const hook = a.command_hook;
|
|
13836
|
-
return hook && "file" in hook ? hook.file : undefined;
|
|
14872
|
+
return hook && "file" in hook ? agentUserPath(a.id, hook.file) : undefined;
|
|
13837
14873
|
}
|
|
13838
14874
|
// (hard methods: claude-pretooluse, codex-pretooluse, opencode-plugin, gemini-beforetool, hermes-plugin, openclaw-plugin.)
|
|
13839
14875
|
// installShrinkHookForAgent installs the command-output compression hook using the
|
|
@@ -13953,6 +14989,8 @@ function writeRecallHookMarker(agentId) {
|
|
|
13953
14989
|
// Fail-open by construction: any problem → exit 0 with no output (never blocks the
|
|
13954
14990
|
// agent, never injects a guess).
|
|
13955
14991
|
async function memRecallHook() {
|
|
14992
|
+
// Host hooks never report command_run: the POST would hold the host's turn.
|
|
14993
|
+
telemetryCommandSent = true;
|
|
13956
14994
|
let raw;
|
|
13957
14995
|
try {
|
|
13958
14996
|
raw = await readHookStdin();
|
|
@@ -14049,6 +15087,17 @@ function hookInstalledPhrase(a) {
|
|
|
14049
15087
|
return `shrink preference added to ${ch.file} ${dim("(a model nudge, not a hard rewrite)")}`;
|
|
14050
15088
|
return "command-output rewrite hook installed";
|
|
14051
15089
|
}
|
|
15090
|
+
// codexRewriteRetired: codex's profile still declares the `codex-pretooluse` hard
|
|
15091
|
+
// tier, but shrinkHook has declined every Codex tool event since #1037 — rewriting
|
|
15092
|
+
// the command breaks the user's saved approval rules. Installing that hook would
|
|
15093
|
+
// register a callback with no behavior behind it and report a rewrite that does not
|
|
15094
|
+
// happen. Retiring the tier in the profile is the real fix and is NOT done here: the
|
|
15095
|
+
// same `command_hook` entry carries codex's directives instructions-file, and
|
|
15096
|
+
// nativeHooksDocument would have to migrate the entry `caveman enable codex` already
|
|
15097
|
+
// wrote. Both are maintainer decisions; this just stops making the false claim.
|
|
15098
|
+
function codexRewriteRetired(a) {
|
|
15099
|
+
return a.id === "codex";
|
|
15100
|
+
}
|
|
14052
15101
|
// ── soft tier: instruction-note ──────────────────────────────────────────────
|
|
14053
15102
|
// For agents with no deterministic command-rewrite surface, we append a
|
|
14054
15103
|
// clearly-delimited note to a file the agent auto-reads as model instructions,
|
|
@@ -14821,6 +15870,10 @@ function hooksCmd(rest) {
|
|
|
14821
15870
|
let n = 0;
|
|
14822
15871
|
let hard = 0;
|
|
14823
15872
|
for (const a of targets) {
|
|
15873
|
+
if (codexRewriteRetired(a)) {
|
|
15874
|
+
process.stderr.write(`${mark("warn")} ${a.display_name}: no command-output rewrite — it breaks saved Codex approval rules (#1037); run noisy commands through ${cyan("caveman shrink -- <cmd>")}\n`);
|
|
15875
|
+
continue;
|
|
15876
|
+
}
|
|
14824
15877
|
if (installShrinkHookForAgent(a)) {
|
|
14825
15878
|
writeShrinkHookMarker(a.id);
|
|
14826
15879
|
n++;
|
|
@@ -14908,12 +15961,45 @@ function evalsRun(argv = []) {
|
|
|
14908
15961
|
// owns the ~/.caveman/ SQLite store. The CLI carries no database dependency, so
|
|
14909
15962
|
// it reads through the same Go binary `caveman start` launches.
|
|
14910
15963
|
function stats(argv = []) {
|
|
14911
|
-
if (argv.length
|
|
14912
|
-
|
|
15964
|
+
if (argv.length === 1 && ["--help", "-h", "help"].includes(argv[0])) {
|
|
15965
|
+
process.stdout.write(STATS_HELP);
|
|
15966
|
+
return;
|
|
15967
|
+
}
|
|
15968
|
+
let options;
|
|
15969
|
+
try {
|
|
15970
|
+
options = parseStatsOptions(argv);
|
|
15971
|
+
}
|
|
15972
|
+
catch (error) {
|
|
15973
|
+
console.error(error.message);
|
|
15974
|
+
commandUsage(STATS_USAGE);
|
|
15975
|
+
}
|
|
14913
15976
|
const bin = cavemanBin("caveman-proxy", "CAVEMAN_PROXY_BIN");
|
|
14914
15977
|
try {
|
|
14915
|
-
const
|
|
14916
|
-
|
|
15978
|
+
const args = ["stats", "--report", ...options.filters];
|
|
15979
|
+
if (!options.json || options.out)
|
|
15980
|
+
args.push("--write-report");
|
|
15981
|
+
if (options.out)
|
|
15982
|
+
args.push("--out", resolve(options.out));
|
|
15983
|
+
const out = execFileSync(bin, args, { encoding: "utf8", timeout: 60_000, maxBuffer: 32 * 1024 * 1024 });
|
|
15984
|
+
const report = JSON.parse(out);
|
|
15985
|
+
// Older companion binaries ignore --report. Keep their measurements
|
|
15986
|
+
// readable, but never pretend they generated the new accounting report.
|
|
15987
|
+
if (report.schema !== "caveman.stats.v1") {
|
|
15988
|
+
if (options.filters.length || options.out || options.open) {
|
|
15989
|
+
throw new Error("installed proxy does not support filtered stats or HTML reports; run caveman setup --install");
|
|
15990
|
+
}
|
|
15991
|
+
process.stdout.write(out);
|
|
15992
|
+
if (!options.json)
|
|
15993
|
+
process.stderr.write("Detailed stats require an updated proxy: caveman setup --install\n");
|
|
15994
|
+
return;
|
|
15995
|
+
}
|
|
15996
|
+
if (options.json)
|
|
15997
|
+
process.stdout.write(out);
|
|
15998
|
+
else {
|
|
15999
|
+
process.stdout.write(renderStatsSummary(report));
|
|
16000
|
+
if (report.report_path && (options.open || (!options.plain && learnTuiTerminal())))
|
|
16001
|
+
openLearnReport(report.report_path);
|
|
16002
|
+
}
|
|
14917
16003
|
}
|
|
14918
16004
|
catch (error) {
|
|
14919
16005
|
console.error(`failed to read stats via ${bin}: ${error.message}`);
|
|
@@ -15032,6 +16118,39 @@ async function trial(rest) {
|
|
|
15032
16118
|
const proxyResolved = which(proxyBin());
|
|
15033
16119
|
if (!proxyResolved)
|
|
15034
16120
|
return startMissingProxyUI(proxyBin());
|
|
16121
|
+
// A trial measures traffic by standing up its OWN proxy on a free port under
|
|
16122
|
+
// a `trial:<id>` label and pointing the child at it through the environment.
|
|
16123
|
+
// Native routing pins the base URL inside the agent's own config file, and an
|
|
16124
|
+
// agent reads its config in preference to its environment — so the child goes
|
|
16125
|
+
// to the persistent listener instead, which carries no trial label.
|
|
16126
|
+
// RecordPayload only stores payloads for a `trial:` label, so trial_payloads
|
|
16127
|
+
// stays empty, the replay optimizer has nothing to replay, and every number
|
|
16128
|
+
// in the report renders 0. Nothing errors; the trial exits 0 and reports a
|
|
16129
|
+
// measurement of nothing. Refuse up front instead of producing that report,
|
|
16130
|
+
// and refuse BEFORE `trial start` so no orphan trial row is opened. (#1068)
|
|
16131
|
+
const pinned = nativeRoutePinnedFor(agent?.id ?? requested);
|
|
16132
|
+
if (pinned) {
|
|
16133
|
+
console.error(pinned.pending
|
|
16134
|
+
? `caveman trial cannot measure ${agent?.id ?? requested}: an interrupted native install left its routing in place.`
|
|
16135
|
+
: `caveman trial cannot measure ${agent?.id ?? requested} while native routing is enabled.`);
|
|
16136
|
+
console.error("");
|
|
16137
|
+
console.error(` ${pinned.file}`);
|
|
16138
|
+
console.error(` pins the base URL to ${pinned.route}`);
|
|
16139
|
+
console.error("");
|
|
16140
|
+
console.error("A trial runs its own proxy on its own port and points the agent at it through");
|
|
16141
|
+
console.error("the environment. That config file wins, so the agent would keep talking to the");
|
|
16142
|
+
console.error("persistent listener, the trial would capture nothing, and the report would say");
|
|
16143
|
+
console.error("zero requests and $0.0000 — which reads as a measurement rather than as silence.");
|
|
16144
|
+
console.error("");
|
|
16145
|
+
// invokedAs(), not invokedCommand(): invokedCommand renders the verb of the
|
|
16146
|
+
// CURRENT invocation, which is always "trial" here, so it would print
|
|
16147
|
+
// "caveman trial <agent>" for the disable and enable lines.
|
|
16148
|
+
console.error(`Turn native routing off for the duration of the trial, then put it back:`);
|
|
16149
|
+
console.error(` ${invokedAs()} disable ${agent?.id ?? requested}`);
|
|
16150
|
+
console.error(` ${invokedAs()} trial -- ${command.join(" ")}`);
|
|
16151
|
+
console.error(` ${invokedAs()} enable ${agent?.id ?? requested}`);
|
|
16152
|
+
process.exit(2);
|
|
16153
|
+
}
|
|
15035
16154
|
const port = await freePort();
|
|
15036
16155
|
const listen = `127.0.0.1:${port}`;
|
|
15037
16156
|
const trialURL = `http://${listen}`;
|
|
@@ -15065,12 +16184,39 @@ async function trial(rest) {
|
|
|
15065
16184
|
throw error;
|
|
15066
16185
|
}
|
|
15067
16186
|
}
|
|
15068
|
-
|
|
15069
|
-
|
|
16187
|
+
// learnEmpty names the window the proxy actually scanned (plan.window.since;
|
|
16188
|
+
// older proxies omit it and always scanned 30d).
|
|
16189
|
+
function learnEmpty(plan) {
|
|
16190
|
+
const since = learnSince(plan.window?.since || "30d");
|
|
16191
|
+
return `no Claude Code, Codex, Gemini CLI, opencode or aider sessions found in the last ${since}. A score needs the same text repeated in at least 3 sessions. Use your agent a few times (for example \`caveman claude\`), then run \`caveman learn\` again`;
|
|
16192
|
+
}
|
|
16193
|
+
// learnNoScoreYet explains why there is no score: the score needs the same
|
|
16194
|
+
// text repeated in at least 3 sessions.
|
|
16195
|
+
function learnNoScoreYet(sessions) {
|
|
16196
|
+
return `${commaCount(sessions)} sessions read · no score yet: it needs the same text repeated in at least 3 sessions. Keep using your agent (for example \`${invokedAs()} claude\`), then run \`${invokedAs()} learn\` again`;
|
|
16197
|
+
}
|
|
16198
|
+
const LEARN_CLASS_LABELS = {
|
|
16199
|
+
reducible: "safe fix",
|
|
16200
|
+
recurring_context: "repeated text",
|
|
16201
|
+
behavioral: "habit",
|
|
16202
|
+
load_bearing: "needed",
|
|
16203
|
+
};
|
|
16204
|
+
function learnClassLabel(klass) {
|
|
16205
|
+
return LEARN_CLASS_LABELS[klass] ?? klass.replaceAll("_", " ");
|
|
16206
|
+
}
|
|
16207
|
+
// learnSince turns a --since value like "30d" into "30 days".
|
|
16208
|
+
function learnSince(since) {
|
|
16209
|
+
const days = /^(\d+)d$/.exec(since)?.[1];
|
|
16210
|
+
return days ? `${days} day${days === "1" ? "" : "s"}` : since;
|
|
16211
|
+
}
|
|
16212
|
+
function commaCount(value) {
|
|
16213
|
+
return Math.round(value).toLocaleString("en-US");
|
|
16214
|
+
}
|
|
16215
|
+
const LEARN_DETAILED_NEXT = "next: caveman tools skills install caveman-learn (review and apply fixes; asks first) · preview one fix: caveman learn apply <id> --dry-run";
|
|
15070
16216
|
const LEARN_ALL_FOOTER = [
|
|
15071
|
-
"advanced: caveman learn applied <
|
|
15072
|
-
"simulate: caveman learn simulate <
|
|
15073
|
-
"scope: caveman learn --repo <substring>
|
|
16217
|
+
"advanced: caveman learn applied <id> [--fix-kind <kind>] [--note <text>] record a fix you approved, so later runs can measure it",
|
|
16218
|
+
"simulate: caveman learn simulate <id...> estimate what fixes would have saved over your past sessions",
|
|
16219
|
+
"scope: caveman learn --repo <substring> only read sessions from matching repositories",
|
|
15074
16220
|
];
|
|
15075
16221
|
const LEARN_SUMMARY_LIMIT = 3;
|
|
15076
16222
|
function learnReportPath() {
|
|
@@ -15098,14 +16244,15 @@ function renderLearnDetailedRows(plan, markdown) {
|
|
|
15098
16244
|
const lines = [];
|
|
15099
16245
|
for (const [index, sink] of plan.sinks.entries()) {
|
|
15100
16246
|
const lead = markdown ? `${index + 1}. **${sink.title}**` : `${index + 1}. ${sink.title}`;
|
|
15101
|
-
lines.push(
|
|
16247
|
+
lines.push(lead);
|
|
16248
|
+
lines.push(` ${learnClassLabel(sink.class)} · id: ${sink.sink_id}`);
|
|
15102
16249
|
const observed = typeof sink.tokens_observed === "number" && sink.tokens_observed > 0
|
|
15103
|
-
? ` ·
|
|
16250
|
+
? ` · ${commaCount(sink.tokens_observed)} tokens so far`
|
|
15104
16251
|
: "";
|
|
15105
16252
|
const prefix = learnMeasuredPrefixSuffix(sink);
|
|
15106
|
-
lines.push(`
|
|
16253
|
+
lines.push(` ${commaCount(sink.tokens_per_turn)} tokens per message · ${commaCount(sink.tokens_per_day_rate)} tokens a day${observed} · estimate${prefix}`);
|
|
15107
16254
|
if (KNOWN_PRACTICE_IDS.has(sink.practice_id)) {
|
|
15108
|
-
lines.push(` practice: ${sink.practice_id} ·
|
|
16255
|
+
lines.push(` practice: ${sink.practice_id} · not measured or verified yet`);
|
|
15109
16256
|
}
|
|
15110
16257
|
if (sink.suggestion)
|
|
15111
16258
|
lines.push(` ${sink.suggestion}`);
|
|
@@ -15121,7 +16268,7 @@ function learnMeasuredPrefixSuffix(sink) {
|
|
|
15121
16268
|
return "";
|
|
15122
16269
|
const measured = learnEvidenceNumber(sink, "measured_prefix_tokens");
|
|
15123
16270
|
return measured && measured > 0
|
|
15124
|
-
? ` ·
|
|
16271
|
+
? ` · a session's first message is ~${humanTokens(measured)} tokens (typical, counted by your provider)`
|
|
15125
16272
|
: "";
|
|
15126
16273
|
}
|
|
15127
16274
|
function compactLearnText(value, max = 108) {
|
|
@@ -15135,6 +16282,12 @@ function compactLearnText(value, max = 108) {
|
|
|
15135
16282
|
const wordEnd = prefix.lastIndexOf(" ");
|
|
15136
16283
|
return `${prefix.slice(0, wordEnd > 0 ? wordEnd : prefix.length)}…`;
|
|
15137
16284
|
}
|
|
16285
|
+
// learnMemoryHealthLine points at the memory & rules doctor findings in one
|
|
16286
|
+
// line; they carry no token rate, so they rarely make the top moves.
|
|
16287
|
+
function learnMemoryHealthLine(plan) {
|
|
16288
|
+
const count = plan.sinks.filter((sink) => sink.sink_id.startsWith("memory_health:")).length;
|
|
16289
|
+
return count > 0 ? `memory files ${count} finding${count === 1 ? "" : "s"} — see ${invokedAs()} learn --all` : undefined;
|
|
16290
|
+
}
|
|
15138
16291
|
export function learnSummaryMoves(plan) {
|
|
15139
16292
|
const moves = [];
|
|
15140
16293
|
const best = plan.portfolio?.best_next_move;
|
|
@@ -15142,17 +16295,17 @@ export function learnSummaryMoves(plan) {
|
|
|
15142
16295
|
if (best) {
|
|
15143
16296
|
const confidenceLabels = {
|
|
15144
16297
|
measured_usage: "measured",
|
|
15145
|
-
transcript_inferred: "
|
|
16298
|
+
transcript_inferred: "estimated from transcripts",
|
|
15146
16299
|
static_estimate: "estimate",
|
|
15147
16300
|
};
|
|
15148
16301
|
const confidence = confidenceLabels[best.confidence] ?? best.confidence;
|
|
15149
16302
|
const detail = [
|
|
15150
|
-
|
|
16303
|
+
best.fix_label,
|
|
15151
16304
|
best.combined_rate_per_day > 0
|
|
15152
|
-
? `~${humanTokens(best.combined_rate_per_day)} tokens
|
|
16305
|
+
? `~${humanTokens(best.combined_rate_per_day)} tokens a day`
|
|
15153
16306
|
: "",
|
|
15154
16307
|
best.combined_observed_in_window > 0
|
|
15155
|
-
? `~${humanTokens(best.combined_observed_in_window)} tokens
|
|
16308
|
+
? `~${humanTokens(best.combined_observed_in_window)} tokens so far`
|
|
15156
16309
|
: "",
|
|
15157
16310
|
confidence,
|
|
15158
16311
|
].filter(Boolean);
|
|
@@ -15176,28 +16329,30 @@ export function learnSummaryMoves(plan) {
|
|
|
15176
16329
|
const largest = Math.max(0, ...recurring.map((item) => learnEvidenceNumber(item, "block_tokens") ?? 0));
|
|
15177
16330
|
const sessions = Math.max(0, ...recurring.map((item) => learnEvidenceNumber(item, "recurrence_sessions") ?? 0));
|
|
15178
16331
|
const facts = [
|
|
15179
|
-
"
|
|
16332
|
+
"repeated text",
|
|
15180
16333
|
largest > 0 ? `largest ~${humanTokens(largest)} tokens` : "",
|
|
15181
|
-
sessions > 0 ? `up to ${sessions} sessions` : "",
|
|
15182
|
-
"
|
|
16334
|
+
sessions > 0 ? `in up to ${commaCount(sessions)} sessions` : "",
|
|
16335
|
+
"estimate",
|
|
15183
16336
|
].filter(Boolean);
|
|
15184
16337
|
moves.push({
|
|
15185
|
-
title:
|
|
15186
|
-
|
|
16338
|
+
title: recurring.length === 1
|
|
16339
|
+
? "1 piece of text gets pasted again in many sessions"
|
|
16340
|
+
: `${recurring.length} pieces of text get pasted again in many sessions`,
|
|
16341
|
+
kind: "repeated text",
|
|
15187
16342
|
detail: facts.join(" · "),
|
|
15188
|
-
action: "
|
|
16343
|
+
action: "Check each one before moving it to Caveman memory. Repeating doesn't prove the text is unneeded.",
|
|
15189
16344
|
});
|
|
15190
16345
|
}
|
|
15191
16346
|
else {
|
|
15192
16347
|
const rates = [
|
|
15193
|
-
sink.class
|
|
15194
|
-
sink.tokens_per_turn > 0 ? `~${humanTokens(sink.tokens_per_turn)} tokens
|
|
15195
|
-
sink.tokens_per_day_rate > 0 ? `~${humanTokens(sink.tokens_per_day_rate)} tokens
|
|
15196
|
-
"
|
|
16348
|
+
learnClassLabel(sink.class),
|
|
16349
|
+
sink.tokens_per_turn > 0 ? `~${humanTokens(sink.tokens_per_turn)} tokens in every message` : "",
|
|
16350
|
+
sink.tokens_per_day_rate > 0 ? `~${humanTokens(sink.tokens_per_day_rate)} tokens a day` : "",
|
|
16351
|
+
"estimate",
|
|
15197
16352
|
].filter(Boolean);
|
|
15198
16353
|
moves.push({
|
|
15199
16354
|
title: sink.title,
|
|
15200
|
-
kind: sink.class
|
|
16355
|
+
kind: learnClassLabel(sink.class),
|
|
15201
16356
|
detail: rates.join(" · "),
|
|
15202
16357
|
...(sink.suggestion ? { action: compactLearnText(sink.suggestion) } : {}),
|
|
15203
16358
|
});
|
|
@@ -15220,23 +16375,23 @@ function renderLearnSummaryRows(plan) {
|
|
|
15220
16375
|
function learnSourceLine(plan, sessions) {
|
|
15221
16376
|
const by = plan.sessions_by_source ?? {};
|
|
15222
16377
|
const sourceBits = [
|
|
15223
|
-
by.claude ? `Claude ${by.claude}` : "",
|
|
15224
|
-
by.codex ? `Codex ${by.codex}` : "",
|
|
15225
|
-
by.gemini ? `Gemini ${by.gemini}` : "",
|
|
15226
|
-
by.opencode ? `opencode ${by.opencode}` : "",
|
|
15227
|
-
by.aider ? `aider ${by.aider}` : "",
|
|
16378
|
+
by.claude ? `Claude ${commaCount(by.claude)}` : "",
|
|
16379
|
+
by.codex ? `Codex ${commaCount(by.codex)}` : "",
|
|
16380
|
+
by.gemini ? `Gemini ${commaCount(by.gemini)}` : "",
|
|
16381
|
+
by.opencode ? `opencode ${commaCount(by.opencode)}` : "",
|
|
16382
|
+
by.aider ? `aider ${commaCount(by.aider)}` : "",
|
|
15228
16383
|
].filter(Boolean);
|
|
15229
|
-
return `${sessions} sessions${sourceBits.length ? ` · ${sourceBits.join(" · ")}` : ""}`;
|
|
16384
|
+
return `${commaCount(sessions)} sessions read${sourceBits.length ? ` · ${sourceBits.join(" · ")}` : ""}`;
|
|
15230
16385
|
}
|
|
15231
16386
|
function learnDiffText(diff) {
|
|
15232
16387
|
if (!diff)
|
|
15233
16388
|
return undefined;
|
|
15234
16389
|
const bits = [
|
|
15235
|
-
diff.gone ? `${diff.gone}
|
|
15236
|
-
diff.back ? `${diff.back} back` : "",
|
|
16390
|
+
diff.gone ? `${diff.gone} finding${diff.gone === 1 ? "" : "s"} gone` : "",
|
|
16391
|
+
diff.back ? `${diff.back} came back` : "",
|
|
15237
16392
|
diff.fresh ? `${diff.fresh} new` : "",
|
|
15238
16393
|
].filter(Boolean);
|
|
15239
|
-
return bits.length ? `since your last run ${diff.days}
|
|
16394
|
+
return bits.length ? `since your last run ${diff.days} day${diff.days === 1 ? "" : "s"} ago: ${bits.join(" · ")}` : undefined;
|
|
15240
16395
|
}
|
|
15241
16396
|
export function buildLearnTuiModel(plan, options = {}) {
|
|
15242
16397
|
const sessions = Math.max(0, Number(plan.sessions_scanned ?? 0));
|
|
@@ -15244,54 +16399,75 @@ export function buildLearnTuiModel(plan, options = {}) {
|
|
|
15244
16399
|
const protectedSink = plan.sinks.find((sink) => sink.class === "load_bearing");
|
|
15245
16400
|
const confirmed = plan.confirmed?.length ?? 0;
|
|
15246
16401
|
const diffText = learnDiffText(options.diff);
|
|
16402
|
+
const trend = learnTrendLines(plan.trends);
|
|
16403
|
+
const memory = learnMemoryHealthLine(plan);
|
|
15247
16404
|
const status = sessions === 0
|
|
15248
|
-
?
|
|
16405
|
+
? learnEmpty(plan)
|
|
15249
16406
|
: !recurring
|
|
15250
|
-
?
|
|
16407
|
+
? learnNoScoreYet(sessions)
|
|
15251
16408
|
: undefined;
|
|
15252
16409
|
return {
|
|
15253
16410
|
score: recurring ? plan.cave_score.score : null,
|
|
15254
|
-
scope:
|
|
16411
|
+
scope: LEARN_SCORE_SCOPE,
|
|
15255
16412
|
sessions: learnSourceLine(plan, sessions),
|
|
15256
16413
|
...(diffText ? { diff: diffText } : {}),
|
|
16414
|
+
...(trend.length ? { trend } : {}),
|
|
15257
16415
|
...(status ? { status } : {}),
|
|
15258
16416
|
moves: learnSummaryMoves(plan),
|
|
15259
16417
|
...(protectedSink
|
|
15260
|
-
? { protected:
|
|
16418
|
+
? { protected: learnProtectedText(protectedSink) }
|
|
15261
16419
|
: {}),
|
|
16420
|
+
...(memory ? { memory } : {}),
|
|
15262
16421
|
...(confirmed > 0 ? { confirmed } : {}),
|
|
15263
16422
|
findings: plan.sinks.length,
|
|
15264
16423
|
report: options.report ?? learnReportPath(),
|
|
15265
16424
|
};
|
|
15266
16425
|
}
|
|
16426
|
+
const LEARN_SCORE_SCOPE = "your setup on this computer · an estimate, not your bill · separate from Caveman Cloud's team score";
|
|
16427
|
+
// learnProtectedText describes the needed (load-bearing) baseline: counted in
|
|
16428
|
+
// the score, never changed.
|
|
16429
|
+
function learnProtectedText(sink) {
|
|
16430
|
+
return `${sink.title} · counts in the score, but Caveman never changes it${learnMeasuredPrefixSuffix(sink)}`;
|
|
16431
|
+
}
|
|
15267
16432
|
// renderLearnSpendLines shows what the scanned window cost and, more usefully,
|
|
15268
16433
|
// what a million input tokens ACTUALLY cost after the user's own cache mix.
|
|
15269
16434
|
// The multiplier is the one number that decides whether every other finding in
|
|
15270
16435
|
// the report is expensive or trivial, so it earns a line above the moves.
|
|
15271
|
-
function renderLearnSpendLines(spend, markdown) {
|
|
16436
|
+
function renderLearnSpendLines(spend, markdown, full = true) {
|
|
15272
16437
|
if (!spend)
|
|
15273
16438
|
return [];
|
|
15274
16439
|
const lines = [];
|
|
15275
16440
|
const currency = spend.currency || "USD";
|
|
15276
|
-
const label = markdown ? "###
|
|
16441
|
+
const label = markdown ? "### Cost" : "cost";
|
|
15277
16442
|
if (spend.usd > 0) {
|
|
15278
|
-
const window = spend.window_days ? `
|
|
15279
|
-
lines.push(`${label} ${fmtMoney(spend.usd, currency)}${window} · provider
|
|
16443
|
+
const window = spend.window_days ? ` for the last ${spend.window_days} day${spend.window_days === 1 ? "" : "s"}` : "";
|
|
16444
|
+
lines.push(`${label} ${fmtMoney(spend.usd, currency)}${window} · tokens your provider counted, at list prices`);
|
|
15280
16445
|
}
|
|
15281
16446
|
const multiplier = spend.effective_input_multiplier ?? 0;
|
|
15282
16447
|
const rate = spend.effective_input_usd_per_mtok ?? 0;
|
|
15283
16448
|
if (multiplier > 0 && rate > 0) {
|
|
15284
|
-
|
|
16449
|
+
const share = multiplier * 100 >= 1 ? `${Math.round(multiplier * 100)}%` : "under 1%";
|
|
16450
|
+
// Same thresholds as the proxy's effectiveInputSummary.
|
|
16451
|
+
const verdict = multiplier < 0.25 ? "caching is doing its job" : multiplier < 0.6 ? "some caching" : "little or no caching";
|
|
16452
|
+
lines.push(`input really costs ${fmtMoney(rate, currency)} per 1M tokens · ${share} of list price — ${verdict}`);
|
|
15285
16453
|
}
|
|
15286
16454
|
const components = (spend.components ?? []).filter((component) => component.usd > 0);
|
|
15287
16455
|
if (components.length > 0 && spend.usd > 0) {
|
|
15288
|
-
lines.push(components.map((component) => `${component.key.
|
|
16456
|
+
lines.push(`where it went ${components.map((component) => `${component.key.replaceAll("_", " ")} ${Math.round(component.share_pct ?? 0)}%`).join(" · ")}`);
|
|
15289
16457
|
}
|
|
15290
|
-
|
|
15291
|
-
|
|
16458
|
+
const unpriced = spend.unpriced ?? [];
|
|
16459
|
+
if (!full && unpriced.length > 1) {
|
|
16460
|
+
// Compact view: one line; --all, --md, JSON and HTML keep every model.
|
|
16461
|
+
const tokens = unpriced.reduce((sum, row) => sum + row.tokens, 0);
|
|
16462
|
+
lines.push(`no price ${unpriced.length} models (${humanTokens(tokens)} tokens) left out, so the real total is higher · ${invokedAs()} learn --all lists them`);
|
|
16463
|
+
}
|
|
16464
|
+
else {
|
|
16465
|
+
for (const row of unpriced) {
|
|
16466
|
+
lines.push(`no price ${row.provider}/${row.model} ${humanTokens(row.tokens)} tokens left out, so the real total is higher`);
|
|
16467
|
+
}
|
|
15292
16468
|
}
|
|
15293
16469
|
if (lines.length > 0) {
|
|
15294
|
-
lines.push("subscription
|
|
16470
|
+
lines.push("on a subscription plan you pay nothing extra per token; the cost then shows what the tokens would cost on the API");
|
|
15295
16471
|
}
|
|
15296
16472
|
return lines;
|
|
15297
16473
|
}
|
|
@@ -15304,56 +16480,65 @@ export function renderLearnPlan(plan, options = {}) {
|
|
|
15304
16480
|
const lines = [];
|
|
15305
16481
|
const confirmedLines = renderLearnConfirmed(plan.confirmed, markdown);
|
|
15306
16482
|
if (sessions === 0) {
|
|
15307
|
-
lines.push(
|
|
16483
|
+
lines.push(learnEmpty(plan));
|
|
15308
16484
|
if (confirmedLines.length > 0)
|
|
15309
16485
|
lines.push("", ...confirmedLines);
|
|
15310
16486
|
}
|
|
15311
16487
|
else if (!recurring) {
|
|
15312
16488
|
if (plan.sinks.length > 0) {
|
|
15313
|
-
lines.push(...(verbose ? renderLearnDetailedRows(plan, markdown) : ["top
|
|
16489
|
+
lines.push(...(verbose ? renderLearnDetailedRows(plan, markdown) : ["top findings", ...renderLearnSummaryRows(plan)]), "");
|
|
16490
|
+
const memory = verbose ? undefined : learnMemoryHealthLine(plan);
|
|
16491
|
+
if (memory)
|
|
16492
|
+
lines.push(memory, "");
|
|
15314
16493
|
}
|
|
15315
|
-
lines.push(
|
|
16494
|
+
lines.push(learnNoScoreYet(sessions));
|
|
16495
|
+
lines.push(...(verbose ? [] : learnTrendLines(plan.trends)));
|
|
15316
16496
|
if (confirmedLines.length > 0)
|
|
15317
16497
|
lines.push("", ...confirmedLines);
|
|
15318
16498
|
}
|
|
15319
16499
|
else {
|
|
15320
16500
|
lines.push(markdown
|
|
15321
|
-
? `## Setup Score ${plan.cave_score.score} —
|
|
16501
|
+
? `## Setup Score ${plan.cave_score.score}/100 — an estimate from your local sessions, not your bill`
|
|
15322
16502
|
: verbose
|
|
15323
|
-
? `Setup Score ${plan.cave_score.score} ·
|
|
16503
|
+
? `Setup Score ${plan.cave_score.score}/100 · an estimate from your local sessions, not your bill`
|
|
15324
16504
|
: `Setup Score ${plan.cave_score.score}/100`);
|
|
15325
16505
|
if (verbose) {
|
|
15326
|
-
lines.push("scores your
|
|
15327
|
-
lines.push("the two
|
|
15328
|
-
lines.push(
|
|
16506
|
+
lines.push("scores your agent setup on this computer. Caveman Cloud's team score measures your team's traffic;");
|
|
16507
|
+
lines.push("the two use different scales and will not match");
|
|
16508
|
+
lines.push(learnSourceLine(plan, sessions));
|
|
15329
16509
|
}
|
|
15330
16510
|
else {
|
|
15331
|
-
lines.push(
|
|
16511
|
+
lines.push(LEARN_SCORE_SCOPE);
|
|
15332
16512
|
lines.push(learnSourceLine(plan, sessions));
|
|
15333
16513
|
}
|
|
15334
16514
|
const diffText = learnDiffText(options.diff);
|
|
15335
16515
|
if (diffText)
|
|
15336
16516
|
lines.push(diffText);
|
|
15337
|
-
|
|
16517
|
+
lines.push(...(verbose ? [] : learnTrendLines(plan.trends)));
|
|
16518
|
+
const spendLines = renderLearnSpendLines(plan.spend, markdown, verbose);
|
|
15338
16519
|
if (spendLines.length > 0)
|
|
15339
16520
|
lines.push("", ...spendLines);
|
|
15340
16521
|
if (confirmedLines.length > 0)
|
|
15341
16522
|
lines.push("", ...confirmedLines);
|
|
15342
16523
|
if (verbose) {
|
|
16524
|
+
const trendTable = learnTrendTable(plan.trends, markdown);
|
|
16525
|
+
if (trendTable.length > 0)
|
|
16526
|
+
lines.push("", ...trendTable);
|
|
15343
16527
|
lines.push("", ...renderLearnDetailedRows(plan, markdown), "", LEARN_DETAILED_NEXT);
|
|
15344
16528
|
}
|
|
15345
16529
|
else {
|
|
15346
16530
|
const protectedSink = plan.sinks.find((sink) => sink.class === "load_bearing");
|
|
15347
|
-
lines.push("", "top
|
|
15348
|
-
if (protectedSink)
|
|
15349
|
-
|
|
15350
|
-
|
|
15351
|
-
|
|
15352
|
-
|
|
16531
|
+
lines.push("", "top findings", ...renderLearnSummaryRows(plan));
|
|
16532
|
+
if (protectedSink)
|
|
16533
|
+
lines.push(`needed ${learnProtectedText(protectedSink)}`);
|
|
16534
|
+
const memory = learnMemoryHealthLine(plan);
|
|
16535
|
+
if (memory)
|
|
16536
|
+
lines.push(memory);
|
|
16537
|
+
lines.push("", `next: ${invokedAs()} learn implement fix with Claude Code or Codex; asks before every edit`, `details: ${invokedAs()} learn --all all ${plan.sinks.length} findings`);
|
|
15353
16538
|
}
|
|
15354
16539
|
}
|
|
15355
16540
|
if (options.all === true && (plan.repos?.length ?? 0) > 0) {
|
|
15356
|
-
lines.push("", markdown ? "### Per
|
|
16541
|
+
lines.push("", markdown ? "### Per repository" : "per repository", ...renderLearnRepos(plan.repos, markdown));
|
|
15357
16542
|
}
|
|
15358
16543
|
if (options.all === true) {
|
|
15359
16544
|
lines.push("", ...(markdown ? ["### Advanced", ...LEARN_ALL_FOOTER.map((line) => `- ${line}`)] : LEARN_ALL_FOOTER));
|
|
@@ -15370,9 +16555,9 @@ function learnMeasureValue(value) {
|
|
|
15370
16555
|
}
|
|
15371
16556
|
function learnMeasureUnit(unit) {
|
|
15372
16557
|
const labels = {
|
|
15373
|
-
config_tokens_per_turn: "
|
|
15374
|
-
turns_over_half_window_pct: "
|
|
15375
|
-
recurrence_present: "
|
|
16558
|
+
config_tokens_per_turn: "setup tokens per message",
|
|
16559
|
+
turns_over_half_window_pct: "% of messages past half the window",
|
|
16560
|
+
recurrence_present: "repeated text still present",
|
|
15376
16561
|
};
|
|
15377
16562
|
return labels[unit] ?? unit.replaceAll("_", " ");
|
|
15378
16563
|
}
|
|
@@ -15391,7 +16576,7 @@ function renderLearnConfirmed(confirmed, markdown) {
|
|
|
15391
16576
|
const rows = confirmed.flatMap((entry) => {
|
|
15392
16577
|
const applied = learnAppliedDate(entry.applied_at);
|
|
15393
16578
|
if (entry.verdict === "insufficient_data") {
|
|
15394
|
-
const line = `${symbols[entry.verdict]} ${entry.sink_id} — applied ${applied} · needs more
|
|
16579
|
+
const line = `${symbols[entry.verdict]} ${entry.sink_id} — applied ${applied} · needs more sessions after the fix (${entry.sessions_after} so far)`;
|
|
15395
16580
|
return [markdown ? `- *${line}*` : line];
|
|
15396
16581
|
}
|
|
15397
16582
|
if (entry.after === undefined || !Number.isFinite(entry.after))
|
|
@@ -15399,17 +16584,17 @@ function renderLearnConfirmed(confirmed, markdown) {
|
|
|
15399
16584
|
// How it was measured travels with the number. A confirmed row without its
|
|
15400
16585
|
// attribution reads as stronger evidence than it is.
|
|
15401
16586
|
const attribution = entry.attribution
|
|
15402
|
-
? ` · ${entry.attribution.method} (${entry.attribution.confidence}${entry.attribution.provenance === "intact" ? "" : `, ${entry.attribution.provenance}`})`
|
|
16587
|
+
? ` · ${learnMethodLabel(entry.attribution.method)} (${entry.attribution.confidence}${entry.attribution.provenance === "intact" ? "" : `, ${learnProvenanceLabel(entry.attribution.provenance)}`})`
|
|
15403
16588
|
: "";
|
|
15404
16589
|
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}${attribution}`;
|
|
15405
16590
|
return [markdown ? `- ${line}` : line];
|
|
15406
16591
|
});
|
|
15407
16592
|
if (rows.length === 0)
|
|
15408
16593
|
return [];
|
|
15409
|
-
return [markdown ? "###
|
|
16594
|
+
return [markdown ? "### Fixes you applied" : "fixes you applied", ...rows];
|
|
15410
16595
|
}
|
|
15411
16596
|
function renderLearnRepos(repos, markdown) {
|
|
15412
|
-
return repos.map((repo) => `${markdown ? "- " : ""}${repo.repo} · ${repo.sessions} sessions ·
|
|
16597
|
+
return repos.map((repo) => `${markdown ? "- " : ""}${repo.repo} · ${commaCount(repo.sessions)} sessions · ${repo.dumbzone_pct}% of messages past half the window · typical message ~${humanTokens(repo.median_context)} tokens`);
|
|
15413
16598
|
}
|
|
15414
16599
|
function readLearnDiff(current) {
|
|
15415
16600
|
const dir = join(cavemanHome(), "reports");
|
|
@@ -15482,7 +16667,7 @@ function proxyExecLearn(proxyArgs, progress) {
|
|
|
15482
16667
|
catch (error) {
|
|
15483
16668
|
const e = error;
|
|
15484
16669
|
if (e.code === "ETIMEDOUT" || (e.killed && e.code !== "ENOBUFS")) {
|
|
15485
|
-
console.error(`learn scan timed out after ${seconds}s
|
|
16670
|
+
console.error(`learn scan timed out after ${seconds}s, so there is no score; run \`caveman learn --json\` to capture the raw scan`);
|
|
15486
16671
|
process.exit(1);
|
|
15487
16672
|
}
|
|
15488
16673
|
if (e.stderr)
|
|
@@ -15532,7 +16717,7 @@ function proxyExecLearnAsync(proxyArgs, onProgress) {
|
|
|
15532
16717
|
child.once("close", (code) => {
|
|
15533
16718
|
clearTimeout(timer);
|
|
15534
16719
|
if (timedOut) {
|
|
15535
|
-
reject(new Error(`learn scan timed out after ${seconds}s
|
|
16720
|
+
reject(new Error(`learn scan timed out after ${seconds}s, so there is no score; run \`caveman learn --json\` to capture the raw scan`));
|
|
15536
16721
|
return;
|
|
15537
16722
|
}
|
|
15538
16723
|
if (code !== 0) {
|
|
@@ -15584,24 +16769,24 @@ function renderLearnApply(raw, dryRun) {
|
|
|
15584
16769
|
const candidate = (raw.candidate && typeof raw.candidate === "object" ? raw.candidate : {});
|
|
15585
16770
|
const klass = String(raw.class ?? candidate.class ?? "");
|
|
15586
16771
|
if (klass === "behavioral" || klass === "load_bearing") {
|
|
15587
|
-
return "
|
|
16772
|
+
return "this is a habit or a needed part of your setup — there is no automatic fix; the caveman-learn skill can turn it into a reminder, with your yes\n";
|
|
15588
16773
|
}
|
|
15589
16774
|
const lines = [
|
|
15590
16775
|
String(candidate.title ?? raw.sink_id ?? "learn candidate"),
|
|
15591
|
-
`
|
|
16776
|
+
`id: ${String(raw.sink_id ?? candidate.sink_id ?? "")}`,
|
|
15592
16777
|
];
|
|
15593
16778
|
const locations = candidate.what_to_offload?.locators ?? candidate.evidence?.locators;
|
|
15594
16779
|
if (locations)
|
|
15595
16780
|
lines.push(`locations: ${JSON.stringify(locations)}`);
|
|
15596
16781
|
if (candidate.expected_tokens_per_turn_saved != null) {
|
|
15597
|
-
lines.push(`expected: ~${humanTokens(Number(candidate.expected_tokens_per_turn_saved))} tokens
|
|
16782
|
+
lines.push(`expected: ~${humanTokens(Number(candidate.expected_tokens_per_turn_saved))} fewer tokens in every message`);
|
|
15598
16783
|
}
|
|
15599
|
-
lines.push("
|
|
16784
|
+
lines.push("applies only if: it uses fewer tokens overall · and answers don't get worse");
|
|
15600
16785
|
if (dryRun)
|
|
15601
16786
|
lines.push("nothing changed — this is a preview");
|
|
15602
16787
|
else {
|
|
15603
16788
|
lines.push(`prepared, not applied — ${String(raw.candidate_path ?? join(cavemanHome(), "candidates", `learn-${raw.sink_id}.json`))}`);
|
|
15604
|
-
lines.push("
|
|
16789
|
+
lines.push("to apply it, use the caveman-learn skill: caveman tools skills install caveman-learn");
|
|
15605
16790
|
}
|
|
15606
16791
|
return `${lines.join("\n")}\n`;
|
|
15607
16792
|
}
|
|
@@ -15615,7 +16800,7 @@ export function renderLearnSavings(raw) {
|
|
|
15615
16800
|
const out = [];
|
|
15616
16801
|
if (rows.length === 0) {
|
|
15617
16802
|
out.push("no fix recorded yet");
|
|
15618
|
-
out.push("apply one
|
|
16803
|
+
out.push("apply one with the caveman-learn skill and it shows up here, with how it was measured");
|
|
15619
16804
|
for (const caveat of (raw.caveats ?? []))
|
|
15620
16805
|
out.push(dim(`· ${caveat}`));
|
|
15621
16806
|
return `${out.join("\n")}\n`;
|
|
@@ -15631,8 +16816,8 @@ export function renderLearnSavings(raw) {
|
|
|
15631
16816
|
for (const [method, group] of grouped) {
|
|
15632
16817
|
const total = byRung?.[method];
|
|
15633
16818
|
const head = total != null && currency
|
|
15634
|
-
? `${method} ${fmtMoney(total, currency)}/day`
|
|
15635
|
-
: method;
|
|
16819
|
+
? `${learnMethodLabel(method)} ${fmtMoney(total, currency)}/day`
|
|
16820
|
+
: learnMethodLabel(method);
|
|
15636
16821
|
out.push(bold(head));
|
|
15637
16822
|
for (const row of group) {
|
|
15638
16823
|
const verdict = String(row.verdict ?? "");
|
|
@@ -15642,7 +16827,7 @@ export function renderLearnSavings(raw) {
|
|
|
15642
16827
|
: verdict;
|
|
15643
16828
|
const money = row.saved_usd != null && currency ? ` ${fmtMoney(Number(row.saved_usd), currency)}/day` : "";
|
|
15644
16829
|
out.push(` ${badge} ${String(row.sink_id ?? "")} ${saved}${money}`);
|
|
15645
|
-
out.push(dim(` ${String(row.attribution?.provenance ?? "")} · confidence ${String(row.attribution?.confidence ?? "")}`));
|
|
16830
|
+
out.push(dim(` ${learnProvenanceLabel(String(row.attribution?.provenance ?? ""))} · confidence ${String(row.attribution?.confidence ?? "")}`));
|
|
15646
16831
|
for (const confounder of (row.attribution?.confounders ?? [])) {
|
|
15647
16832
|
out.push(dim(` · ${confounder}`));
|
|
15648
16833
|
}
|
|
@@ -15653,6 +16838,27 @@ export function renderLearnSavings(raw) {
|
|
|
15653
16838
|
out.push(dim(`· ${caveat}`));
|
|
15654
16839
|
return `${out.join("\n")}\n`;
|
|
15655
16840
|
}
|
|
16841
|
+
// Plain names for attribution methods and provenance; the enums stay in JSON.
|
|
16842
|
+
const LEARN_METHOD_LABELS = {
|
|
16843
|
+
deterministic_remeasure: "re-counted the edited file",
|
|
16844
|
+
counterfactual_replay: "replayed past sessions",
|
|
16845
|
+
controlled_holdout: "on/off experiment",
|
|
16846
|
+
interrupted_time_series: "before vs after",
|
|
16847
|
+
unattributed: "not measured yet",
|
|
16848
|
+
};
|
|
16849
|
+
const LEARN_PROVENANCE_LABELS = {
|
|
16850
|
+
intact: "fix still in place",
|
|
16851
|
+
changed_since: "file changed since the fix",
|
|
16852
|
+
target_missing: "file is gone",
|
|
16853
|
+
not_fingerprinted: "can't confirm the fix is still there",
|
|
16854
|
+
not_applicable: "",
|
|
16855
|
+
};
|
|
16856
|
+
function learnMethodLabel(method) {
|
|
16857
|
+
return LEARN_METHOD_LABELS[method] ?? method.replaceAll("_", " ");
|
|
16858
|
+
}
|
|
16859
|
+
function learnProvenanceLabel(provenance) {
|
|
16860
|
+
return LEARN_PROVENANCE_LABELS[provenance] ?? provenance.replaceAll("_", " ");
|
|
16861
|
+
}
|
|
15656
16862
|
// fmtMoney keeps sub-cent figures legible instead of rounding real spend to
|
|
15657
16863
|
// $0.00, which reads as "nothing" when it is not.
|
|
15658
16864
|
export function fmtMoney(value, currency) {
|
|
@@ -15660,7 +16866,7 @@ export function fmtMoney(value, currency) {
|
|
|
15660
16866
|
if (!Number.isFinite(value))
|
|
15661
16867
|
return `${symbol}0`;
|
|
15662
16868
|
if (Math.abs(value) >= 1)
|
|
15663
|
-
return `${symbol}${value.
|
|
16869
|
+
return `${symbol}${value.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
|
|
15664
16870
|
if (Math.abs(value) >= 0.01)
|
|
15665
16871
|
return `${symbol}${value.toFixed(3)}`;
|
|
15666
16872
|
return `${symbol}${value.toFixed(5)}`;
|
|
@@ -15672,11 +16878,11 @@ export function renderExperimentReport(raw) {
|
|
|
15672
16878
|
const arms = Array.isArray(raw.arms) ? raw.arms : [];
|
|
15673
16879
|
const out = [bold(`experiment ${String(raw.label ?? "")}`)];
|
|
15674
16880
|
if (raw.sink_id)
|
|
15675
|
-
out.push(dim(`
|
|
16881
|
+
out.push(dim(`id ${String(raw.sink_id)} · ${String(raw.fix_kind ?? "")}`));
|
|
15676
16882
|
for (const arm of arms) {
|
|
15677
|
-
out.push(` ${String(arm.arm).padEnd(4)} ${arm.sessions} sessions
|
|
16883
|
+
out.push(` ${String(arm.arm).padEnd(4)} ${arm.sessions} sessions typical session ${humanTokens(Number(arm.median_session_tokens ?? 0))} tokens ${Number(arm.error_turns_per_turn ?? 0).toFixed(2)} errors per message`);
|
|
15678
16884
|
}
|
|
15679
|
-
const verdict = String(raw.verdict ?? "insufficient_data");
|
|
16885
|
+
const verdict = String(raw.verdict ?? "insufficient_data").replace("insufficient_data", "not enough data yet");
|
|
15680
16886
|
const badge = verdict === "improved" ? green("✓") : verdict === "regressed" ? red("✗") : yellow("~");
|
|
15681
16887
|
const delta = raw.median_session_tokens_delta_pct != null
|
|
15682
16888
|
? ` ${Number(raw.median_session_tokens_delta_pct) > 0 ? "+" : ""}${Number(raw.median_session_tokens_delta_pct).toFixed(1)}%`
|
|
@@ -15686,7 +16892,7 @@ export function renderExperimentReport(raw) {
|
|
|
15686
16892
|
: "";
|
|
15687
16893
|
out.push(` ${badge} ${verdict}${delta}${money}`);
|
|
15688
16894
|
if (raw.attribution?.method) {
|
|
15689
|
-
out.push(dim(` ${String(raw.attribution.method)} · confidence ${String(raw.attribution.confidence ?? "")}`));
|
|
16895
|
+
out.push(dim(` ${learnMethodLabel(String(raw.attribution.method))} · confidence ${String(raw.attribution.confidence ?? "")}`));
|
|
15690
16896
|
for (const confounder of (raw.attribution.confounders ?? []))
|
|
15691
16897
|
out.push(dim(` · ${confounder}`));
|
|
15692
16898
|
}
|
|
@@ -15694,36 +16900,83 @@ export function renderExperimentReport(raw) {
|
|
|
15694
16900
|
out.push(dim(` · ${caveat}`));
|
|
15695
16901
|
return `${out.join("\n")}\n`;
|
|
15696
16902
|
}
|
|
16903
|
+
// renderExperiments prints start/arm/stop (one experiment) or list (many):
|
|
16904
|
+
// label, state, and the arm currently running.
|
|
16905
|
+
export function renderExperiments(raw) {
|
|
16906
|
+
const experiments = Array.isArray(raw) ? raw : [raw];
|
|
16907
|
+
if (experiments.length === 0)
|
|
16908
|
+
return "no experiments yet — start one: caveman learn experiment start <label>\n";
|
|
16909
|
+
return experiments.map((exp) => {
|
|
16910
|
+
const arms = Array.isArray(exp.arms) ? exp.arms : [];
|
|
16911
|
+
const open = arms.find((arm) => !arm.ended_at);
|
|
16912
|
+
const state = exp.stopped_at ? "stopped" : open ? `${String(open.arm)} since ${String(open.started_at)}` : "paused";
|
|
16913
|
+
const sink = exp.sink_id ? dim(` id ${String(exp.sink_id)}${exp.fix_kind ? ` · ${String(exp.fix_kind)}` : ""}`) : "";
|
|
16914
|
+
return `${bold(String(exp.label ?? ""))} ${state} ${arms.length} on/off period${arms.length === 1 ? "" : "s"}${sink}\n`;
|
|
16915
|
+
}).join("");
|
|
16916
|
+
}
|
|
16917
|
+
// renderLearnDigest names the file to inspect; the digest itself is the file.
|
|
16918
|
+
export function renderLearnDigest(raw) {
|
|
16919
|
+
return `digest written: ${String(raw.path ?? "")}\n${dim(String(raw.summary ?? ""))}\ninspect it before sharing; --json prints it\n`;
|
|
16920
|
+
}
|
|
16921
|
+
// renderLearnReconcile prints measured vs billed per model. Coverage is a token
|
|
16922
|
+
// comparison, never a savings claim, so there is no money column.
|
|
16923
|
+
export function renderLearnReconcile(raw) {
|
|
16924
|
+
const rows = Array.isArray(raw.models) ? raw.models : [];
|
|
16925
|
+
const out = [bold(`reconcile ${Number(raw.coverage_pct ?? 0).toFixed(1)}% of billed tokens seen locally`)];
|
|
16926
|
+
for (const row of rows) {
|
|
16927
|
+
out.push(` ${String(row.model ?? "")} billed ${humanTokens(Number(row.billed_tokens ?? 0))} measured ${humanTokens(Number(row.measured_tokens ?? 0))} ${Number(row.coverage_pct ?? 0).toFixed(1)}%`);
|
|
16928
|
+
}
|
|
16929
|
+
out.push(` billed but not seen here ${humanTokens(Number(raw.unattributed_tokens ?? 0))} tokens`);
|
|
16930
|
+
for (const caveat of (raw.caveats ?? []))
|
|
16931
|
+
out.push(dim(` · ${caveat}`));
|
|
16932
|
+
return `${out.join("\n")}\n`;
|
|
16933
|
+
}
|
|
15697
16934
|
function learnUsage() {
|
|
15698
16935
|
console.log(`${invokedAs()} learn [--all|--plain|--json|--md] [--since 30d] [--sources claude,codex,gemini,opencode,aider]
|
|
15699
|
-
|
|
15700
|
-
|
|
15701
|
-
--
|
|
15702
|
-
--
|
|
16936
|
+
shows where your agent's tokens go, and what to fix first
|
|
16937
|
+
default interactive Setup Score + top findings
|
|
16938
|
+
--plain short text; no animation or keyboard menu
|
|
16939
|
+
--all every finding, with its id and suggested fix
|
|
16940
|
+
--json|--md output for tools, or a full Markdown report
|
|
15703
16941
|
implement open Claude Code or Codex to review and fix findings
|
|
15704
|
-
apply prepare one
|
|
16942
|
+
apply prepare one fix; nothing changes without your yes
|
|
16943
|
+
autopilot [status|on|off] refresh the report after sessions end
|
|
15705
16944
|
|
|
15706
|
-
savings what applied
|
|
15707
|
-
experiment
|
|
16945
|
+
savings what fixes you applied saved, grouped by how it was measured
|
|
16946
|
+
experiment test a change by switching it on and off across your own sessions
|
|
15708
16947
|
start <label> [--sink <id>] · arm <label> on|off · report <label>
|
|
15709
16948
|
· list · stop <label>
|
|
15710
|
-
export privacy-safe
|
|
16949
|
+
export a privacy-safe summary of findings (names and sizes only)
|
|
15711
16950
|
reconcile --usage-export <csv>
|
|
15712
|
-
compare what
|
|
16951
|
+
compare what Caveman measured with what your provider billed
|
|
15713
16952
|
|
|
15714
16953
|
advanced:
|
|
15715
|
-
applied <
|
|
15716
|
-
record
|
|
15717
|
-
simulate <
|
|
15718
|
-
|
|
16954
|
+
applied <id> [--fix-kind <kind>] [--note <text>]
|
|
16955
|
+
record a fix you approved, so later runs can measure it
|
|
16956
|
+
simulate <id...>
|
|
16957
|
+
estimate what fixes would have saved over your past sessions
|
|
15719
16958
|
--repo <substring>
|
|
15720
|
-
|
|
16959
|
+
only read sessions from matching repositories`);
|
|
16960
|
+
}
|
|
16961
|
+
// learnAutopilot: status/on/off for the SessionEnd background refresh. `run`
|
|
16962
|
+
// is the detached child the native hook spawns (see learn-autopilot.ts).
|
|
16963
|
+
function learnAutopilot(rest) {
|
|
16964
|
+
const sub = rest[0] ?? "status";
|
|
16965
|
+
if (sub === "run") {
|
|
16966
|
+
process.exitCode = runAutopilot(proxyBin());
|
|
16967
|
+
return;
|
|
16968
|
+
}
|
|
16969
|
+
if (sub === "on" || sub === "off")
|
|
16970
|
+
mutateRawConfig((out) => { out.learnAutopilot = sub === "on"; });
|
|
16971
|
+
else if (sub !== "status")
|
|
16972
|
+
return commandUsage("learn autopilot [status|on|off]");
|
|
16973
|
+
process.stdout.write(autopilotStatusText());
|
|
15721
16974
|
}
|
|
15722
16975
|
function learnImplementUsage() {
|
|
15723
16976
|
console.log(`${invokedAs()} learn implement [claude|codex] [--prompt "<focus>"]
|
|
15724
16977
|
opens an interactive agent with the current local learn report
|
|
15725
16978
|
installs the caveman-learn safety guide when missing
|
|
15726
|
-
never edits
|
|
16979
|
+
never edits findings marked needed; asks before every edit`);
|
|
15727
16980
|
}
|
|
15728
16981
|
function learnImplementPrompt(focus) {
|
|
15729
16982
|
const lines = [
|
|
@@ -15731,7 +16984,7 @@ function learnImplementPrompt(focus) {
|
|
|
15731
16984
|
"Run `caveman learn report --json`; if no current report exists, run `caveman learn --json` once and retry. Then present a short list of actionable findings.",
|
|
15732
16985
|
"Work through selected fixes one at a time. Never edit load_bearing findings.",
|
|
15733
16986
|
"Show the proposed diff and before → after token count, ask before every edit, apply only approved changes, then verify the reduction and any recall path.",
|
|
15734
|
-
"Keep every local savings claim labeled inferred and never
|
|
16987
|
+
"Keep every local savings claim labeled inferred. Attach currency only where the report itself carries it (the spend block and priced savings rows), with that block's framing: window-bounded, never projected, never verified.",
|
|
15735
16988
|
];
|
|
15736
16989
|
if (focus)
|
|
15737
16990
|
lines.push(`User focus: ${focus}`);
|
|
@@ -15740,7 +16993,7 @@ function learnImplementPrompt(focus) {
|
|
|
15740
16993
|
function ensureLearnAgentGuide(agent) {
|
|
15741
16994
|
const path = agent.id === "claude"
|
|
15742
16995
|
? join(process.cwd(), ".claude", "skills", "caveman-learn", "SKILL.md")
|
|
15743
|
-
: join(
|
|
16996
|
+
: join(codexHomeDir(), "skills", "caveman-learn", "SKILL.md");
|
|
15744
16997
|
try {
|
|
15745
16998
|
readFileSync(path);
|
|
15746
16999
|
return "";
|
|
@@ -15830,20 +17083,20 @@ async function learn(rest) {
|
|
|
15830
17083
|
return learnUsage();
|
|
15831
17084
|
if (sub === "implement")
|
|
15832
17085
|
return learnImplement(rest.slice(1));
|
|
15833
|
-
if (sub === "
|
|
15834
|
-
|
|
15835
|
-
|
|
15836
|
-
// reconciliation is a table, not a headline.
|
|
15837
|
-
process.stdout.write(formatLearnProxyJSON(proxyExecLearn(["learn", ...rest], false)));
|
|
15838
|
-
return;
|
|
15839
|
-
}
|
|
15840
|
-
if (sub === "experiment") {
|
|
17086
|
+
if (sub === "autopilot")
|
|
17087
|
+
return learnAutopilot(rest.slice(1));
|
|
17088
|
+
if (sub === "export" || sub === "reconcile" || sub === "experiment") {
|
|
15841
17089
|
const rawText = proxyExecLearn(["learn", ...rest], false);
|
|
15842
|
-
if (rest.includes("--json")
|
|
17090
|
+
if (rest.includes("--json")) {
|
|
15843
17091
|
process.stdout.write(formatLearnProxyJSON(rawText));
|
|
15844
17092
|
return;
|
|
15845
17093
|
}
|
|
15846
|
-
|
|
17094
|
+
const parsed = JSON.parse(rawText);
|
|
17095
|
+
const render = sub === "export" ? renderLearnDigest
|
|
17096
|
+
: sub === "reconcile" ? renderLearnReconcile
|
|
17097
|
+
: rest[1] === "report" ? renderExperimentReport
|
|
17098
|
+
: renderExperiments;
|
|
17099
|
+
process.stdout.write(render(parsed));
|
|
15847
17100
|
return;
|
|
15848
17101
|
}
|
|
15849
17102
|
if (sub === "savings") {
|
|
@@ -15885,7 +17138,13 @@ async function learn(rest) {
|
|
|
15885
17138
|
if (tui) {
|
|
15886
17139
|
const learnTui = await import("./learn-tui.js");
|
|
15887
17140
|
const progress = learnTui.createLearnProgress();
|
|
15888
|
-
|
|
17141
|
+
const flag = (name) => {
|
|
17142
|
+
const at = forwarded.findIndex((arg) => arg === name || arg.startsWith(`${name}=`));
|
|
17143
|
+
if (at < 0)
|
|
17144
|
+
return undefined;
|
|
17145
|
+
return forwarded[at].includes("=") ? forwarded[at].split("=")[1] : forwarded[at + 1];
|
|
17146
|
+
};
|
|
17147
|
+
progress.start(`Reading ${flag("--sources") ?? "local agent"} sessions from the last ${flag("--since") ?? "30d"}`);
|
|
15889
17148
|
try {
|
|
15890
17149
|
const scanRaw = await proxyExecLearnAsync(["learn", "scan", "--write-report", "--write-report-token", reportToken, ...forwarded], progress.update);
|
|
15891
17150
|
// Pre-bundled proxies ignore unknown flags. Fall back once when report
|
|
@@ -16421,6 +17680,9 @@ function readRawProxyRunState(port) {
|
|
|
16421
17680
|
...(typeof parsed.started_at === "string" ? { started_at: parsed.started_at } : {}),
|
|
16422
17681
|
...(typeof parsed.version === "string" ? { version: parsed.version } : {}),
|
|
16423
17682
|
...(typeof parsed.recovery_via_mcp === "boolean" ? { recovery_via_mcp: parsed.recovery_via_mcp } : {}),
|
|
17683
|
+
provider_upstreams: publishedUpstreamsOf(parsed.provider_upstreams),
|
|
17684
|
+
compat_upstreams: publishedUpstreamsOf(parsed.compat_upstreams),
|
|
17685
|
+
compat_forward_headers: publishedForwardHeadersOf(parsed.compat_forward_headers),
|
|
16424
17686
|
};
|
|
16425
17687
|
}
|
|
16426
17688
|
catch {
|
|
@@ -16437,6 +17699,7 @@ function processAlive(pid) {
|
|
|
16437
17699
|
}
|
|
16438
17700
|
}
|
|
16439
17701
|
function createProxySessionMarker(port) {
|
|
17702
|
+
pruneDeadProxySessionMarkers(port);
|
|
16440
17703
|
const dir = proxySessionDir(port);
|
|
16441
17704
|
try {
|
|
16442
17705
|
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
@@ -16458,51 +17721,40 @@ function createProxySessionMarker(port) {
|
|
|
16458
17721
|
}
|
|
16459
17722
|
return null;
|
|
16460
17723
|
}
|
|
16461
|
-
|
|
16462
|
-
|
|
16463
|
-
|
|
16464
|
-
try {
|
|
16465
|
-
unlinkSync(marker);
|
|
16466
|
-
}
|
|
16467
|
-
catch (error) {
|
|
16468
|
-
if (error.code !== "ENOENT") {
|
|
16469
|
-
// Marker cleanup is best-effort; the next reader prunes a dead owner.
|
|
16470
|
-
}
|
|
16471
|
-
}
|
|
16472
|
-
}
|
|
16473
|
-
function countOtherLiveProxySessions(port, ownMarker) {
|
|
17724
|
+
// pruneDeadProxySessionMarkers removes markers whose owner died. Their absence
|
|
17725
|
+
// never authorizes a restart, so nothing reads the surviving count.
|
|
17726
|
+
function pruneDeadProxySessionMarkers(port) {
|
|
16474
17727
|
let names;
|
|
16475
17728
|
try {
|
|
16476
17729
|
names = readdirSync(proxySessionDir(port));
|
|
16477
17730
|
}
|
|
16478
17731
|
catch {
|
|
16479
|
-
return
|
|
17732
|
+
return;
|
|
16480
17733
|
}
|
|
16481
|
-
let live = 0;
|
|
16482
17734
|
for (const name of names) {
|
|
16483
|
-
const marker = join(proxySessionDir(port), name);
|
|
16484
|
-
if (ownMarker && marker === ownMarker)
|
|
16485
|
-
continue;
|
|
16486
17735
|
const match = /^(\d+)-/.exec(name);
|
|
16487
17736
|
const pid = match ? Number(match[1]) : NaN;
|
|
16488
|
-
if (
|
|
16489
|
-
try {
|
|
16490
|
-
unlinkSync(marker);
|
|
16491
|
-
}
|
|
16492
|
-
catch {
|
|
16493
|
-
// Concurrent cleanup or a read-only directory: neither upgrades ownership.
|
|
16494
|
-
}
|
|
17737
|
+
if (Number.isSafeInteger(pid) && pid > 0 && processAlive(pid))
|
|
16495
17738
|
continue;
|
|
17739
|
+
try {
|
|
17740
|
+
unlinkSync(join(proxySessionDir(port), name));
|
|
17741
|
+
}
|
|
17742
|
+
catch {
|
|
17743
|
+
// Concurrent cleanup or a read-only directory: neither upgrades ownership.
|
|
16496
17744
|
}
|
|
16497
|
-
live++;
|
|
16498
17745
|
}
|
|
16499
|
-
return live;
|
|
16500
17746
|
}
|
|
16501
|
-
function
|
|
16502
|
-
|
|
16503
|
-
|
|
16504
|
-
|
|
16505
|
-
|
|
17747
|
+
function removeProxySessionMarker(marker) {
|
|
17748
|
+
if (!marker)
|
|
17749
|
+
return;
|
|
17750
|
+
try {
|
|
17751
|
+
unlinkSync(marker);
|
|
17752
|
+
}
|
|
17753
|
+
catch (error) {
|
|
17754
|
+
if (error.code !== "ENOENT") {
|
|
17755
|
+
// Marker cleanup is best-effort; the next reader prunes a dead owner.
|
|
17756
|
+
}
|
|
17757
|
+
}
|
|
16506
17758
|
}
|
|
16507
17759
|
function probeProxyVersion() {
|
|
16508
17760
|
const binary = resolveGoBin("caveman-proxy", "CAVEMAN_PROXY_BIN");
|
|
@@ -16552,6 +17804,9 @@ function readProxyRuntimeState(port, versionInfo) {
|
|
|
16552
17804
|
...(typeof parsed.started_at === "string" ? { started_at: parsed.started_at } : {}),
|
|
16553
17805
|
...(typeof parsed.version === "string" ? { version: parsed.version } : {}),
|
|
16554
17806
|
...(typeof parsed.recovery_via_mcp === "boolean" ? { recovery_via_mcp: parsed.recovery_via_mcp } : {}),
|
|
17807
|
+
provider_upstreams: publishedUpstreamsOf(parsed.provider_upstreams),
|
|
17808
|
+
compat_upstreams: publishedUpstreamsOf(parsed.compat_upstreams),
|
|
17809
|
+
compat_forward_headers: publishedForwardHeadersOf(parsed.compat_forward_headers),
|
|
16555
17810
|
};
|
|
16556
17811
|
}
|
|
16557
17812
|
catch {
|
|
@@ -16671,7 +17926,7 @@ export function renderStatus(view) {
|
|
|
16671
17926
|
lines.push(statusRow("plan", `${String(view.plan.plan)} · ${humanTokens(Number(view.plan.used))} of ${humanTokens(Number(view.plan.allowance))} optimized tokens this week · resets Mon 00:00 UTC · connected traffic only`));
|
|
16672
17927
|
}
|
|
16673
17928
|
lines.push(statusRow("config", `think: ${view.config_sources.think} · remember: ${view.config_sources.remember} · execute: ${view.config_sources.execute}`));
|
|
16674
|
-
lines.push(statusRow("telemetry", `${view.telemetry.state} ·
|
|
17929
|
+
lines.push(statusRow("telemetry", `${view.telemetry.state} · usage ping · change: ${view.telemetry.change}`));
|
|
16675
17930
|
if (view.next)
|
|
16676
17931
|
lines.push("", `next: ${view.next}`);
|
|
16677
17932
|
return `${lines.join("\n")}\n`;
|
|
@@ -16740,7 +17995,7 @@ async function status(argv) {
|
|
|
16740
17995
|
const plan = entitlement && allowance !== null && entitlement.optimized_tokens_week !== undefined
|
|
16741
17996
|
? { plan: entitlement.plan, used: entitlement.optimized_tokens_week, allowance }
|
|
16742
17997
|
: null;
|
|
16743
|
-
const telemetry =
|
|
17998
|
+
const telemetry = sessionTelemetryState();
|
|
16744
17999
|
const view = {
|
|
16745
18000
|
mode: runningMode ?? resolvedMode,
|
|
16746
18001
|
mode_source: runningMode ? "running" : "resolved",
|
|
@@ -17628,7 +18883,7 @@ function renderRecipe(recipe, baseURL, app) {
|
|
|
17628
18883
|
}
|
|
17629
18884
|
function renderRecipeTemplate(value, baseURL, app) {
|
|
17630
18885
|
return value
|
|
17631
|
-
.replaceAll("{{baseURL}}", baseURL
|
|
18886
|
+
.replaceAll("{{baseURL}}", trimTrailingSlashes(baseURL))
|
|
17632
18887
|
.replaceAll("{{app}}", app);
|
|
17633
18888
|
}
|
|
17634
18889
|
function recipeCommentPrefix(lang) {
|
|
@@ -17821,12 +19076,11 @@ async function readRawConfig() {
|
|
|
17821
19076
|
}
|
|
17822
19077
|
async function writeRawConfig(out) {
|
|
17823
19078
|
await mkdir(dirname(configPath()), { recursive: true });
|
|
17824
|
-
|
|
17825
|
-
|
|
17826
|
-
}
|
|
17827
|
-
|
|
17828
|
-
|
|
17829
|
-
chmodSync(configPath(), 0o600);
|
|
19079
|
+
const target = configWriteTarget();
|
|
19080
|
+
const tmp = `${target}.${process.pid}.tmp`;
|
|
19081
|
+
await writeFile(tmp, JSON.stringify(out, null, 2), { mode: 0o600 });
|
|
19082
|
+
await rename(tmp, target);
|
|
19083
|
+
chmodSync(target, 0o600);
|
|
17830
19084
|
}
|
|
17831
19085
|
async function saveConfig(cfg) {
|
|
17832
19086
|
const out = await readRawConfig();
|
|
@@ -17949,6 +19203,7 @@ async function refreshCLIConfig(cfg) {
|
|
|
17949
19203
|
try {
|
|
17950
19204
|
const response = await fetch(`${cfg.baseURL}/api/v1/auth/refresh`, {
|
|
17951
19205
|
method: "POST",
|
|
19206
|
+
redirect: "manual",
|
|
17952
19207
|
headers: { "content-type": "application/json", "x-cave-client": "cli" },
|
|
17953
19208
|
body: JSON.stringify({ refresh_token: cfg.refreshToken }),
|
|
17954
19209
|
signal: AbortSignal.timeout(5000),
|