@caveman-ai/cli 1.3.4 → 2.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -21
- package/NOTICE +66 -0
- package/README.md +20 -0
- package/dist/agent-skills.generated.js +28 -4
- package/dist/agents.generated.js +26 -26
- package/dist/binaries.generated.js +1 -1
- package/dist/caveman-delegate-mcp.mjs +0 -0
- package/dist/caveman-pi-extension.mjs +79 -14
- package/dist/index.js +1644 -285
- 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 +17 -4
- package/dist/native-pack.generated.js +1 -1
- package/dist/provider-routing.js +9 -2
- package/package.json +12 -12
- package/dist/cloud-client.mjs +0 -22
- package/dist/cloud-mcp.mjs +0 -75
- package/dist/surface.json +0 -299
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { execFileSync, spawn, spawnSync } from "node:child_process";
|
|
3
|
-
import { accessSync, appendFileSync, closeSync, cpSync, existsSync, fchmodSync, fsyncSync, chmodSync, constants, copyFileSync, linkSync, mkdirSync, mkdtempSync, openSync, lstatSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, symlinkSync, unlinkSync, writeFileSync, } from "node:fs";
|
|
3
|
+
import { accessSync, appendFileSync, closeSync, cpSync, existsSync, fchmodSync, fsyncSync, chmodSync, constants, copyFileSync, linkSync, mkdirSync, mkdtempSync, openSync, lstatSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, symlinkSync, unlinkSync, utimesSync, writeFileSync, writeSync, } from "node:fs";
|
|
4
4
|
import { chmod, mkdir, open, readFile, rename, writeFile } from "node:fs/promises";
|
|
5
5
|
import { homedir, hostname, tmpdir, userInfo } from "node:os";
|
|
6
6
|
import { basename, delimiter, dirname, extname, isAbsolute, join, normalize, parse, relative, resolve, sep } from "node:path";
|
|
@@ -11,6 +11,7 @@ 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
16
|
import { installProxyAwareFetch, resolveProxyUrl } from "./proxy-fetch.js";
|
|
16
17
|
import { RECIPES } from "./recipes.generated.js";
|
|
@@ -22,7 +23,8 @@ 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";
|
|
25
|
-
import {
|
|
26
|
+
import { learnTrendLines, learnTrendTable } from "./learn-trends.js";
|
|
27
|
+
import { publishedForwardHeadersOf, publishedUpstreamsOf, trimTrailingSlashes, unforwardedProviderHeaders, verifiedProviderRoute } from "./provider-routing.js";
|
|
26
28
|
import { openClawRequestCompatibilityIssue, preserveOpenClawProviderCompat } from "./openclaw-provider-compat.js";
|
|
27
29
|
import { parseStatsOptions, renderStatsSummary, STATS_HELP, STATS_USAGE } from "./stats-cli.js";
|
|
28
30
|
export const overlayBuilders = {};
|
|
@@ -124,7 +126,7 @@ const CLOUD_DISCOVERY = [
|
|
|
124
126
|
{ heading: "governance", verbs: [
|
|
125
127
|
{ verb: "audit", description: "import or report audit evidence" },
|
|
126
128
|
{ verb: "sync", description: "sync local metadata to connected org" },
|
|
127
|
-
{ verb: "agent", description: "inspect
|
|
129
|
+
{ verb: "agent", description: "inspect agents and optimization proposals" },
|
|
128
130
|
] },
|
|
129
131
|
];
|
|
130
132
|
const TOOL_VERBS = new Set(TOOL_DISCOVERY.flatMap((group) => group.verbs.map((entry) => entry.verb)));
|
|
@@ -233,14 +235,22 @@ const CLOUD_HANDLERS = {
|
|
|
233
235
|
},
|
|
234
236
|
audit,
|
|
235
237
|
sync: () => sync(),
|
|
236
|
-
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
|
+
}
|
|
237
247
|
if (argv[0] === "list")
|
|
238
248
|
return get("/api/v1/optimization-proposals").then(print);
|
|
239
249
|
if (argv[0] === "show")
|
|
240
250
|
return get(`/api/v1/optimization-proposals/${argv[1] ?? ""}`).then(print);
|
|
241
251
|
if (argv[0] === "run")
|
|
242
252
|
return post(`/api/v1/optimization-proposals/${argv[1] ?? ""}/run`, {}).then(print);
|
|
243
|
-
return commandUsage("agent list|show <id>|run <id>");
|
|
253
|
+
return commandUsage("agent list|show <id>|run <id> | agent factory list|show <id>");
|
|
244
254
|
},
|
|
245
255
|
};
|
|
246
256
|
const LEGACY_HANDLERS = {
|
|
@@ -403,18 +413,20 @@ function invokedCommand(legacyVerb, groupedTail = "") {
|
|
|
403
413
|
}
|
|
404
414
|
let currentInvocation;
|
|
405
415
|
currentInvocation = resolveInvocation(process.argv.slice(2));
|
|
406
|
-
// Version
|
|
407
|
-
//
|
|
408
|
-
//
|
|
409
|
-
//
|
|
410
|
-
//
|
|
411
|
-
//
|
|
412
|
-
|
|
413
|
-
const
|
|
414
|
-
//
|
|
415
|
-
|
|
416
|
-
const PROD_API_URL =
|
|
417
|
-
|
|
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";
|
|
418
430
|
// Reading token totals means spawning caveman-proxy to query the local SQLite
|
|
419
431
|
// store. It runs after the command's own work, so the cost lands on process exit;
|
|
420
432
|
// a slow or wedged binary drops the token fields rather than holding the CLI.
|
|
@@ -479,10 +491,25 @@ function telemetryState() {
|
|
|
479
491
|
}
|
|
480
492
|
// telemetrySendable is the single choke point every emitter must pass: on, and
|
|
481
493
|
// never the un-persisted default (no silent sends, no ephemeral-id retention
|
|
482
|
-
// 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.
|
|
483
498
|
function telemetrySendable(state) {
|
|
499
|
+
if (state.source === "config" && (state.config?.promptVersion ?? 0) < TELEMETRY_PROMPT_VERSION)
|
|
500
|
+
return false;
|
|
484
501
|
return state.state === "on" && state.source !== "default";
|
|
485
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
|
+
}
|
|
486
513
|
function envTruthy(v) {
|
|
487
514
|
return v !== undefined && v !== "" && v !== "0" && v.toLowerCase() !== "false";
|
|
488
515
|
}
|
|
@@ -524,6 +551,7 @@ function parseTelemetryConfig(value) {
|
|
|
524
551
|
// any persisted decision — including a "no" to the old v1 prompt — win.
|
|
525
552
|
async function ensureTelemetryDefault() {
|
|
526
553
|
const state = telemetryState();
|
|
554
|
+
await persistTelemetryEnvKill(state);
|
|
527
555
|
if (isHelpLikeInvocation())
|
|
528
556
|
return;
|
|
529
557
|
// `caveman telemetry …` manages the decision explicitly — don't pre-mint an
|
|
@@ -551,6 +579,28 @@ async function ensureTelemetryDefault() {
|
|
|
551
579
|
}
|
|
552
580
|
process.stderr.write(`${dim(TELEMETRY_DISCLOSURE_LINE)}\n`);
|
|
553
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
|
+
}
|
|
554
604
|
// ensureTelemetryDisclosureVersion reprints the disclosure once for someone who
|
|
555
605
|
// consented under older wording. v4 widened command_run with token volume, and a
|
|
556
606
|
// v3 "yes" was given for command counts alone — it stays a yes (re-asking would
|
|
@@ -621,12 +671,19 @@ async function telemetryCmd(argv) {
|
|
|
621
671
|
return telemetryOn();
|
|
622
672
|
if (sub === "off")
|
|
623
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();
|
|
624
679
|
emitCommandRunOnce("error", "usage");
|
|
625
680
|
console.error(`usage: ${invokedCommand("telemetry")} [status|on|off]`);
|
|
626
681
|
process.exit(2);
|
|
627
682
|
}
|
|
628
683
|
function telemetryStatus() {
|
|
629
|
-
|
|
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();
|
|
630
687
|
print({
|
|
631
688
|
enabled: state.state === "on",
|
|
632
689
|
state: state.state,
|
|
@@ -644,6 +701,8 @@ async function telemetryOn() {
|
|
|
644
701
|
promptVersion: TELEMETRY_PROMPT_VERSION,
|
|
645
702
|
};
|
|
646
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`);
|
|
647
706
|
if (!(prior?.enabled && prior.anonymousId) && !telemetryEnvForcesOff())
|
|
648
707
|
emitConsentGranted(anonymousId);
|
|
649
708
|
if (telemetryEnvForcesOff()) {
|
|
@@ -653,6 +712,7 @@ async function telemetryOn() {
|
|
|
653
712
|
print({ telemetry: "on", anonymous_id: anonymousId });
|
|
654
713
|
}
|
|
655
714
|
async function telemetryOff() {
|
|
715
|
+
const prior = telemetryConfigFromDisk();
|
|
656
716
|
const telemetry = {
|
|
657
717
|
enabled: false,
|
|
658
718
|
decidedAt: new Date().toISOString(),
|
|
@@ -670,8 +730,96 @@ async function telemetryOff() {
|
|
|
670
730
|
catch {
|
|
671
731
|
/* best effort: the decision itself is already persisted */
|
|
672
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
|
+
}
|
|
673
739
|
print({ telemetry: "off", anonymous_id: "none" });
|
|
674
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
|
+
}
|
|
675
823
|
function telemetryCommandName() {
|
|
676
824
|
if (currentInvocation.verb === "mcp-serve")
|
|
677
825
|
return "mcp";
|
|
@@ -781,6 +929,8 @@ function readProxyTokenTotals() {
|
|
|
781
929
|
encoding: "utf8",
|
|
782
930
|
timeout: TELEMETRY_TOKEN_READ_TIMEOUT_MS,
|
|
783
931
|
stdio: ["ignore", "pipe", "ignore"],
|
|
932
|
+
// The detached session sender has no console; without this Windows opens one.
|
|
933
|
+
windowsHide: true,
|
|
784
934
|
});
|
|
785
935
|
const parsed = parseProxyStatsPayload(out);
|
|
786
936
|
if (!parsed)
|
|
@@ -825,6 +975,90 @@ function telemetryTokenWatermarkFromDisk() {
|
|
|
825
975
|
return null;
|
|
826
976
|
}
|
|
827
977
|
}
|
|
978
|
+
// telemetryClaimLockPath is the sidecar used to serialize the read-compare-write
|
|
979
|
+
// below across OS processes; it sits beside config.json so its permission and
|
|
980
|
+
// cross-filesystem behavior always matches the file it protects.
|
|
981
|
+
function telemetryClaimLockPath() {
|
|
982
|
+
return `${configPath()}.telemetry.lock`;
|
|
983
|
+
}
|
|
984
|
+
// A lock older than this is presumed abandoned by a crashed holder; kept far
|
|
985
|
+
// above a real claim's own write time and above any waiter's acquire budget,
|
|
986
|
+
// so a slow but live holder is never mistaken for a dead one.
|
|
987
|
+
const TELEMETRY_CLAIM_LOCK_STALE_MS = 5000;
|
|
988
|
+
// acquireClaimLock spins on an atomic O_CREAT|O_EXCL create until it wins the
|
|
989
|
+
// lock or the budget runs out; a lock whose mtime is older than staleMs is
|
|
990
|
+
// treated as abandoned by a crashed holder and reclaimed, so a killed process
|
|
991
|
+
// cannot wedge the guarded operation off permanently.
|
|
992
|
+
//
|
|
993
|
+
// Shared by every watermark claim rather than copied per caller: the telemetry
|
|
994
|
+
// claim (#1116) and the sync claim (#1132) are the same read-mutate-write
|
|
995
|
+
// hazard over different state files, and a second copy of this spin is how the
|
|
996
|
+
// two would drift apart. Callers supply their own stale window because their
|
|
997
|
+
// hold times differ by orders of magnitude — see refreshClaimLock.
|
|
998
|
+
function acquireClaimLock(lockPath, budgetMs, staleMs) {
|
|
999
|
+
try {
|
|
1000
|
+
mkdirSync(dirname(lockPath), { recursive: true });
|
|
1001
|
+
}
|
|
1002
|
+
catch {
|
|
1003
|
+
return null;
|
|
1004
|
+
}
|
|
1005
|
+
// The token names THIS holder. releaseClaimLock unlinks only a lock that
|
|
1006
|
+
// still carries it, so a holder that was reclaimed as stale mid-section
|
|
1007
|
+
// cannot delete its successor's lock on the way out.
|
|
1008
|
+
const token = `${process.pid}:${randomUUID()}`;
|
|
1009
|
+
const deadline = Date.now() + budgetMs;
|
|
1010
|
+
for (;;) {
|
|
1011
|
+
try {
|
|
1012
|
+
const fd = openSync(lockPath, "wx");
|
|
1013
|
+
try {
|
|
1014
|
+
writeSync(fd, token);
|
|
1015
|
+
}
|
|
1016
|
+
finally {
|
|
1017
|
+
closeSync(fd);
|
|
1018
|
+
}
|
|
1019
|
+
return token;
|
|
1020
|
+
}
|
|
1021
|
+
catch (err) {
|
|
1022
|
+
if (err.code !== "EEXIST")
|
|
1023
|
+
return null;
|
|
1024
|
+
try {
|
|
1025
|
+
if (Date.now() - statSync(lockPath).mtimeMs > staleMs) {
|
|
1026
|
+
// Reclaim by rename, not unlink. Two waiters can both see the same
|
|
1027
|
+
// stale lock; with unlink the slower one would delete the lock the
|
|
1028
|
+
// faster one had already created in its place, and both would hold
|
|
1029
|
+
// it. Only one rename of the stale file can succeed; the loser's
|
|
1030
|
+
// rename fails and it loops back to the create attempt.
|
|
1031
|
+
const grave = `${lockPath}.${process.pid}.${Date.now()}.stale`;
|
|
1032
|
+
renameSync(lockPath, grave);
|
|
1033
|
+
unlinkSync(grave);
|
|
1034
|
+
}
|
|
1035
|
+
}
|
|
1036
|
+
catch {
|
|
1037
|
+
/* raced the holder releasing it, or another waiter reclaiming; loop back */
|
|
1038
|
+
}
|
|
1039
|
+
if (Date.now() >= deadline)
|
|
1040
|
+
return null;
|
|
1041
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 5);
|
|
1042
|
+
}
|
|
1043
|
+
}
|
|
1044
|
+
}
|
|
1045
|
+
// releaseClaimLock drops a lock taken above, but only while it is still ours:
|
|
1046
|
+
// a lock a waiter reclaimed as stale carries the waiter's token now, and
|
|
1047
|
+
// unlinking it would hand the guarded section to a third process. The read
|
|
1048
|
+
// and the unlink are not one step; a reclaim between them needs the lock to
|
|
1049
|
+
// cross the stale threshold in that gap, which the sync heartbeat and the
|
|
1050
|
+
// millisecond telemetry hold keep far away. Never throws: a lock already gone
|
|
1051
|
+
// is the same end state as one we removed.
|
|
1052
|
+
function releaseClaimLock(lockPath, token) {
|
|
1053
|
+
try {
|
|
1054
|
+
if (readFileSync(lockPath, "utf8") !== token)
|
|
1055
|
+
return;
|
|
1056
|
+
unlinkSync(lockPath);
|
|
1057
|
+
}
|
|
1058
|
+
catch {
|
|
1059
|
+
/* already gone */
|
|
1060
|
+
}
|
|
1061
|
+
}
|
|
828
1062
|
// telemetryTokenDelta returns what to report for THIS event and advances the
|
|
829
1063
|
// watermark to the totals it read. The send is fire-and-forget, so a dropped POST
|
|
830
1064
|
// loses that delta rather than replaying it — undercounting beats double-counting
|
|
@@ -847,11 +1081,15 @@ function telemetryTokenDelta() {
|
|
|
847
1081
|
const rebaselining = prior === null || rewound;
|
|
848
1082
|
if (processed === 0 && saved === 0 && !rebaselining)
|
|
849
1083
|
return null;
|
|
850
|
-
// Claim the delta
|
|
851
|
-
//
|
|
852
|
-
//
|
|
853
|
-
|
|
1084
|
+
// Claim the delta under a lock, not a bare compare: two processes exiting
|
|
1085
|
+
// together can both read the pre-write watermark before either commits (see
|
|
1086
|
+
// the regression test below).
|
|
1087
|
+
const lockPath = telemetryClaimLockPath();
|
|
1088
|
+
const lockToken = acquireClaimLock(lockPath, 500, TELEMETRY_CLAIM_LOCK_STALE_MS);
|
|
1089
|
+
if (!lockToken)
|
|
1090
|
+
return null;
|
|
854
1091
|
let claimed = true;
|
|
1092
|
+
let readOnly = false;
|
|
855
1093
|
try {
|
|
856
1094
|
mutateRawConfig((out) => {
|
|
857
1095
|
const current = parseTelemetryTokenWatermark(out.telemetryTokens);
|
|
@@ -867,10 +1105,12 @@ function telemetryTokenDelta() {
|
|
|
867
1105
|
});
|
|
868
1106
|
}
|
|
869
1107
|
catch {
|
|
870
|
-
// Read-only home: report nothing rather than resend the same delta forever.
|
|
871
|
-
|
|
1108
|
+
readOnly = true; // Read-only home: report nothing rather than resend the same delta forever.
|
|
1109
|
+
}
|
|
1110
|
+
finally {
|
|
1111
|
+
releaseClaimLock(lockPath, lockToken);
|
|
872
1112
|
}
|
|
873
|
-
if (!claimed)
|
|
1113
|
+
if (readOnly || !claimed)
|
|
874
1114
|
return null;
|
|
875
1115
|
if (processed === 0 && saved === 0)
|
|
876
1116
|
return null;
|
|
@@ -908,8 +1148,8 @@ function commandRunEventOnce(exitClass, errorClass) {
|
|
|
908
1148
|
event.agent = agent;
|
|
909
1149
|
if (exitClass === "error")
|
|
910
1150
|
event.error_class = errorClass ?? "other";
|
|
911
|
-
// Token volume rides on command_run
|
|
912
|
-
//
|
|
1151
|
+
// Token volume rides on command_run and session_start only; the watermark
|
|
1152
|
+
// claim in telemetryTokenDelta keeps concurrent readers from double counting.
|
|
913
1153
|
const tokens = telemetryTokenDelta();
|
|
914
1154
|
if (tokens) {
|
|
915
1155
|
event.tokens_processed = tokens.processed;
|
|
@@ -955,15 +1195,90 @@ function emitRuntimeBootstrap(exitClass, durationMS, errorClass) {
|
|
|
955
1195
|
event.error_class = errorClass ?? "other";
|
|
956
1196
|
emitTelemetryEvents([event]);
|
|
957
1197
|
}
|
|
1198
|
+
// Fields every event carries. Cheap local reads only: no keychain lookup, no
|
|
1199
|
+
// network, and the install path never leaves the machine — only its channel.
|
|
1200
|
+
function telemetryContext() {
|
|
1201
|
+
let raw = {};
|
|
1202
|
+
try {
|
|
1203
|
+
raw = JSON.parse(readFileSync(configPath(), "utf8"));
|
|
1204
|
+
}
|
|
1205
|
+
catch {
|
|
1206
|
+
/* no config yet */
|
|
1207
|
+
}
|
|
1208
|
+
const connected = Boolean(process.env.CAVE_TOKEN || raw.tokenStore || raw.token);
|
|
1209
|
+
const out = {
|
|
1210
|
+
account: connected ? "connected" : "none",
|
|
1211
|
+
install_channel: telemetryInstallChannel(),
|
|
1212
|
+
};
|
|
1213
|
+
// Logout leaves the cached entitlement behind, so only a live account's
|
|
1214
|
+
// unexpired plan counts.
|
|
1215
|
+
const entitlement = connected ? parseWrapEntitlement(raw.wrapEntitlement) : null;
|
|
1216
|
+
if (entitlement?.plan && !(Date.parse(entitlement.expires_at) < Date.now()))
|
|
1217
|
+
out.plan = entitlement.plan;
|
|
1218
|
+
try {
|
|
1219
|
+
const { timeZone, locale } = Intl.DateTimeFormat().resolvedOptions();
|
|
1220
|
+
if (timeZone)
|
|
1221
|
+
out.timezone = timeZone;
|
|
1222
|
+
if (locale)
|
|
1223
|
+
out.locale = locale;
|
|
1224
|
+
}
|
|
1225
|
+
catch {
|
|
1226
|
+
/* runtime without Intl data */
|
|
1227
|
+
}
|
|
1228
|
+
return out;
|
|
1229
|
+
}
|
|
1230
|
+
function telemetryInstallChannel() {
|
|
1231
|
+
const path = fileURLToPath(import.meta.url).replace(/\\/g, "/");
|
|
1232
|
+
if (path.includes("/_npx/"))
|
|
1233
|
+
return "npx";
|
|
1234
|
+
if (path.includes("/.pnpm/"))
|
|
1235
|
+
return "pnpm";
|
|
1236
|
+
if (path.includes("/.bun/") || path.includes("/bunx-"))
|
|
1237
|
+
return "bun";
|
|
1238
|
+
if (path.includes("/node_modules/"))
|
|
1239
|
+
return "npm";
|
|
1240
|
+
return "source";
|
|
1241
|
+
}
|
|
1242
|
+
function telemetryBody(events) {
|
|
1243
|
+
const context = telemetryContext();
|
|
1244
|
+
return JSON.stringify(events.map((event) => ({ ...event, ...context })));
|
|
1245
|
+
}
|
|
1246
|
+
// Sends run in a detached child so no command waits on the network at exit.
|
|
1247
|
+
// The child has no user-facing deadline, so it can outwait a cold endpoint.
|
|
958
1248
|
function emitTelemetryEvents(events) {
|
|
1249
|
+
const body = telemetryBody(events);
|
|
1250
|
+
try {
|
|
1251
|
+
const child = spawn(process.execPath, [fileURLToPath(import.meta.url), "telemetry", "send"], {
|
|
1252
|
+
detached: true,
|
|
1253
|
+
stdio: "ignore",
|
|
1254
|
+
windowsHide: true,
|
|
1255
|
+
env: { ...process.env, CAVEMAN_TELEMETRY_PAYLOAD: body },
|
|
1256
|
+
});
|
|
1257
|
+
child.on("error", () => { });
|
|
1258
|
+
child.unref();
|
|
1259
|
+
return Promise.resolve();
|
|
1260
|
+
}
|
|
1261
|
+
catch {
|
|
1262
|
+
return postTelemetry(body, 1500);
|
|
1263
|
+
}
|
|
1264
|
+
}
|
|
1265
|
+
function postTelemetry(body, timeoutMs) {
|
|
959
1266
|
const url = process.env.CAVEMAN_TELEMETRY_URL || TELEMETRY_URL;
|
|
960
1267
|
return fetch(url, {
|
|
961
1268
|
method: "POST",
|
|
962
1269
|
headers: { "content-type": "application/json" },
|
|
963
|
-
body
|
|
964
|
-
signal: AbortSignal.timeout(
|
|
1270
|
+
body,
|
|
1271
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
965
1272
|
}).then(() => { }).catch(() => { });
|
|
966
1273
|
}
|
|
1274
|
+
// `caveman telemetry send` (unprinted): the detached child emitTelemetryEvents
|
|
1275
|
+
// spawns. Consent was checked by the emitter; this only delivers.
|
|
1276
|
+
async function telemetrySend() {
|
|
1277
|
+
telemetryCommandSent = true;
|
|
1278
|
+
const body = process.env.CAVEMAN_TELEMETRY_PAYLOAD;
|
|
1279
|
+
if (body)
|
|
1280
|
+
await postTelemetry(body, 10_000);
|
|
1281
|
+
}
|
|
967
1282
|
function classifyTelemetryError(error) {
|
|
968
1283
|
const message = error instanceof Error ? error.message : "";
|
|
969
1284
|
if (telemetryCommandName() === "unknown" || message.startsWith("unknown command:"))
|
|
@@ -2173,7 +2488,22 @@ function verifiedLocalInstall(binDir) {
|
|
|
2173
2488
|
}
|
|
2174
2489
|
return installed;
|
|
2175
2490
|
}
|
|
2176
|
-
|
|
2491
|
+
// A signed manifest names its release through a `RELEASE` entry: the sha256 of
|
|
2492
|
+
// the release asset `RELEASE`, whose content is "<tag>\n". Without it, anyone
|
|
2493
|
+
// able to edit a release page could serve an older, validly signed manifest
|
|
2494
|
+
// and its binaries. It rides as an ordinary checksum line so the shipped
|
|
2495
|
+
// wedge installers' strict parsers keep accepting the manifest. Releases
|
|
2496
|
+
// before bin-v2.0.0 were signed without it, so it is required from there on.
|
|
2497
|
+
const FIRST_RELEASE_WITH_SIGNED_NAME = [2, 0, 0];
|
|
2498
|
+
function releaseRequiresSignedName(release) {
|
|
2499
|
+
const match = release.match(/^bin-v(\d+)\.(\d+)\.(\d+)/);
|
|
2500
|
+
if (!match)
|
|
2501
|
+
return true;
|
|
2502
|
+
const version = match.slice(1, 4).map(Number);
|
|
2503
|
+
const i = version.findIndex((part, index) => part !== FIRST_RELEASE_WITH_SIGNED_NAME[index]);
|
|
2504
|
+
return i === -1 || version[i] > FIRST_RELEASE_WITH_SIGNED_NAME[i];
|
|
2505
|
+
}
|
|
2506
|
+
export function parseSignedChecksums(raw, release = BINARY_RELEASE) {
|
|
2177
2507
|
const checksums = new Map();
|
|
2178
2508
|
for (const line of raw.split("\n")) {
|
|
2179
2509
|
if (!line)
|
|
@@ -2186,6 +2516,10 @@ function parseSignedChecksums(raw) {
|
|
|
2186
2516
|
throw new Error(`duplicate checksum manifest entry: ${filename}`);
|
|
2187
2517
|
checksums.set(filename, match[1]);
|
|
2188
2518
|
}
|
|
2519
|
+
const signedName = checksums.get("RELEASE");
|
|
2520
|
+
if (signedName === undefined ? releaseRequiresSignedName(release) : signedName !== createHash("sha256").update(`${release}\n`).digest("hex")) {
|
|
2521
|
+
throw new Error(`manifest is not signed for release ${release}`);
|
|
2522
|
+
}
|
|
2189
2523
|
return checksums;
|
|
2190
2524
|
}
|
|
2191
2525
|
function verifyChecksumSignature(checksums, signature) {
|
|
@@ -2326,7 +2660,7 @@ async function setupInstall(json, options = {}) {
|
|
|
2326
2660
|
printInstallResult(local, platform, binDir, json, options.continuing);
|
|
2327
2661
|
return;
|
|
2328
2662
|
}
|
|
2329
|
-
const base = (process.env.CAVE_BINARY_RELEASE_BASE ?? BINARY_RELEASE_BASE_DEFAULT)
|
|
2663
|
+
const base = trimTrailingSlashes(process.env.CAVE_BINARY_RELEASE_BASE ?? BINARY_RELEASE_BASE_DEFAULT);
|
|
2330
2664
|
const releaseBase = `${base}/${BINARY_RELEASE}`;
|
|
2331
2665
|
let checksumsRaw;
|
|
2332
2666
|
let signatureRaw;
|
|
@@ -2347,8 +2681,8 @@ async function setupInstall(json, options = {}) {
|
|
|
2347
2681
|
try {
|
|
2348
2682
|
checksums = parseSignedChecksums(checksumsRaw);
|
|
2349
2683
|
}
|
|
2350
|
-
catch {
|
|
2351
|
-
throw new Error(
|
|
2684
|
+
catch (error) {
|
|
2685
|
+
throw new Error(`signature check failed for checksums.txt (${error.message}) — refusing to install; partial download deleted`);
|
|
2352
2686
|
}
|
|
2353
2687
|
const installed = [];
|
|
2354
2688
|
const artifactDigests = {};
|
|
@@ -2407,7 +2741,7 @@ function cliVersionBehind(current, latest) {
|
|
|
2407
2741
|
return false;
|
|
2408
2742
|
}
|
|
2409
2743
|
async function latestPublishedCliVersion(timeoutSeconds) {
|
|
2410
|
-
const registry = (process.env.CAVEMAN_NPM_REGISTRY ?? "https://registry.npmjs.org")
|
|
2744
|
+
const registry = trimTrailingSlashes(process.env.CAVEMAN_NPM_REGISTRY ?? "https://registry.npmjs.org");
|
|
2411
2745
|
try {
|
|
2412
2746
|
const response = await fetch(`${registry}/@caveman-ai%2fcli`, {
|
|
2413
2747
|
headers: { accept: "application/vnd.npm.install-v1+json" },
|
|
@@ -2814,7 +3148,12 @@ function removeAgentNativeBundle(agent) {
|
|
|
2814
3148
|
recoverPendingAgentNativeBundle(agent);
|
|
2815
3149
|
const journal = readAgentNativeBundleJournal(agent);
|
|
2816
3150
|
if (!journal) {
|
|
2817
|
-
|
|
3151
|
+
// Accurate, but on its own a dead end (#1134): this verb undoes the bundle that
|
|
3152
|
+
// `setup --agent-native` installs, and nothing else. A user who reached the same
|
|
3153
|
+
// config through `caveman <agent>` or `caveman enable <agent>` has no bundle and
|
|
3154
|
+
// reads this as "caveman cannot be uninstalled". Name the verb that undoes theirs.
|
|
3155
|
+
process.stderr.write(`${mark("warn")} ${agent}: no agent-native bundle journal found — nothing was installed by \`caveman setup --agent-native ${agent}\`\n`);
|
|
3156
|
+
process.stderr.write(dim(` if you set it up with \`caveman ${agent}\` or \`caveman enable ${agent}\`, remove that with \`caveman disable ${agent}\`\n`));
|
|
2818
3157
|
return;
|
|
2819
3158
|
}
|
|
2820
3159
|
for (const skill of journal.skills) {
|
|
@@ -3650,14 +3989,28 @@ function mutateRawConfig(fn) {
|
|
|
3650
3989
|
}
|
|
3651
3990
|
fn(out);
|
|
3652
3991
|
mkdirSync(dirname(configPath()), { recursive: true });
|
|
3653
|
-
|
|
3992
|
+
const target = configWriteTarget();
|
|
3993
|
+
const tmp = `${target}.${process.pid}.tmp`;
|
|
3994
|
+
writeFileSync(tmp, JSON.stringify(out, null, 2), { mode: 0o600 });
|
|
3995
|
+
renameSync(tmp, target);
|
|
3654
3996
|
try {
|
|
3655
|
-
chmodSync(
|
|
3997
|
+
chmodSync(target, 0o600);
|
|
3656
3998
|
}
|
|
3657
3999
|
catch {
|
|
3658
4000
|
/* best effort */
|
|
3659
4001
|
}
|
|
3660
4002
|
}
|
|
4003
|
+
// Config writes go temp-file + rename so a concurrent reader (background
|
|
4004
|
+
// session senders) never sees a truncated file and rewrites it as {}. Resolves
|
|
4005
|
+
// a symlinked config.json so the rename replaces its target, not the link.
|
|
4006
|
+
function configWriteTarget() {
|
|
4007
|
+
try {
|
|
4008
|
+
return realpathSync(configPath());
|
|
4009
|
+
}
|
|
4010
|
+
catch {
|
|
4011
|
+
return configPath();
|
|
4012
|
+
}
|
|
4013
|
+
}
|
|
3661
4014
|
// ensureDeviceId returns a stable, opaque per-machine id, generated once and
|
|
3662
4015
|
// persisted in config.json. The entitlement device_hash is sha256(deviceId) — a
|
|
3663
4016
|
// random per-install id, NEVER derived from a hardware serial.
|
|
@@ -4749,6 +5102,23 @@ async function agentShortcut(rest) {
|
|
|
4749
5102
|
process.exitCode = result.status ?? 1;
|
|
4750
5103
|
return;
|
|
4751
5104
|
}
|
|
5105
|
+
// Some host surfaces cannot run routed at all — Claude Code Remote Control
|
|
5106
|
+
// refuses any non-first-party ANTHROPIC_BASE_URL and its escape hatch does not
|
|
5107
|
+
// cover the check (#947, #1101). The native door would install machine-wide
|
|
5108
|
+
// routing and then launch the host straight into that refusal, leaving the
|
|
5109
|
+
// user both unrouted and unable to start the surface they asked for. Resolve
|
|
5110
|
+
// the override before any persistent write and hand these to wrap, whose
|
|
5111
|
+
// route-override path launches the host directly and writes nothing.
|
|
5112
|
+
const shortcutRouteOverride = agentRouteOverride(agent, rest.slice(1));
|
|
5113
|
+
if (shortcutRouteOverride) {
|
|
5114
|
+
// A native install already owns the host's base URL from its own config
|
|
5115
|
+
// file, which launching directly cannot undo — say so rather than let the
|
|
5116
|
+
// surface fail with the host's own opaque refusal.
|
|
5117
|
+
if (readNativeJournal(native)) {
|
|
5118
|
+
process.stderr.write(`${mark("warn")} ${routeOverrideLabel(agent)} ${shortcutRouteOverride.surface} ${shortcutRouteOverride.reason}, and the native integration still routes ${binOf(agent)} from its own config — run \`caveman disable ${native}\` first, then \`caveman enable ${native}\` afterwards\n`);
|
|
5119
|
+
}
|
|
5120
|
+
return wrap(rest);
|
|
5121
|
+
}
|
|
4752
5122
|
// A Cave Build lock is enforced at the wrap door (claudeCaveBuildEnv); the
|
|
4753
5123
|
// native door applies none of its transforms, so a locked project must keep
|
|
4754
5124
|
// routing through wrap or the lock would be silently unenforced.
|
|
@@ -4843,7 +5213,7 @@ async function agentShortcut(rest) {
|
|
|
4843
5213
|
// is the one-command compression path. If the proxy can't be reached, a TTY run
|
|
4844
5214
|
// offers to launch the agent directly (no Caveman, no compression this run) rather
|
|
4845
5215
|
// 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
|
|
5216
|
+
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
5217
|
const result = await spawnWrapped(bin, cmdArgs, agent, opts, gatewayURL(), codexSubscription, routeDecision);
|
|
4848
5218
|
// Preflight route bypass is intentionally outside Caveman's lifecycle: no
|
|
4849
5219
|
// savings read, sync, telemetry, or other post-child mutation.
|
|
@@ -4909,7 +5279,21 @@ function routedAiderArgs(args) {
|
|
|
4909
5279
|
process.stderr.write(`caveman: aider model not set; routing with --model ${AIDER_ROUTED_DEFAULT_MODEL}\n`);
|
|
4910
5280
|
return ["--model", AIDER_ROUTED_DEFAULT_MODEL, ...args];
|
|
4911
5281
|
}
|
|
4912
|
-
async function spawnWrapped(bin, cmdArgs, agent, opts, gw,
|
|
5282
|
+
async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscriptionOverride, routeDecision) {
|
|
5283
|
+
// Which Codex route is correct is a fact about ~/.codex/auth.json, not about
|
|
5284
|
+
// the caller: a ChatGPT login must reach the `/chatgpt` mux handler, an api-key
|
|
5285
|
+
// login the attributed `/w/codex/v1`. This used to be a defaulted parameter, so
|
|
5286
|
+
// every caller had to remember to pass it. `wrap codex` did (it resolves the
|
|
5287
|
+
// mode for --pixel anyway); `trial` and the interactive picker did not, and
|
|
5288
|
+
// their `false` built an ephemeral CODEX_HOME pinning the api-key route. Codex
|
|
5289
|
+
// then sent the OAuth token to the platform Responses API, which rejects it
|
|
5290
|
+
// with "Missing scopes: api.responses.write", while the model refresh 404s
|
|
5291
|
+
// because `/w/codex/v1/models` is not in the openai adapter's closed
|
|
5292
|
+
// allowlist (#1092). Resolving it here fixes every caller that forgets; an
|
|
5293
|
+
// explicit override still wins, which is what `wrap` passes.
|
|
5294
|
+
const codexSubscription = agent?.id === "codex"
|
|
5295
|
+
? codexSubscriptionOverride ?? detectCodexWrapAuthMode() === "subscription"
|
|
5296
|
+
: false;
|
|
4913
5297
|
const { host, port } = gatewayHostPort(gw);
|
|
4914
5298
|
const local = wrapMode(gw) === "local";
|
|
4915
5299
|
let proxyStarted = false;
|
|
@@ -5179,7 +5563,7 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = f
|
|
|
5179
5563
|
if (direct) {
|
|
5180
5564
|
// buildWrapEnv writes the agent-attributed `${gw}/w/<agent>` form, and an
|
|
5181
5565
|
// outer routed wrap may leak the bare form; a direct launch strips both.
|
|
5182
|
-
const gwPrefix = `${gw
|
|
5566
|
+
const gwPrefix = `${trimTrailingSlashes(gw)}/`;
|
|
5183
5567
|
for (const k of WRAP_BASE_URL_ENV_VARS) {
|
|
5184
5568
|
const value = env[k];
|
|
5185
5569
|
if (value !== undefined && (value === gw || value.startsWith(gwPrefix)))
|
|
@@ -5367,7 +5751,13 @@ function applyHermesAuthEnv(env, gw, modeGw = gw) {
|
|
|
5367
5751
|
if (key && name)
|
|
5368
5752
|
env[name] = key;
|
|
5369
5753
|
}
|
|
5370
|
-
|
|
5754
|
+
// spawnLocalProxyProcess resolves the proxy binary, builds its env, and spawns
|
|
5755
|
+
// it detached + unref'd — the part every caller needs identically. Split out
|
|
5756
|
+
// of startWrapProxy so a caller that only wants to kick the proxy off (never
|
|
5757
|
+
// waiting to confirm it came up) doesn't have to either duplicate this env
|
|
5758
|
+
// assembly or pay for the readiness-poll loop below, which holds this
|
|
5759
|
+
// process's event loop open via a non-unref'd sleep() timer.
|
|
5760
|
+
function spawnLocalProxyProcess(mode, mcpRecovery, toon, pixelModels, pixelDensity, gw, purpose, observeEstimate) {
|
|
5371
5761
|
const bin = cavemanBin("caveman-proxy", "CAVEMAN_PROXY_BIN");
|
|
5372
5762
|
const resolved = which(bin);
|
|
5373
5763
|
if (!resolved) {
|
|
@@ -5377,7 +5767,7 @@ async function startWrapProxy(mode, mcpRecovery, toon, pixelModels, pixelDensity
|
|
|
5377
5767
|
else {
|
|
5378
5768
|
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`);
|
|
5379
5769
|
}
|
|
5380
|
-
return
|
|
5770
|
+
return null;
|
|
5381
5771
|
}
|
|
5382
5772
|
const { host, port } = gatewayHostPort(gw);
|
|
5383
5773
|
const env = {
|
|
@@ -5425,14 +5815,59 @@ async function startWrapProxy(mode, mcpRecovery, toon, pixelModels, pixelDensity
|
|
|
5425
5815
|
process.stderr.write(`${mark("warn")} could not start ${bin}: ${error.message}\n`);
|
|
5426
5816
|
});
|
|
5427
5817
|
child.unref();
|
|
5818
|
+
return { host, port };
|
|
5819
|
+
}
|
|
5820
|
+
// Best-effort "there should be a proxy on this port now" for the `enable` door.
|
|
5821
|
+
// Fire-and-forget: the caller never waits, so `enable` returns at its own pace.
|
|
5822
|
+
//
|
|
5823
|
+
// Deliberately not startWrapProxy: that readiness poll's sleep() timer is not
|
|
5824
|
+
// unref'd, so awaiting it would hold this command's process open for up to two
|
|
5825
|
+
// seconds on every enable where nothing is listening yet — the common case this
|
|
5826
|
+
// exists to cover. Probe first (one fast TCP connect, not the retry loop) so a
|
|
5827
|
+
// second enable against a live proxy spawns nothing; the redundant process that
|
|
5828
|
+
// skipping the probe would create is harmless, since run state is only written
|
|
5829
|
+
// once the listener binds, but free beats harmless.
|
|
5830
|
+
//
|
|
5831
|
+
// aider is excluded on purpose. It is the one native agent installed without an
|
|
5832
|
+
// MCP binary (see nativeMcpBinaryRequired's aider branch), so the recovery flag
|
|
5833
|
+
// derived below would stamp CAVEMAN_RECOVERY=mcp onto a proxy with no retrieve
|
|
5834
|
+
// tool to back it — the exact leak the explicit stamping elsewhere exists to
|
|
5835
|
+
// prevent. Giving aider a proxy needs recovery pinned off and its own coverage;
|
|
5836
|
+
// until then it keeps the pre-existing behaviour, no better and no worse.
|
|
5837
|
+
function ensureLocalProxyForNative(agent, gw) {
|
|
5838
|
+
if (agent === "aider" || wrapMode(gw) !== "local")
|
|
5839
|
+
return;
|
|
5840
|
+
void (async () => {
|
|
5841
|
+
try {
|
|
5842
|
+
const opts = defaultWrapOptions();
|
|
5843
|
+
// Every other spawn site gates on this (agentShortcut, the native hook).
|
|
5844
|
+
// Without it, `enable` starts a proxy the user's config switched off.
|
|
5845
|
+
if (opts.noProxy)
|
|
5846
|
+
return;
|
|
5847
|
+
const { host, port } = gatewayHostPort(gw);
|
|
5848
|
+
if (await portListening(host, port))
|
|
5849
|
+
return;
|
|
5850
|
+
const subscription = agent === "codex" && detectCodexWrapAuthMode() === "subscription";
|
|
5851
|
+
const mode = subscription && opts.mode === "pixel" ? "record" : opts.mode;
|
|
5852
|
+
const recovery = Boolean(probeMcpBinary()?.probe.current);
|
|
5853
|
+
spawnLocalProxyProcess(mode, recovery, subscription ? false : opts.toon, opts.pixelModels, opts.pixelDensity, gw, subscription ? "codex-subscription" : "standard", false);
|
|
5854
|
+
}
|
|
5855
|
+
catch { /* fail-open, same as the SessionStart hook and the shortcut door */ }
|
|
5856
|
+
})();
|
|
5857
|
+
}
|
|
5858
|
+
async function startWrapProxy(mode, mcpRecovery, toon, pixelModels, pixelDensity, gw = gatewayURL(), purpose = "standard", observeEstimate = false) {
|
|
5859
|
+
const spawned = spawnLocalProxyProcess(mode, mcpRecovery, toon, pixelModels, pixelDensity, gw, purpose, observeEstimate);
|
|
5860
|
+
if (!spawned)
|
|
5861
|
+
return false;
|
|
5862
|
+
const { host, port } = spawned;
|
|
5428
5863
|
for (let i = 0; i < 20; i++) {
|
|
5429
5864
|
await sleep(100);
|
|
5430
5865
|
if (await portListening(host, port)) {
|
|
5431
|
-
process.stderr.write(dim(`→ started Caveman proxy on ${host}:${port} (${
|
|
5866
|
+
process.stderr.write(dim(`→ started Caveman proxy on ${host}:${port} (${mode})\n`));
|
|
5432
5867
|
return true;
|
|
5433
5868
|
}
|
|
5434
5869
|
}
|
|
5435
|
-
process.stderr.write(`${mark("warn")} started ${
|
|
5870
|
+
process.stderr.write(`${mark("warn")} started ${cavemanBin("caveman-proxy", "CAVEMAN_PROXY_BIN")}, but proxy did not become ready on ${host}:${port}\n`);
|
|
5436
5871
|
return false;
|
|
5437
5872
|
}
|
|
5438
5873
|
// startProxyKeepalive heartbeats the local proxy while the wrapped agent process
|
|
@@ -5833,7 +6268,7 @@ function freshOpenClawModelRef(ctx) {
|
|
|
5833
6268
|
return { provider: "openai", model: OPENCLAW_FRESH_MODEL, raw: `openai/${OPENCLAW_FRESH_MODEL}` };
|
|
5834
6269
|
}
|
|
5835
6270
|
function appendUrlPath(base, path) {
|
|
5836
|
-
return `${base
|
|
6271
|
+
return `${trimTrailingSlashes(base)}${path}`;
|
|
5837
6272
|
}
|
|
5838
6273
|
export function claudeConfigDir(env = process.env) {
|
|
5839
6274
|
return env.CLAUDE_CONFIG_DIR ? resolve(env.CLAUDE_CONFIG_DIR) : join(homedir(), ".claude");
|
|
@@ -5952,7 +6387,7 @@ function stripCodexCavemanProviderToml(text) {
|
|
|
5952
6387
|
// The api-key Codex route, in ONE place: the provider TOML writes it, the
|
|
5953
6388
|
// install journal records it, and the doctor compares against it, and a route
|
|
5954
6389
|
// only three of those four agree on reads as permanently degraded.
|
|
5955
|
-
const
|
|
6390
|
+
const CODEX_PAYG_ROUTE = "/w/codex/v1";
|
|
5956
6391
|
function codexGatewayBase(gw, subscription) {
|
|
5957
6392
|
// Codex's OpenAI-Responses client appends "/responses" onto base_url itself,
|
|
5958
6393
|
// exactly as it does against the real api.openai.com, so what the proxy
|
|
@@ -5963,7 +6398,7 @@ function codexGatewayBase(gw, subscription) {
|
|
|
5963
6398
|
// convention aider already uses (`/w/aider/openai/v1`). The subscription
|
|
5964
6399
|
// route is a different mux handler (`/chatgpt/`) that takes the suffix
|
|
5965
6400
|
// verbatim, so it must NOT gain a "/v1".
|
|
5966
|
-
return appendUrlPath(gw, subscription ? "/chatgpt" :
|
|
6401
|
+
return appendUrlPath(gw, subscription ? "/chatgpt" : CODEX_PAYG_ROUTE);
|
|
5967
6402
|
}
|
|
5968
6403
|
// Codex clears the stdio MCP environment, including these non-secret store
|
|
5969
6404
|
// selectors. Forward their names so the proxy and recovery server share the
|
|
@@ -6257,12 +6692,109 @@ function assertNativeHooksShape(path, root, agentId) {
|
|
|
6257
6692
|
}
|
|
6258
6693
|
}
|
|
6259
6694
|
}
|
|
6695
|
+
// #1137, in one place: every persistent artifact caveman writes bakes in the
|
|
6696
|
+
// invocation `enable` resolved, and nothing checked that the invocation still
|
|
6697
|
+
// resolves. nvm installs each Node release in its own directory and
|
|
6698
|
+
// `nvm uninstall <old>` deletes it, so a routine upgrade leaves every baked
|
|
6699
|
+
// path dangling — while the artifact's own bytes are untouched, which is what
|
|
6700
|
+
// every ownership check looked at. The hosts differ only in where the
|
|
6701
|
+
// invocation is written; whether its targets exist is one question, asked here.
|
|
6702
|
+
//
|
|
6703
|
+
// `which` answers an absolute path by testing it directly, so this covers both
|
|
6704
|
+
// a bare name resolved through PATH and a path into a removed directory.
|
|
6705
|
+
function invocationTargetsExist(tokens) {
|
|
6706
|
+
const executable = tokens[0];
|
|
6707
|
+
if (executable === undefined || !which(executable))
|
|
6708
|
+
return false;
|
|
6709
|
+
// A `node <script>` invocation and a `--adapter <file>` argument name files
|
|
6710
|
+
// the executable itself cannot vouch for: node exists on every host after an
|
|
6711
|
+
// upgrade, the script it was pointed at does not.
|
|
6712
|
+
const files = [hookCommandBasename(executable) === "node" ? tokens[1] : undefined];
|
|
6713
|
+
const adapter = tokens.indexOf("--adapter");
|
|
6714
|
+
if (adapter !== -1)
|
|
6715
|
+
files.push(tokens[adapter + 1]);
|
|
6716
|
+
return !files.some((file) => file !== undefined && !existsSync(file));
|
|
6717
|
+
}
|
|
6718
|
+
// The generated opencode plugin and Pi extension bake their invocation as a
|
|
6719
|
+
// source literal rather than a host hook command, so ownership was judged by
|
|
6720
|
+
// the marker comment alone and #1137 stayed invisible on both. Parse what the
|
|
6721
|
+
// generators emit — not the journal, which for an install made before this
|
|
6722
|
+
// check records no invocation at all, and these are the installs already
|
|
6723
|
+
// broken on disk.
|
|
6724
|
+
//
|
|
6725
|
+
// Deliberately fail-open on an unrecognized shape: there is nothing to verify,
|
|
6726
|
+
// and answering `false` would report every install degraded. The regression
|
|
6727
|
+
// tests assert the emitted shape still matches, so a generator refactor that
|
|
6728
|
+
// silences this fails the suite instead of silently verifying nothing.
|
|
6729
|
+
function generatedInvocation(text) {
|
|
6730
|
+
// opencode: `const command = "…";` with `const prefix = […];`
|
|
6731
|
+
const command = text.match(/^const command = ("(?:[^"\\]|\\.)*");$/m);
|
|
6732
|
+
if (command) {
|
|
6733
|
+
const prefix = text.match(/^const prefix = (\[(?:[^[\]\\]|\\.)*\]);$/m);
|
|
6734
|
+
// A prefix line we cannot read means we cannot see the whole invocation,
|
|
6735
|
+
// and verifying the executable alone would be worse than verifying
|
|
6736
|
+
// nothing: `node` survives every upgrade, so the dangling member would be
|
|
6737
|
+
// exactly the script in the prefix we failed to parse.
|
|
6738
|
+
if (!prefix && /^const prefix = /m.test(text))
|
|
6739
|
+
return undefined;
|
|
6740
|
+
try {
|
|
6741
|
+
const parsedPrefix = prefix ? JSON.parse(prefix[1]) : [];
|
|
6742
|
+
if (!Array.isArray(parsedPrefix) || parsedPrefix.some((item) => typeof item !== "string"))
|
|
6743
|
+
return undefined;
|
|
6744
|
+
return [JSON.parse(command[1]), ...parsedPrefix];
|
|
6745
|
+
}
|
|
6746
|
+
catch {
|
|
6747
|
+
return undefined;
|
|
6748
|
+
}
|
|
6749
|
+
}
|
|
6750
|
+
// Pi: `process.env.CAVEMAN_PI_HOOK_CMD ??= "<json array, re-encoded>";`
|
|
6751
|
+
const pi = text.match(/^process\.env\.CAVEMAN_PI_HOOK_CMD \?\?= ("(?:[^"\\]|\\.)*");$/m);
|
|
6752
|
+
if (pi) {
|
|
6753
|
+
try {
|
|
6754
|
+
const parsed = JSON.parse(JSON.parse(pi[1]));
|
|
6755
|
+
if (!Array.isArray(parsed) || parsed.length === 0 || parsed.some((item) => typeof item !== "string"))
|
|
6756
|
+
return undefined;
|
|
6757
|
+
return parsed;
|
|
6758
|
+
}
|
|
6759
|
+
catch {
|
|
6760
|
+
return undefined;
|
|
6761
|
+
}
|
|
6762
|
+
}
|
|
6763
|
+
return undefined;
|
|
6764
|
+
}
|
|
6765
|
+
function generatedArtifactTargetsExist(text) {
|
|
6766
|
+
const tokens = generatedInvocation(text);
|
|
6767
|
+
return tokens === undefined || invocationTargetsExist(tokens);
|
|
6768
|
+
}
|
|
6769
|
+
// A managed hook is only healthy while the files its command runs still exist.
|
|
6770
|
+
// Identity is judged by basename, so a hook rendered into a directory that has
|
|
6771
|
+
// since been deleted (an nvm Node upgrade, #1137) kept matching the expected
|
|
6772
|
+
// document while the host ran a missing binary or adapter.
|
|
6773
|
+
function managedHookTargetsExist(root) {
|
|
6774
|
+
const hooks = root.hooks && typeof root.hooks === "object" && !Array.isArray(root.hooks)
|
|
6775
|
+
? root.hooks
|
|
6776
|
+
: {};
|
|
6777
|
+
for (const raw of Object.values(hooks)) {
|
|
6778
|
+
if (!Array.isArray(raw))
|
|
6779
|
+
continue;
|
|
6780
|
+
for (const entry of raw) {
|
|
6781
|
+
const command = entry && typeof entry === "object" ? hookEntryCommand(entry) : undefined;
|
|
6782
|
+
if (command === undefined || managedHookIdentity(command) === undefined)
|
|
6783
|
+
continue;
|
|
6784
|
+
if (!invocationTargetsExist(hookCommandTokens(command)))
|
|
6785
|
+
return false;
|
|
6786
|
+
}
|
|
6787
|
+
}
|
|
6788
|
+
return true;
|
|
6789
|
+
}
|
|
6260
6790
|
function nativeHookEntriesHealthy(root, agentId) {
|
|
6261
6791
|
const hooks = root.hooks && typeof root.hooks === "object" && !Array.isArray(root.hooks)
|
|
6262
6792
|
? root.hooks
|
|
6263
6793
|
: undefined;
|
|
6264
6794
|
if (!hooks)
|
|
6265
6795
|
return false;
|
|
6796
|
+
if (!managedHookTargetsExist(root))
|
|
6797
|
+
return false;
|
|
6266
6798
|
const expected = nativeHooksDocument(agentId, nativeShrinkEnabled()).hooks;
|
|
6267
6799
|
const required = Object.entries(expected).every(([event, expectedRaw]) => {
|
|
6268
6800
|
const actual = Array.isArray(hooks[event]) ? hooks[event] : [];
|
|
@@ -6768,7 +7300,30 @@ function geminiNativeMutations(gw, mcpBinary) {
|
|
|
6768
7300
|
function opencodeNativePluginPath() {
|
|
6769
7301
|
return join(homedir(), ".config", "opencode", "plugins", "caveman-native.js");
|
|
6770
7302
|
}
|
|
7303
|
+
function opencodePluginMajor() {
|
|
7304
|
+
const profile = AGENTS.find((agent) => agent.id === "opencode");
|
|
7305
|
+
const semver = parsedSemver(profile ? detectedAgentVersion(profile) : null);
|
|
7306
|
+
return semver ? semver[0] : null;
|
|
7307
|
+
}
|
|
6771
7308
|
function opencodeNativePluginSource() {
|
|
7309
|
+
// OpenCode 2 replaced the plugin API: a V1 hook map no longer loads
|
|
7310
|
+
// (PluginModule.LoadError, missing "default"). Emit the implementation
|
|
7311
|
+
// matching the detected host major. See #1083.
|
|
7312
|
+
//
|
|
7313
|
+
// An unreadable version keeps V1, the status quo. nativeHostProbe returns
|
|
7314
|
+
// version: null for an empty/non-zero/unspawnable `opencode --version`
|
|
7315
|
+
// ("version_probe_failed"), and #1081 records exactly that state on a live
|
|
7316
|
+
// OpenCode 1.18.31 host — so "unknown" is not evidence of "new". Defaulting
|
|
7317
|
+
// it to V2 would break a 1.x user whose probe merely flaked, turning a
|
|
7318
|
+
// working install into one whose plugin the host refuses to load; a 2.x user
|
|
7319
|
+
// in the same state is no worse off than before this gate existed. Only a
|
|
7320
|
+
// version that positively reads as major >= 2 opts into the V2 API.
|
|
7321
|
+
const major = opencodePluginMajor();
|
|
7322
|
+
if (major === null || major < 2)
|
|
7323
|
+
return opencodeNativePluginSourceV1();
|
|
7324
|
+
return opencodeNativePluginSourceV2();
|
|
7325
|
+
}
|
|
7326
|
+
function opencodeNativePluginSourceV1() {
|
|
6772
7327
|
const { cmd, pre } = cavemanInvocation();
|
|
6773
7328
|
return `// caveman:native-opencode — GENERATED by \`caveman enable opencode\`.
|
|
6774
7329
|
// Contract: @opencode-ai/plugin 1.17.8 Hooks (installed local type source).
|
|
@@ -6939,6 +7494,211 @@ export const CavemanNative = async () => ({
|
|
|
6939
7494
|
});
|
|
6940
7495
|
`;
|
|
6941
7496
|
}
|
|
7497
|
+
function opencodeNativePluginSourceV2() {
|
|
7498
|
+
const { cmd, pre } = cavemanInvocation();
|
|
7499
|
+
return `// caveman:native-opencode — GENERATED by \`caveman enable opencode\`.
|
|
7500
|
+
// Contract: OpenCode 2 plugin API — default export { id, setup }
|
|
7501
|
+
// (https://opencode.ai/v2/docs/build/plugins/migrate-v1).
|
|
7502
|
+
import { execFileSync } from "node:child_process";
|
|
7503
|
+
import { createHash } from "node:crypto";
|
|
7504
|
+
|
|
7505
|
+
const command = ${JSON.stringify(cmd)};
|
|
7506
|
+
const prefix = ${JSON.stringify(pre)};
|
|
7507
|
+
|
|
7508
|
+
function call(event, payload = {}) {
|
|
7509
|
+
try {
|
|
7510
|
+
const raw = execFileSync(command, [...prefix, "native-hook", "opencode", event], {
|
|
7511
|
+
input: JSON.stringify({ event_name: event, ...payload }),
|
|
7512
|
+
encoding: "utf8",
|
|
7513
|
+
timeout: 2000,
|
|
7514
|
+
maxBuffer: 2 * 1024 * 1024,
|
|
7515
|
+
});
|
|
7516
|
+
if (!raw.trim()) return undefined;
|
|
7517
|
+
const value = JSON.parse(raw);
|
|
7518
|
+
return value && typeof value === "object" ? value : undefined;
|
|
7519
|
+
} catch { return undefined; }
|
|
7520
|
+
}
|
|
7521
|
+
|
|
7522
|
+
function digest(value) {
|
|
7523
|
+
try {
|
|
7524
|
+
const raw = JSON.stringify(value);
|
|
7525
|
+
return { bytes: Buffer.byteLength(raw), sha256: "sha256:" + createHash("sha256").update(raw).digest("hex") };
|
|
7526
|
+
} catch { return undefined; }
|
|
7527
|
+
}
|
|
7528
|
+
|
|
7529
|
+
function taskType(value) {
|
|
7530
|
+
let text;
|
|
7531
|
+
try { text = JSON.stringify(value).toLowerCase(); } catch { return "general"; }
|
|
7532
|
+
const has = (...terms) => terms.some((term) => text.includes(term));
|
|
7533
|
+
if (has("migration", "migrate", "schema change", "backfill", "rollback")) return "migration";
|
|
7534
|
+
if (has("bug", "fix", "broken", "regression", "crash", "error", "incorrect")) return "bugfix";
|
|
7535
|
+
if (has("investigate", "diagnose", "root cause", "why does", "trace")) return "investigation";
|
|
7536
|
+
if (has("refactor", "restructure", "reorganize", "cleanup")) return "refactor";
|
|
7537
|
+
if (has("review", "audit", "critique", "assess")) return "review";
|
|
7538
|
+
if (has("verify", "verification", "prove", "validate", "check that")) return "verification";
|
|
7539
|
+
if (has("build", "implement", "add", "create", "ship", "feature")) return "feature";
|
|
7540
|
+
return "general";
|
|
7541
|
+
}
|
|
7542
|
+
|
|
7543
|
+
function taskTerms(value) {
|
|
7544
|
+
let text;
|
|
7545
|
+
try { text = JSON.stringify(value); } catch { return []; }
|
|
7546
|
+
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"]);
|
|
7547
|
+
const out = [];
|
|
7548
|
+
const seen = new Set();
|
|
7549
|
+
for (const raw of text.match(/[A-Za-z][A-Za-z0-9_./-]{2,63}/g) ?? []) {
|
|
7550
|
+
const term = raw.toLowerCase().replace(/^[-./]+|[-./]+$/g, "");
|
|
7551
|
+
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;
|
|
7552
|
+
seen.add(term);
|
|
7553
|
+
out.push(term);
|
|
7554
|
+
if (out.length === 12) break;
|
|
7555
|
+
}
|
|
7556
|
+
return out;
|
|
7557
|
+
}
|
|
7558
|
+
|
|
7559
|
+
function taskContinuation(value) {
|
|
7560
|
+
const visit = (item) => {
|
|
7561
|
+
if (typeof item === "string") return item;
|
|
7562
|
+
if (Array.isArray(item)) return item.map(visit).filter(Boolean).join(" ");
|
|
7563
|
+
if (!item || typeof item !== "object") return "";
|
|
7564
|
+
return visit(item.text ?? item.content ?? item.message ?? "");
|
|
7565
|
+
};
|
|
7566
|
+
const prompt = visit(value).trim().toLowerCase();
|
|
7567
|
+
if (!prompt || prompt.length > 160 || prompt.split(/\\s+/).length > 14) return false;
|
|
7568
|
+
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);
|
|
7569
|
+
}
|
|
7570
|
+
|
|
7571
|
+
export default {
|
|
7572
|
+
id: "caveman-native",
|
|
7573
|
+
async setup(ctx) {
|
|
7574
|
+
// Per-plugin-instance state: one setup() runs per location, so two
|
|
7575
|
+
// projects never share session context through module scope.
|
|
7576
|
+
const contexts = new Map();
|
|
7577
|
+
const pending = new Map();
|
|
7578
|
+
|
|
7579
|
+
function sessionContext(sessionID) {
|
|
7580
|
+
if (!contexts.has(sessionID)) {
|
|
7581
|
+
const out = call("SessionStart", { session_id: sessionID, surface: "cli" });
|
|
7582
|
+
const context = out?.hookSpecificOutput?.additionalContext;
|
|
7583
|
+
contexts.set(sessionID, typeof context === "string" ? context : "");
|
|
7584
|
+
}
|
|
7585
|
+
return contexts.get(sessionID);
|
|
7586
|
+
}
|
|
7587
|
+
|
|
7588
|
+
const controller = new AbortController();
|
|
7589
|
+
const events = (async () => {
|
|
7590
|
+
for await (const event of ctx.event.subscribe({ signal: controller.signal })) {
|
|
7591
|
+
handleEvent(event);
|
|
7592
|
+
}
|
|
7593
|
+
})().catch(() => {
|
|
7594
|
+
if (!controller.signal.aborted) console.warn("[caveman-native] Event subscription failed");
|
|
7595
|
+
});
|
|
7596
|
+
|
|
7597
|
+
function sameLocation(event) {
|
|
7598
|
+
return event.location?.directory === ctx.location.directory &&
|
|
7599
|
+
event.location?.workspaceID === ctx.location.workspaceID;
|
|
7600
|
+
}
|
|
7601
|
+
|
|
7602
|
+
function handleEvent(event) {
|
|
7603
|
+
if (!sameLocation(event)) return;
|
|
7604
|
+
const type = event.type;
|
|
7605
|
+
const sessionID = event.data?.sessionID;
|
|
7606
|
+
if (typeof sessionID !== "string" || !sessionID) return;
|
|
7607
|
+
if (type === "session.created") sessionContext(sessionID);
|
|
7608
|
+
if (type === "session.idle") call("Stop", { session_id: sessionID });
|
|
7609
|
+
// "session.compacted" is the V1 event name; V2 reports compaction
|
|
7610
|
+
// through "session.compaction.ended". Handle both.
|
|
7611
|
+
if (type === "session.compaction.ended" || type === "session.compacted") {
|
|
7612
|
+
const out = call("PostCompact", { session_id: sessionID });
|
|
7613
|
+
const context = out?.hookSpecificOutput?.additionalContext;
|
|
7614
|
+
if (typeof context === "string" && context) contexts.set(sessionID, context);
|
|
7615
|
+
}
|
|
7616
|
+
if (type === "session.deleted") {
|
|
7617
|
+
call("SessionEnd", { session_id: sessionID });
|
|
7618
|
+
contexts.delete(sessionID);
|
|
7619
|
+
pending.delete(sessionID);
|
|
7620
|
+
}
|
|
7621
|
+
}
|
|
7622
|
+
|
|
7623
|
+
await ctx.session.hook("prompt", (event) => {
|
|
7624
|
+
const prompt = event.prompt ?? {};
|
|
7625
|
+
const decision = call("UserPromptSubmit", {
|
|
7626
|
+
session_id: event.sessionID,
|
|
7627
|
+
prompt: digest(prompt),
|
|
7628
|
+
task_type: taskType(prompt),
|
|
7629
|
+
task_terms: taskTerms(prompt),
|
|
7630
|
+
task_continuation: taskContinuation(prompt),
|
|
7631
|
+
});
|
|
7632
|
+
const dynamic = decision?.hookSpecificOutput?.additionalContext;
|
|
7633
|
+
if (typeof dynamic === "string" && dynamic) pending.set(event.sessionID, dynamic);
|
|
7634
|
+
});
|
|
7635
|
+
|
|
7636
|
+
await ctx.session.hook("context", (event) => {
|
|
7637
|
+
const stable = sessionContext(event.sessionID);
|
|
7638
|
+
if (stable) event.system.push({ type: "text", text: stable });
|
|
7639
|
+
const hint = pending.get(event.sessionID);
|
|
7640
|
+
if (hint) {
|
|
7641
|
+
event.system.push({ type: "text", text: hint });
|
|
7642
|
+
pending.delete(event.sessionID);
|
|
7643
|
+
}
|
|
7644
|
+
});
|
|
7645
|
+
|
|
7646
|
+
await ctx.session.hook("compaction", (event) => {
|
|
7647
|
+
call("PreCompact", { session_id: event.sessionID });
|
|
7648
|
+
const stable = sessionContext(event.sessionID);
|
|
7649
|
+
if (stable) event.system.push({ type: "text", text: stable });
|
|
7650
|
+
});
|
|
7651
|
+
|
|
7652
|
+
await ctx.tool.hook("execute.before", (event) => {
|
|
7653
|
+
const decision = call("PreToolUse", {
|
|
7654
|
+
session_id: event.sessionID,
|
|
7655
|
+
tool_name: event.tool,
|
|
7656
|
+
tool_input: event.input,
|
|
7657
|
+
});
|
|
7658
|
+
if (typeof decision?.hookSpecificOutput?.additionalContext === "string") {
|
|
7659
|
+
pending.set(event.sessionID, decision.hookSpecificOutput.additionalContext);
|
|
7660
|
+
}
|
|
7661
|
+
// V1 named this tool "bash"; V2 renamed the permission action to
|
|
7662
|
+
// "shell". Accept both so the rewrite survives either host.
|
|
7663
|
+
const input = event.input;
|
|
7664
|
+
if ((event.tool === "bash" || event.tool === "shell") &&
|
|
7665
|
+
input && typeof input === "object" && typeof input.command === "string") {
|
|
7666
|
+
try {
|
|
7667
|
+
const raw = execFileSync(command, [...prefix, "shrink-hook"], {
|
|
7668
|
+
input: JSON.stringify({ tool_name: "Bash", tool_input: { command: input.command } }),
|
|
7669
|
+
encoding: "utf8",
|
|
7670
|
+
timeout: 750,
|
|
7671
|
+
});
|
|
7672
|
+
const rewritten = JSON.parse(raw)?.hookSpecificOutput?.updatedInput?.command;
|
|
7673
|
+
if (typeof rewritten === "string" && rewritten) input.command = rewritten;
|
|
7674
|
+
} catch {}
|
|
7675
|
+
}
|
|
7676
|
+
});
|
|
7677
|
+
|
|
7678
|
+
await ctx.tool.hook("execute.after", (event) => {
|
|
7679
|
+
if (event.status !== "completed") return;
|
|
7680
|
+
const decision = call("PostToolUse", {
|
|
7681
|
+
session_id: event.sessionID,
|
|
7682
|
+
tool_name: event.tool,
|
|
7683
|
+
tool_input: event.input,
|
|
7684
|
+
tool_output: event.result,
|
|
7685
|
+
});
|
|
7686
|
+
const replacement = decision?.hookSpecificOutput?.updatedToolOutput ?? decision?.output_replacement;
|
|
7687
|
+
if (typeof replacement === "string") {
|
|
7688
|
+
event.result = { ...event.result, content: replacement };
|
|
7689
|
+
}
|
|
7690
|
+
});
|
|
7691
|
+
|
|
7692
|
+
return () => {
|
|
7693
|
+
controller.abort();
|
|
7694
|
+
for (const sessionID of contexts.keys()) call("SessionEnd", { session_id: sessionID });
|
|
7695
|
+
contexts.clear();
|
|
7696
|
+
pending.clear();
|
|
7697
|
+
};
|
|
7698
|
+
},
|
|
7699
|
+
};
|
|
7700
|
+
`;
|
|
7701
|
+
}
|
|
6942
7702
|
function opencodeNativeMutations(gw, mcpBinary) {
|
|
6943
7703
|
const configPath = join(homedir(), ".config", "opencode", "opencode.json");
|
|
6944
7704
|
const before = fileBytes(configPath);
|
|
@@ -7671,6 +8431,69 @@ function readNativeJournal(agent) {
|
|
|
7671
8431
|
function readPendingNativeJournal(agent) {
|
|
7672
8432
|
return readNativeJournalAt(nativePendingJournalPath(agent), agent);
|
|
7673
8433
|
}
|
|
8434
|
+
// nativeRoutePinnedFor reports the config file that pins this agent's base URL,
|
|
8435
|
+
// when native routing is installed for it, or null when nothing is pinned.
|
|
8436
|
+
//
|
|
8437
|
+
// It reads the install journal rather than re-deriving per-agent config shapes,
|
|
8438
|
+
// so it covers every native host by construction: claude's settings.json env
|
|
8439
|
+
// block, codex's config.toml model_provider, hermes/gemini/aider's marker
|
|
8440
|
+
// fences, opencode's routes map, pi's bundle. A caller that needs to point an
|
|
8441
|
+
// agent somewhere else for one run has to know that any of these outranks the
|
|
8442
|
+
// environment it is about to set.
|
|
8443
|
+
//
|
|
8444
|
+
// Deliberately journal-only and file-cheap: unlike nativeIntegrationStatus this
|
|
8445
|
+
// probes no binary, proxy or MCP server, because the question is only "is a
|
|
8446
|
+
// route pinned on disk", not "is the whole integration healthy".
|
|
8447
|
+
//
|
|
8448
|
+
// The PENDING journal has to be consulted too, and the two are read differently.
|
|
8449
|
+
// installNativeAgent writes the pending journal first, then each host file, and
|
|
8450
|
+
// publishes the committed journal LAST. So a process death between those leaves
|
|
8451
|
+
// a fully applied, fully readable pinned route on disk with only the pending
|
|
8452
|
+
// journal to show for it — which is exactly the state this guard exists to
|
|
8453
|
+
// catch, reached by a crash instead of a successful install.
|
|
8454
|
+
//
|
|
8455
|
+
// A committed journal is taken at its word: enable finished, the route is
|
|
8456
|
+
// pinned. A pending one is genuinely ambiguous — the mutation may or may not
|
|
8457
|
+
// have landed before the process died — so it is resolved against the file
|
|
8458
|
+
// itself using the after_sha256 the journal already records. That is
|
|
8459
|
+
// agent-agnostic (no per-host config shapes here) and avoids refusing a trial
|
|
8460
|
+
// over a stale pending journal whose writes never happened.
|
|
8461
|
+
function nativeRoutePinnedFor(agent) {
|
|
8462
|
+
const routeIn = (owned) => {
|
|
8463
|
+
if (!owned)
|
|
8464
|
+
return null;
|
|
8465
|
+
if (typeof owned.route === "string" && owned.route)
|
|
8466
|
+
return owned.route;
|
|
8467
|
+
// opencode pins one route per protocol instead of a single base URL.
|
|
8468
|
+
const routes = owned.routes;
|
|
8469
|
+
if (routes && typeof routes === "object" && !Array.isArray(routes)) {
|
|
8470
|
+
for (const value of Object.values(routes)) {
|
|
8471
|
+
if (typeof value === "string" && value)
|
|
8472
|
+
return value;
|
|
8473
|
+
}
|
|
8474
|
+
}
|
|
8475
|
+
return null;
|
|
8476
|
+
};
|
|
8477
|
+
const committed = readNativeJournal(agent);
|
|
8478
|
+
for (const operation of committed?.operations ?? []) {
|
|
8479
|
+
const route = routeIn(operation.owned);
|
|
8480
|
+
if (route)
|
|
8481
|
+
return { file: operation.file, route, pending: false };
|
|
8482
|
+
}
|
|
8483
|
+
const pending = readPendingNativeJournal(agent);
|
|
8484
|
+
for (const operation of pending?.operations ?? []) {
|
|
8485
|
+
const route = routeIn(operation.owned);
|
|
8486
|
+
if (!route)
|
|
8487
|
+
continue;
|
|
8488
|
+
const current = fileBytes(operation.file);
|
|
8489
|
+
// No file, or contents that are not what this operation would have written,
|
|
8490
|
+
// means the interrupted install never got as far as pinning this route.
|
|
8491
|
+
if (current && bytesHash(current) === operation.after_sha256) {
|
|
8492
|
+
return { file: operation.file, route, pending: true };
|
|
8493
|
+
}
|
|
8494
|
+
}
|
|
8495
|
+
return null;
|
|
8496
|
+
}
|
|
7674
8497
|
function recoverPendingNativeInstallUnlocked(agent) {
|
|
7675
8498
|
const pending = readPendingNativeJournal(agent);
|
|
7676
8499
|
if (!pending)
|
|
@@ -7780,6 +8603,22 @@ function enableNative(argv) {
|
|
|
7780
8603
|
applyNativeMutations(agent, profile, mutations);
|
|
7781
8604
|
return "enabled";
|
|
7782
8605
|
});
|
|
8606
|
+
// Outside the lock, and on BOTH outcomes. The native SessionStart hook
|
|
8607
|
+
// autostarts the proxy, but only once the host has approved the installed
|
|
8608
|
+
// hooks (Codex gates this behind /hooks), and `enable` run on its own —
|
|
8609
|
+
// outside the `caveman <agent>` shortcut, which has its own blocking
|
|
8610
|
+
// pre-start at its call site — otherwise leaves that window open
|
|
8611
|
+
// indefinitely: config.toml/settings route every request through a proxy
|
|
8612
|
+
// nothing has confirmed is listening, which is what turns a fresh Codex
|
|
8613
|
+
// session into a mid-stream disconnect rather than a connection error.
|
|
8614
|
+
//
|
|
8615
|
+
// "already" has to run it too. Re-running `enable` is exactly what someone
|
|
8616
|
+
// does when the route is dead, and the installed-state branch returns
|
|
8617
|
+
// before any of this; gating on a fresh install would make proxy startup an
|
|
8618
|
+
// accidental side effect of the first install rather than something the
|
|
8619
|
+
// command does. The integration lock is for file mutations — a liveness
|
|
8620
|
+
// probe and a detached spawn need no part of it.
|
|
8621
|
+
ensureLocalProxyForNative(agent, gw);
|
|
7783
8622
|
if (outcome === "already") {
|
|
7784
8623
|
process.stderr.write(`${mark("ok")} ${profile.display_name}: ${agent === "aider" ? "shallow" : "native"} Caveman already enabled\n`);
|
|
7785
8624
|
continue;
|
|
@@ -8256,10 +9095,12 @@ function nativeIntegrationStatus(agent) {
|
|
|
8256
9095
|
}) && JSON.stringify(mcp.caveman) === JSON.stringify(operation.owned?.installed_mcp);
|
|
8257
9096
|
}
|
|
8258
9097
|
else if (operation.kind === "opencode-plugin") {
|
|
8259
|
-
|
|
9098
|
+
const text = current.toString("utf8");
|
|
9099
|
+
owned = text.includes("caveman:native-opencode") && generatedArtifactTargetsExist(text);
|
|
8260
9100
|
}
|
|
8261
9101
|
else if (operation.kind === "pi-extension") {
|
|
8262
|
-
|
|
9102
|
+
const text = current.toString("utf8");
|
|
9103
|
+
owned = text.includes("caveman:native-pi") && generatedArtifactTargetsExist(text);
|
|
8263
9104
|
}
|
|
8264
9105
|
else if (operation.kind === "aider-config") {
|
|
8265
9106
|
const text = current.toString("utf8");
|
|
@@ -8311,13 +9152,38 @@ function nativeIntegrationStatus(agent) {
|
|
|
8311
9152
|
return false;
|
|
8312
9153
|
}
|
|
8313
9154
|
})();
|
|
9155
|
+
// Same class as piBundleCurrent above, one step removed: opencode's plugin API
|
|
9156
|
+
// is chosen when the mutations are built, so an install made against OpenCode
|
|
9157
|
+
// 1.x keeps its V1 hook map after the host upgrades to 2.x — which that host
|
|
9158
|
+
// refuses to load (#1083). Nothing else drifts on that upgrade: same journal,
|
|
9159
|
+
// same bytes, so packCurrent and ownedHealthy both still pass and doctor called
|
|
9160
|
+
// an unloadable plugin "installed". `caveman opencode` deliberately skips
|
|
9161
|
+
// enableNative whenever a journal exists (status probes spawn subprocesses),
|
|
9162
|
+
// which is exactly why that skip's own comment names doctor as the repair door
|
|
9163
|
+
// for drifted installs — so the drift has to be visible here to be repairable.
|
|
9164
|
+
// An unreadable version yields no judgement, matching opencodeNativePluginSource:
|
|
9165
|
+
// "unknown" is not evidence of a new host, so it must not degrade a good install.
|
|
9166
|
+
const opencodePluginApiCurrent = agent !== "opencode" || (() => {
|
|
9167
|
+
const operation = journal?.operations.find((item) => item.kind === "opencode-plugin");
|
|
9168
|
+
const current = operation ? fileBytes(operation.file)?.toString("utf8") : null;
|
|
9169
|
+
if (!current)
|
|
9170
|
+
return true;
|
|
9171
|
+
const installedV2 = current.includes("async setup(ctx)");
|
|
9172
|
+
const installedV1 = current.includes("export const CavemanNative");
|
|
9173
|
+
if (installedV1 === installedV2)
|
|
9174
|
+
return true;
|
|
9175
|
+
const semver = parsedSemver(host.version);
|
|
9176
|
+
if (!semver)
|
|
9177
|
+
return true;
|
|
9178
|
+
return (semver[0] >= 2) === installedV2;
|
|
9179
|
+
})();
|
|
8314
9180
|
const routeHealthy = ownedHealthy && (agent === "opencode"
|
|
8315
9181
|
? routeOperation?.owned?.routes?.openai === appendUrlPath(expectedRoute, "/openai/v1")
|
|
8316
9182
|
&& routeOperation?.owned?.routes?.anthropic === appendUrlPath(expectedRoute, "/anthropic/v1")
|
|
8317
9183
|
: agent === "pi" ? piBundleCurrent : routeOperation?.owned?.route === expectedRoute);
|
|
8318
9184
|
const proxyHealthy = wrapMode(gatewayURL()) === "managed" || Boolean(probeProxyVersion()?.capabilities.includes("native_runtime_v1"));
|
|
8319
9185
|
const recoveryHealthy = agent === "aider" || Boolean(mcp?.probe.current);
|
|
8320
|
-
const state = !available ? "unavailable" : transactionPending ? "degraded" : !installed ? "available" : !packCurrent || !ownedHealthy || !routeHealthy || !proxyHealthy || !recoveryHealthy ? "degraded" : "installed";
|
|
9186
|
+
const state = !available ? "unavailable" : transactionPending ? "degraded" : !installed ? "available" : !packCurrent || !ownedHealthy || !routeHealthy || !proxyHealthy || !recoveryHealthy || !opencodePluginApiCurrent ? "degraded" : "installed";
|
|
8321
9187
|
const coreSupported = agent === "aider" ? ownedHealthy : ownedHealthy && Boolean(NATIVE_PACK.core);
|
|
8322
9188
|
const coreActive = agent === "aider"
|
|
8323
9189
|
? ownedHealthy
|
|
@@ -8325,7 +9191,8 @@ function nativeIntegrationStatus(agent) {
|
|
|
8325
9191
|
const fileText = checks.map((check) => fileBytes(check.file)?.toString("utf8") ?? "").join("\n");
|
|
8326
9192
|
const components = {
|
|
8327
9193
|
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)),
|
|
8328
|
-
|
|
9194
|
+
// A plugin the host cannot load runs no hooks, whatever its bytes hash to.
|
|
9195
|
+
lifecycle_hooks: agent !== "aider" && ownedHealthy && opencodePluginApiCurrent,
|
|
8329
9196
|
core: coreActive,
|
|
8330
9197
|
mcp_recovery: agent !== "aider" && ownedHealthy && Boolean(mcp?.probe.current),
|
|
8331
9198
|
// Codex is false for the same reason hermes is: no command rewrite happens. The
|
|
@@ -8893,6 +9760,70 @@ function wrapBaseUrlEnv(gw) {
|
|
|
8893
9760
|
env.ENABLE_TOOL_SEARCH = TOOL_SEARCH_DEFAULT;
|
|
8894
9761
|
return env;
|
|
8895
9762
|
}
|
|
9763
|
+
// wrapWorkTags names the repository and branch a wrapped session is launched
|
|
9764
|
+
// in, as the managed gateway's x-cave-tags value ("repo=owner/name,branch=…").
|
|
9765
|
+
// Delivery joins coding-agent spend to merged changes on exactly these two
|
|
9766
|
+
// keys, and nothing else in the request carries them. Read once at spawn with
|
|
9767
|
+
// hardened git (git-safe.ts); a launch outside a repository, without an origin,
|
|
9768
|
+
// or on a detached HEAD yields the tags it can and never fails the wrap.
|
|
9769
|
+
// The value is fixed for the process: a branch switch mid-session is picked up
|
|
9770
|
+
// by the next launch, not this one.
|
|
9771
|
+
//
|
|
9772
|
+
// Only github.com remotes are tagged: Cloud joins tags['repo'] to the GitHub
|
|
9773
|
+
// pull requests it imported, keyed owner/name, so a same-named fork on another
|
|
9774
|
+
// host would collide with the wrong repository. Values are printable ASCII
|
|
9775
|
+
// without comma or equals — a header value must be a ByteString, and the tag
|
|
9776
|
+
// list is comma/equals delimited — anything else drops the tag, never the wrap.
|
|
9777
|
+
export function wrapWorkTags(cwd = process.cwd()) {
|
|
9778
|
+
const read = (...args) => {
|
|
9779
|
+
try {
|
|
9780
|
+
return execFileSync("git", hardenedGitArgs(cwd, ...args), {
|
|
9781
|
+
encoding: "utf8", env: hardenedGitEnv(), stdio: ["ignore", "pipe", "ignore"], timeout: 2000,
|
|
9782
|
+
}).trim();
|
|
9783
|
+
}
|
|
9784
|
+
catch {
|
|
9785
|
+
return "";
|
|
9786
|
+
}
|
|
9787
|
+
};
|
|
9788
|
+
const parts = [];
|
|
9789
|
+
const repo = repoSlugFromRemote(read("remote", "get-url", "origin"));
|
|
9790
|
+
if (repo)
|
|
9791
|
+
parts.push(`repo=${repo}`);
|
|
9792
|
+
const branch = read("branch", "--show-current");
|
|
9793
|
+
if (branch && branch.length <= 255 && workTagValueSafe(branch))
|
|
9794
|
+
parts.push(`branch=${branch}`);
|
|
9795
|
+
return parts.join(",");
|
|
9796
|
+
}
|
|
9797
|
+
// workTagValueSafe: printable ASCII (0x21–0x7E) with no comma or equals.
|
|
9798
|
+
export function workTagValueSafe(value) {
|
|
9799
|
+
return /^[\x21-\x2B\x2D-\x3C\x3E-\x7E]+$/.test(value);
|
|
9800
|
+
}
|
|
9801
|
+
// repoSlugFromRemote reduces a github.com remote URL to owner/name — the form
|
|
9802
|
+
// Cloud's Delivery join and its imported pull requests use — or "" when the
|
|
9803
|
+
// remote is on any other host or has no such shape. Never the URL itself: a
|
|
9804
|
+
// remote can embed a credential.
|
|
9805
|
+
export function repoSlugFromRemote(remote) {
|
|
9806
|
+
const cleaned = trimTrailingSlashes(remote.trim()).replace(/\.git$/i, "");
|
|
9807
|
+
let host = "";
|
|
9808
|
+
let path = "";
|
|
9809
|
+
const url = /^[a-z][a-z0-9+.-]*:\/\/([^/]+)\/(.*)$/i.exec(cleaned);
|
|
9810
|
+
const scp = /^(?:[^@/:]+@)?([^/:]+):(.*)$/.exec(cleaned);
|
|
9811
|
+
if (url) {
|
|
9812
|
+
host = url[1].replace(/^[^@]*@/, "").replace(/:\d+$/, "");
|
|
9813
|
+
path = url[2];
|
|
9814
|
+
}
|
|
9815
|
+
else if (scp) {
|
|
9816
|
+
host = scp[1];
|
|
9817
|
+
path = scp[2];
|
|
9818
|
+
}
|
|
9819
|
+
else {
|
|
9820
|
+
return "";
|
|
9821
|
+
}
|
|
9822
|
+
if (host.toLowerCase() !== "github.com")
|
|
9823
|
+
return "";
|
|
9824
|
+
const match = /^([A-Za-z0-9._-]+)\/([A-Za-z0-9._-]+)$/.exec(path);
|
|
9825
|
+
return match ? `${match[1]}/${match[2]}` : "";
|
|
9826
|
+
}
|
|
8896
9827
|
function attributedGatewayUrl(gw, agent) {
|
|
8897
9828
|
return appendUrlPath(gw, `/w/${agent.id}`);
|
|
8898
9829
|
}
|
|
@@ -8914,6 +9845,22 @@ function mergeAnthropicCustomHeader(raw, name, value) {
|
|
|
8914
9845
|
kept.push(`${name}: ${value}`);
|
|
8915
9846
|
return kept.join("\n");
|
|
8916
9847
|
}
|
|
9848
|
+
// existingCustomHeader returns the value of one header inside the newline-
|
|
9849
|
+
// separated ANTHROPIC_CUSTOM_HEADERS block ("" when present but empty), or
|
|
9850
|
+
// undefined when absent.
|
|
9851
|
+
function existingCustomHeader(raw, name) {
|
|
9852
|
+
const target = name.toLowerCase();
|
|
9853
|
+
for (const line of (raw ?? "").split(/\r\n|\n|\r/)) {
|
|
9854
|
+
const colon = line.indexOf(":");
|
|
9855
|
+
if (colon > 0 && line.slice(0, colon).trim().toLowerCase() === target)
|
|
9856
|
+
return line.slice(colon + 1).trim();
|
|
9857
|
+
}
|
|
9858
|
+
return undefined;
|
|
9859
|
+
}
|
|
9860
|
+
// workTagsOff: CAVEMAN_WORK_TAGS=0 (or false/off/no) stops the repo/branch tags.
|
|
9861
|
+
export function workTagsOff(value) {
|
|
9862
|
+
return /^(0|false|off|no)$/i.test((value ?? "").trim());
|
|
9863
|
+
}
|
|
8917
9864
|
function bedrockCredentialEnvValue(env, name) {
|
|
8918
9865
|
const raw = env[name];
|
|
8919
9866
|
if (typeof raw !== "string" || !raw.trim())
|
|
@@ -9102,6 +10049,16 @@ export function buildWrapEnv(agent, gw = gatewayURL(), mcpMode = "auto", agentAr
|
|
|
9102
10049
|
}
|
|
9103
10050
|
if (agent.id === "hermes")
|
|
9104
10051
|
applyHermesAuthEnv(env, renderedGw, gw);
|
|
10052
|
+
if (agent.id === "claude" && wrapMode(gw) === "managed") {
|
|
10053
|
+
// Repository and branch ride every request as x-cave-tags so the managed
|
|
10054
|
+
// gateway can join this session's spend to the change it ships. A user's
|
|
10055
|
+
// own x-cave-tags is sent exactly as set (even empty), and CAVEMAN_WORK_TAGS=0 sends none.
|
|
10056
|
+
const tags = workTagsOff(env.CAVEMAN_WORK_TAGS) || existingCustomHeader(env.ANTHROPIC_CUSTOM_HEADERS, "x-cave-tags") !== undefined
|
|
10057
|
+
? ""
|
|
10058
|
+
: wrapWorkTags();
|
|
10059
|
+
if (tags)
|
|
10060
|
+
env.ANTHROPIC_CUSTOM_HEADERS = mergeAnthropicCustomHeader(env.ANTHROPIC_CUSTOM_HEADERS, "x-cave-tags", tags);
|
|
10061
|
+
}
|
|
9105
10062
|
if (agent.id === "claude" && wrapMode(gw) === "local" && env[CLAUDE_ASSUME_FIRST_PARTY_ENV] === undefined && proxyAnthropicUpstreamIsFirstParty()) {
|
|
9106
10063
|
// Keep Claude Code's first-party capability set (1M context window /
|
|
9107
10064
|
// ~600k auto-compact window) intact behind the local pass-through proxy
|
|
@@ -9236,28 +10193,59 @@ export function shouldOpenLoginBrowser(noBrowser, interactive = Boolean(process.
|
|
|
9236
10193
|
}
|
|
9237
10194
|
function validateLoginArgs(argv) {
|
|
9238
10195
|
let noBrowser = false;
|
|
10196
|
+
const values = new Map();
|
|
10197
|
+
const usage = "login [--no-browser] [--instance <https-origin> | --base-url <url> [--gateway-url <url>]]";
|
|
9239
10198
|
for (let index = 0; index < argv.length; index++) {
|
|
9240
10199
|
const arg = argv[index];
|
|
9241
10200
|
if (arg === "--no-browser") {
|
|
9242
10201
|
if (noBrowser)
|
|
9243
|
-
commandUsage(
|
|
10202
|
+
commandUsage(usage);
|
|
9244
10203
|
noBrowser = true;
|
|
9245
10204
|
continue;
|
|
9246
10205
|
}
|
|
9247
|
-
|
|
9248
|
-
|
|
9249
|
-
|
|
9250
|
-
|
|
10206
|
+
const flag = arg.split("=", 1)[0];
|
|
10207
|
+
if (["--instance", "--base-url", "--gateway-url"].includes(flag)) {
|
|
10208
|
+
const value = arg.includes("=") ? arg.slice(arg.indexOf("=") + 1) : argv[++index];
|
|
10209
|
+
if (!value || value.startsWith("-") || values.has(flag))
|
|
10210
|
+
commandUsage(usage);
|
|
10211
|
+
values.set(flag, value);
|
|
9251
10212
|
continue;
|
|
9252
10213
|
}
|
|
9253
|
-
|
|
9254
|
-
|
|
9255
|
-
|
|
9256
|
-
|
|
9257
|
-
}
|
|
9258
|
-
|
|
10214
|
+
commandUsage(usage);
|
|
10215
|
+
}
|
|
10216
|
+
const instance = values.get("--instance");
|
|
10217
|
+
if (instance === undefined)
|
|
10218
|
+
return { noBrowser };
|
|
10219
|
+
if (values.has("--base-url") || values.has("--gateway-url"))
|
|
10220
|
+
commandUsage(usage);
|
|
10221
|
+
const url = new URL(instance);
|
|
10222
|
+
if (!secureLoginURL(url) || url.pathname !== "/" || url.search || url.hash || url.hostname.replace(/\.$/, "") === new URL(PROD_API_URL).hostname) {
|
|
10223
|
+
throw new Error("--instance requires a private HTTPS origin (HTTP loopback is allowed for local development)");
|
|
10224
|
+
}
|
|
10225
|
+
return { noBrowser, instance: url.origin };
|
|
10226
|
+
}
|
|
10227
|
+
function secureLoginURL(url, allowLoopback = true) {
|
|
10228
|
+
return !url.username && !url.password && (url.protocol === "https:" ||
|
|
10229
|
+
(allowLoopback && url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)));
|
|
10230
|
+
}
|
|
10231
|
+
function privateVerificationURL(code, instance) {
|
|
10232
|
+
if (typeof code.device_code !== "string" || !code.device_code || code.device_code.length > 4096 ||
|
|
10233
|
+
typeof code.user_code !== "string" || !/^[A-HJ-NP-Z2-9]{4}-[A-HJ-NP-Z2-9]{4}$/.test(code.user_code) ||
|
|
10234
|
+
typeof code.expires_in !== "number" || !Number.isFinite(code.expires_in) || code.expires_in <= 0 || code.expires_in > 3600 ||
|
|
10235
|
+
(code.interval !== undefined && (typeof code.interval !== "number" || !Number.isFinite(code.interval) || code.interval < 0 || code.interval > 60))) {
|
|
10236
|
+
throw new Error("private device authorization returned an invalid code response");
|
|
10237
|
+
}
|
|
10238
|
+
const value = code.verification_uri_complete ?? code.verification_uri;
|
|
10239
|
+
if (typeof value !== "string")
|
|
10240
|
+
throw new Error("private device authorization omitted its browser URL");
|
|
10241
|
+
const url = new URL(value);
|
|
10242
|
+
if (!secureLoginURL(url, new URL(instance).protocol === "http:") || url.hash) {
|
|
10243
|
+
throw new Error("private device authorization returned an unsafe browser URL");
|
|
9259
10244
|
}
|
|
9260
|
-
|
|
10245
|
+
url.searchParams.set("user_code", code.user_code);
|
|
10246
|
+
url.searchParams.set("connection", "mcp");
|
|
10247
|
+
url.searchParams.set("client_name", "Caveman CLI");
|
|
10248
|
+
return url.href;
|
|
9261
10249
|
}
|
|
9262
10250
|
function openLoginBrowser(url) {
|
|
9263
10251
|
const opener = loginBrowserOpener(url);
|
|
@@ -9280,6 +10268,7 @@ async function acknowledgeDeviceGrant(baseURL, accessToken, deviceCode, ackToken
|
|
|
9280
10268
|
try {
|
|
9281
10269
|
const response = await fetch(`${baseURL}/api/v1/auth/device/ack`, {
|
|
9282
10270
|
method: "POST",
|
|
10271
|
+
redirect: "manual",
|
|
9283
10272
|
headers: {
|
|
9284
10273
|
authorization: `Bearer ${accessToken}`,
|
|
9285
10274
|
"content-type": "application/json",
|
|
@@ -9308,17 +10297,18 @@ async function acknowledgeDeviceGrant(baseURL, accessToken, deviceCode, ackToken
|
|
|
9308
10297
|
}
|
|
9309
10298
|
// 0600 credentials file) — never in plaintext config. organization_id is bound
|
|
9310
10299
|
// from the returned token, never from any local input.
|
|
9311
|
-
//
|
|
9312
|
-
// runs before argument parsing, network requests, browser launch, or local writes.
|
|
10300
|
+
// Hosted login remains gated; explicit private instances use project access.
|
|
9313
10301
|
function blockCloudLoginWhileBeta() {
|
|
9314
10302
|
throw new Error("Caveman Cloud platform is still in beta.");
|
|
9315
10303
|
}
|
|
9316
10304
|
async function login(argv = []) {
|
|
9317
|
-
|
|
9318
|
-
|
|
9319
|
-
const
|
|
10305
|
+
if (!argv.some((arg) => arg === "--instance" || arg.startsWith("--instance=")))
|
|
10306
|
+
blockCloudLoginWhileBeta();
|
|
10307
|
+
const { noBrowser, instance } = validateLoginArgs(argv);
|
|
10308
|
+
const baseURL = instance ?? resolveLoginBaseUrl(argv);
|
|
9320
10309
|
const codeResp = await fetch(`${baseURL}/api/v1/auth/device/code`, {
|
|
9321
10310
|
method: "POST",
|
|
10311
|
+
redirect: "error",
|
|
9322
10312
|
headers: { "content-type": "application/json" },
|
|
9323
10313
|
body: "{}",
|
|
9324
10314
|
signal: AbortSignal.timeout(5000),
|
|
@@ -9327,8 +10317,8 @@ async function login(argv = []) {
|
|
|
9327
10317
|
throw new Error(`device authorization failed: HTTP ${codeResp.status}`);
|
|
9328
10318
|
const code = await codeResp.json();
|
|
9329
10319
|
if (!code.device_code)
|
|
9330
|
-
throw new Error(
|
|
9331
|
-
const verificationURL = code.verification_uri_complete ?? code.verification_uri;
|
|
10320
|
+
throw new Error("device authorization failed: missing device code");
|
|
10321
|
+
const verificationURL = instance ? privateVerificationURL(code, instance) : code.verification_uri_complete ?? code.verification_uri;
|
|
9332
10322
|
console.error(`\n Authorize this device in your browser:`);
|
|
9333
10323
|
console.error(` ${verificationURL}`);
|
|
9334
10324
|
console.error(` code: ${code.user_code}\n`);
|
|
@@ -9343,6 +10333,7 @@ async function login(argv = []) {
|
|
|
9343
10333
|
try {
|
|
9344
10334
|
const tokResp = await fetch(`${baseURL}/api/v1/auth/device/token`, {
|
|
9345
10335
|
method: "POST",
|
|
10336
|
+
redirect: "manual",
|
|
9346
10337
|
headers: { "content-type": "application/json" },
|
|
9347
10338
|
body: JSON.stringify({ device_code: code.device_code }),
|
|
9348
10339
|
signal: AbortSignal.timeout(5000),
|
|
@@ -9354,7 +10345,7 @@ async function login(argv = []) {
|
|
|
9354
10345
|
if (Number.isFinite(seconds) && seconds >= 0)
|
|
9355
10346
|
retryAfterMs = seconds * 1000;
|
|
9356
10347
|
}
|
|
9357
|
-
tok = await tokResp.json();
|
|
10348
|
+
tok = tokenStatus >= 300 && tokenStatus < 400 ? {} : await tokResp.json();
|
|
9358
10349
|
}
|
|
9359
10350
|
catch (error) {
|
|
9360
10351
|
// RFC 8628 polling is retryable: a dropped connection or malformed
|
|
@@ -9367,6 +10358,8 @@ async function login(argv = []) {
|
|
|
9367
10358
|
await sleep(Math.max(intervalMs, retryAfterMs, 200));
|
|
9368
10359
|
continue;
|
|
9369
10360
|
}
|
|
10361
|
+
if (tokenStatus >= 300 && tokenStatus < 400)
|
|
10362
|
+
throw new Error("device login refused a redirected token endpoint");
|
|
9370
10363
|
if (tokenStatus === 429) {
|
|
9371
10364
|
// rateLimitAuth returns a nested cave error envelope rather than the RFC
|
|
9372
10365
|
// `error` string. Status is the authoritative retry signal here.
|
|
@@ -9375,6 +10368,13 @@ async function login(argv = []) {
|
|
|
9375
10368
|
}
|
|
9376
10369
|
const accessToken = typeof tok.access_token === "string" ? tok.access_token : "";
|
|
9377
10370
|
if (accessToken) {
|
|
10371
|
+
if (instance && (tokenStatus < 200 || tokenStatus >= 300 || tok.credential_kind !== "none" ||
|
|
10372
|
+
["gateway_api_key", "gateway_key_id", "gateway_url"].some((key) => tok[key] != null) ||
|
|
10373
|
+
typeof tok.refresh_token !== "string" || !tok.refresh_token || typeof tok.project_id !== "string" || !tok.project_id ||
|
|
10374
|
+
typeof tok.delivery_ack_token !== "string" || !tok.delivery_ack_token || typeof tok.scope !== "string" || !tok.scope ||
|
|
10375
|
+
tok.scope.split(/\s+/).some((scope) => scope === "proxy:write" || scope === "sdk:write"))) {
|
|
10376
|
+
throw new Error("private device login requires a keyless project grant with a refresh token and delivery acknowledgement");
|
|
10377
|
+
}
|
|
9378
10378
|
const credentials = {
|
|
9379
10379
|
access_token: accessToken,
|
|
9380
10380
|
...(typeof tok.refresh_token === "string" && tok.refresh_token ? { refresh_token: tok.refresh_token } : {}),
|
|
@@ -9384,7 +10384,7 @@ async function login(argv = []) {
|
|
|
9384
10384
|
};
|
|
9385
10385
|
const tokenStore = storeCredentials(credentials);
|
|
9386
10386
|
const organizationId = orgFromToken(accessToken);
|
|
9387
|
-
const gateway = resolveLoginGatewayUrl(baseURL, tok, code, argv);
|
|
10387
|
+
const gateway = instance ? "" : resolveLoginGatewayUrl(baseURL, tok, code, argv);
|
|
9388
10388
|
const saved = { baseURL, token: "", tokenStore };
|
|
9389
10389
|
if (organizationId)
|
|
9390
10390
|
saved.organizationId = organizationId;
|
|
@@ -9406,6 +10406,10 @@ async function login(argv = []) {
|
|
|
9406
10406
|
// until the control plane has recorded that this CLI stored the bundle.
|
|
9407
10407
|
await acknowledgeDeviceGrant(baseURL, credentials.access_token, code.device_code, ackToken);
|
|
9408
10408
|
}
|
|
10409
|
+
if (instance) {
|
|
10410
|
+
print({ authenticated: true, baseURL, organization_id: organizationId ?? null, project_id: credentials.project_id, scope: tok.scope, credential_kind: "none", token_store: tokenStore });
|
|
10411
|
+
return;
|
|
10412
|
+
}
|
|
9409
10413
|
// Mint/refresh the local-wrap entitlement for this device. Best
|
|
9410
10414
|
// effort: login never fails for seats or a down entitlement service.
|
|
9411
10415
|
await fetchAndStoreWrapEntitlement(baseURL, credentials.access_token);
|
|
@@ -9463,6 +10467,7 @@ async function logout() {
|
|
|
9463
10467
|
};
|
|
9464
10468
|
const request = {
|
|
9465
10469
|
method: "POST",
|
|
10470
|
+
redirect: "manual",
|
|
9466
10471
|
headers,
|
|
9467
10472
|
signal: AbortSignal.timeout(5000),
|
|
9468
10473
|
};
|
|
@@ -9736,6 +10741,37 @@ function writeSyncWatermark(key, id) {
|
|
|
9736
10741
|
mkdirSync(dirname(syncStatePath()), { recursive: true });
|
|
9737
10742
|
writeFileSync(syncStatePath(), JSON.stringify(state, null, 2) + "\n", { mode: 0o600 });
|
|
9738
10743
|
}
|
|
10744
|
+
// syncClaimLockPath is the sidecar that serializes the read-query-POST-write
|
|
10745
|
+
// in syncLocalSavings across OS processes; it sits beside sync.json so its
|
|
10746
|
+
// permission and cross-filesystem behavior always matches the file it protects.
|
|
10747
|
+
function syncClaimLockPath() {
|
|
10748
|
+
return `${syncStatePath()}.lock`;
|
|
10749
|
+
}
|
|
10750
|
+
// How long a waiter blocks before giving up and reporting `busy`. Deliberately
|
|
10751
|
+
// short: syncAfterWrap runs on the wrap exit path, and making a user wait out
|
|
10752
|
+
// someone else's upload to close a shell is worse than deferring their rows to
|
|
10753
|
+
// the next sync — nothing is lost either way, the watermark simply has not moved.
|
|
10754
|
+
const SYNC_CLAIM_LOCK_BUDGET_MS = 5000;
|
|
10755
|
+
// A sync lock is held across a network POST, which has no bounded duration, so
|
|
10756
|
+
// unlike the telemetry claim its stale window cannot be a guess at the hold
|
|
10757
|
+
// time: a live holder on a slow link would be judged dead and its rows POSTed
|
|
10758
|
+
// twice, which is the very bug the lock exists to prevent. The holder instead
|
|
10759
|
+
// heartbeats the lock while it works, so this window only has to outlast a
|
|
10760
|
+
// couple of missed beats.
|
|
10761
|
+
const SYNC_CLAIM_LOCK_STALE_MS = 15000;
|
|
10762
|
+
const SYNC_CLAIM_LOCK_HEARTBEAT_MS = 3000;
|
|
10763
|
+
// refreshClaimLock bumps a held lock's mtime so waiters keep seeing it as live.
|
|
10764
|
+
// Never throws — if the lock is gone the guarded work is already compromised,
|
|
10765
|
+
// and crashing the sync on a touch failure would lose the rows in flight.
|
|
10766
|
+
function refreshClaimLock(lockPath) {
|
|
10767
|
+
try {
|
|
10768
|
+
const now = new Date();
|
|
10769
|
+
utimesSync(lockPath, now, now);
|
|
10770
|
+
}
|
|
10771
|
+
catch {
|
|
10772
|
+
/* lock vanished or the FS refused the touch; the POST still completes */
|
|
10773
|
+
}
|
|
10774
|
+
}
|
|
9739
10775
|
// deriveDashboardUrl maps the control-api base URL to the dashboard costs page
|
|
9740
10776
|
// for the two shapes Caveman ships (local docker web :3000; hosted api.<domain>
|
|
9741
10777
|
// → apex, which serves the dashboard). Anything else returns "" — no guessing.
|
|
@@ -9800,7 +10836,7 @@ function localScanSyncLine(out) {
|
|
|
9800
10836
|
return `synced 30-day local scan · inferred token summary · separate from gateway spend and verified savings${destination}`;
|
|
9801
10837
|
}
|
|
9802
10838
|
// syncRequestSpan converts one local `requests` row into a caveman-jsonl span
|
|
9803
|
-
// line (public/shared/platform/importers Span shape; timestamps are already in
|
|
10839
|
+
// line (Caveman-Cloud public/shared/platform/importers Span shape; timestamps are already in
|
|
9804
10840
|
// the ClickHouse layout because the proxy writes them that way). The basis and
|
|
9805
10841
|
// per-row inferred savings ride in attributes — the spans schema has no savings
|
|
9806
10842
|
// column, and imported rows must never look like verified ledger entries.
|
|
@@ -9877,82 +10913,112 @@ async function syncLocalSavings(cfg) {
|
|
|
9877
10913
|
}
|
|
9878
10914
|
const db = new DatabaseSync(dbPath, { readOnly: true });
|
|
9879
10915
|
let rows;
|
|
9880
|
-
|
|
9881
|
-
const firstSync = !hasSyncWatermark(key);
|
|
9882
|
-
const since = readSyncWatermark(key);
|
|
10916
|
+
let key;
|
|
9883
10917
|
try {
|
|
9884
|
-
|
|
9885
|
-
.map((row) => typeof row.name === "string" ? row.name : "")
|
|
9886
|
-
.filter(Boolean));
|
|
9887
|
-
const optional = (name, fallback) => columns.has(name) ? name : `${fallback} AS ${name}`;
|
|
9888
|
-
rows = db
|
|
9889
|
-
.prepare(`SELECT id, ts, request_id, trace_id, agent_slug, provider, model,
|
|
9890
|
-
status_code, error_code, latency_ms, request_bytes, response_bytes,
|
|
9891
|
-
input_tokens, output_tokens, cached_input_tokens,
|
|
9892
|
-
${optional("cache_creation_input_tokens", "0")}, total_cost_usd,
|
|
9893
|
-
savings_usd, basis, ${optional("token_usage_basis", "'unavailable'")},
|
|
9894
|
-
${optional("auth_mode", "'unknown'")}, runtime_mode, optimization_ids,
|
|
9895
|
-
compression_tokens_before, compression_tokens_after,
|
|
9896
|
-
${optional("compression_token_count_basis", "'unavailable'")}
|
|
9897
|
-
FROM requests WHERE id > ? ORDER BY id`)
|
|
9898
|
-
.all(since);
|
|
10918
|
+
key = syncWatermarkKey(cfg, dbFingerprint(db, dbPath, DatabaseSync));
|
|
9899
10919
|
}
|
|
9900
|
-
|
|
10920
|
+
catch (err) {
|
|
9901
10921
|
db.close();
|
|
10922
|
+
throw err;
|
|
10923
|
+
}
|
|
10924
|
+
// Everything from here to the watermark write is one claim: reading the
|
|
10925
|
+
// watermark, selecting the rows past it, POSTing them and committing the new
|
|
10926
|
+
// watermark. Without the lock two processes starting together both read the
|
|
10927
|
+
// pre-write watermark, both select the same rows and both POST them, so the
|
|
10928
|
+
// same spans land server-side twice (#1132). A waiter that cannot take the
|
|
10929
|
+
// lock in its budget sends nothing and leaves the watermark alone, so its
|
|
10930
|
+
// rows are picked up by the next sync rather than duplicated by this one.
|
|
10931
|
+
const lockPath = syncClaimLockPath();
|
|
10932
|
+
const lockToken = acquireClaimLock(lockPath, SYNC_CLAIM_LOCK_BUDGET_MS, SYNC_CLAIM_LOCK_STALE_MS);
|
|
10933
|
+
if (!lockToken) {
|
|
10934
|
+
db.close();
|
|
10935
|
+
return { kind: "busy" };
|
|
9902
10936
|
}
|
|
9903
|
-
|
|
9904
|
-
|
|
9905
|
-
|
|
9906
|
-
|
|
9907
|
-
|
|
9908
|
-
|
|
9909
|
-
|
|
9910
|
-
|
|
9911
|
-
|
|
9912
|
-
|
|
9913
|
-
|
|
9914
|
-
|
|
9915
|
-
|
|
9916
|
-
|
|
9917
|
-
|
|
9918
|
-
|
|
9919
|
-
|
|
9920
|
-
|
|
9921
|
-
|
|
9922
|
-
|
|
9923
|
-
|
|
9924
|
-
|
|
9925
|
-
|
|
9926
|
-
|
|
9927
|
-
|
|
9928
|
-
|
|
9929
|
-
|
|
9930
|
-
|
|
9931
|
-
|
|
9932
|
-
|
|
10937
|
+
// The POST below is unbounded, so keep proving this holder is alive; see
|
|
10938
|
+
// SYNC_CLAIM_LOCK_STALE_MS.
|
|
10939
|
+
const heartbeat = setInterval(() => refreshClaimLock(lockPath), SYNC_CLAIM_LOCK_HEARTBEAT_MS);
|
|
10940
|
+
heartbeat.unref();
|
|
10941
|
+
try {
|
|
10942
|
+
const firstSync = !hasSyncWatermark(key);
|
|
10943
|
+
const since = readSyncWatermark(key);
|
|
10944
|
+
try {
|
|
10945
|
+
const columns = new Set(db.prepare("PRAGMA table_info(requests)").all()
|
|
10946
|
+
.map((row) => typeof row.name === "string" ? row.name : "")
|
|
10947
|
+
.filter(Boolean));
|
|
10948
|
+
const optional = (name, fallback) => columns.has(name) ? name : `${fallback} AS ${name}`;
|
|
10949
|
+
rows = db
|
|
10950
|
+
.prepare(`SELECT id, ts, request_id, trace_id, agent_slug, provider, model,
|
|
10951
|
+
status_code, error_code, latency_ms, request_bytes, response_bytes,
|
|
10952
|
+
input_tokens, output_tokens, cached_input_tokens,
|
|
10953
|
+
${optional("cache_creation_input_tokens", "0")}, total_cost_usd,
|
|
10954
|
+
savings_usd, basis, ${optional("token_usage_basis", "'unavailable'")},
|
|
10955
|
+
${optional("auth_mode", "'unknown'")}, runtime_mode, optimization_ids,
|
|
10956
|
+
compression_tokens_before, compression_tokens_after,
|
|
10957
|
+
${optional("compression_token_count_basis", "'unavailable'")}
|
|
10958
|
+
FROM requests WHERE id > ? ORDER BY id`)
|
|
10959
|
+
.all(since);
|
|
10960
|
+
}
|
|
10961
|
+
finally {
|
|
10962
|
+
db.close();
|
|
10963
|
+
}
|
|
10964
|
+
if (rows.length === 0)
|
|
10965
|
+
return { kind: "empty" };
|
|
10966
|
+
// Per-row directive labels (review M12): a row synced from BEFORE a
|
|
10967
|
+
// directive's install carries no label — backlog sessions are not evidence
|
|
10968
|
+
// about a directive that did not exist yet. An unparseable row timestamp
|
|
10969
|
+
// labels nothing (fail closed).
|
|
10970
|
+
const directiveInstalls = installedDirectivesWithTimes();
|
|
10971
|
+
const rowDirectives = (r) => {
|
|
10972
|
+
if (directiveInstalls.length === 0)
|
|
10973
|
+
return [];
|
|
10974
|
+
const ts = typeof r.ts === "string" ? r.ts : "";
|
|
10975
|
+
// The proxy writes ClickHouse-layout UTC timestamps ("YYYY-MM-DD HH:MM:SS.mmm").
|
|
10976
|
+
const ms = Date.parse(ts.includes("T") ? ts : ts.replace(" ", "T") + "Z");
|
|
10977
|
+
if (!Number.isFinite(ms))
|
|
10978
|
+
return [];
|
|
10979
|
+
return directiveInstalls.filter((d) => ms >= d.installedAtMs).map((d) => d.id);
|
|
10980
|
+
};
|
|
10981
|
+
const body = rows.map((r) => syncRequestSpan(r, rowDirectives(r))).join("\n") + "\n";
|
|
10982
|
+
const response = await fetch(`${cfg.baseURL}/api/v1/imports?format=caveman-jsonl`, {
|
|
10983
|
+
method: "POST",
|
|
10984
|
+
headers: {
|
|
10985
|
+
authorization: `Bearer ${cfg.token}`,
|
|
10986
|
+
"content-type": "application/octet-stream",
|
|
10987
|
+
"x-cave-csrf": "cli",
|
|
10988
|
+
},
|
|
10989
|
+
body,
|
|
10990
|
+
});
|
|
10991
|
+
const result = (await response.json().catch(() => ({})));
|
|
10992
|
+
if (!response.ok || result.status !== "completed") {
|
|
10993
|
+
throw new Error(result.error?.message ?? `sync import failed (${response.status})`);
|
|
10994
|
+
}
|
|
10995
|
+
const num = (v) => (typeof v === "bigint" ? Number(v) : typeof v === "number" && Number.isFinite(v) ? v : 0);
|
|
10996
|
+
const maxId = rows.reduce((m, r) => Math.max(m, num(r.id)), since);
|
|
10997
|
+
writeSyncWatermark(key, maxId);
|
|
10998
|
+
const tokensSaved = rows.reduce((sum, r) => sum + Math.max(0, num(r.compression_tokens_before) - num(r.compression_tokens_after)), 0);
|
|
10999
|
+
const tokenBases = new Set(rows.map((r) => (typeof r.compression_token_count_basis === "string" ? r.compression_token_count_basis : "")).filter(Boolean));
|
|
11000
|
+
const tokenCountBasis = tokenBases.size === 0 ? "unavailable" : tokenBases.size === 1 ? [...tokenBases][0] ?? "unavailable" : "mixed";
|
|
11001
|
+
const cachedInputTokens = rows.reduce((sum, r) => sum + Math.max(0, num(r.cached_input_tokens)), 0);
|
|
11002
|
+
const cacheCreationInputTokens = rows.reduce((sum, r) => sum + Math.max(0, num(r.cache_creation_input_tokens)), 0);
|
|
11003
|
+
const headlineCompressionRefused = cacheCreationInputTokens > cachedInputTokens;
|
|
11004
|
+
const savingsUSD = rows.reduce((sum, r) => sum + num(r.savings_usd), 0);
|
|
11005
|
+
return {
|
|
11006
|
+
kind: "synced",
|
|
11007
|
+
spans: rows.length,
|
|
11008
|
+
tokensSaved,
|
|
11009
|
+
tokenCountBasis,
|
|
11010
|
+
cachedInputTokens,
|
|
11011
|
+
cacheCreationInputTokens,
|
|
11012
|
+
headlineCompressionRefused,
|
|
11013
|
+
savingsUSD,
|
|
11014
|
+
dashboard: deriveDashboardUrl(cfg.baseURL),
|
|
11015
|
+
firstSync,
|
|
11016
|
+
};
|
|
11017
|
+
}
|
|
11018
|
+
finally {
|
|
11019
|
+
clearInterval(heartbeat);
|
|
11020
|
+
releaseClaimLock(lockPath, lockToken);
|
|
9933
11021
|
}
|
|
9934
|
-
const num = (v) => (typeof v === "bigint" ? Number(v) : typeof v === "number" && Number.isFinite(v) ? v : 0);
|
|
9935
|
-
const maxId = rows.reduce((m, r) => Math.max(m, num(r.id)), since);
|
|
9936
|
-
writeSyncWatermark(key, maxId);
|
|
9937
|
-
const tokensSaved = rows.reduce((sum, r) => sum + Math.max(0, num(r.compression_tokens_before) - num(r.compression_tokens_after)), 0);
|
|
9938
|
-
const tokenBases = new Set(rows.map((r) => (typeof r.compression_token_count_basis === "string" ? r.compression_token_count_basis : "")).filter(Boolean));
|
|
9939
|
-
const tokenCountBasis = tokenBases.size === 0 ? "unavailable" : tokenBases.size === 1 ? [...tokenBases][0] ?? "unavailable" : "mixed";
|
|
9940
|
-
const cachedInputTokens = rows.reduce((sum, r) => sum + Math.max(0, num(r.cached_input_tokens)), 0);
|
|
9941
|
-
const cacheCreationInputTokens = rows.reduce((sum, r) => sum + Math.max(0, num(r.cache_creation_input_tokens)), 0);
|
|
9942
|
-
const headlineCompressionRefused = cacheCreationInputTokens > cachedInputTokens;
|
|
9943
|
-
const savingsUSD = rows.reduce((sum, r) => sum + num(r.savings_usd), 0);
|
|
9944
|
-
return {
|
|
9945
|
-
kind: "synced",
|
|
9946
|
-
spans: rows.length,
|
|
9947
|
-
tokensSaved,
|
|
9948
|
-
tokenCountBasis,
|
|
9949
|
-
cachedInputTokens,
|
|
9950
|
-
cacheCreationInputTokens,
|
|
9951
|
-
headlineCompressionRefused,
|
|
9952
|
-
savingsUSD,
|
|
9953
|
-
dashboard: deriveDashboardUrl(cfg.baseURL),
|
|
9954
|
-
firstSync,
|
|
9955
|
-
};
|
|
9956
11022
|
}
|
|
9957
11023
|
function syncSavingsLine(out, local = false) {
|
|
9958
11024
|
const destination = out.dashboard ? ` → ${out.dashboard}` : "";
|
|
@@ -10039,6 +11105,11 @@ async function sync() {
|
|
|
10039
11105
|
else if (out.kind === "empty") {
|
|
10040
11106
|
console.log("nothing new to sync — local inferred savings are already up to date");
|
|
10041
11107
|
}
|
|
11108
|
+
else if (out.kind === "busy") {
|
|
11109
|
+
// Not a failure: another caveman process holds the watermark and is
|
|
11110
|
+
// uploading these rows right now. Exit 0 — re-running is always safe.
|
|
11111
|
+
console.log("another sync is already running — local spans left for the next `caveman sync`");
|
|
11112
|
+
}
|
|
10042
11113
|
else {
|
|
10043
11114
|
if (out.firstSync)
|
|
10044
11115
|
console.log(SYNC_DISCLOSURE);
|
|
@@ -10086,6 +11157,9 @@ async function syncAfterLogin() {
|
|
|
10086
11157
|
if (savingsLane.value.kind === "synced") {
|
|
10087
11158
|
console.error(` ${mark("ok")} ${syncSavingsLine(savingsLane.value, true)}`);
|
|
10088
11159
|
}
|
|
11160
|
+
else if (savingsLane.value.kind === "busy") {
|
|
11161
|
+
console.error(dim(` another sync is already running — run \`${invokedAs()} sync\` afterwards to pick up the rest`));
|
|
11162
|
+
}
|
|
10089
11163
|
else {
|
|
10090
11164
|
console.error(dim(" no local spans to sync yet — `caveman wrap <agent>` records inferred savings locally; `caveman sync` uploads them"));
|
|
10091
11165
|
}
|
|
@@ -10233,9 +11307,38 @@ function mcpServerInstalled(agentId, serverName) {
|
|
|
10233
11307
|
return false;
|
|
10234
11308
|
}
|
|
10235
11309
|
}
|
|
11310
|
+
function nativeOpencodeMcpInstalled() {
|
|
11311
|
+
const journal = readNativeJournal("opencode");
|
|
11312
|
+
if (!journal)
|
|
11313
|
+
return false;
|
|
11314
|
+
const operation = journal.operations.find((item) => item.kind === "opencode-config");
|
|
11315
|
+
if (!operation?.owned?.installed_mcp)
|
|
11316
|
+
return false;
|
|
11317
|
+
const current = fileBytes(operation.file);
|
|
11318
|
+
if (!current)
|
|
11319
|
+
return false;
|
|
11320
|
+
try {
|
|
11321
|
+
const root = parseJsonFileObject(operation.file, current);
|
|
11322
|
+
const mcp = root.mcp && typeof root.mcp === "object" && !Array.isArray(root.mcp)
|
|
11323
|
+
? root.mcp
|
|
11324
|
+
: {};
|
|
11325
|
+
// canonicalize, not JSON.stringify: the comparison is about whether the
|
|
11326
|
+
// registration is still ours, and key order is not part of that. Any writer
|
|
11327
|
+
// that round-trips opencode.json through a rebuilt or sorted map reorders
|
|
11328
|
+
// these keys without changing the registration, and a raw stringify compare
|
|
11329
|
+
// would then report "MCP recovery missing" for a registration that is
|
|
11330
|
+
// present and correct — the same false negative this function exists to fix.
|
|
11331
|
+
return canonicalize(mcp.caveman) === canonicalize(operation.owned.installed_mcp);
|
|
11332
|
+
}
|
|
11333
|
+
catch {
|
|
11334
|
+
return false;
|
|
11335
|
+
}
|
|
11336
|
+
}
|
|
10236
11337
|
function mcpInstalled(agentId, agentArgs = []) {
|
|
10237
11338
|
if (agentId === "kilo" || agentId === "qwen")
|
|
10238
11339
|
return ownedMcpRegistration(agentId, agentArgs) !== null;
|
|
11340
|
+
if (agentId === "opencode" && nativeOpencodeMcpInstalled())
|
|
11341
|
+
return true;
|
|
10239
11342
|
return mcpServerInstalled(agentId, "caveman");
|
|
10240
11343
|
}
|
|
10241
11344
|
// configFileOverlayHasMcp asks whether the PROFILE would inject this MCP server
|
|
@@ -11179,6 +12282,10 @@ function qwenStringList(root, path, fallback) {
|
|
|
11179
12282
|
return null;
|
|
11180
12283
|
return resolved;
|
|
11181
12284
|
}
|
|
12285
|
+
// Through qwenCavemanToolDenied below: ported, with changes, from Qwen Code
|
|
12286
|
+
// 0.22.3 (https://github.com/QwenLM/qwen-code), Copyright 2025 Google LLC and
|
|
12287
|
+
// Copyright 2025 Qwen, Apache License 2.0. See NOTICE.
|
|
12288
|
+
//
|
|
11182
12289
|
// Exact wildcard matcher used by Qwen 0.22 for mcp.allowed/mcp.excluded:
|
|
11183
12290
|
// `*` spans any run, `?` spans one character, everything else is literal.
|
|
11184
12291
|
function qwenMcpServerPatternMatches(name, pattern) {
|
|
@@ -12077,11 +13184,33 @@ function agentRouteOverride(agent, args) {
|
|
|
12077
13184
|
return qwenRouteOverride(agent, args);
|
|
12078
13185
|
// Claude Code 2.1.196+ refuses Remote Control unless ANTHROPIC_BASE_URL is
|
|
12079
13186
|
// api.anthropic.com, and the first-party escape hatch does not apply (#947).
|
|
12080
|
-
if (agent.id === "claude" && args
|
|
13187
|
+
if (agent.id === "claude" && claudeStartsRemoteControl(args)) {
|
|
12081
13188
|
return { surface: "remote-control", reason: "only runs against api.anthropic.com, so it cannot route through the proxy" };
|
|
12082
13189
|
}
|
|
12083
13190
|
return null;
|
|
12084
13191
|
}
|
|
13192
|
+
// Claude Code spells Remote Control `--remote-control [name]`; the bare
|
|
13193
|
+
// `remote-control` word is the legacy subcommand. #947 matched only the latter,
|
|
13194
|
+
// so every user who followed the documented flag kept routing through the proxy
|
|
13195
|
+
// and kept being refused by the host (#1101).
|
|
13196
|
+
//
|
|
13197
|
+
// `--remote-control-session-name-prefix` only names auto-generated sessions and
|
|
13198
|
+
// does NOT start Remote Control, so it must not match — bypassing on it would
|
|
13199
|
+
// silently drop compression for a session that never needed the bypass. Scanning
|
|
13200
|
+
// stops at `--`, after which argv belongs to the agent's own payload.
|
|
13201
|
+
function claudeStartsRemoteControl(args) {
|
|
13202
|
+
// The bare legacy word is a subcommand, so it counts only in first position;
|
|
13203
|
+
// anywhere else it is a value (`-p remote-control`) and must keep routing.
|
|
13204
|
+
if (args[0] === "remote-control")
|
|
13205
|
+
return true;
|
|
13206
|
+
for (const arg of args) {
|
|
13207
|
+
if (arg === "--")
|
|
13208
|
+
return false;
|
|
13209
|
+
if (arg === "--remote-control" || arg.startsWith("--remote-control="))
|
|
13210
|
+
return true;
|
|
13211
|
+
}
|
|
13212
|
+
return false;
|
|
13213
|
+
}
|
|
12085
13214
|
function routeOverrideLabel(agent) {
|
|
12086
13215
|
if (agent.id === "qwen")
|
|
12087
13216
|
return "Qwen";
|
|
@@ -12785,7 +13914,13 @@ function installMcpCodexToml(mcp, serverName = "caveman") {
|
|
|
12785
13914
|
}
|
|
12786
13915
|
const blockStart = headerMatch.index + (headerMatch[1] ? 1 : 0);
|
|
12787
13916
|
const contentStart = headerMatch.index + headerMatch[0].length;
|
|
12788
|
-
|
|
13917
|
+
// /^[ \t]*\[/ — NOT [ \\t]. In a regex LITERAL `\\t` is an escaped backslash, so
|
|
13918
|
+
// the class was [space, backslash, "t"] and never matched a tab (#1134). A
|
|
13919
|
+
// tab-indented table is valid TOML, and Codex writes one for every trusted
|
|
13920
|
+
// project, so the boundary ran past it: the verify below never compared equal,
|
|
13921
|
+
// and the splice above deleted the user's tables. The uninstall twin
|
|
13922
|
+
// (removeMcpCodexToml) has always spelled this correctly.
|
|
13923
|
+
const nextHeaderOffset = existing.slice(contentStart).search(/^[ \t]*\[/m);
|
|
12789
13924
|
const blockEnd = nextHeaderOffset === -1 ? existing.length : contentStart + nextHeaderOffset;
|
|
12790
13925
|
const currentBlock = existing.slice(blockStart, blockEnd).trim();
|
|
12791
13926
|
if (currentBlock === expectedBlock.trim()) {
|
|
@@ -12826,7 +13961,8 @@ function codexMcpRegistrationMatches(serverName, mcp) {
|
|
|
12826
13961
|
return false;
|
|
12827
13962
|
const blockStart = headerMatch.index + (headerMatch[1] ? 1 : 0);
|
|
12828
13963
|
const contentStart = headerMatch.index + headerMatch[0].length;
|
|
12829
|
-
|
|
13964
|
+
// See the note in installMcpCodexToml: a literal [ \\t] never matched a tab (#1134).
|
|
13965
|
+
const nextHeaderOffset = existing.slice(contentStart).search(/^[ \t]*\[/m);
|
|
12830
13966
|
const blockEnd = nextHeaderOffset === -1 ? existing.length : contentStart + nextHeaderOffset;
|
|
12831
13967
|
const argsLine = mcp.args.length ? `\nargs = [${mcp.args.map((arg) => JSON.stringify(arg)).join(", ")}]` : "";
|
|
12832
13968
|
const recoveryEnv = serverName === "caveman" ? `\n${CODEX_RECOVERY_ENV}` : "";
|
|
@@ -13135,6 +14271,18 @@ const SHRINK_ALLOW = new Set([
|
|
|
13135
14271
|
"ls", "tree", "du", "df", "ps", "docker", "kubectl", "terraform", "helm",
|
|
13136
14272
|
"aws", "gcloud", "az", "gh",
|
|
13137
14273
|
]);
|
|
14274
|
+
// Subcommands that must never be wrapped even though their tool is allowlisted:
|
|
14275
|
+
// they open an editor, attach a tty, or wait on a human. Keyed by tool, matched
|
|
14276
|
+
// against every token so a global option cannot hide the subcommand (#1133).
|
|
14277
|
+
const SHRINK_SKIP_SUBCOMMANDS = new Map([
|
|
14278
|
+
["git", new Set(["commit", "rebase", "mergetool"])],
|
|
14279
|
+
["npm", new Set(["init"])],
|
|
14280
|
+
["yarn", new Set(["init"])],
|
|
14281
|
+
["pnpm", new Set(["init"])],
|
|
14282
|
+
["docker", new Set(["run", "exec", "attach"])],
|
|
14283
|
+
["kubectl", new Set(["edit", "exec", "attach"])],
|
|
14284
|
+
["terraform", new Set(["apply", "destroy"])],
|
|
14285
|
+
]);
|
|
13138
14286
|
// shouldShrink decides whether a Bash command's output should be routed through
|
|
13139
14287
|
// `caveman shrink`. Conservative by design: it only rewrites a known-noisy,
|
|
13140
14288
|
// finite, non-interactive command with no shell operators (shrink execs argv
|
|
@@ -13152,13 +14300,16 @@ function shouldShrink(command) {
|
|
|
13152
14300
|
return false; // streaming/interactive
|
|
13153
14301
|
const tokens = cmd.split(/\s+/);
|
|
13154
14302
|
const first = tokens[0] ?? "";
|
|
13155
|
-
|
|
13156
|
-
|
|
13157
|
-
|
|
13158
|
-
|
|
13159
|
-
|
|
13160
|
-
|
|
13161
|
-
|
|
14303
|
+
// The excluded subcommand can sit anywhere after the tool, because a global
|
|
14304
|
+
// option may precede it and an option may or may not take a separate value
|
|
14305
|
+
// (`git -C . commit`, `docker --context x exec`, `terraform -chdir=infra apply`).
|
|
14306
|
+
// Comparing only tokens[1] let every one of those walk past the guard and get
|
|
14307
|
+
// wrapped anyway (#1133). We do not try to parse each tool's option grammar to
|
|
14308
|
+
// find "the" subcommand — we fail closed and decline if the word appears at all.
|
|
14309
|
+
// Over-matching costs one uncompressed command; under-matching hands `shrink`,
|
|
14310
|
+
// which captures output and must terminate, a command that opens an editor.
|
|
14311
|
+
const skip = SHRINK_SKIP_SUBCOMMANDS.get(first);
|
|
14312
|
+
if (skip && tokens.slice(1).some((token) => skip.has(token)))
|
|
13162
14313
|
return false;
|
|
13163
14314
|
return SHRINK_ALLOW.has(first);
|
|
13164
14315
|
}
|
|
@@ -13186,6 +14337,8 @@ function cavemanBinForHook(powershell = process.platform === "win32") {
|
|
|
13186
14337
|
// unverified contract; if Codex ever honors that, caveman silently auto-approves a
|
|
13187
14338
|
// command the user's `approval_policy` meant to gate. Both ends fail closed instead.
|
|
13188
14339
|
async function shrinkHook() {
|
|
14340
|
+
// Host hooks never report command_run: the POST would hold the host's turn.
|
|
14341
|
+
telemetryCommandSent = true;
|
|
13189
14342
|
if (nativePolicyMode() === "record" || !new Set(["full-safe", "full-max"]).has(nativeProfile()))
|
|
13190
14343
|
process.exit(0);
|
|
13191
14344
|
let raw;
|
|
@@ -13216,10 +14369,21 @@ async function shrinkHook() {
|
|
|
13216
14369
|
// not hook's explicit PowerShell shell. Never leak PowerShell `&` into it.
|
|
13217
14370
|
const rewritten = `${cavemanBinForHook(false)} shrink -- ${command.trim()}`;
|
|
13218
14371
|
// Gemini merges hookSpecificOutput.tool_input (snake_case, no event discriminator);
|
|
13219
|
-
// Claude
|
|
14372
|
+
// Claude REPLACES via hookSpecificOutput.updatedInput (camelCase + hookEventName).
|
|
14373
|
+
// Because Claude replaces, updatedInput must carry every field the host sent —
|
|
14374
|
+
// rebuilding it from `command` alone dropped timeout, run_in_background and
|
|
14375
|
+
// description, changing how the command ran (#1133). Gemini's merge already
|
|
14376
|
+
// preserves the rest, so sending only `command` there is correct as written.
|
|
14377
|
+
//
|
|
14378
|
+
// No permissionDecision either. It is the same objection #1037 raised for Codex,
|
|
14379
|
+
// and Claude Code — unlike Codex — provably honors it: answering "allow" turned a
|
|
14380
|
+
// compression decision into a permission grant covering every state-changing
|
|
14381
|
+
// command the allowlist accepts (`git push --force`, `kubectl delete`, `aws s3 rm`).
|
|
14382
|
+
// Whether the host applies updatedInput without a decision is its call; if it does
|
|
14383
|
+
// not, the command runs unwrapped and uncompressed, which is the safe direction.
|
|
13220
14384
|
const out = isGemini
|
|
13221
14385
|
? { hookSpecificOutput: { tool_input: { command: rewritten } } }
|
|
13222
|
-
: { hookSpecificOutput: { hookEventName: "PreToolUse",
|
|
14386
|
+
: { hookSpecificOutput: { hookEventName: "PreToolUse", updatedInput: { ...evt.tool_input, command: rewritten } } };
|
|
13223
14387
|
process.stdout.write(JSON.stringify(out));
|
|
13224
14388
|
}
|
|
13225
14389
|
const NATIVE_PROFILES = new Set([
|
|
@@ -13461,7 +14625,7 @@ function nativeRepositoryState(cwd) {
|
|
|
13461
14625
|
try {
|
|
13462
14626
|
const status = execFileSync("git", hardenedGitArgs(cwd, "status", "--porcelain=v1", "-z", "--branch", "--untracked-files=all"), {
|
|
13463
14627
|
env: hardenedGitEnv(),
|
|
13464
|
-
timeout:
|
|
14628
|
+
timeout: 500, // same budget as nativehook.repositoryStatusBudget; 100ms emptied the state under load
|
|
13465
14629
|
maxBuffer: 8 * 1024 * 1024,
|
|
13466
14630
|
encoding: "buffer",
|
|
13467
14631
|
stdio: ["ignore", "pipe", "ignore"],
|
|
@@ -13784,6 +14948,8 @@ function nativeWhy(argv) {
|
|
|
13784
14948
|
// never cross the adapter boundary. Any malformed input/write failure stays
|
|
13785
14949
|
// fail-open and emits no blocking decision.
|
|
13786
14950
|
async function nativeHook(argv) {
|
|
14951
|
+
// Host hooks never report command_run: the POST would hold the host's turn.
|
|
14952
|
+
telemetryCommandSent = true;
|
|
13787
14953
|
const agent = argv[0] === "claude" || argv[0] === "codex" || argv[0] === "hermes" || argv[0] === "gemini" || argv[0] === "opencode" || argv[0] === "pi" ? argv[0] : undefined;
|
|
13788
14954
|
if (!agent)
|
|
13789
14955
|
process.exit(0);
|
|
@@ -13818,6 +14984,9 @@ async function nativeHook(argv) {
|
|
|
13818
14984
|
}[rawEventName] ?? rawEventName : rawEventName;
|
|
13819
14985
|
const normalizedEvent = eventName && NATIVE_EVENT_NAMES.has(eventName) ? eventName : "Unknown";
|
|
13820
14986
|
const sessionId = boundedHookString(event.session_id ?? event.sessionId);
|
|
14987
|
+
// A compaction re-fires SessionStart inside the same session; count real starts.
|
|
14988
|
+
if (normalizedEvent === "SessionStart" && event.source !== "compact")
|
|
14989
|
+
startSessionTelemetry(agent, sessionId, event.source);
|
|
13821
14990
|
const toolName = boundedHookString(event.tool_name ?? event.toolName);
|
|
13822
14991
|
const cwd = boundedHookString(event.cwd, 4096);
|
|
13823
14992
|
const entry = {
|
|
@@ -13834,6 +15003,8 @@ async function nativeHook(argv) {
|
|
|
13834
15003
|
entry.tool_name = toolName;
|
|
13835
15004
|
if (cwd)
|
|
13836
15005
|
entry.cwd_sha256 = `sha256:${createHash("sha256").update(cwd).digest("hex")}`;
|
|
15006
|
+
if (normalizedEvent === "SessionEnd")
|
|
15007
|
+
maybeSpawnAutopilot();
|
|
13837
15008
|
// SessionStart revives a missing local proxy, but native routing points every
|
|
13838
15009
|
// LATER turn of the session at that proxy too. Current proxies never expire,
|
|
13839
15010
|
// but crashes and older binaries can still leave a dead base URL. A plain
|
|
@@ -13885,10 +15056,23 @@ async function nativeHook(argv) {
|
|
|
13885
15056
|
// it before provider forwarding. Generated structure/order are byte-stable.
|
|
13886
15057
|
const stableContext = [coreContext, marker].filter(Boolean).join("\n");
|
|
13887
15058
|
const compactContext = [coreContext, runtimeContext, marker].filter(Boolean).join("\n");
|
|
13888
|
-
|
|
15059
|
+
// systemMessage is the user-visible channel on Claude/Codex/Gemini SessionStart;
|
|
15060
|
+
// additionalContext would put the nudge in model context instead.
|
|
15061
|
+
// Under the fast hook the parent owns the token and confirms after relaying
|
|
15062
|
+
// our stdout, since it may still drop the output on its own timeout.
|
|
15063
|
+
const relayedToken = boundedHookString(process.env.CAVEMAN_LEARN_NUDGE_TOKEN);
|
|
15064
|
+
const learnNudgeToken = relayedToken || randomUUID();
|
|
15065
|
+
const learnNudge = normalizedEvent === "SessionStart" && (agent === "claude" || agent === "codex" || agent === "gemini")
|
|
15066
|
+
? claimLearnNudge(boundedHookString(event.source), learnNudgeToken)
|
|
15067
|
+
: undefined;
|
|
15068
|
+
if (normalizedEvent === "SessionStart" && agent !== "hermes" && (stableContext || learnNudge)) {
|
|
13889
15069
|
process.stdout.write(JSON.stringify({
|
|
13890
|
-
|
|
13891
|
-
|
|
15070
|
+
...(learnNudge ? { systemMessage: learnNudge } : {}),
|
|
15071
|
+
...(stableContext ? { hookSpecificOutput: { hookEventName: normalizedEvent, additionalContext: stableContext } } : {}),
|
|
15072
|
+
}), () => {
|
|
15073
|
+
if (learnNudge && !relayedToken)
|
|
15074
|
+
confirmLearnNudge(learnNudgeToken);
|
|
15075
|
+
});
|
|
13892
15076
|
}
|
|
13893
15077
|
else if (normalizedEvent === "PostCompact" && agent !== "hermes" && compactContext) {
|
|
13894
15078
|
process.stdout.write(JSON.stringify({
|
|
@@ -14169,6 +15353,8 @@ function writeRecallHookMarker(agentId) {
|
|
|
14169
15353
|
// Fail-open by construction: any problem → exit 0 with no output (never blocks the
|
|
14170
15354
|
// agent, never injects a guess).
|
|
14171
15355
|
async function memRecallHook() {
|
|
15356
|
+
// Host hooks never report command_run: the POST would hold the host's turn.
|
|
15357
|
+
telemetryCommandSent = true;
|
|
14172
15358
|
let raw;
|
|
14173
15359
|
try {
|
|
14174
15360
|
raw = await readHookStdin();
|
|
@@ -15296,6 +16482,39 @@ async function trial(rest) {
|
|
|
15296
16482
|
const proxyResolved = which(proxyBin());
|
|
15297
16483
|
if (!proxyResolved)
|
|
15298
16484
|
return startMissingProxyUI(proxyBin());
|
|
16485
|
+
// A trial measures traffic by standing up its OWN proxy on a free port under
|
|
16486
|
+
// a `trial:<id>` label and pointing the child at it through the environment.
|
|
16487
|
+
// Native routing pins the base URL inside the agent's own config file, and an
|
|
16488
|
+
// agent reads its config in preference to its environment — so the child goes
|
|
16489
|
+
// to the persistent listener instead, which carries no trial label.
|
|
16490
|
+
// RecordPayload only stores payloads for a `trial:` label, so trial_payloads
|
|
16491
|
+
// stays empty, the replay optimizer has nothing to replay, and every number
|
|
16492
|
+
// in the report renders 0. Nothing errors; the trial exits 0 and reports a
|
|
16493
|
+
// measurement of nothing. Refuse up front instead of producing that report,
|
|
16494
|
+
// and refuse BEFORE `trial start` so no orphan trial row is opened. (#1068)
|
|
16495
|
+
const pinned = nativeRoutePinnedFor(agent?.id ?? requested);
|
|
16496
|
+
if (pinned) {
|
|
16497
|
+
console.error(pinned.pending
|
|
16498
|
+
? `caveman trial cannot measure ${agent?.id ?? requested}: an interrupted native install left its routing in place.`
|
|
16499
|
+
: `caveman trial cannot measure ${agent?.id ?? requested} while native routing is enabled.`);
|
|
16500
|
+
console.error("");
|
|
16501
|
+
console.error(` ${pinned.file}`);
|
|
16502
|
+
console.error(` pins the base URL to ${pinned.route}`);
|
|
16503
|
+
console.error("");
|
|
16504
|
+
console.error("A trial runs its own proxy on its own port and points the agent at it through");
|
|
16505
|
+
console.error("the environment. That config file wins, so the agent would keep talking to the");
|
|
16506
|
+
console.error("persistent listener, the trial would capture nothing, and the report would say");
|
|
16507
|
+
console.error("zero requests and $0.0000 — which reads as a measurement rather than as silence.");
|
|
16508
|
+
console.error("");
|
|
16509
|
+
// invokedAs(), not invokedCommand(): invokedCommand renders the verb of the
|
|
16510
|
+
// CURRENT invocation, which is always "trial" here, so it would print
|
|
16511
|
+
// "caveman trial <agent>" for the disable and enable lines.
|
|
16512
|
+
console.error(`Turn native routing off for the duration of the trial, then put it back:`);
|
|
16513
|
+
console.error(` ${invokedAs()} disable ${agent?.id ?? requested}`);
|
|
16514
|
+
console.error(` ${invokedAs()} trial -- ${command.join(" ")}`);
|
|
16515
|
+
console.error(` ${invokedAs()} enable ${agent?.id ?? requested}`);
|
|
16516
|
+
process.exit(2);
|
|
16517
|
+
}
|
|
15299
16518
|
const port = await freePort();
|
|
15300
16519
|
const listen = `127.0.0.1:${port}`;
|
|
15301
16520
|
const trialURL = `http://${listen}`;
|
|
@@ -15329,12 +16548,39 @@ async function trial(rest) {
|
|
|
15329
16548
|
throw error;
|
|
15330
16549
|
}
|
|
15331
16550
|
}
|
|
15332
|
-
|
|
15333
|
-
|
|
16551
|
+
// learnEmpty names the window the proxy actually scanned (plan.window.since;
|
|
16552
|
+
// older proxies omit it and always scanned 30d).
|
|
16553
|
+
function learnEmpty(plan) {
|
|
16554
|
+
const since = learnSince(plan.window?.since || "30d");
|
|
16555
|
+
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`;
|
|
16556
|
+
}
|
|
16557
|
+
// learnNoScoreYet explains why there is no score: the score needs the same
|
|
16558
|
+
// text repeated in at least 3 sessions.
|
|
16559
|
+
function learnNoScoreYet(sessions) {
|
|
16560
|
+
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`;
|
|
16561
|
+
}
|
|
16562
|
+
const LEARN_CLASS_LABELS = {
|
|
16563
|
+
reducible: "safe fix",
|
|
16564
|
+
recurring_context: "repeated text",
|
|
16565
|
+
behavioral: "habit",
|
|
16566
|
+
load_bearing: "needed",
|
|
16567
|
+
};
|
|
16568
|
+
function learnClassLabel(klass) {
|
|
16569
|
+
return LEARN_CLASS_LABELS[klass] ?? klass.replaceAll("_", " ");
|
|
16570
|
+
}
|
|
16571
|
+
// learnSince turns a --since value like "30d" into "30 days".
|
|
16572
|
+
function learnSince(since) {
|
|
16573
|
+
const days = /^(\d+)d$/.exec(since)?.[1];
|
|
16574
|
+
return days ? `${days} day${days === "1" ? "" : "s"}` : since;
|
|
16575
|
+
}
|
|
16576
|
+
function commaCount(value) {
|
|
16577
|
+
return Math.round(value).toLocaleString("en-US");
|
|
16578
|
+
}
|
|
16579
|
+
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";
|
|
15334
16580
|
const LEARN_ALL_FOOTER = [
|
|
15335
|
-
"advanced: caveman learn applied <
|
|
15336
|
-
"simulate: caveman learn simulate <
|
|
15337
|
-
"scope: caveman learn --repo <substring>
|
|
16581
|
+
"advanced: caveman learn applied <id> [--fix-kind <kind>] [--note <text>] record a fix you approved, so later runs can measure it",
|
|
16582
|
+
"simulate: caveman learn simulate <id...> estimate what fixes would have saved over your past sessions",
|
|
16583
|
+
"scope: caveman learn --repo <substring> only read sessions from matching repositories",
|
|
15338
16584
|
];
|
|
15339
16585
|
const LEARN_SUMMARY_LIMIT = 3;
|
|
15340
16586
|
function learnReportPath() {
|
|
@@ -15362,14 +16608,15 @@ function renderLearnDetailedRows(plan, markdown) {
|
|
|
15362
16608
|
const lines = [];
|
|
15363
16609
|
for (const [index, sink] of plan.sinks.entries()) {
|
|
15364
16610
|
const lead = markdown ? `${index + 1}. **${sink.title}**` : `${index + 1}. ${sink.title}`;
|
|
15365
|
-
lines.push(
|
|
16611
|
+
lines.push(lead);
|
|
16612
|
+
lines.push(` ${learnClassLabel(sink.class)} · id: ${sink.sink_id}`);
|
|
15366
16613
|
const observed = typeof sink.tokens_observed === "number" && sink.tokens_observed > 0
|
|
15367
|
-
? ` ·
|
|
16614
|
+
? ` · ${commaCount(sink.tokens_observed)} tokens so far`
|
|
15368
16615
|
: "";
|
|
15369
16616
|
const prefix = learnMeasuredPrefixSuffix(sink);
|
|
15370
|
-
lines.push(`
|
|
16617
|
+
lines.push(` ${commaCount(sink.tokens_per_turn)} tokens per message · ${commaCount(sink.tokens_per_day_rate)} tokens a day${observed} · estimate${prefix}`);
|
|
15371
16618
|
if (KNOWN_PRACTICE_IDS.has(sink.practice_id)) {
|
|
15372
|
-
lines.push(` practice: ${sink.practice_id} ·
|
|
16619
|
+
lines.push(` practice: ${sink.practice_id} · not measured or verified yet`);
|
|
15373
16620
|
}
|
|
15374
16621
|
if (sink.suggestion)
|
|
15375
16622
|
lines.push(` ${sink.suggestion}`);
|
|
@@ -15385,7 +16632,7 @@ function learnMeasuredPrefixSuffix(sink) {
|
|
|
15385
16632
|
return "";
|
|
15386
16633
|
const measured = learnEvidenceNumber(sink, "measured_prefix_tokens");
|
|
15387
16634
|
return measured && measured > 0
|
|
15388
|
-
? ` ·
|
|
16635
|
+
? ` · a session's first message is ~${humanTokens(measured)} tokens (typical, counted by your provider)`
|
|
15389
16636
|
: "";
|
|
15390
16637
|
}
|
|
15391
16638
|
function compactLearnText(value, max = 108) {
|
|
@@ -15399,6 +16646,12 @@ function compactLearnText(value, max = 108) {
|
|
|
15399
16646
|
const wordEnd = prefix.lastIndexOf(" ");
|
|
15400
16647
|
return `${prefix.slice(0, wordEnd > 0 ? wordEnd : prefix.length)}…`;
|
|
15401
16648
|
}
|
|
16649
|
+
// learnMemoryHealthLine points at the memory & rules doctor findings in one
|
|
16650
|
+
// line; they carry no token rate, so they rarely make the top moves.
|
|
16651
|
+
function learnMemoryHealthLine(plan) {
|
|
16652
|
+
const count = plan.sinks.filter((sink) => sink.sink_id.startsWith("memory_health:")).length;
|
|
16653
|
+
return count > 0 ? `memory files ${count} finding${count === 1 ? "" : "s"} — see ${invokedAs()} learn --all` : undefined;
|
|
16654
|
+
}
|
|
15402
16655
|
export function learnSummaryMoves(plan) {
|
|
15403
16656
|
const moves = [];
|
|
15404
16657
|
const best = plan.portfolio?.best_next_move;
|
|
@@ -15406,17 +16659,17 @@ export function learnSummaryMoves(plan) {
|
|
|
15406
16659
|
if (best) {
|
|
15407
16660
|
const confidenceLabels = {
|
|
15408
16661
|
measured_usage: "measured",
|
|
15409
|
-
transcript_inferred: "
|
|
16662
|
+
transcript_inferred: "estimated from transcripts",
|
|
15410
16663
|
static_estimate: "estimate",
|
|
15411
16664
|
};
|
|
15412
16665
|
const confidence = confidenceLabels[best.confidence] ?? best.confidence;
|
|
15413
16666
|
const detail = [
|
|
15414
|
-
|
|
16667
|
+
best.fix_label,
|
|
15415
16668
|
best.combined_rate_per_day > 0
|
|
15416
|
-
? `~${humanTokens(best.combined_rate_per_day)} tokens
|
|
16669
|
+
? `~${humanTokens(best.combined_rate_per_day)} tokens a day`
|
|
15417
16670
|
: "",
|
|
15418
16671
|
best.combined_observed_in_window > 0
|
|
15419
|
-
? `~${humanTokens(best.combined_observed_in_window)} tokens
|
|
16672
|
+
? `~${humanTokens(best.combined_observed_in_window)} tokens so far`
|
|
15420
16673
|
: "",
|
|
15421
16674
|
confidence,
|
|
15422
16675
|
].filter(Boolean);
|
|
@@ -15440,28 +16693,30 @@ export function learnSummaryMoves(plan) {
|
|
|
15440
16693
|
const largest = Math.max(0, ...recurring.map((item) => learnEvidenceNumber(item, "block_tokens") ?? 0));
|
|
15441
16694
|
const sessions = Math.max(0, ...recurring.map((item) => learnEvidenceNumber(item, "recurrence_sessions") ?? 0));
|
|
15442
16695
|
const facts = [
|
|
15443
|
-
"
|
|
16696
|
+
"repeated text",
|
|
15444
16697
|
largest > 0 ? `largest ~${humanTokens(largest)} tokens` : "",
|
|
15445
|
-
sessions > 0 ? `up to ${sessions} sessions` : "",
|
|
15446
|
-
"
|
|
16698
|
+
sessions > 0 ? `in up to ${commaCount(sessions)} sessions` : "",
|
|
16699
|
+
"estimate",
|
|
15447
16700
|
].filter(Boolean);
|
|
15448
16701
|
moves.push({
|
|
15449
|
-
title:
|
|
15450
|
-
|
|
16702
|
+
title: recurring.length === 1
|
|
16703
|
+
? "1 piece of text gets pasted again in many sessions"
|
|
16704
|
+
: `${recurring.length} pieces of text get pasted again in many sessions`,
|
|
16705
|
+
kind: "repeated text",
|
|
15451
16706
|
detail: facts.join(" · "),
|
|
15452
|
-
action: "
|
|
16707
|
+
action: "Check each one before moving it to Caveman memory. Repeating doesn't prove the text is unneeded.",
|
|
15453
16708
|
});
|
|
15454
16709
|
}
|
|
15455
16710
|
else {
|
|
15456
16711
|
const rates = [
|
|
15457
|
-
sink.class
|
|
15458
|
-
sink.tokens_per_turn > 0 ? `~${humanTokens(sink.tokens_per_turn)} tokens
|
|
15459
|
-
sink.tokens_per_day_rate > 0 ? `~${humanTokens(sink.tokens_per_day_rate)} tokens
|
|
15460
|
-
"
|
|
16712
|
+
learnClassLabel(sink.class),
|
|
16713
|
+
sink.tokens_per_turn > 0 ? `~${humanTokens(sink.tokens_per_turn)} tokens in every message` : "",
|
|
16714
|
+
sink.tokens_per_day_rate > 0 ? `~${humanTokens(sink.tokens_per_day_rate)} tokens a day` : "",
|
|
16715
|
+
"estimate",
|
|
15461
16716
|
].filter(Boolean);
|
|
15462
16717
|
moves.push({
|
|
15463
16718
|
title: sink.title,
|
|
15464
|
-
kind: sink.class
|
|
16719
|
+
kind: learnClassLabel(sink.class),
|
|
15465
16720
|
detail: rates.join(" · "),
|
|
15466
16721
|
...(sink.suggestion ? { action: compactLearnText(sink.suggestion) } : {}),
|
|
15467
16722
|
});
|
|
@@ -15484,23 +16739,23 @@ function renderLearnSummaryRows(plan) {
|
|
|
15484
16739
|
function learnSourceLine(plan, sessions) {
|
|
15485
16740
|
const by = plan.sessions_by_source ?? {};
|
|
15486
16741
|
const sourceBits = [
|
|
15487
|
-
by.claude ? `Claude ${by.claude}` : "",
|
|
15488
|
-
by.codex ? `Codex ${by.codex}` : "",
|
|
15489
|
-
by.gemini ? `Gemini ${by.gemini}` : "",
|
|
15490
|
-
by.opencode ? `opencode ${by.opencode}` : "",
|
|
15491
|
-
by.aider ? `aider ${by.aider}` : "",
|
|
16742
|
+
by.claude ? `Claude ${commaCount(by.claude)}` : "",
|
|
16743
|
+
by.codex ? `Codex ${commaCount(by.codex)}` : "",
|
|
16744
|
+
by.gemini ? `Gemini ${commaCount(by.gemini)}` : "",
|
|
16745
|
+
by.opencode ? `opencode ${commaCount(by.opencode)}` : "",
|
|
16746
|
+
by.aider ? `aider ${commaCount(by.aider)}` : "",
|
|
15492
16747
|
].filter(Boolean);
|
|
15493
|
-
return `${sessions} sessions${sourceBits.length ? ` · ${sourceBits.join(" · ")}` : ""}`;
|
|
16748
|
+
return `${commaCount(sessions)} sessions read${sourceBits.length ? ` · ${sourceBits.join(" · ")}` : ""}`;
|
|
15494
16749
|
}
|
|
15495
16750
|
function learnDiffText(diff) {
|
|
15496
16751
|
if (!diff)
|
|
15497
16752
|
return undefined;
|
|
15498
16753
|
const bits = [
|
|
15499
|
-
diff.gone ? `${diff.gone}
|
|
15500
|
-
diff.back ? `${diff.back} back` : "",
|
|
16754
|
+
diff.gone ? `${diff.gone} finding${diff.gone === 1 ? "" : "s"} gone` : "",
|
|
16755
|
+
diff.back ? `${diff.back} came back` : "",
|
|
15501
16756
|
diff.fresh ? `${diff.fresh} new` : "",
|
|
15502
16757
|
].filter(Boolean);
|
|
15503
|
-
return bits.length ? `since your last run ${diff.days}
|
|
16758
|
+
return bits.length ? `since your last run ${diff.days} day${diff.days === 1 ? "" : "s"} ago: ${bits.join(" · ")}` : undefined;
|
|
15504
16759
|
}
|
|
15505
16760
|
export function buildLearnTuiModel(plan, options = {}) {
|
|
15506
16761
|
const sessions = Math.max(0, Number(plan.sessions_scanned ?? 0));
|
|
@@ -15508,54 +16763,75 @@ export function buildLearnTuiModel(plan, options = {}) {
|
|
|
15508
16763
|
const protectedSink = plan.sinks.find((sink) => sink.class === "load_bearing");
|
|
15509
16764
|
const confirmed = plan.confirmed?.length ?? 0;
|
|
15510
16765
|
const diffText = learnDiffText(options.diff);
|
|
16766
|
+
const trend = learnTrendLines(plan.trends);
|
|
16767
|
+
const memory = learnMemoryHealthLine(plan);
|
|
15511
16768
|
const status = sessions === 0
|
|
15512
|
-
?
|
|
16769
|
+
? learnEmpty(plan)
|
|
15513
16770
|
: !recurring
|
|
15514
|
-
?
|
|
16771
|
+
? learnNoScoreYet(sessions)
|
|
15515
16772
|
: undefined;
|
|
15516
16773
|
return {
|
|
15517
16774
|
score: recurring ? plan.cave_score.score : null,
|
|
15518
|
-
scope:
|
|
16775
|
+
scope: LEARN_SCORE_SCOPE,
|
|
15519
16776
|
sessions: learnSourceLine(plan, sessions),
|
|
15520
16777
|
...(diffText ? { diff: diffText } : {}),
|
|
16778
|
+
...(trend.length ? { trend } : {}),
|
|
15521
16779
|
...(status ? { status } : {}),
|
|
15522
16780
|
moves: learnSummaryMoves(plan),
|
|
15523
16781
|
...(protectedSink
|
|
15524
|
-
? { protected:
|
|
16782
|
+
? { protected: learnProtectedText(protectedSink) }
|
|
15525
16783
|
: {}),
|
|
16784
|
+
...(memory ? { memory } : {}),
|
|
15526
16785
|
...(confirmed > 0 ? { confirmed } : {}),
|
|
15527
16786
|
findings: plan.sinks.length,
|
|
15528
16787
|
report: options.report ?? learnReportPath(),
|
|
15529
16788
|
};
|
|
15530
16789
|
}
|
|
16790
|
+
const LEARN_SCORE_SCOPE = "your setup on this computer · an estimate, not your bill · separate from Caveman Cloud's team score";
|
|
16791
|
+
// learnProtectedText describes the needed (load-bearing) baseline: counted in
|
|
16792
|
+
// the score, never changed.
|
|
16793
|
+
function learnProtectedText(sink) {
|
|
16794
|
+
return `${sink.title} · counts in the score, but Caveman never changes it${learnMeasuredPrefixSuffix(sink)}`;
|
|
16795
|
+
}
|
|
15531
16796
|
// renderLearnSpendLines shows what the scanned window cost and, more usefully,
|
|
15532
16797
|
// what a million input tokens ACTUALLY cost after the user's own cache mix.
|
|
15533
16798
|
// The multiplier is the one number that decides whether every other finding in
|
|
15534
16799
|
// the report is expensive or trivial, so it earns a line above the moves.
|
|
15535
|
-
function renderLearnSpendLines(spend, markdown) {
|
|
16800
|
+
function renderLearnSpendLines(spend, markdown, full = true) {
|
|
15536
16801
|
if (!spend)
|
|
15537
16802
|
return [];
|
|
15538
16803
|
const lines = [];
|
|
15539
16804
|
const currency = spend.currency || "USD";
|
|
15540
|
-
const label = markdown ? "###
|
|
16805
|
+
const label = markdown ? "### Cost" : "cost";
|
|
15541
16806
|
if (spend.usd > 0) {
|
|
15542
|
-
const window = spend.window_days ? `
|
|
15543
|
-
lines.push(`${label} ${fmtMoney(spend.usd, currency)}${window} · provider
|
|
16807
|
+
const window = spend.window_days ? ` for the last ${spend.window_days} day${spend.window_days === 1 ? "" : "s"}` : "";
|
|
16808
|
+
lines.push(`${label} ${fmtMoney(spend.usd, currency)}${window} · tokens your provider counted, at list prices`);
|
|
15544
16809
|
}
|
|
15545
16810
|
const multiplier = spend.effective_input_multiplier ?? 0;
|
|
15546
16811
|
const rate = spend.effective_input_usd_per_mtok ?? 0;
|
|
15547
16812
|
if (multiplier > 0 && rate > 0) {
|
|
15548
|
-
|
|
16813
|
+
const share = multiplier * 100 >= 1 ? `${Math.round(multiplier * 100)}%` : "under 1%";
|
|
16814
|
+
// Same thresholds as the proxy's effectiveInputSummary.
|
|
16815
|
+
const verdict = multiplier < 0.25 ? "caching is doing its job" : multiplier < 0.6 ? "some caching" : "little or no caching";
|
|
16816
|
+
lines.push(`input really costs ${fmtMoney(rate, currency)} per 1M tokens · ${share} of list price — ${verdict}`);
|
|
15549
16817
|
}
|
|
15550
16818
|
const components = (spend.components ?? []).filter((component) => component.usd > 0);
|
|
15551
16819
|
if (components.length > 0 && spend.usd > 0) {
|
|
15552
|
-
lines.push(components.map((component) => `${component.key.
|
|
16820
|
+
lines.push(`where it went ${components.map((component) => `${component.key.replaceAll("_", " ")} ${Math.round(component.share_pct ?? 0)}%`).join(" · ")}`);
|
|
15553
16821
|
}
|
|
15554
|
-
|
|
15555
|
-
|
|
16822
|
+
const unpriced = spend.unpriced ?? [];
|
|
16823
|
+
if (!full && unpriced.length > 1) {
|
|
16824
|
+
// Compact view: one line; --all, --md, JSON and HTML keep every model.
|
|
16825
|
+
const tokens = unpriced.reduce((sum, row) => sum + row.tokens, 0);
|
|
16826
|
+
lines.push(`no price ${unpriced.length} models (${humanTokens(tokens)} tokens) left out, so the real total is higher · ${invokedAs()} learn --all lists them`);
|
|
16827
|
+
}
|
|
16828
|
+
else {
|
|
16829
|
+
for (const row of unpriced) {
|
|
16830
|
+
lines.push(`no price ${row.provider}/${row.model} ${humanTokens(row.tokens)} tokens left out, so the real total is higher`);
|
|
16831
|
+
}
|
|
15556
16832
|
}
|
|
15557
16833
|
if (lines.length > 0) {
|
|
15558
|
-
lines.push("subscription
|
|
16834
|
+
lines.push("on a subscription plan you pay nothing extra per token; the cost then shows what the tokens would cost on the API");
|
|
15559
16835
|
}
|
|
15560
16836
|
return lines;
|
|
15561
16837
|
}
|
|
@@ -15568,56 +16844,65 @@ export function renderLearnPlan(plan, options = {}) {
|
|
|
15568
16844
|
const lines = [];
|
|
15569
16845
|
const confirmedLines = renderLearnConfirmed(plan.confirmed, markdown);
|
|
15570
16846
|
if (sessions === 0) {
|
|
15571
|
-
lines.push(
|
|
16847
|
+
lines.push(learnEmpty(plan));
|
|
15572
16848
|
if (confirmedLines.length > 0)
|
|
15573
16849
|
lines.push("", ...confirmedLines);
|
|
15574
16850
|
}
|
|
15575
16851
|
else if (!recurring) {
|
|
15576
16852
|
if (plan.sinks.length > 0) {
|
|
15577
|
-
lines.push(...(verbose ? renderLearnDetailedRows(plan, markdown) : ["top
|
|
16853
|
+
lines.push(...(verbose ? renderLearnDetailedRows(plan, markdown) : ["top findings", ...renderLearnSummaryRows(plan)]), "");
|
|
16854
|
+
const memory = verbose ? undefined : learnMemoryHealthLine(plan);
|
|
16855
|
+
if (memory)
|
|
16856
|
+
lines.push(memory, "");
|
|
15578
16857
|
}
|
|
15579
|
-
lines.push(
|
|
16858
|
+
lines.push(learnNoScoreYet(sessions));
|
|
16859
|
+
lines.push(...(verbose ? [] : learnTrendLines(plan.trends)));
|
|
15580
16860
|
if (confirmedLines.length > 0)
|
|
15581
16861
|
lines.push("", ...confirmedLines);
|
|
15582
16862
|
}
|
|
15583
16863
|
else {
|
|
15584
16864
|
lines.push(markdown
|
|
15585
|
-
? `## Setup Score ${plan.cave_score.score} —
|
|
16865
|
+
? `## Setup Score ${plan.cave_score.score}/100 — an estimate from your local sessions, not your bill`
|
|
15586
16866
|
: verbose
|
|
15587
|
-
? `Setup Score ${plan.cave_score.score} ·
|
|
16867
|
+
? `Setup Score ${plan.cave_score.score}/100 · an estimate from your local sessions, not your bill`
|
|
15588
16868
|
: `Setup Score ${plan.cave_score.score}/100`);
|
|
15589
16869
|
if (verbose) {
|
|
15590
|
-
lines.push("scores your
|
|
15591
|
-
lines.push("the two
|
|
15592
|
-
lines.push(
|
|
16870
|
+
lines.push("scores your agent setup on this computer. Caveman Cloud's team score measures your team's traffic;");
|
|
16871
|
+
lines.push("the two use different scales and will not match");
|
|
16872
|
+
lines.push(learnSourceLine(plan, sessions));
|
|
15593
16873
|
}
|
|
15594
16874
|
else {
|
|
15595
|
-
lines.push(
|
|
16875
|
+
lines.push(LEARN_SCORE_SCOPE);
|
|
15596
16876
|
lines.push(learnSourceLine(plan, sessions));
|
|
15597
16877
|
}
|
|
15598
16878
|
const diffText = learnDiffText(options.diff);
|
|
15599
16879
|
if (diffText)
|
|
15600
16880
|
lines.push(diffText);
|
|
15601
|
-
|
|
16881
|
+
lines.push(...(verbose ? [] : learnTrendLines(plan.trends)));
|
|
16882
|
+
const spendLines = renderLearnSpendLines(plan.spend, markdown, verbose);
|
|
15602
16883
|
if (spendLines.length > 0)
|
|
15603
16884
|
lines.push("", ...spendLines);
|
|
15604
16885
|
if (confirmedLines.length > 0)
|
|
15605
16886
|
lines.push("", ...confirmedLines);
|
|
15606
16887
|
if (verbose) {
|
|
16888
|
+
const trendTable = learnTrendTable(plan.trends, markdown);
|
|
16889
|
+
if (trendTable.length > 0)
|
|
16890
|
+
lines.push("", ...trendTable);
|
|
15607
16891
|
lines.push("", ...renderLearnDetailedRows(plan, markdown), "", LEARN_DETAILED_NEXT);
|
|
15608
16892
|
}
|
|
15609
16893
|
else {
|
|
15610
16894
|
const protectedSink = plan.sinks.find((sink) => sink.class === "load_bearing");
|
|
15611
|
-
lines.push("", "top
|
|
15612
|
-
if (protectedSink)
|
|
15613
|
-
|
|
15614
|
-
|
|
15615
|
-
|
|
15616
|
-
|
|
16895
|
+
lines.push("", "top findings", ...renderLearnSummaryRows(plan));
|
|
16896
|
+
if (protectedSink)
|
|
16897
|
+
lines.push(`needed ${learnProtectedText(protectedSink)}`);
|
|
16898
|
+
const memory = learnMemoryHealthLine(plan);
|
|
16899
|
+
if (memory)
|
|
16900
|
+
lines.push(memory);
|
|
16901
|
+
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`);
|
|
15617
16902
|
}
|
|
15618
16903
|
}
|
|
15619
16904
|
if (options.all === true && (plan.repos?.length ?? 0) > 0) {
|
|
15620
|
-
lines.push("", markdown ? "### Per
|
|
16905
|
+
lines.push("", markdown ? "### Per repository" : "per repository", ...renderLearnRepos(plan.repos, markdown));
|
|
15621
16906
|
}
|
|
15622
16907
|
if (options.all === true) {
|
|
15623
16908
|
lines.push("", ...(markdown ? ["### Advanced", ...LEARN_ALL_FOOTER.map((line) => `- ${line}`)] : LEARN_ALL_FOOTER));
|
|
@@ -15634,9 +16919,9 @@ function learnMeasureValue(value) {
|
|
|
15634
16919
|
}
|
|
15635
16920
|
function learnMeasureUnit(unit) {
|
|
15636
16921
|
const labels = {
|
|
15637
|
-
config_tokens_per_turn: "
|
|
15638
|
-
turns_over_half_window_pct: "
|
|
15639
|
-
recurrence_present: "
|
|
16922
|
+
config_tokens_per_turn: "setup tokens per message",
|
|
16923
|
+
turns_over_half_window_pct: "% of messages past half the window",
|
|
16924
|
+
recurrence_present: "repeated text still present",
|
|
15640
16925
|
};
|
|
15641
16926
|
return labels[unit] ?? unit.replaceAll("_", " ");
|
|
15642
16927
|
}
|
|
@@ -15655,7 +16940,7 @@ function renderLearnConfirmed(confirmed, markdown) {
|
|
|
15655
16940
|
const rows = confirmed.flatMap((entry) => {
|
|
15656
16941
|
const applied = learnAppliedDate(entry.applied_at);
|
|
15657
16942
|
if (entry.verdict === "insufficient_data") {
|
|
15658
|
-
const line = `${symbols[entry.verdict]} ${entry.sink_id} — applied ${applied} · needs more
|
|
16943
|
+
const line = `${symbols[entry.verdict]} ${entry.sink_id} — applied ${applied} · needs more sessions after the fix (${entry.sessions_after} so far)`;
|
|
15659
16944
|
return [markdown ? `- *${line}*` : line];
|
|
15660
16945
|
}
|
|
15661
16946
|
if (entry.after === undefined || !Number.isFinite(entry.after))
|
|
@@ -15663,17 +16948,17 @@ function renderLearnConfirmed(confirmed, markdown) {
|
|
|
15663
16948
|
// How it was measured travels with the number. A confirmed row without its
|
|
15664
16949
|
// attribution reads as stronger evidence than it is.
|
|
15665
16950
|
const attribution = entry.attribution
|
|
15666
|
-
? ` · ${entry.attribution.method} (${entry.attribution.confidence}${entry.attribution.provenance === "intact" ? "" : `, ${entry.attribution.provenance}`})`
|
|
16951
|
+
? ` · ${learnMethodLabel(entry.attribution.method)} (${entry.attribution.confidence}${entry.attribution.provenance === "intact" ? "" : `, ${learnProvenanceLabel(entry.attribution.provenance)}`})`
|
|
15667
16952
|
: "";
|
|
15668
16953
|
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}`;
|
|
15669
16954
|
return [markdown ? `- ${line}` : line];
|
|
15670
16955
|
});
|
|
15671
16956
|
if (rows.length === 0)
|
|
15672
16957
|
return [];
|
|
15673
|
-
return [markdown ? "###
|
|
16958
|
+
return [markdown ? "### Fixes you applied" : "fixes you applied", ...rows];
|
|
15674
16959
|
}
|
|
15675
16960
|
function renderLearnRepos(repos, markdown) {
|
|
15676
|
-
return repos.map((repo) => `${markdown ? "- " : ""}${repo.repo} · ${repo.sessions} sessions ·
|
|
16961
|
+
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`);
|
|
15677
16962
|
}
|
|
15678
16963
|
function readLearnDiff(current) {
|
|
15679
16964
|
const dir = join(cavemanHome(), "reports");
|
|
@@ -15746,7 +17031,7 @@ function proxyExecLearn(proxyArgs, progress) {
|
|
|
15746
17031
|
catch (error) {
|
|
15747
17032
|
const e = error;
|
|
15748
17033
|
if (e.code === "ETIMEDOUT" || (e.killed && e.code !== "ENOBUFS")) {
|
|
15749
|
-
console.error(`learn scan timed out after ${seconds}s
|
|
17034
|
+
console.error(`learn scan timed out after ${seconds}s, so there is no score; run \`caveman learn --json\` to capture the raw scan`);
|
|
15750
17035
|
process.exit(1);
|
|
15751
17036
|
}
|
|
15752
17037
|
if (e.stderr)
|
|
@@ -15796,7 +17081,7 @@ function proxyExecLearnAsync(proxyArgs, onProgress) {
|
|
|
15796
17081
|
child.once("close", (code) => {
|
|
15797
17082
|
clearTimeout(timer);
|
|
15798
17083
|
if (timedOut) {
|
|
15799
|
-
reject(new Error(`learn scan timed out after ${seconds}s
|
|
17084
|
+
reject(new Error(`learn scan timed out after ${seconds}s, so there is no score; run \`caveman learn --json\` to capture the raw scan`));
|
|
15800
17085
|
return;
|
|
15801
17086
|
}
|
|
15802
17087
|
if (code !== 0) {
|
|
@@ -15848,24 +17133,24 @@ function renderLearnApply(raw, dryRun) {
|
|
|
15848
17133
|
const candidate = (raw.candidate && typeof raw.candidate === "object" ? raw.candidate : {});
|
|
15849
17134
|
const klass = String(raw.class ?? candidate.class ?? "");
|
|
15850
17135
|
if (klass === "behavioral" || klass === "load_bearing") {
|
|
15851
|
-
return "
|
|
17136
|
+
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";
|
|
15852
17137
|
}
|
|
15853
17138
|
const lines = [
|
|
15854
17139
|
String(candidate.title ?? raw.sink_id ?? "learn candidate"),
|
|
15855
|
-
`
|
|
17140
|
+
`id: ${String(raw.sink_id ?? candidate.sink_id ?? "")}`,
|
|
15856
17141
|
];
|
|
15857
17142
|
const locations = candidate.what_to_offload?.locators ?? candidate.evidence?.locators;
|
|
15858
17143
|
if (locations)
|
|
15859
17144
|
lines.push(`locations: ${JSON.stringify(locations)}`);
|
|
15860
17145
|
if (candidate.expected_tokens_per_turn_saved != null) {
|
|
15861
|
-
lines.push(`expected: ~${humanTokens(Number(candidate.expected_tokens_per_turn_saved))} tokens
|
|
17146
|
+
lines.push(`expected: ~${humanTokens(Number(candidate.expected_tokens_per_turn_saved))} fewer tokens in every message`);
|
|
15862
17147
|
}
|
|
15863
|
-
lines.push("
|
|
17148
|
+
lines.push("applies only if: it uses fewer tokens overall · and answers don't get worse");
|
|
15864
17149
|
if (dryRun)
|
|
15865
17150
|
lines.push("nothing changed — this is a preview");
|
|
15866
17151
|
else {
|
|
15867
17152
|
lines.push(`prepared, not applied — ${String(raw.candidate_path ?? join(cavemanHome(), "candidates", `learn-${raw.sink_id}.json`))}`);
|
|
15868
|
-
lines.push("
|
|
17153
|
+
lines.push("to apply it, use the caveman-learn skill: caveman tools skills install caveman-learn");
|
|
15869
17154
|
}
|
|
15870
17155
|
return `${lines.join("\n")}\n`;
|
|
15871
17156
|
}
|
|
@@ -15879,7 +17164,7 @@ export function renderLearnSavings(raw) {
|
|
|
15879
17164
|
const out = [];
|
|
15880
17165
|
if (rows.length === 0) {
|
|
15881
17166
|
out.push("no fix recorded yet");
|
|
15882
|
-
out.push("apply one
|
|
17167
|
+
out.push("apply one with the caveman-learn skill and it shows up here, with how it was measured");
|
|
15883
17168
|
for (const caveat of (raw.caveats ?? []))
|
|
15884
17169
|
out.push(dim(`· ${caveat}`));
|
|
15885
17170
|
return `${out.join("\n")}\n`;
|
|
@@ -15895,8 +17180,8 @@ export function renderLearnSavings(raw) {
|
|
|
15895
17180
|
for (const [method, group] of grouped) {
|
|
15896
17181
|
const total = byRung?.[method];
|
|
15897
17182
|
const head = total != null && currency
|
|
15898
|
-
? `${method} ${fmtMoney(total, currency)}/day`
|
|
15899
|
-
: method;
|
|
17183
|
+
? `${learnMethodLabel(method)} ${fmtMoney(total, currency)}/day`
|
|
17184
|
+
: learnMethodLabel(method);
|
|
15900
17185
|
out.push(bold(head));
|
|
15901
17186
|
for (const row of group) {
|
|
15902
17187
|
const verdict = String(row.verdict ?? "");
|
|
@@ -15906,7 +17191,7 @@ export function renderLearnSavings(raw) {
|
|
|
15906
17191
|
: verdict;
|
|
15907
17192
|
const money = row.saved_usd != null && currency ? ` ${fmtMoney(Number(row.saved_usd), currency)}/day` : "";
|
|
15908
17193
|
out.push(` ${badge} ${String(row.sink_id ?? "")} ${saved}${money}`);
|
|
15909
|
-
out.push(dim(` ${String(row.attribution?.provenance ?? "")} · confidence ${String(row.attribution?.confidence ?? "")}`));
|
|
17194
|
+
out.push(dim(` ${learnProvenanceLabel(String(row.attribution?.provenance ?? ""))} · confidence ${String(row.attribution?.confidence ?? "")}`));
|
|
15910
17195
|
for (const confounder of (row.attribution?.confounders ?? [])) {
|
|
15911
17196
|
out.push(dim(` · ${confounder}`));
|
|
15912
17197
|
}
|
|
@@ -15917,6 +17202,27 @@ export function renderLearnSavings(raw) {
|
|
|
15917
17202
|
out.push(dim(`· ${caveat}`));
|
|
15918
17203
|
return `${out.join("\n")}\n`;
|
|
15919
17204
|
}
|
|
17205
|
+
// Plain names for attribution methods and provenance; the enums stay in JSON.
|
|
17206
|
+
const LEARN_METHOD_LABELS = {
|
|
17207
|
+
deterministic_remeasure: "re-counted the edited file",
|
|
17208
|
+
counterfactual_replay: "replayed past sessions",
|
|
17209
|
+
controlled_holdout: "on/off experiment",
|
|
17210
|
+
interrupted_time_series: "before vs after",
|
|
17211
|
+
unattributed: "not measured yet",
|
|
17212
|
+
};
|
|
17213
|
+
const LEARN_PROVENANCE_LABELS = {
|
|
17214
|
+
intact: "fix still in place",
|
|
17215
|
+
changed_since: "file changed since the fix",
|
|
17216
|
+
target_missing: "file is gone",
|
|
17217
|
+
not_fingerprinted: "can't confirm the fix is still there",
|
|
17218
|
+
not_applicable: "",
|
|
17219
|
+
};
|
|
17220
|
+
function learnMethodLabel(method) {
|
|
17221
|
+
return LEARN_METHOD_LABELS[method] ?? method.replaceAll("_", " ");
|
|
17222
|
+
}
|
|
17223
|
+
function learnProvenanceLabel(provenance) {
|
|
17224
|
+
return LEARN_PROVENANCE_LABELS[provenance] ?? provenance.replaceAll("_", " ");
|
|
17225
|
+
}
|
|
15920
17226
|
// fmtMoney keeps sub-cent figures legible instead of rounding real spend to
|
|
15921
17227
|
// $0.00, which reads as "nothing" when it is not.
|
|
15922
17228
|
export function fmtMoney(value, currency) {
|
|
@@ -15924,7 +17230,7 @@ export function fmtMoney(value, currency) {
|
|
|
15924
17230
|
if (!Number.isFinite(value))
|
|
15925
17231
|
return `${symbol}0`;
|
|
15926
17232
|
if (Math.abs(value) >= 1)
|
|
15927
|
-
return `${symbol}${value.
|
|
17233
|
+
return `${symbol}${value.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
|
|
15928
17234
|
if (Math.abs(value) >= 0.01)
|
|
15929
17235
|
return `${symbol}${value.toFixed(3)}`;
|
|
15930
17236
|
return `${symbol}${value.toFixed(5)}`;
|
|
@@ -15936,11 +17242,11 @@ export function renderExperimentReport(raw) {
|
|
|
15936
17242
|
const arms = Array.isArray(raw.arms) ? raw.arms : [];
|
|
15937
17243
|
const out = [bold(`experiment ${String(raw.label ?? "")}`)];
|
|
15938
17244
|
if (raw.sink_id)
|
|
15939
|
-
out.push(dim(`
|
|
17245
|
+
out.push(dim(`id ${String(raw.sink_id)} · ${String(raw.fix_kind ?? "")}`));
|
|
15940
17246
|
for (const arm of arms) {
|
|
15941
|
-
out.push(` ${String(arm.arm).padEnd(4)} ${arm.sessions} sessions
|
|
17247
|
+
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`);
|
|
15942
17248
|
}
|
|
15943
|
-
const verdict = String(raw.verdict ?? "insufficient_data");
|
|
17249
|
+
const verdict = String(raw.verdict ?? "insufficient_data").replace("insufficient_data", "not enough data yet");
|
|
15944
17250
|
const badge = verdict === "improved" ? green("✓") : verdict === "regressed" ? red("✗") : yellow("~");
|
|
15945
17251
|
const delta = raw.median_session_tokens_delta_pct != null
|
|
15946
17252
|
? ` ${Number(raw.median_session_tokens_delta_pct) > 0 ? "+" : ""}${Number(raw.median_session_tokens_delta_pct).toFixed(1)}%`
|
|
@@ -15950,7 +17256,7 @@ export function renderExperimentReport(raw) {
|
|
|
15950
17256
|
: "";
|
|
15951
17257
|
out.push(` ${badge} ${verdict}${delta}${money}`);
|
|
15952
17258
|
if (raw.attribution?.method) {
|
|
15953
|
-
out.push(dim(` ${String(raw.attribution.method)} · confidence ${String(raw.attribution.confidence ?? "")}`));
|
|
17259
|
+
out.push(dim(` ${learnMethodLabel(String(raw.attribution.method))} · confidence ${String(raw.attribution.confidence ?? "")}`));
|
|
15954
17260
|
for (const confounder of (raw.attribution.confounders ?? []))
|
|
15955
17261
|
out.push(dim(` · ${confounder}`));
|
|
15956
17262
|
}
|
|
@@ -15958,36 +17264,83 @@ export function renderExperimentReport(raw) {
|
|
|
15958
17264
|
out.push(dim(` · ${caveat}`));
|
|
15959
17265
|
return `${out.join("\n")}\n`;
|
|
15960
17266
|
}
|
|
17267
|
+
// renderExperiments prints start/arm/stop (one experiment) or list (many):
|
|
17268
|
+
// label, state, and the arm currently running.
|
|
17269
|
+
export function renderExperiments(raw) {
|
|
17270
|
+
const experiments = Array.isArray(raw) ? raw : [raw];
|
|
17271
|
+
if (experiments.length === 0)
|
|
17272
|
+
return "no experiments yet — start one: caveman learn experiment start <label>\n";
|
|
17273
|
+
return experiments.map((exp) => {
|
|
17274
|
+
const arms = Array.isArray(exp.arms) ? exp.arms : [];
|
|
17275
|
+
const open = arms.find((arm) => !arm.ended_at);
|
|
17276
|
+
const state = exp.stopped_at ? "stopped" : open ? `${String(open.arm)} since ${String(open.started_at)}` : "paused";
|
|
17277
|
+
const sink = exp.sink_id ? dim(` id ${String(exp.sink_id)}${exp.fix_kind ? ` · ${String(exp.fix_kind)}` : ""}`) : "";
|
|
17278
|
+
return `${bold(String(exp.label ?? ""))} ${state} ${arms.length} on/off period${arms.length === 1 ? "" : "s"}${sink}\n`;
|
|
17279
|
+
}).join("");
|
|
17280
|
+
}
|
|
17281
|
+
// renderLearnDigest names the file to inspect; the digest itself is the file.
|
|
17282
|
+
export function renderLearnDigest(raw) {
|
|
17283
|
+
return `digest written: ${String(raw.path ?? "")}\n${dim(String(raw.summary ?? ""))}\ninspect it before sharing; --json prints it\n`;
|
|
17284
|
+
}
|
|
17285
|
+
// renderLearnReconcile prints measured vs billed per model. Coverage is a token
|
|
17286
|
+
// comparison, never a savings claim, so there is no money column.
|
|
17287
|
+
export function renderLearnReconcile(raw) {
|
|
17288
|
+
const rows = Array.isArray(raw.models) ? raw.models : [];
|
|
17289
|
+
const out = [bold(`reconcile ${Number(raw.coverage_pct ?? 0).toFixed(1)}% of billed tokens seen locally`)];
|
|
17290
|
+
for (const row of rows) {
|
|
17291
|
+
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)}%`);
|
|
17292
|
+
}
|
|
17293
|
+
out.push(` billed but not seen here ${humanTokens(Number(raw.unattributed_tokens ?? 0))} tokens`);
|
|
17294
|
+
for (const caveat of (raw.caveats ?? []))
|
|
17295
|
+
out.push(dim(` · ${caveat}`));
|
|
17296
|
+
return `${out.join("\n")}\n`;
|
|
17297
|
+
}
|
|
15961
17298
|
function learnUsage() {
|
|
15962
17299
|
console.log(`${invokedAs()} learn [--all|--plain|--json|--md] [--since 30d] [--sources claude,codex,gemini,opencode,aider]
|
|
15963
|
-
|
|
15964
|
-
|
|
15965
|
-
--
|
|
15966
|
-
--
|
|
17300
|
+
shows where your agent's tokens go, and what to fix first
|
|
17301
|
+
default interactive Setup Score + top findings
|
|
17302
|
+
--plain short text; no animation or keyboard menu
|
|
17303
|
+
--all every finding, with its id and suggested fix
|
|
17304
|
+
--json|--md output for tools, or a full Markdown report
|
|
15967
17305
|
implement open Claude Code or Codex to review and fix findings
|
|
15968
|
-
apply prepare one
|
|
17306
|
+
apply prepare one fix; nothing changes without your yes
|
|
17307
|
+
autopilot [status|on|off] refresh the report after sessions end
|
|
15969
17308
|
|
|
15970
|
-
savings what applied
|
|
15971
|
-
experiment
|
|
17309
|
+
savings what fixes you applied saved, grouped by how it was measured
|
|
17310
|
+
experiment test a change by switching it on and off across your own sessions
|
|
15972
17311
|
start <label> [--sink <id>] · arm <label> on|off · report <label>
|
|
15973
17312
|
· list · stop <label>
|
|
15974
|
-
export privacy-safe
|
|
17313
|
+
export a privacy-safe summary of findings (names and sizes only)
|
|
15975
17314
|
reconcile --usage-export <csv>
|
|
15976
|
-
compare what
|
|
17315
|
+
compare what Caveman measured with what your provider billed
|
|
15977
17316
|
|
|
15978
17317
|
advanced:
|
|
15979
|
-
applied <
|
|
15980
|
-
record
|
|
15981
|
-
simulate <
|
|
15982
|
-
|
|
17318
|
+
applied <id> [--fix-kind <kind>] [--note <text>]
|
|
17319
|
+
record a fix you approved, so later runs can measure it
|
|
17320
|
+
simulate <id...>
|
|
17321
|
+
estimate what fixes would have saved over your past sessions
|
|
15983
17322
|
--repo <substring>
|
|
15984
|
-
|
|
17323
|
+
only read sessions from matching repositories`);
|
|
17324
|
+
}
|
|
17325
|
+
// learnAutopilot: status/on/off for the SessionEnd background refresh. `run`
|
|
17326
|
+
// is the detached child the native hook spawns (see learn-autopilot.ts).
|
|
17327
|
+
function learnAutopilot(rest) {
|
|
17328
|
+
const sub = rest[0] ?? "status";
|
|
17329
|
+
if (sub === "run") {
|
|
17330
|
+
process.exitCode = runAutopilot(proxyBin());
|
|
17331
|
+
return;
|
|
17332
|
+
}
|
|
17333
|
+
if (sub === "on" || sub === "off")
|
|
17334
|
+
mutateRawConfig((out) => { out.learnAutopilot = sub === "on"; });
|
|
17335
|
+
else if (sub !== "status")
|
|
17336
|
+
return commandUsage("learn autopilot [status|on|off]");
|
|
17337
|
+
process.stdout.write(autopilotStatusText());
|
|
15985
17338
|
}
|
|
15986
17339
|
function learnImplementUsage() {
|
|
15987
17340
|
console.log(`${invokedAs()} learn implement [claude|codex] [--prompt "<focus>"]
|
|
15988
17341
|
opens an interactive agent with the current local learn report
|
|
15989
17342
|
installs the caveman-learn safety guide when missing
|
|
15990
|
-
never edits
|
|
17343
|
+
never edits findings marked needed; asks before every edit`);
|
|
15991
17344
|
}
|
|
15992
17345
|
function learnImplementPrompt(focus) {
|
|
15993
17346
|
const lines = [
|
|
@@ -15995,7 +17348,7 @@ function learnImplementPrompt(focus) {
|
|
|
15995
17348
|
"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.",
|
|
15996
17349
|
"Work through selected fixes one at a time. Never edit load_bearing findings.",
|
|
15997
17350
|
"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.",
|
|
15998
|
-
"Keep every local savings claim labeled inferred and never
|
|
17351
|
+
"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.",
|
|
15999
17352
|
];
|
|
16000
17353
|
if (focus)
|
|
16001
17354
|
lines.push(`User focus: ${focus}`);
|
|
@@ -16094,20 +17447,20 @@ async function learn(rest) {
|
|
|
16094
17447
|
return learnUsage();
|
|
16095
17448
|
if (sub === "implement")
|
|
16096
17449
|
return learnImplement(rest.slice(1));
|
|
16097
|
-
if (sub === "
|
|
16098
|
-
|
|
16099
|
-
|
|
16100
|
-
// reconciliation is a table, not a headline.
|
|
16101
|
-
process.stdout.write(formatLearnProxyJSON(proxyExecLearn(["learn", ...rest], false)));
|
|
16102
|
-
return;
|
|
16103
|
-
}
|
|
16104
|
-
if (sub === "experiment") {
|
|
17450
|
+
if (sub === "autopilot")
|
|
17451
|
+
return learnAutopilot(rest.slice(1));
|
|
17452
|
+
if (sub === "export" || sub === "reconcile" || sub === "experiment") {
|
|
16105
17453
|
const rawText = proxyExecLearn(["learn", ...rest], false);
|
|
16106
|
-
if (rest.includes("--json")
|
|
17454
|
+
if (rest.includes("--json")) {
|
|
16107
17455
|
process.stdout.write(formatLearnProxyJSON(rawText));
|
|
16108
17456
|
return;
|
|
16109
17457
|
}
|
|
16110
|
-
|
|
17458
|
+
const parsed = JSON.parse(rawText);
|
|
17459
|
+
const render = sub === "export" ? renderLearnDigest
|
|
17460
|
+
: sub === "reconcile" ? renderLearnReconcile
|
|
17461
|
+
: rest[1] === "report" ? renderExperimentReport
|
|
17462
|
+
: renderExperiments;
|
|
17463
|
+
process.stdout.write(render(parsed));
|
|
16111
17464
|
return;
|
|
16112
17465
|
}
|
|
16113
17466
|
if (sub === "savings") {
|
|
@@ -16149,7 +17502,13 @@ async function learn(rest) {
|
|
|
16149
17502
|
if (tui) {
|
|
16150
17503
|
const learnTui = await import("./learn-tui.js");
|
|
16151
17504
|
const progress = learnTui.createLearnProgress();
|
|
16152
|
-
|
|
17505
|
+
const flag = (name) => {
|
|
17506
|
+
const at = forwarded.findIndex((arg) => arg === name || arg.startsWith(`${name}=`));
|
|
17507
|
+
if (at < 0)
|
|
17508
|
+
return undefined;
|
|
17509
|
+
return forwarded[at].includes("=") ? forwarded[at].split("=")[1] : forwarded[at + 1];
|
|
17510
|
+
};
|
|
17511
|
+
progress.start(`Reading ${flag("--sources") ?? "local agent"} sessions from the last ${flag("--since") ?? "30d"}`);
|
|
16153
17512
|
try {
|
|
16154
17513
|
const scanRaw = await proxyExecLearnAsync(["learn", "scan", "--write-report", "--write-report-token", reportToken, ...forwarded], progress.update);
|
|
16155
17514
|
// Pre-bundled proxies ignore unknown flags. Fall back once when report
|
|
@@ -16578,7 +17937,7 @@ function readStdin() {
|
|
|
16578
17937
|
return;
|
|
16579
17938
|
}
|
|
16580
17939
|
const chunks = [];
|
|
16581
|
-
process.stdin.on("data", (chunk) => chunks.push(chunk));
|
|
17940
|
+
process.stdin.on("data", (chunk) => chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)));
|
|
16582
17941
|
process.stdin.on("end", () => resolve(Buffer.concat(chunks)));
|
|
16583
17942
|
process.stdin.on("error", reject);
|
|
16584
17943
|
});
|
|
@@ -16931,7 +18290,7 @@ export function renderStatus(view) {
|
|
|
16931
18290
|
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`));
|
|
16932
18291
|
}
|
|
16933
18292
|
lines.push(statusRow("config", `think: ${view.config_sources.think} · remember: ${view.config_sources.remember} · execute: ${view.config_sources.execute}`));
|
|
16934
|
-
lines.push(statusRow("telemetry", `${view.telemetry.state} ·
|
|
18293
|
+
lines.push(statusRow("telemetry", `${view.telemetry.state} · usage ping · change: ${view.telemetry.change}`));
|
|
16935
18294
|
if (view.next)
|
|
16936
18295
|
lines.push("", `next: ${view.next}`);
|
|
16937
18296
|
return `${lines.join("\n")}\n`;
|
|
@@ -17000,7 +18359,7 @@ async function status(argv) {
|
|
|
17000
18359
|
const plan = entitlement && allowance !== null && entitlement.optimized_tokens_week !== undefined
|
|
17001
18360
|
? { plan: entitlement.plan, used: entitlement.optimized_tokens_week, allowance }
|
|
17002
18361
|
: null;
|
|
17003
|
-
const telemetry =
|
|
18362
|
+
const telemetry = sessionTelemetryState();
|
|
17004
18363
|
const view = {
|
|
17005
18364
|
mode: runningMode ?? resolvedMode,
|
|
17006
18365
|
mode_source: runningMode ? "running" : "resolved",
|
|
@@ -17888,7 +19247,7 @@ function renderRecipe(recipe, baseURL, app) {
|
|
|
17888
19247
|
}
|
|
17889
19248
|
function renderRecipeTemplate(value, baseURL, app) {
|
|
17890
19249
|
return value
|
|
17891
|
-
.replaceAll("{{baseURL}}", baseURL
|
|
19250
|
+
.replaceAll("{{baseURL}}", trimTrailingSlashes(baseURL))
|
|
17892
19251
|
.replaceAll("{{app}}", app);
|
|
17893
19252
|
}
|
|
17894
19253
|
function recipeCommentPrefix(lang) {
|
|
@@ -18081,12 +19440,11 @@ async function readRawConfig() {
|
|
|
18081
19440
|
}
|
|
18082
19441
|
async function writeRawConfig(out) {
|
|
18083
19442
|
await mkdir(dirname(configPath()), { recursive: true });
|
|
18084
|
-
|
|
18085
|
-
|
|
18086
|
-
}
|
|
18087
|
-
|
|
18088
|
-
|
|
18089
|
-
chmodSync(configPath(), 0o600);
|
|
19443
|
+
const target = configWriteTarget();
|
|
19444
|
+
const tmp = `${target}.${process.pid}.tmp`;
|
|
19445
|
+
await writeFile(tmp, JSON.stringify(out, null, 2), { mode: 0o600 });
|
|
19446
|
+
await rename(tmp, target);
|
|
19447
|
+
chmodSync(target, 0o600);
|
|
18090
19448
|
}
|
|
18091
19449
|
async function saveConfig(cfg) {
|
|
18092
19450
|
const out = await readRawConfig();
|
|
@@ -18209,6 +19567,7 @@ async function refreshCLIConfig(cfg) {
|
|
|
18209
19567
|
try {
|
|
18210
19568
|
const response = await fetch(`${cfg.baseURL}/api/v1/auth/refresh`, {
|
|
18211
19569
|
method: "POST",
|
|
19570
|
+
redirect: "manual",
|
|
18212
19571
|
headers: { "content-type": "application/json", "x-cave-client": "cli" },
|
|
18213
19572
|
body: JSON.stringify({ refresh_token: cfg.refreshToken }),
|
|
18214
19573
|
signal: AbortSignal.timeout(5000),
|