@caveman-ai/cli 1.2.0 → 1.2.3
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/dist/agent-skills.generated.js +1 -1
- package/dist/agents.generated.js +28 -0
- package/dist/binaries.generated.js +1 -1
- package/dist/caveman-pi-extension.mjs +787 -0
- package/dist/index.js +538 -50
- package/dist/learn-tui.js +43 -43
- package/dist/native-hook-fast.js +24 -3
- package/dist/portable-command.js +56 -12
- package/dist/portable-process.mjs +17 -7
- package/package.json +4 -4
package/dist/index.js
CHANGED
|
@@ -25,6 +25,11 @@ const wrapTempDirs = new Set();
|
|
|
25
25
|
// `caveman wrap` points agents at it.
|
|
26
26
|
const PROXY_ADDR = "127.0.0.1:8787";
|
|
27
27
|
const PROXY_URL = `http://${PROXY_ADDR}`;
|
|
28
|
+
// Restores Claude Code's tool search after we take over ANTHROPIC_BASE_URL.
|
|
29
|
+
// "auto" defers to Claude Code's own tool-catalog size threshold, so a user with
|
|
30
|
+
// two small MCP servers pays no extra round-trip while a heavy setup stops
|
|
31
|
+
// inlining every schema. "true" would force it on regardless.
|
|
32
|
+
const TOOL_SEARCH_DEFAULT = "auto";
|
|
28
33
|
// Gateway resolution is dynamic — resolved per invocation, never frozen at module
|
|
29
34
|
// load — so `caveman login` persisting a managed gateway URL flips `wrap` to the
|
|
30
35
|
// cloud with no env var (SIMPLICITY_SPEC §6.5, audit finding #3). `caveman start`
|
|
@@ -244,6 +249,9 @@ const LEGACY_HANDLERS = {
|
|
|
244
249
|
// humans should not need to.
|
|
245
250
|
"native-hook": (argv) => nativeHook(argv),
|
|
246
251
|
setup: (argv) => setup(argv),
|
|
252
|
+
// Unprinted (porcelain caps): sync Go binaries to this CLI's pin, then check
|
|
253
|
+
// npm for a newer CLI — the one verb that answers "am I current?".
|
|
254
|
+
update: (argv) => update(argv),
|
|
247
255
|
opportunities: (argv) => argv[0] === "list" ? get("/api/v1/opportunities").then(print) : commandUsage("opportunities list"),
|
|
248
256
|
snippets,
|
|
249
257
|
dev: (argv) => {
|
|
@@ -397,13 +405,15 @@ const TELEMETRY_DISCLOSURE_LINE = "anonymous usage stats on — command counts a
|
|
|
397
405
|
// Reading token totals means spawning caveman-proxy to query the local SQLite
|
|
398
406
|
// store. It runs after the command's own work, so the cost lands on process exit;
|
|
399
407
|
// a slow or wedged binary drops the token fields rather than holding the CLI.
|
|
400
|
-
|
|
408
|
+
// Env-overridable because a loaded CI runner can exceed 400ms just spawning the
|
|
409
|
+
// stub, which made the token-delta tests flaky under concurrency.
|
|
410
|
+
const TELEMETRY_TOKEN_READ_TIMEOUT_MS = Number(process.env.CAVEMAN_TELEMETRY_TOKEN_READ_TIMEOUT_MS) || 400;
|
|
401
411
|
const SYNC_DISCLOSURE = "sync uploads span metadata to your org's dashboard — tokens, cost, latency, model, status. Imported standalone observations never affect managed budgets, verified savings, or billing. Subscription/OAuth sessions carry token counts only — no dollar figure. Never prompt or response bytes.";
|
|
402
412
|
const TELEMETRY_COMMAND_ALLOWLIST = [
|
|
403
413
|
"agent", "audit", "billing", "browse", "compress", "convert", "costs", "deploy", "dev", "doctor", "evals", "experiments",
|
|
404
414
|
"explore", "help", "hooks", "init", "keys", "learn", "login", "logout", "mcp", "mem", "opportunities", "plan",
|
|
405
415
|
"projects", "providers", "receipts", "retrieve", "score", "sdk", "setup", "shrink", "shrink-hook", "skills",
|
|
406
|
-
"run", "snippets", "start", "stats", "status", "sync", "telemetry", "toon", "traces", "trial", "unknown", "usage", "verify", "version", "welcome", "whoami", "wrap",
|
|
416
|
+
"run", "snippets", "start", "stats", "status", "sync", "telemetry", "toon", "traces", "trial", "unknown", "update", "usage", "verify", "version", "welcome", "whoami", "wrap",
|
|
407
417
|
];
|
|
408
418
|
const TELEMETRY_COMMANDS = new Set(TELEMETRY_COMMAND_ALLOWLIST);
|
|
409
419
|
const TELEMETRY_SUBCOMMANDS = new Set([
|
|
@@ -942,6 +952,11 @@ function classifyTelemetryError(error) {
|
|
|
942
952
|
const message = error instanceof Error ? error.message : "";
|
|
943
953
|
if (telemetryCommandName() === "unknown" || message.startsWith("unknown command:"))
|
|
944
954
|
return "unknown_command";
|
|
955
|
+
// Spawn failures and Windows shim rejections (portable-command.ts) — keep
|
|
956
|
+
// these out of "other" so agent-launch breakage is visible in telemetry. The
|
|
957
|
+
// bare "spawn E…" form covers sync spawn throws that skip the exec wrappers.
|
|
958
|
+
if (/^failed to exec |^spawn |windows command shim/i.test(message))
|
|
959
|
+
return "exec_failed";
|
|
945
960
|
if (/not logged in|unauthorized|forbidden|auth/i.test(message))
|
|
946
961
|
return "auth";
|
|
947
962
|
if (/fetch failed|ECONN|ENOTFOUND|ETIMEDOUT|network/i.test(message))
|
|
@@ -2351,6 +2366,55 @@ async function setupInstall(json, options = {}) {
|
|
|
2351
2366
|
await chmod(binaryInstallManifestPath(), 0o600);
|
|
2352
2367
|
printInstallResult(installed, platform, binDir, json, options.continuing);
|
|
2353
2368
|
}
|
|
2369
|
+
// ── caveman update ───────────────────────────────────────────────────────────
|
|
2370
|
+
// Syncs the Go binaries in ~/.caveman/bin to the release this CLI pins
|
|
2371
|
+
// (setupInstall is idempotent: stale manifest or checksum mismatch
|
|
2372
|
+
// re-downloads, current binaries print "already installed"), then checks npm
|
|
2373
|
+
// for a newer CLI. A newer CLI pins a newer binary release, so an outdated or
|
|
2374
|
+
// unverifiable CLI means the update is not proven complete — exit non-zero.
|
|
2375
|
+
function cliVersionBehind(current, latest) {
|
|
2376
|
+
const have = current.split(".").map((part) => parseInt(part, 10) || 0);
|
|
2377
|
+
const want = latest.split(".").map((part) => parseInt(part, 10) || 0);
|
|
2378
|
+
for (let i = 0; i < 3; i++) {
|
|
2379
|
+
if ((want[i] ?? 0) !== (have[i] ?? 0))
|
|
2380
|
+
return (want[i] ?? 0) > (have[i] ?? 0);
|
|
2381
|
+
}
|
|
2382
|
+
return false;
|
|
2383
|
+
}
|
|
2384
|
+
async function latestPublishedCliVersion(timeoutSeconds) {
|
|
2385
|
+
const registry = (process.env.CAVEMAN_NPM_REGISTRY ?? "https://registry.npmjs.org").replace(/\/+$/, "");
|
|
2386
|
+
try {
|
|
2387
|
+
const response = await fetch(`${registry}/@caveman-ai%2fcli`, {
|
|
2388
|
+
headers: { accept: "application/vnd.npm.install-v1+json" },
|
|
2389
|
+
signal: AbortSignal.timeout(timeoutSeconds * 1000),
|
|
2390
|
+
});
|
|
2391
|
+
if (!response.ok)
|
|
2392
|
+
return null;
|
|
2393
|
+
const parsed = (await response.json());
|
|
2394
|
+
const latest = parsed?.["dist-tags"]?.latest;
|
|
2395
|
+
return typeof latest === "string" && latest ? latest : null;
|
|
2396
|
+
}
|
|
2397
|
+
catch {
|
|
2398
|
+
return null;
|
|
2399
|
+
}
|
|
2400
|
+
}
|
|
2401
|
+
async function update(argv = []) {
|
|
2402
|
+
if (argv.length > 0)
|
|
2403
|
+
commandUsage("update");
|
|
2404
|
+
await setupInstall(false, { continuing: true });
|
|
2405
|
+
const current = cliVersion();
|
|
2406
|
+
const latest = await latestPublishedCliVersion(setupTimeoutSeconds());
|
|
2407
|
+
if (!latest) {
|
|
2408
|
+
console.error(`${mark("warn")} binaries synced to ${BINARY_RELEASE}, but npm was unreachable — cannot confirm CLI ${current} is the latest`);
|
|
2409
|
+
process.exit(1);
|
|
2410
|
+
}
|
|
2411
|
+
if (cliVersionBehind(current, latest)) {
|
|
2412
|
+
console.error(`${mark("warn")} binaries synced for CLI ${current}, but ${latest} is out — update the CLI, then run this again:`);
|
|
2413
|
+
console.error(` ${cyan("npm install -g @caveman-ai/cli@latest")}`);
|
|
2414
|
+
process.exit(1);
|
|
2415
|
+
}
|
|
2416
|
+
console.log(`${mark("ok")} up to date — CLI ${current}, binaries ${BINARY_RELEASE}`);
|
|
2417
|
+
}
|
|
2354
2418
|
function agentNativeBundleJournalPath(agent, pending = false) {
|
|
2355
2419
|
return join(cavemanHome(), "integrations", `${agent}.agent-native-bundle${pending ? ".pending" : ""}.json`);
|
|
2356
2420
|
}
|
|
@@ -2997,6 +3061,83 @@ function proxyYamlMode() {
|
|
|
2997
3061
|
return undefined;
|
|
2998
3062
|
}
|
|
2999
3063
|
}
|
|
3064
|
+
// Claude Code treats any ANTHROPIC_BASE_URL whose host is not api.anthropic.com
|
|
3065
|
+
// as a custom endpoint and withholds first-party-only capabilities — most
|
|
3066
|
+
// visibly the 1M-token context window, whose loss shrinks the auto-compact
|
|
3067
|
+
// window to the 200k default (#865). The local proxy is a byte-safe
|
|
3068
|
+
// pass-through whose anthropic upstream IS api.anthropic.com unless the
|
|
3069
|
+
// operator overrides providers.anthropic.base_url in caveman.yaml, so for the
|
|
3070
|
+
// default upstream the first-party assertion is truthful and we make it
|
|
3071
|
+
// through Claude Code's own escape hatch. Never overrides a value the user
|
|
3072
|
+
// already set, and never asserts when the upstream cannot be verified.
|
|
3073
|
+
const CLAUDE_ASSUME_FIRST_PARTY_ENV = "_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL";
|
|
3074
|
+
// yamlProviderBaseUrl scans an indentation-nested `providers.<name>.base_url`
|
|
3075
|
+
// key without a YAML dependency (the published CLI has zero runtime deps).
|
|
3076
|
+
// Returns the value when found, null when the providers/<name> block or key is
|
|
3077
|
+
// absent, and undefined when the document uses a shape the scan cannot follow
|
|
3078
|
+
// (flow-style `{...}` blocks) — callers must treat undefined as unverifiable.
|
|
3079
|
+
function yamlProviderBaseUrl(raw, provider) {
|
|
3080
|
+
const lines = raw.split(/\r?\n/);
|
|
3081
|
+
let providersIndent = -1;
|
|
3082
|
+
let providerIndent = -1;
|
|
3083
|
+
for (const line of lines) {
|
|
3084
|
+
const code = line.split("#", 1)[0];
|
|
3085
|
+
if (!code.trim())
|
|
3086
|
+
continue;
|
|
3087
|
+
const indent = code.length - code.trimStart().length;
|
|
3088
|
+
const keyMatch = code.trim().match(/^([A-Za-z0-9_-]+)\s*:\s*(.*)$/);
|
|
3089
|
+
if (providersIndent !== -1 && indent <= providersIndent)
|
|
3090
|
+
providersIndent = -1;
|
|
3091
|
+
if (providerIndent !== -1 && indent <= providerIndent)
|
|
3092
|
+
providerIndent = -1;
|
|
3093
|
+
if (!keyMatch)
|
|
3094
|
+
continue;
|
|
3095
|
+
const key = keyMatch[1];
|
|
3096
|
+
const rest = keyMatch[2] ?? "";
|
|
3097
|
+
if (rest.startsWith("{") || rest.startsWith("[")) {
|
|
3098
|
+
// Flow-style collections keep their children on this line; a providers
|
|
3099
|
+
// subtree written that way is beyond this scan, so report unverifiable.
|
|
3100
|
+
if (key === "providers" || providersIndent !== -1)
|
|
3101
|
+
return undefined;
|
|
3102
|
+
continue;
|
|
3103
|
+
}
|
|
3104
|
+
if (providerIndent !== -1 && key === "base_url") {
|
|
3105
|
+
const value = rest.replace(/^["']|["']\s*$/g, "").trim();
|
|
3106
|
+
return value || null;
|
|
3107
|
+
}
|
|
3108
|
+
if (providersIndent !== -1 && key === provider && providerIndent === -1)
|
|
3109
|
+
providerIndent = indent;
|
|
3110
|
+
else if (key === "providers" && providersIndent === -1 && providerIndent === -1 && indent === 0)
|
|
3111
|
+
providersIndent = indent;
|
|
3112
|
+
}
|
|
3113
|
+
return null;
|
|
3114
|
+
}
|
|
3115
|
+
// proxyAnthropicUpstreamIsFirstParty answers whether the local proxy's
|
|
3116
|
+
// anthropic upstream is verifiably api.anthropic.com: a missing caveman.yaml
|
|
3117
|
+
// means the compiled-in default upstream, an explicit override must name the
|
|
3118
|
+
// first-party host, and anything unverifiable (unreadable file, flow-style
|
|
3119
|
+
// YAML) refuses the assertion — withholding it only keeps today's behavior.
|
|
3120
|
+
function proxyAnthropicUpstreamIsFirstParty() {
|
|
3121
|
+
const path = process.env.CAVEMAN_CONFIG ?? join(cavemanHome(), "caveman.yaml");
|
|
3122
|
+
let raw;
|
|
3123
|
+
try {
|
|
3124
|
+
raw = readFileSync(path, "utf8");
|
|
3125
|
+
}
|
|
3126
|
+
catch (e) {
|
|
3127
|
+
return e?.code === "ENOENT";
|
|
3128
|
+
}
|
|
3129
|
+
const override = yamlProviderBaseUrl(raw, "anthropic");
|
|
3130
|
+
if (override === undefined)
|
|
3131
|
+
return false;
|
|
3132
|
+
if (override === null)
|
|
3133
|
+
return true;
|
|
3134
|
+
try {
|
|
3135
|
+
return new URL(override).host === "api.anthropic.com";
|
|
3136
|
+
}
|
|
3137
|
+
catch {
|
|
3138
|
+
return false;
|
|
3139
|
+
}
|
|
3140
|
+
}
|
|
3000
3141
|
function projectCapabilityDocument() {
|
|
3001
3142
|
try {
|
|
3002
3143
|
return objectValue(JSON.parse(readFileSync(join(process.cwd(), ".caveman", "config.json"), "utf8")));
|
|
@@ -3930,7 +4071,7 @@ export function formatSessionSavings(kind, s, authModes = [], windowTruncated =
|
|
|
3930
4071
|
// `caveman doctor` only accepts these targets; a wrappable agent that isn't
|
|
3931
4072
|
// one (e.g. openclaw) must fall back to `generic` so the remediation hint is a
|
|
3932
4073
|
// runnable command, not a usage error.
|
|
3933
|
-
const doctorTargets = new Set(["claude", "codex", "hermes", "gemini", "opencode", "aider"]);
|
|
4074
|
+
const doctorTargets = new Set(["claude", "codex", "hermes", "gemini", "opencode", "pi", "aider"]);
|
|
3934
4075
|
const rawTarget = agentId && agentId.trim() ? agentId.trim() : "";
|
|
3935
4076
|
const doctorTarget = rawTarget ? (doctorTargets.has(rawTarget) ? rawTarget : "generic") : "<agent>";
|
|
3936
4077
|
// A null summary means the proxy could NOT be read (binary missing, db locked,
|
|
@@ -4513,7 +4654,7 @@ function normalizeAgentShortcutWrapArgs(input) {
|
|
|
4513
4654
|
// native path would ever start the proxy or apply routedAiderArgs — a direct
|
|
4514
4655
|
// launch would point it at a dead endpoint. Aider keeps the wrap door.
|
|
4515
4656
|
function nativeAgentId(id) {
|
|
4516
|
-
return id === "claude" || id === "codex" || id === "hermes" || id === "gemini" || id === "opencode" ? id : undefined;
|
|
4657
|
+
return id === "claude" || id === "codex" || id === "hermes" || id === "gemini" || id === "opencode" || id === "pi" ? id : undefined;
|
|
4517
4658
|
}
|
|
4518
4659
|
// `caveman <agent>` — the default door. It persistently enables the native
|
|
4519
4660
|
// integration (the same journaled user-scoped writes as `caveman enable <agent>`)
|
|
@@ -4573,9 +4714,18 @@ async function agentShortcut(rest) {
|
|
|
4573
4714
|
catch { /* runtime startup is fail-open; the native hook retries at SessionStart */ }
|
|
4574
4715
|
if (native === "hermes")
|
|
4575
4716
|
maybeWarnHermesMissingKey(agent, gatewayURL());
|
|
4717
|
+
const stopProxyKeepalive = startProxyKeepalive();
|
|
4576
4718
|
const code = await new Promise((resolve, reject) => {
|
|
4577
4719
|
const invocation = portableInvocation(bin, [...agent.args, ...rest.slice(1)]);
|
|
4578
|
-
|
|
4720
|
+
let child;
|
|
4721
|
+
try {
|
|
4722
|
+
child = spawn(invocation.command, invocation.args, { stdio: "inherit" });
|
|
4723
|
+
}
|
|
4724
|
+
catch (error) {
|
|
4725
|
+
// macOS reports some exec failures (e.g. ENOEXEC) synchronously — wrap
|
|
4726
|
+
// them like the async 'error' path so the message names the binary.
|
|
4727
|
+
throw new Error(`failed to exec ${bin}: ${error.message}`);
|
|
4728
|
+
}
|
|
4579
4729
|
// tty-generated signals (Ctrl+C / Ctrl+\) already reach the child through
|
|
4580
4730
|
// the shared foreground group — forwarding would double-deliver them. But
|
|
4581
4731
|
// process-directed SIGTERM/SIGHUP (timeout(1), supervisors, pkill) only hit
|
|
@@ -4604,6 +4754,7 @@ async function agentShortcut(rest) {
|
|
|
4604
4754
|
resolve(exitCode ?? signalExitCode(signal));
|
|
4605
4755
|
});
|
|
4606
4756
|
});
|
|
4757
|
+
stopProxyKeepalive();
|
|
4607
4758
|
const exitClass = code === 0 ? "ok" : "error";
|
|
4608
4759
|
const event = commandRunEventOnce(exitClass, exitClass === "error" ? "other" : undefined);
|
|
4609
4760
|
if (event)
|
|
@@ -4939,6 +5090,8 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = f
|
|
|
4939
5090
|
const pluginDir = buildClaudeEphemeralPlugin(ephemeralMcpBinary, includeShrink, Boolean(opts.autoRecall), ephemeralDelegateMcp);
|
|
4940
5091
|
childArgs = ["--plugin-dir", pluginDir, ...cmdArgs];
|
|
4941
5092
|
}
|
|
5093
|
+
if (!direct && agent?.id === "pi")
|
|
5094
|
+
childArgs = buildPiWrapArgs(cmdArgs, env, gw);
|
|
4942
5095
|
if (!direct && agent?.id === "aider")
|
|
4943
5096
|
childArgs = routedAiderArgs(cmdArgs);
|
|
4944
5097
|
}
|
|
@@ -4968,11 +5121,20 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = f
|
|
|
4968
5121
|
summaryKind = "compress";
|
|
4969
5122
|
}
|
|
4970
5123
|
const sessionStart = summaryKind ? new Date().toISOString() : undefined;
|
|
5124
|
+
const stopProxyKeepalive = !direct && local && !opts.noProxy ? startProxyKeepalive(gw) : () => { };
|
|
4971
5125
|
let code;
|
|
4972
5126
|
try {
|
|
4973
5127
|
code = await new Promise((resolve, reject) => {
|
|
4974
5128
|
const invocation = portableInvocation(bin, childArgs);
|
|
4975
|
-
|
|
5129
|
+
let child;
|
|
5130
|
+
try {
|
|
5131
|
+
child = spawn(invocation.command, invocation.args, { stdio: "inherit", env });
|
|
5132
|
+
}
|
|
5133
|
+
catch (error) {
|
|
5134
|
+
// macOS reports some exec failures (e.g. ENOEXEC) synchronously — wrap
|
|
5135
|
+
// them like the async 'error' path so the message names the binary.
|
|
5136
|
+
throw new Error(`failed to exec ${bin}: ${error.message}`);
|
|
5137
|
+
}
|
|
4976
5138
|
const signalHandlers = new Map();
|
|
4977
5139
|
const removeSignalHandlers = () => {
|
|
4978
5140
|
for (const [signal, handler] of signalHandlers)
|
|
@@ -5026,6 +5188,7 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = f
|
|
|
5026
5188
|
});
|
|
5027
5189
|
}
|
|
5028
5190
|
finally {
|
|
5191
|
+
stopProxyKeepalive();
|
|
5029
5192
|
cleanupWrapTempDirs();
|
|
5030
5193
|
removeProxySessionMarker(sessionMarker);
|
|
5031
5194
|
}
|
|
@@ -5176,6 +5339,16 @@ async function startWrapProxy(mode, mcpRecovery, toon, pixelModels, pixelDensity
|
|
|
5176
5339
|
// Same reason as `start`: the dead account variable never rides along inherited.
|
|
5177
5340
|
delete env.CAVEMAN_WRAP_ENTITLED;
|
|
5178
5341
|
const child = spawn(resolved, [], { stdio: "ignore", env, detached: true, windowsHide: true });
|
|
5342
|
+
// The caller wraps this in try/catch for fail-open startup, but a try/catch
|
|
5343
|
+
// cannot catch an EventEmitter 'error' — it arrives asynchronously and becomes
|
|
5344
|
+
// an uncaughtException that kills the CLI before the agent ever launches. A
|
|
5345
|
+
// wrong-arch binary (ENOEXEC), a lost x-bit between the isExecutable check and
|
|
5346
|
+
// the spawn (EACCES), or CAVEMAN_PROXY_BIN pointing at a Windows .cmd shim
|
|
5347
|
+
// (EINVAL) all take that path. Every other spawn in this file guards it; the
|
|
5348
|
+
// proxy start is exactly the one that must degrade to "no proxy", not die.
|
|
5349
|
+
child.on("error", (error) => {
|
|
5350
|
+
process.stderr.write(`${mark("warn")} could not start ${bin}: ${error.message}\n`);
|
|
5351
|
+
});
|
|
5179
5352
|
child.unref();
|
|
5180
5353
|
for (let i = 0; i < 20; i++) {
|
|
5181
5354
|
await sleep(100);
|
|
@@ -5187,6 +5360,25 @@ async function startWrapProxy(mode, mcpRecovery, toon, pixelModels, pixelDensity
|
|
|
5187
5360
|
process.stderr.write(`${mark("warn")} started ${bin}, but proxy did not become ready on ${host}:${port}\n`);
|
|
5188
5361
|
return false;
|
|
5189
5362
|
}
|
|
5363
|
+
// startProxyKeepalive heartbeats the local proxy while the wrapped agent process
|
|
5364
|
+
// is alive, so a wrap-owned proxy's idle exit cannot fire under an open-but-quiet
|
|
5365
|
+
// session whose ANTHROPIC_BASE_URL still points at it (#860). The proxy treats
|
|
5366
|
+
// the beat as activity only — nothing is recorded. No immediate beat: launching
|
|
5367
|
+
// is already activity, and short-lived runs should never touch the port. The
|
|
5368
|
+
// timer is unref'd and every failure is ignored (fail-open, like the hooks).
|
|
5369
|
+
function startProxyKeepalive(gw = gatewayURL()) {
|
|
5370
|
+
if (wrapMode(gw) !== "local")
|
|
5371
|
+
return () => { };
|
|
5372
|
+
const { host, port } = gatewayHostPort(gw);
|
|
5373
|
+
const timer = setInterval(() => {
|
|
5374
|
+
const req = httpRequest({ host, port, path: "/caveman/keepalive", method: "POST", timeout: 3000 }, (res) => res.resume());
|
|
5375
|
+
req.on("timeout", () => req.destroy());
|
|
5376
|
+
req.on("error", () => { });
|
|
5377
|
+
req.end();
|
|
5378
|
+
}, 5 * 60 * 1000);
|
|
5379
|
+
timer.unref();
|
|
5380
|
+
return () => clearInterval(timer);
|
|
5381
|
+
}
|
|
5190
5382
|
// wrapMode selects which injection variant to use: "managed" when traffic is aimed
|
|
5191
5383
|
// off-loopback (CAVE_GATEWAY_URL points at a hosted gateway), else "local". Keying
|
|
5192
5384
|
// off where the bytes actually go means `caveman start` (local proxy) and a hosted
|
|
@@ -5818,6 +6010,7 @@ const NATIVE_CAPABILITY_SUPPORT = {
|
|
|
5818
6010
|
hermes: new Set(["provider_proxy", "session_start", "prompt_submit", "model_after", "pre_tool", "post_tool", "session_end", "mcp", "native_package", "local_runtime_available"]),
|
|
5819
6011
|
gemini: new Set(["provider_proxy", "session_start", "prompt_submit", "model_before", "model_after", "pre_tool", "post_tool", "pre_compact", "session_end", "mcp", "local_runtime_available"]),
|
|
5820
6012
|
opencode: new Set(["provider_proxy", "session_start", "prompt_submit", "pre_tool", "post_tool", "post_tool_rewrite", "pre_compact", "post_compact", "session_end", "mcp", "native_package", "skills", "local_runtime_available"]),
|
|
6013
|
+
pi: new Set(["provider_proxy", "session_start", "prompt_submit", "model_before", "model_after", "pre_tool", "post_tool", "post_tool_rewrite", "pre_compact", "post_compact", "session_end", "mcp", "native_package", "local_runtime_available"]),
|
|
5821
6014
|
aider: new Set(["provider_proxy", "local_runtime_available"]),
|
|
5822
6015
|
};
|
|
5823
6016
|
function parsedSemver(value) {
|
|
@@ -5858,7 +6051,7 @@ function nativeCapabilityReport(agent, components, versionStatus) {
|
|
|
5858
6051
|
if (capability === "native_package")
|
|
5859
6052
|
return components.lifecycle_hooks;
|
|
5860
6053
|
if (capability === "post_tool_rewrite")
|
|
5861
|
-
return lifecycleActive && (agent === "claude" || agent === "opencode");
|
|
6054
|
+
return lifecycleActive && (agent === "claude" || agent === "opencode" || agent === "pi");
|
|
5862
6055
|
return lifecycleActive;
|
|
5863
6056
|
};
|
|
5864
6057
|
const basis = versionStatus === "tested" ? "tested_manifest" : "installed_surface_probe_safe_subset";
|
|
@@ -5980,6 +6173,23 @@ function claudeNativeMutations(gw, mcpBinary) {
|
|
|
5980
6173
|
const route = appendUrlPath(gw, "/w/claude");
|
|
5981
6174
|
const previousRoute = env.ANTHROPIC_BASE_URL;
|
|
5982
6175
|
env.ANTHROPIC_BASE_URL = route;
|
|
6176
|
+
// Routing through the local proxy makes ANTHROPIC_BASE_URL non-first-party in
|
|
6177
|
+
// Claude Code's eyes, which silently drops the 1M context / ~600k
|
|
6178
|
+
// auto-compact window to 200k (#865). When the proxy's anthropic upstream is
|
|
6179
|
+
// verifiably api.anthropic.com, assert first-party through Claude Code's own
|
|
6180
|
+
// escape hatch. Never touches a value the user already carries in settings.
|
|
6181
|
+
const assumeFirstParty = env[CLAUDE_ASSUME_FIRST_PARTY_ENV] === undefined
|
|
6182
|
+
&& wrapMode(gw) === "local" && proxyAnthropicUpstreamIsFirstParty();
|
|
6183
|
+
if (assumeFirstParty)
|
|
6184
|
+
env[CLAUDE_ASSUME_FIRST_PARTY_ENV] = "1";
|
|
6185
|
+
// Claude Code turns tool search (progressive MCP tool disclosure) OFF as soon
|
|
6186
|
+
// as ANTHROPIC_BASE_URL is not a first-party Anthropic host, so pointing it at
|
|
6187
|
+
// caveman would otherwise force every MCP tool schema inline on every request
|
|
6188
|
+
// — measured at ~48k extra prompt tokens on a 4-server setup. The proxy
|
|
6189
|
+
// forwards tool_reference blocks byte-identically, which is the condition
|
|
6190
|
+
// Claude Code names for the override. Never clobber an explicit user value.
|
|
6191
|
+
if (env.ENABLE_TOOL_SEARCH === undefined)
|
|
6192
|
+
env.ENABLE_TOOL_SEARCH = TOOL_SEARCH_DEFAULT;
|
|
5983
6193
|
settings.env = env;
|
|
5984
6194
|
const withHooks = nativeHooksDocument("claude", true, settings);
|
|
5985
6195
|
const mcpPath = join(homedir(), ".claude.json");
|
|
@@ -6001,7 +6211,7 @@ function claudeNativeMutations(gw, mcpBinary) {
|
|
|
6001
6211
|
before: settingsBefore,
|
|
6002
6212
|
after: Buffer.from(JSON.stringify(withHooks, null, 2) + "\n"),
|
|
6003
6213
|
kind: "claude-settings",
|
|
6004
|
-
owned: { route, previous_route: previousRoute ?? null },
|
|
6214
|
+
owned: { route, previous_route: previousRoute ?? null, assume_first_party: assumeFirstParty ? "1" : null },
|
|
6005
6215
|
},
|
|
6006
6216
|
{
|
|
6007
6217
|
file: mcpPath,
|
|
@@ -6293,6 +6503,32 @@ function opencodeNativeMutations(gw, mcpBinary) {
|
|
|
6293
6503
|
},
|
|
6294
6504
|
];
|
|
6295
6505
|
}
|
|
6506
|
+
function piNativeMutations() {
|
|
6507
|
+
const extensionDir = join(homedir(), ".pi", "agent", "extensions");
|
|
6508
|
+
// Pi's extension auto-discovery accepts only .ts/.js (isExtensionFile in
|
|
6509
|
+
// pi-coding-agent 0.84.2); a .mjs here would journal fine and never load.
|
|
6510
|
+
const extensionPath = join(extensionDir, "caveman-native.js");
|
|
6511
|
+
const before = fileBytes(extensionPath);
|
|
6512
|
+
if (before && !before.toString("utf8").includes("caveman:native-pi")) {
|
|
6513
|
+
throw new Error(`${extensionPath} already exists and is not Caveman-owned; refusing to overwrite it`);
|
|
6514
|
+
}
|
|
6515
|
+
// Plain `pi` launches carry no wrap env, so the persistent artifact bakes in
|
|
6516
|
+
// the invocation this enable resolved (falling back to PATH when unset) —
|
|
6517
|
+
// same pattern as the generated opencode plugin.
|
|
6518
|
+
const { cmd, pre } = cavemanInvocation();
|
|
6519
|
+
const after = Buffer.concat([
|
|
6520
|
+
Buffer.from("// caveman:native-pi — GENERATED by `caveman enable pi`.\n"),
|
|
6521
|
+
Buffer.from(`process.env.CAVEMAN_PI_HOOK_CMD ??= ${JSON.stringify(JSON.stringify([cmd, ...pre]))};\n`),
|
|
6522
|
+
readFileSync(resolvePiExtension()),
|
|
6523
|
+
]);
|
|
6524
|
+
return [{
|
|
6525
|
+
file: extensionPath,
|
|
6526
|
+
before,
|
|
6527
|
+
after,
|
|
6528
|
+
kind: "pi-extension",
|
|
6529
|
+
owned: { sha256: bytesHash(after), created_extension_dir: !existsSync(extensionDir) },
|
|
6530
|
+
}];
|
|
6531
|
+
}
|
|
6296
6532
|
function aiderCorePath() {
|
|
6297
6533
|
return join(cavemanHome(), "packs", "aider", "CAVEMAN.md");
|
|
6298
6534
|
}
|
|
@@ -6901,19 +7137,21 @@ function nativeMutationsFor(agent, gw, mcpBinary) {
|
|
|
6901
7137
|
? geminiNativeMutations(gw, mcpBinary)
|
|
6902
7138
|
: agent === "opencode"
|
|
6903
7139
|
? opencodeNativeMutations(gw, mcpBinary)
|
|
6904
|
-
:
|
|
7140
|
+
: agent === "pi"
|
|
7141
|
+
? piNativeMutations()
|
|
7142
|
+
: aiderNativeMutations(gw);
|
|
6905
7143
|
}
|
|
6906
7144
|
function enableNative(argv) {
|
|
6907
7145
|
const detected = argv.includes("--detected");
|
|
6908
7146
|
const target = argv.find((arg) => !arg.startsWith("--"));
|
|
6909
7147
|
if ((!detected && !target) || (detected && target) || argv.some((arg) => arg !== "--detected" && arg !== target)) {
|
|
6910
|
-
commandUsage("enable <claude|codex|hermes|gemini|opencode|aider> | enable --detected");
|
|
7148
|
+
commandUsage("enable <claude|codex|hermes|gemini|opencode|pi|aider> | enable --detected");
|
|
6911
7149
|
}
|
|
6912
7150
|
const profiles = detected
|
|
6913
|
-
? AGENTS.filter((agent) => (agent.id === "claude" || agent.id === "codex" || agent.id === "hermes" || agent.id === "gemini" || agent.id === "opencode" || agent.id === "aider") && which(binOf(agent)))
|
|
6914
|
-
: AGENTS.filter((agent) => agent.id === target && (agent.id === "claude" || agent.id === "codex" || agent.id === "hermes" || agent.id === "gemini" || agent.id === "opencode" || agent.id === "aider"));
|
|
7151
|
+
? AGENTS.filter((agent) => (agent.id === "claude" || agent.id === "codex" || agent.id === "hermes" || agent.id === "gemini" || agent.id === "opencode" || agent.id === "pi" || agent.id === "aider") && which(binOf(agent)))
|
|
7152
|
+
: AGENTS.filter((agent) => agent.id === target && (agent.id === "claude" || agent.id === "codex" || agent.id === "hermes" || agent.id === "gemini" || agent.id === "opencode" || agent.id === "pi" || agent.id === "aider"));
|
|
6915
7153
|
if (profiles.length === 0) {
|
|
6916
|
-
console.error(detected ? "no supported native agent detected on PATH" : `caveman enable: supported agents are claude, codex, hermes, gemini, opencode, and aider (got ${target ?? ""})`);
|
|
7154
|
+
console.error(detected ? "no supported native agent detected on PATH" : `caveman enable: supported agents are claude, codex, hermes, gemini, opencode, pi, and aider (got ${target ?? ""})`);
|
|
6917
7155
|
process.exit(1);
|
|
6918
7156
|
}
|
|
6919
7157
|
const gw = gatewayURL();
|
|
@@ -6941,7 +7179,9 @@ function enableNative(argv) {
|
|
|
6941
7179
|
process.stderr.write(agent === "aider" ? " recovery MCP: unavailable in Aider\n" : ` recovery MCP: ${mcpBinary}\n`);
|
|
6942
7180
|
process.stderr.write(agent === "aider"
|
|
6943
7181
|
? ` Core: read-only ${aiderCorePath()}; lifecycle/tool interception unavailable; Ledger observational\n`
|
|
6944
|
-
:
|
|
7182
|
+
: agent === "pi"
|
|
7183
|
+
? ` lifecycle/Core/tool rewrite: bundled Pi extension -> ${nativeHookCommand(agent)}\n`
|
|
7184
|
+
: ` lifecycle/Core/tool rewrite: ${nativeHookCommand(agent)}${agent === "hermes" ? " via native plugin" : ` + ${cavemanBinForHook()} shrink-hook`}\n`);
|
|
6945
7185
|
applyNativeMutations(agent, profile, mutations);
|
|
6946
7186
|
return "enabled";
|
|
6947
7187
|
});
|
|
@@ -7034,6 +7274,19 @@ function restoreNativeOperation(operation) {
|
|
|
7034
7274
|
else
|
|
7035
7275
|
currentEnv.ANTHROPIC_BASE_URL = beforeEnv.ANTHROPIC_BASE_URL;
|
|
7036
7276
|
}
|
|
7277
|
+
// The first-party assertion is only ever written when the user carried no
|
|
7278
|
+
// value of their own, so restore is a plain removal — but only while the
|
|
7279
|
+
// value is still exactly ours; a user's later edit outlives disable.
|
|
7280
|
+
const assume = operation.owned?.assume_first_party;
|
|
7281
|
+
if (typeof assume === "string" && currentEnv[CLAUDE_ASSUME_FIRST_PARTY_ENV] === assume) {
|
|
7282
|
+
delete currentEnv[CLAUDE_ASSUME_FIRST_PARTY_ENV];
|
|
7283
|
+
}
|
|
7284
|
+
// Symmetric to the enable-side ENABLE_TOOL_SEARCH write: only withdraw the
|
|
7285
|
+
// value we introduced ourselves and only while it is still untouched, so a
|
|
7286
|
+
// user who set their own afterwards keeps it.
|
|
7287
|
+
if (beforeEnv.ENABLE_TOOL_SEARCH === undefined && currentEnv.ENABLE_TOOL_SEARCH === TOOL_SEARCH_DEFAULT) {
|
|
7288
|
+
delete currentEnv.ENABLE_TOOL_SEARCH;
|
|
7289
|
+
}
|
|
7037
7290
|
if (Object.keys(currentEnv).length > 0)
|
|
7038
7291
|
currentRoot.env = currentEnv;
|
|
7039
7292
|
else
|
|
@@ -7103,7 +7356,7 @@ function restoreNativeOperation(operation) {
|
|
|
7103
7356
|
}
|
|
7104
7357
|
return Buffer.from(text.replace(`${block}\n\n`, "").replace(`\n\n${block}\n`, "\n").replace(`${block}\n`, "").replace(block, ""));
|
|
7105
7358
|
}
|
|
7106
|
-
if (operation.kind === "opencode-plugin") {
|
|
7359
|
+
if (operation.kind === "opencode-plugin" || operation.kind === "pi-extension") {
|
|
7107
7360
|
throw new Error(`${operation.file} changed after enable; refusing destructive disable`);
|
|
7108
7361
|
}
|
|
7109
7362
|
if (operation.kind === "opencode-config") {
|
|
@@ -7237,29 +7490,40 @@ function restoreNativeJournalFiles(journal) {
|
|
|
7237
7490
|
}
|
|
7238
7491
|
return current;
|
|
7239
7492
|
}
|
|
7240
|
-
function cleanupNativeAgentFiles(target) {
|
|
7241
|
-
if (target
|
|
7242
|
-
|
|
7243
|
-
|
|
7244
|
-
|
|
7245
|
-
|
|
7493
|
+
function cleanupNativeAgentFiles(target, journal) {
|
|
7494
|
+
if (target === "hermes") {
|
|
7495
|
+
try {
|
|
7496
|
+
if (readdirSync(hermesNativePluginDir()).length === 0)
|
|
7497
|
+
rmSync(hermesNativePluginDir(), { recursive: true });
|
|
7498
|
+
}
|
|
7499
|
+
catch { /* absent or non-empty: preserve */ }
|
|
7500
|
+
}
|
|
7501
|
+
if (target === "pi") {
|
|
7502
|
+
const extension = journal.operations.find((operation) => operation.kind === "pi-extension");
|
|
7503
|
+
if (extension?.owned?.created_extension_dir !== true)
|
|
7504
|
+
return;
|
|
7505
|
+
const extensionDir = dirname(extension.file);
|
|
7506
|
+
try {
|
|
7507
|
+
if (readdirSync(extensionDir).length === 0)
|
|
7508
|
+
rmSync(extensionDir, { recursive: true });
|
|
7509
|
+
}
|
|
7510
|
+
catch { /* absent or non-empty: preserve */ }
|
|
7246
7511
|
}
|
|
7247
|
-
catch { /* absent or non-empty: preserve */ }
|
|
7248
7512
|
}
|
|
7249
7513
|
function disableNativeAgent(target) {
|
|
7250
7514
|
const disabled = withIntegrationLock(target, () => {
|
|
7251
7515
|
recoverPendingNativeInstallUnlocked(target);
|
|
7252
7516
|
const journal = readNativeJournal(target);
|
|
7253
7517
|
if (!journal)
|
|
7254
|
-
return
|
|
7518
|
+
return undefined;
|
|
7255
7519
|
restoreNativeJournalFiles(journal);
|
|
7256
|
-
return
|
|
7520
|
+
return journal;
|
|
7257
7521
|
});
|
|
7258
7522
|
if (!disabled) {
|
|
7259
7523
|
process.stderr.write(`${mark("warn")} ${target}: no native Caveman integration journal found\n`);
|
|
7260
7524
|
return false;
|
|
7261
7525
|
}
|
|
7262
|
-
cleanupNativeAgentFiles(target);
|
|
7526
|
+
cleanupNativeAgentFiles(target, disabled);
|
|
7263
7527
|
const name = findAgent(target)?.display_name ?? target;
|
|
7264
7528
|
process.stderr.write(`${mark("ok")} ${name}: ${target === "aider" ? "shallow" : "native"} Caveman disabled; unrelated host edits preserved\n`);
|
|
7265
7529
|
return true;
|
|
@@ -7301,7 +7565,7 @@ function repairNativeAgent(target) {
|
|
|
7301
7565
|
}
|
|
7302
7566
|
function disableNative(argv) {
|
|
7303
7567
|
if (argv.length === 1 && argv[0] === "--all") {
|
|
7304
|
-
const targets = ["claude", "codex", "hermes", "gemini", "opencode", "aider"]
|
|
7568
|
+
const targets = ["claude", "codex", "hermes", "gemini", "opencode", "pi", "aider"]
|
|
7305
7569
|
.filter((agent) => Boolean(readNativeJournal(agent) || readPendingNativeJournal(agent)));
|
|
7306
7570
|
if (targets.length === 0) {
|
|
7307
7571
|
process.stderr.write(`${mark("warn")} no native Caveman integrations are journaled\n`);
|
|
@@ -7322,8 +7586,8 @@ function disableNative(argv) {
|
|
|
7322
7586
|
return;
|
|
7323
7587
|
}
|
|
7324
7588
|
const target = argv[0];
|
|
7325
|
-
if ((target !== "claude" && target !== "codex" && target !== "hermes" && target !== "gemini" && target !== "opencode" && target !== "aider") || argv.length !== 1)
|
|
7326
|
-
commandUsage("disable <claude|codex|hermes|gemini|opencode|aider> | disable --all");
|
|
7589
|
+
if ((target !== "claude" && target !== "codex" && target !== "hermes" && target !== "gemini" && target !== "opencode" && target !== "pi" && target !== "aider") || argv.length !== 1)
|
|
7590
|
+
commandUsage("disable <claude|codex|hermes|gemini|opencode|pi|aider> | disable --all");
|
|
7327
7591
|
disableNativeAgent(target);
|
|
7328
7592
|
}
|
|
7329
7593
|
function nativeIntegrationStatus(agent) {
|
|
@@ -7385,6 +7649,9 @@ function nativeIntegrationStatus(agent) {
|
|
|
7385
7649
|
else if (operation.kind === "opencode-plugin") {
|
|
7386
7650
|
owned = current.toString("utf8").includes("caveman:native-opencode");
|
|
7387
7651
|
}
|
|
7652
|
+
else if (operation.kind === "pi-extension") {
|
|
7653
|
+
owned = current.toString("utf8").includes("caveman:native-pi");
|
|
7654
|
+
}
|
|
7388
7655
|
else if (operation.kind === "aider-config") {
|
|
7389
7656
|
const text = current.toString("utf8");
|
|
7390
7657
|
owned = typeof operation.owned?.route_block === "string" && typeof operation.owned?.read_block === "string"
|
|
@@ -7413,13 +7680,30 @@ function nativeIntegrationStatus(agent) {
|
|
|
7413
7680
|
const coreResolution = runtimeConfig.resolution.values["think.core"];
|
|
7414
7681
|
const coreConfigured = coreResolution.value === true;
|
|
7415
7682
|
const mcp = probeMcpBinary();
|
|
7416
|
-
const expectedRoute = appendUrlPath(gatewayURL(), agent === "claude" ? "/w/claude" : agent === "hermes" ? "/w/hermes" : agent === "gemini" ? "/w/gemini" : agent === "opencode" ? "/w/opencode" : agent === "aider" ? "/w/aider/openai/v1" : detectCodexWrapAuthMode() === "subscription" ? "/chatgpt" : "/w/codex");
|
|
7417
|
-
const routeKind = agent === "claude" ? "claude-settings" : agent === "codex" ? "codex-config" : agent === "hermes" ? "hermes-config" : agent === "gemini" ? "gemini-env" : agent === "opencode" ? "opencode-config" : "aider-config";
|
|
7683
|
+
const expectedRoute = appendUrlPath(gatewayURL(), agent === "claude" ? "/w/claude" : agent === "hermes" ? "/w/hermes" : agent === "gemini" ? "/w/gemini" : agent === "opencode" ? "/w/opencode" : agent === "pi" ? "/w/pi" : agent === "aider" ? "/w/aider/openai/v1" : detectCodexWrapAuthMode() === "subscription" ? "/chatgpt" : "/w/codex");
|
|
7684
|
+
const routeKind = agent === "claude" ? "claude-settings" : agent === "codex" ? "codex-config" : agent === "hermes" ? "hermes-config" : agent === "gemini" ? "gemini-env" : agent === "opencode" ? "opencode-config" : agent === "pi" ? "pi-extension" : "aider-config";
|
|
7418
7685
|
const routeOperation = journal?.operations.find((operation) => operation.kind === routeKind);
|
|
7686
|
+
// Pi's artifact encodes no route: the extension resolves the gateway at
|
|
7687
|
+
// runtime through the same env → config → default chain as gatewayURL(), so
|
|
7688
|
+
// route drift between enable and now cannot happen. What CAN drift is the
|
|
7689
|
+
// bundle itself after a CLI upgrade — require the on-disk artifact to end
|
|
7690
|
+
// with the currently shipped bundle bytes so `doctor pi --fix` sees it.
|
|
7691
|
+
const piBundleCurrent = agent !== "pi" || (() => {
|
|
7692
|
+
const current = routeOperation ? fileBytes(routeOperation.file) : null;
|
|
7693
|
+
if (!current)
|
|
7694
|
+
return false;
|
|
7695
|
+
try {
|
|
7696
|
+
const shipped = readFileSync(resolvePiExtension());
|
|
7697
|
+
return current.length >= shipped.length && current.subarray(current.length - shipped.length).equals(shipped);
|
|
7698
|
+
}
|
|
7699
|
+
catch {
|
|
7700
|
+
return false;
|
|
7701
|
+
}
|
|
7702
|
+
})();
|
|
7419
7703
|
const routeHealthy = ownedHealthy && (agent === "opencode"
|
|
7420
7704
|
? routeOperation?.owned?.routes?.openai === appendUrlPath(expectedRoute, "/openai/v1")
|
|
7421
7705
|
&& routeOperation?.owned?.routes?.anthropic === appendUrlPath(expectedRoute, "/anthropic/v1")
|
|
7422
|
-
: routeOperation?.owned?.route === expectedRoute);
|
|
7706
|
+
: agent === "pi" ? piBundleCurrent : routeOperation?.owned?.route === expectedRoute);
|
|
7423
7707
|
const proxyHealthy = wrapMode(gatewayURL()) === "managed" || Boolean(probeProxyVersion()?.capabilities.includes("native_runtime_v1"));
|
|
7424
7708
|
const recoveryHealthy = agent === "aider" || Boolean(mcp?.probe.current);
|
|
7425
7709
|
const state = !available ? "unavailable" : transactionPending ? "degraded" : !installed ? "available" : !packCurrent || !ownedHealthy || !routeHealthy || !proxyHealthy || !recoveryHealthy ? "degraded" : "installed";
|
|
@@ -7429,11 +7713,11 @@ function nativeIntegrationStatus(agent) {
|
|
|
7429
7713
|
: coreSupported && nativeCoreRuntimeState().active;
|
|
7430
7714
|
const fileText = checks.map((check) => fileBytes(check.file)?.toString("utf8") ?? "").join("\n");
|
|
7431
7715
|
const components = {
|
|
7432
|
-
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") : fileText.includes(AIDER_NATIVE_ROUTE_BEGIN)),
|
|
7716
|
+
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)),
|
|
7433
7717
|
lifecycle_hooks: agent !== "aider" && ownedHealthy,
|
|
7434
7718
|
core: coreActive,
|
|
7435
7719
|
mcp_recovery: agent !== "aider" && ownedHealthy && Boolean(mcp?.probe.current),
|
|
7436
|
-
tool_rewrite: agent !== "aider" && ownedHealthy && (agent === "hermes" ? false : fileText.includes("shrink-hook")),
|
|
7720
|
+
tool_rewrite: agent !== "aider" && ownedHealthy && (agent === "hermes" ? false : agent === "pi" ? fileText.includes("caveman:native-pi") : fileText.includes("shrink-hook")),
|
|
7437
7721
|
shared_runtime: proxyHealthy,
|
|
7438
7722
|
};
|
|
7439
7723
|
const versionStatus = nativeVersionStatus(host.version, profile.tested_agent_version);
|
|
@@ -7516,8 +7800,8 @@ function genericIntegrationStatus(runtimeReachable) {
|
|
|
7516
7800
|
async function nativeDoctor(argv) {
|
|
7517
7801
|
const fix = argv.includes("--fix");
|
|
7518
7802
|
const target = argv.find((arg) => arg !== "--fix");
|
|
7519
|
-
if ((target !== "claude" && target !== "codex" && target !== "hermes" && target !== "gemini" && target !== "opencode" && target !== "aider" && target !== "generic") || argv.length !== (fix ? 2 : 1) || (fix && target === "generic"))
|
|
7520
|
-
commandUsage("doctor <claude|codex|hermes|gemini|opencode|aider|generic> [--fix]");
|
|
7803
|
+
if ((target !== "claude" && target !== "codex" && target !== "hermes" && target !== "gemini" && target !== "opencode" && target !== "pi" && target !== "aider" && target !== "generic") || argv.length !== (fix ? 2 : 1) || (fix && target === "generic"))
|
|
7804
|
+
commandUsage("doctor <claude|codex|hermes|gemini|opencode|pi|aider|generic> [--fix]");
|
|
7521
7805
|
if (target === "generic") {
|
|
7522
7806
|
const { host, port } = gatewayHostPort();
|
|
7523
7807
|
const result = genericIntegrationStatus(await portListening(host, port));
|
|
@@ -7849,6 +8133,12 @@ function wrapBaseUrlEnv(gw) {
|
|
|
7849
8133
|
const env = {};
|
|
7850
8134
|
for (const key of WRAP_BASE_URL_ENV_VARS)
|
|
7851
8135
|
env[key] = gw;
|
|
8136
|
+
// Same reason as the native-enable path: redirecting ANTHROPIC_BASE_URL makes
|
|
8137
|
+
// Claude Code drop tool search and inline every MCP tool schema. Inert for the
|
|
8138
|
+
// other wrappable agents, which never read this variable. A value already in
|
|
8139
|
+
// the environment is the user's choice and wins.
|
|
8140
|
+
if (process.env.ENABLE_TOOL_SEARCH === undefined)
|
|
8141
|
+
env.ENABLE_TOOL_SEARCH = TOOL_SEARCH_DEFAULT;
|
|
7852
8142
|
return env;
|
|
7853
8143
|
}
|
|
7854
8144
|
function attributedGatewayUrl(gw, agent) {
|
|
@@ -7965,7 +8255,10 @@ export function buildWrapEnv(agent, gw = gatewayURL(), mcpMode = "auto") {
|
|
|
7965
8255
|
throw new Error("managed Gemini CLI routing is unsupported because Gemini CLI cannot send separate Caveman and upstream credentials");
|
|
7966
8256
|
}
|
|
7967
8257
|
const renderedGw = agent ? attributedGatewayUrl(gw, agent) : gw;
|
|
7968
|
-
const env = {
|
|
8258
|
+
const env = {
|
|
8259
|
+
...process.env,
|
|
8260
|
+
...(agent?.injection.method === "native-extension" ? {} : wrapBaseUrlEnv(renderedGw)),
|
|
8261
|
+
};
|
|
7969
8262
|
if (wrapMode(gw) === "managed") {
|
|
7970
8263
|
const gatewayKey = connectedGatewayAPIKey();
|
|
7971
8264
|
if (gatewayKey)
|
|
@@ -8003,6 +8296,13 @@ export function buildWrapEnv(agent, gw = gatewayURL(), mcpMode = "auto") {
|
|
|
8003
8296
|
}
|
|
8004
8297
|
if (agent.id === "hermes")
|
|
8005
8298
|
applyHermesAuthEnv(env, renderedGw, gw);
|
|
8299
|
+
if (agent.id === "claude" && wrapMode(gw) === "local" && env[CLAUDE_ASSUME_FIRST_PARTY_ENV] === undefined && proxyAnthropicUpstreamIsFirstParty()) {
|
|
8300
|
+
// Keep Claude Code's first-party capability set (1M context window /
|
|
8301
|
+
// ~600k auto-compact window) intact behind the local pass-through proxy
|
|
8302
|
+
// (#865). Local-mode only: a managed gateway upstream is not verifiable
|
|
8303
|
+
// from here, and a user-exported value always wins.
|
|
8304
|
+
env[CLAUDE_ASSUME_FIRST_PARTY_ENV] = "1";
|
|
8305
|
+
}
|
|
8006
8306
|
return env;
|
|
8007
8307
|
}
|
|
8008
8308
|
// orgIdFromConfigFile reads the (non-secret) organization id straight from
|
|
@@ -9133,6 +9433,14 @@ function queueStaleMcpBinary(probe) {
|
|
|
9133
9433
|
function wrapMcpRecoveryAvailable(agent, opts) {
|
|
9134
9434
|
if (!wrapRecoveryEligible(opts) || !agent)
|
|
9135
9435
|
return false;
|
|
9436
|
+
if (agent.id === "pi") {
|
|
9437
|
+
const compatibility = probeMcpBinary();
|
|
9438
|
+
if (!compatibility)
|
|
9439
|
+
return false;
|
|
9440
|
+
if (!compatibility.probe.current)
|
|
9441
|
+
queueStaleMcpBinary(compatibility.probe);
|
|
9442
|
+
return compatibility.probe.current;
|
|
9443
|
+
}
|
|
9136
9444
|
// Two independent sources of a real caveman_retrieve: a marker from
|
|
9137
9445
|
// `caveman tools mcp install`, or the profile's own config-file overlay. The
|
|
9138
9446
|
// second only counts under `auto`, because that is exactly when buildWrapEnv
|
|
@@ -9187,6 +9495,25 @@ function resolveDelegateMcpCommand() {
|
|
|
9187
9495
|
const script = candidates.find((c) => existsSync(c));
|
|
9188
9496
|
return script ? { command: process.execPath, args: [script] } : null;
|
|
9189
9497
|
}
|
|
9498
|
+
function resolvePiExtension() {
|
|
9499
|
+
const extension = process.env.CAVEMAN_PI_EXTENSION?.trim()
|
|
9500
|
+
|| join(dirname(fileURLToPath(import.meta.url)), "caveman-pi-extension.mjs");
|
|
9501
|
+
if (!existsSync(extension)) {
|
|
9502
|
+
throw new Error(`Pi extension not found at ${extension}; set CAVEMAN_PI_EXTENSION or run the CLI build step`);
|
|
9503
|
+
}
|
|
9504
|
+
return extension;
|
|
9505
|
+
}
|
|
9506
|
+
function buildPiWrapArgs(cmdArgs, env, gw) {
|
|
9507
|
+
const extension = resolvePiExtension();
|
|
9508
|
+
const { cmd, pre } = cavemanInvocation();
|
|
9509
|
+
env.CAVEMAN_PI_HOOK_CMD = JSON.stringify([cmd, ...pre]);
|
|
9510
|
+
env.CAVE_GATEWAY_URL = gw;
|
|
9511
|
+
// The profile's injection block declares the loader flag; using it here keeps the
|
|
9512
|
+
// compiled registry the single source of truth for how the asset is loaded.
|
|
9513
|
+
const profile = AGENTS.find((a) => a.id === "pi");
|
|
9514
|
+
const loaderFlag = profile?.injection.method === "native-extension" ? profile.injection.loader_flag : "--extension";
|
|
9515
|
+
return [loaderFlag, extension, ...cmdArgs];
|
|
9516
|
+
}
|
|
9190
9517
|
const HERMES_MCP_BEGIN = "# >>> caveman:mcp";
|
|
9191
9518
|
const HERMES_MCP_END = "# <<< caveman:mcp";
|
|
9192
9519
|
const HERMES_PLUGIN_ENABLE_BEGIN = "# >>> caveman:hermes-plugin-enable";
|
|
@@ -10662,7 +10989,7 @@ function nativeWhy(argv) {
|
|
|
10662
10989
|
// never cross the adapter boundary. Any malformed input/write failure stays
|
|
10663
10990
|
// fail-open and emits no blocking decision.
|
|
10664
10991
|
async function nativeHook(argv) {
|
|
10665
|
-
const agent = argv[0] === "claude" || argv[0] === "codex" || argv[0] === "hermes" || argv[0] === "gemini" || argv[0] === "opencode" ? argv[0] : undefined;
|
|
10992
|
+
const agent = argv[0] === "claude" || argv[0] === "codex" || argv[0] === "hermes" || argv[0] === "gemini" || argv[0] === "opencode" || argv[0] === "pi" ? argv[0] : undefined;
|
|
10666
10993
|
if (!agent)
|
|
10667
10994
|
process.exit(0);
|
|
10668
10995
|
let raw;
|
|
@@ -10787,7 +11114,7 @@ async function nativeHook(argv) {
|
|
|
10787
11114
|
hookSpecificOutput: { hookEventName: "PostToolUse", updatedToolOutput: runtimeResponse.output_replacement },
|
|
10788
11115
|
}));
|
|
10789
11116
|
}
|
|
10790
|
-
else if (policyMode !== "record" && agent === "opencode" && normalizedEvent === "PostToolUse" && runtimeResponse) {
|
|
11117
|
+
else if (policyMode !== "record" && (agent === "opencode" || agent === "pi") && (normalizedEvent === "PostToolUse" || normalizedEvent === "PostToolUseFailure") && runtimeResponse) {
|
|
10791
11118
|
process.stdout.write(JSON.stringify(runtimeResponse));
|
|
10792
11119
|
}
|
|
10793
11120
|
}
|
|
@@ -10908,11 +11235,15 @@ function expandTilde(p) {
|
|
|
10908
11235
|
// commandHookKind classifies an agent's command-output hook surface so callers can
|
|
10909
11236
|
// speak about it honestly: "hard" = a deterministic pre-exec command rewrite (RTK
|
|
10910
11237
|
// parity), "soft" = a model nudge in an auto-read instructions file (best-effort,
|
|
10911
|
-
// not a rewrite), "
|
|
11238
|
+
// not a rewrite), "native" = the rewrite ships inside the agent's native
|
|
11239
|
+
// extension (`caveman enable <agent>`), nothing separate to install here,
|
|
11240
|
+
// "none" = no surface we can install (manual `caveman shrink` only).
|
|
10912
11241
|
function commandHookKind(a) {
|
|
10913
11242
|
const ch = a.command_hook;
|
|
10914
11243
|
if (!ch)
|
|
10915
11244
|
return "none";
|
|
11245
|
+
if (ch.method === "pi-extension")
|
|
11246
|
+
return "native";
|
|
10916
11247
|
return ch.method === "instruction-note" ? "soft" : "hard";
|
|
10917
11248
|
}
|
|
10918
11249
|
function instructionFileForAgent(a) {
|
|
@@ -10941,6 +11272,10 @@ function installShrinkHookForAgent(a) {
|
|
|
10941
11272
|
return installShrinkPluginHermes();
|
|
10942
11273
|
case "openclaw-plugin":
|
|
10943
11274
|
return installShrinkPluginOpenClaw();
|
|
11275
|
+
case "pi-extension":
|
|
11276
|
+
// Pi's rewrite surface IS the native extension (`caveman enable pi`); there is
|
|
11277
|
+
// no separate hook artifact to install here.
|
|
11278
|
+
return false;
|
|
10944
11279
|
case "instruction-note":
|
|
10945
11280
|
return installShrinkNote(ch.file);
|
|
10946
11281
|
}
|
|
@@ -10962,6 +11297,9 @@ function removeShrinkHookForAgent(a) {
|
|
|
10962
11297
|
return removeShrinkPluginHermes();
|
|
10963
11298
|
case "openclaw-plugin":
|
|
10964
11299
|
return removeShrinkPluginOpenClaw();
|
|
11300
|
+
case "pi-extension":
|
|
11301
|
+
// Removed together with the native extension (`caveman disable pi`).
|
|
11302
|
+
return false;
|
|
10965
11303
|
case "instruction-note":
|
|
10966
11304
|
return removeShrinkNote(ch.file);
|
|
10967
11305
|
}
|
|
@@ -11887,7 +12225,8 @@ function hooksCmd(rest) {
|
|
|
11887
12225
|
else {
|
|
11888
12226
|
// No agent named: target every known agent with an installable hook surface
|
|
11889
12227
|
// that is actually present on PATH (mirrors `mcp install`'s detect-all path).
|
|
11890
|
-
|
|
12228
|
+
// "native" surfaces install through `caveman enable <agent>`, not here.
|
|
12229
|
+
targets = AGENTS.filter((a) => commandHookKind(a) !== "none" && commandHookKind(a) !== "native" && which(binOf(a)));
|
|
11891
12230
|
if (targets.length === 0) {
|
|
11892
12231
|
console.error("no hookable agents detected on PATH; pass an agent id, e.g. `caveman hooks install claude`");
|
|
11893
12232
|
process.exit(1);
|
|
@@ -11904,6 +12243,9 @@ function hooksCmd(rest) {
|
|
|
11904
12243
|
hard++;
|
|
11905
12244
|
process.stderr.write(`${mark("ok")} ${a.display_name}: ${hookInstalledPhrase(a)}\n`);
|
|
11906
12245
|
}
|
|
12246
|
+
else if (commandHookKind(a) === "native") {
|
|
12247
|
+
process.stderr.write(`${mark("ok")} ${a.display_name}: command-output rewrite ships with the native extension — run ${cyan(`caveman enable ${a.id}`)}\n`);
|
|
12248
|
+
}
|
|
11907
12249
|
else if (commandHookKind(a) === "none") {
|
|
11908
12250
|
process.stderr.write(`${mark("warn")} ${a.display_name}: no automatic command-output hook surface — run noisy commands through ${cyan("caveman shrink -- <cmd>")}\n`);
|
|
11909
12251
|
}
|
|
@@ -11924,6 +12266,10 @@ function hooksCmd(rest) {
|
|
|
11924
12266
|
return;
|
|
11925
12267
|
}
|
|
11926
12268
|
for (const a of targets) {
|
|
12269
|
+
if (commandHookKind(a) === "native") {
|
|
12270
|
+
process.stderr.write(`${mark("ok")} ${a.display_name}: command-output rewrite ships with the native extension — remove with ${cyan(`caveman disable ${a.id}`)}\n`);
|
|
12271
|
+
continue;
|
|
12272
|
+
}
|
|
11927
12273
|
const removed = removeShrinkHookForAgent(a);
|
|
11928
12274
|
try {
|
|
11929
12275
|
unlinkSync(shrinkHookMarkerPath(a.id));
|
|
@@ -12122,7 +12468,7 @@ async function trial(rest) {
|
|
|
12122
12468
|
if (learnHistory) {
|
|
12123
12469
|
proxyExecMaybe(["usage", "import", "codex", "--since", since]);
|
|
12124
12470
|
proxyExecMaybe(["usage", "import", "claude", "--since", since]);
|
|
12125
|
-
proxyExecMaybe(["learn", "scan", "--
|
|
12471
|
+
proxyExecMaybe(["learn", "scan", "--since", since]);
|
|
12126
12472
|
}
|
|
12127
12473
|
proxyExec(["trial", "analyze", "--trial-id", trialID], process.env, true);
|
|
12128
12474
|
proxyPassthrough(["trial", "report", "--trial-id", trialID]);
|
|
@@ -12136,6 +12482,11 @@ async function trial(rest) {
|
|
|
12136
12482
|
}
|
|
12137
12483
|
const LEARN_EMPTY = "no Claude Code or Codex sessions found in the last 30d — the plan needs a block repeated across ≥3 sessions; run `caveman claude` a few times, then `caveman learn`";
|
|
12138
12484
|
const LEARN_DETAILED_NEXT = "next: caveman tools skills install caveman-learn (review + apply, with consent) · preview one: caveman learn apply <sink_id> --dry-run";
|
|
12485
|
+
const LEARN_ALL_FOOTER = [
|
|
12486
|
+
"advanced: caveman learn applied <sink_id> [--fix-kind <kind>] [--note <text>] record an approved, re-measured fix",
|
|
12487
|
+
"simulate: caveman learn simulate <sink_id...> sum counterfactual scale over scanned history",
|
|
12488
|
+
"scope: caveman learn --repo <substring> filter sessions before analysis",
|
|
12489
|
+
];
|
|
12139
12490
|
const LEARN_SUMMARY_LIMIT = 3;
|
|
12140
12491
|
function learnReportPath() {
|
|
12141
12492
|
return join(cavemanHome(), "reports", "caveman-learn.html");
|
|
@@ -12163,7 +12514,11 @@ function renderLearnDetailedRows(plan, markdown) {
|
|
|
12163
12514
|
for (const [index, sink] of plan.sinks.entries()) {
|
|
12164
12515
|
const lead = markdown ? `${index + 1}. **${sink.title}**` : `${index + 1}. ${sink.title}`;
|
|
12165
12516
|
lines.push(`${lead} · ${sink.sink_id} · ${sink.class}`);
|
|
12166
|
-
|
|
12517
|
+
const observed = typeof sink.tokens_observed === "number" && sink.tokens_observed > 0
|
|
12518
|
+
? ` · ~${humanTokens(sink.tokens_observed)} tokens observed (historical)`
|
|
12519
|
+
: "";
|
|
12520
|
+
const prefix = learnMeasuredPrefixSuffix(sink);
|
|
12521
|
+
lines.push(` ~${humanTokens(sink.tokens_per_turn)} tokens/turn · ~${humanTokens(sink.tokens_per_day_rate)} tokens/day${observed} · basis: inferred${prefix}`);
|
|
12167
12522
|
if (KNOWN_PRACTICE_IDS.has(sink.practice_id)) {
|
|
12168
12523
|
lines.push(` practice: ${sink.practice_id} · unmeasured — verified nowhere yet`);
|
|
12169
12524
|
}
|
|
@@ -12176,6 +12531,14 @@ function learnEvidenceNumber(sink, key) {
|
|
|
12176
12531
|
const value = sink.evidence?.[key];
|
|
12177
12532
|
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined;
|
|
12178
12533
|
}
|
|
12534
|
+
function learnMeasuredPrefixSuffix(sink) {
|
|
12535
|
+
if (!sink || sink.sink_id !== "config_tax:baseline")
|
|
12536
|
+
return "";
|
|
12537
|
+
const measured = learnEvidenceNumber(sink, "measured_prefix_tokens");
|
|
12538
|
+
return measured && measured > 0
|
|
12539
|
+
? ` · provider-counted prefix ~${humanTokens(measured)} (turn-1 median)`
|
|
12540
|
+
: "";
|
|
12541
|
+
}
|
|
12179
12542
|
function compactLearnText(value, max = 108) {
|
|
12180
12543
|
const oneLine = value.replace(/\s+/g, " ").trim();
|
|
12181
12544
|
if (oneLine.length <= max)
|
|
@@ -12188,10 +12551,37 @@ function compactLearnText(value, max = 108) {
|
|
|
12188
12551
|
return `${prefix.slice(0, wordEnd > 0 ? wordEnd : prefix.length)}…`;
|
|
12189
12552
|
}
|
|
12190
12553
|
export function learnSummaryMoves(plan) {
|
|
12191
|
-
const recurring = plan.sinks.filter((sink) => sink.class === "recurring_context");
|
|
12192
12554
|
const moves = [];
|
|
12555
|
+
const best = plan.portfolio?.best_next_move;
|
|
12556
|
+
const represented = new Set(best?.sink_ids ?? []);
|
|
12557
|
+
if (best) {
|
|
12558
|
+
const confidenceLabels = {
|
|
12559
|
+
measured_usage: "measured",
|
|
12560
|
+
transcript_inferred: "transcript",
|
|
12561
|
+
static_estimate: "estimate",
|
|
12562
|
+
};
|
|
12563
|
+
const confidence = confidenceLabels[best.confidence] ?? best.confidence;
|
|
12564
|
+
const detail = [
|
|
12565
|
+
`sink: ${best.top_sink_id}`,
|
|
12566
|
+
best.combined_rate_per_day > 0
|
|
12567
|
+
? `~${humanTokens(best.combined_rate_per_day)} tokens/day`
|
|
12568
|
+
: "",
|
|
12569
|
+
best.combined_observed_in_window > 0
|
|
12570
|
+
? `~${humanTokens(best.combined_observed_in_window)} tokens observed`
|
|
12571
|
+
: "",
|
|
12572
|
+
confidence,
|
|
12573
|
+
].filter(Boolean);
|
|
12574
|
+
moves.push({
|
|
12575
|
+
title: best.top_sink_title,
|
|
12576
|
+
kind: best.fix_label,
|
|
12577
|
+
detail: detail.join(" · "),
|
|
12578
|
+
...(best.net_note ? { action: compactLearnText(best.net_note) } : {}),
|
|
12579
|
+
});
|
|
12580
|
+
}
|
|
12581
|
+
const remaining = plan.sinks.filter((sink) => !represented.has(sink.sink_id));
|
|
12582
|
+
const recurring = remaining.filter((sink) => sink.class === "recurring_context");
|
|
12193
12583
|
let recurringAdded = false;
|
|
12194
|
-
for (const sink of
|
|
12584
|
+
for (const sink of remaining) {
|
|
12195
12585
|
if (sink.class === "load_bearing")
|
|
12196
12586
|
continue;
|
|
12197
12587
|
if (sink.class === "recurring_context") {
|
|
@@ -12247,6 +12637,9 @@ function learnSourceLine(plan, sessions) {
|
|
|
12247
12637
|
const sourceBits = [
|
|
12248
12638
|
by.claude ? `Claude ${by.claude}` : "",
|
|
12249
12639
|
by.codex ? `Codex ${by.codex}` : "",
|
|
12640
|
+
by.gemini ? `Gemini ${by.gemini}` : "",
|
|
12641
|
+
by.opencode ? `opencode ${by.opencode}` : "",
|
|
12642
|
+
by.aider ? `aider ${by.aider}` : "",
|
|
12250
12643
|
].filter(Boolean);
|
|
12251
12644
|
return `${sessions} sessions${sourceBits.length ? ` · ${sourceBits.join(" · ")}` : ""}`;
|
|
12252
12645
|
}
|
|
@@ -12264,6 +12657,7 @@ export function buildLearnTuiModel(plan, options = {}) {
|
|
|
12264
12657
|
const sessions = Math.max(0, Number(plan.sessions_scanned ?? 0));
|
|
12265
12658
|
const recurring = plan.sinks.some((sink) => sink.class === "recurring_context");
|
|
12266
12659
|
const protectedSink = plan.sinks.find((sink) => sink.class === "load_bearing");
|
|
12660
|
+
const confirmed = plan.confirmed?.length ?? 0;
|
|
12267
12661
|
const diffText = learnDiffText(options.diff);
|
|
12268
12662
|
const status = sessions === 0
|
|
12269
12663
|
? LEARN_EMPTY
|
|
@@ -12278,8 +12672,9 @@ export function buildLearnTuiModel(plan, options = {}) {
|
|
|
12278
12672
|
...(status ? { status } : {}),
|
|
12279
12673
|
moves: learnSummaryMoves(plan),
|
|
12280
12674
|
...(protectedSink
|
|
12281
|
-
? { protected: `${protectedSink.title.replace(/^Your\s+/i, "")} · included in score, never auto-fixed` }
|
|
12675
|
+
? { protected: `${protectedSink.title.replace(/^Your\s+/i, "")} · included in score, never auto-fixed${learnMeasuredPrefixSuffix(protectedSink)}` }
|
|
12282
12676
|
: {}),
|
|
12677
|
+
...(confirmed > 0 ? { confirmed } : {}),
|
|
12283
12678
|
findings: plan.sinks.length,
|
|
12284
12679
|
report: options.report ?? learnReportPath(),
|
|
12285
12680
|
};
|
|
@@ -12291,14 +12686,19 @@ export function renderLearnPlan(plan, options = {}) {
|
|
|
12291
12686
|
const sessions = Math.max(0, Number(plan.sessions_scanned ?? 0));
|
|
12292
12687
|
const recurring = plan.sinks.some((sink) => sink.class === "recurring_context");
|
|
12293
12688
|
const lines = [];
|
|
12689
|
+
const confirmedLines = renderLearnConfirmed(plan.confirmed, markdown);
|
|
12294
12690
|
if (sessions === 0) {
|
|
12295
12691
|
lines.push(LEARN_EMPTY);
|
|
12692
|
+
if (confirmedLines.length > 0)
|
|
12693
|
+
lines.push("", ...confirmedLines);
|
|
12296
12694
|
}
|
|
12297
12695
|
else if (!recurring) {
|
|
12298
12696
|
if (plan.sinks.length > 0) {
|
|
12299
12697
|
lines.push(...(verbose ? renderLearnDetailedRows(plan, markdown) : ["top moves", ...renderLearnSummaryRows(plan)]), "");
|
|
12300
12698
|
}
|
|
12301
12699
|
lines.push(`${sessions} sessions scanned · no block repeated across ≥3 sessions yet — keep running \`caveman claude\`, then re-run \`caveman learn\``);
|
|
12700
|
+
if (confirmedLines.length > 0)
|
|
12701
|
+
lines.push("", ...confirmedLines);
|
|
12302
12702
|
}
|
|
12303
12703
|
else {
|
|
12304
12704
|
lines.push(markdown
|
|
@@ -12318,6 +12718,8 @@ export function renderLearnPlan(plan, options = {}) {
|
|
|
12318
12718
|
const diffText = learnDiffText(options.diff);
|
|
12319
12719
|
if (diffText)
|
|
12320
12720
|
lines.push(diffText);
|
|
12721
|
+
if (confirmedLines.length > 0)
|
|
12722
|
+
lines.push("", ...confirmedLines);
|
|
12321
12723
|
if (verbose) {
|
|
12322
12724
|
lines.push("", ...renderLearnDetailedRows(plan, markdown), "", LEARN_DETAILED_NEXT);
|
|
12323
12725
|
}
|
|
@@ -12326,14 +12728,65 @@ export function renderLearnPlan(plan, options = {}) {
|
|
|
12326
12728
|
lines.push("", "top moves", ...renderLearnSummaryRows(plan));
|
|
12327
12729
|
if (protectedSink) {
|
|
12328
12730
|
const title = protectedSink.title.replace(/^Your\s+/i, "");
|
|
12329
|
-
lines.push(`protected ${title} · included in score, never auto-fixed`);
|
|
12731
|
+
lines.push(`protected ${title} · included in score, never auto-fixed${learnMeasuredPrefixSuffix(protectedSink)}`);
|
|
12330
12732
|
}
|
|
12331
12733
|
lines.push("", `next: ${invokedAs()} learn implement fix with Claude Code or Codex; asks before every edit`, `details: ${invokedAs()} learn --all ${plan.sinks.length} findings`);
|
|
12332
12734
|
}
|
|
12333
12735
|
}
|
|
12736
|
+
if (options.all === true && (plan.repos?.length ?? 0) > 0) {
|
|
12737
|
+
lines.push("", markdown ? "### Per-repo" : "per-repo", ...renderLearnRepos(plan.repos, markdown));
|
|
12738
|
+
}
|
|
12739
|
+
if (options.all === true) {
|
|
12740
|
+
lines.push("", ...(markdown ? ["### Advanced", ...LEARN_ALL_FOOTER.map((line) => `- ${line}`)] : LEARN_ALL_FOOTER));
|
|
12741
|
+
}
|
|
12334
12742
|
lines.push("", `report: ${report}`);
|
|
12335
12743
|
return `${lines.join("\n")}\n`;
|
|
12336
12744
|
}
|
|
12745
|
+
function learnMeasureValue(value) {
|
|
12746
|
+
if (value === undefined || !Number.isFinite(value))
|
|
12747
|
+
return "?";
|
|
12748
|
+
if (Number.isInteger(value))
|
|
12749
|
+
return String(value);
|
|
12750
|
+
return value.toFixed(1).replace(/\.0$/, "");
|
|
12751
|
+
}
|
|
12752
|
+
function learnMeasureUnit(unit) {
|
|
12753
|
+
const labels = {
|
|
12754
|
+
config_tokens_per_turn: "config tokens/turn",
|
|
12755
|
+
turns_over_half_window_pct: "turns over half-window (%)",
|
|
12756
|
+
recurrence_present: "recurrence present",
|
|
12757
|
+
};
|
|
12758
|
+
return labels[unit] ?? unit.replaceAll("_", " ");
|
|
12759
|
+
}
|
|
12760
|
+
function learnAppliedDate(appliedAt) {
|
|
12761
|
+
return appliedAt.slice(0, 10);
|
|
12762
|
+
}
|
|
12763
|
+
function renderLearnConfirmed(confirmed, markdown) {
|
|
12764
|
+
if (!confirmed?.length)
|
|
12765
|
+
return [];
|
|
12766
|
+
const symbols = {
|
|
12767
|
+
improved: "✓",
|
|
12768
|
+
unchanged: "·",
|
|
12769
|
+
regressed: "!",
|
|
12770
|
+
insufficient_data: "·",
|
|
12771
|
+
};
|
|
12772
|
+
const rows = confirmed.flatMap((entry) => {
|
|
12773
|
+
const applied = learnAppliedDate(entry.applied_at);
|
|
12774
|
+
if (entry.verdict === "insufficient_data") {
|
|
12775
|
+
const line = `${symbols[entry.verdict]} ${entry.sink_id} — applied ${applied} · needs more post-fix sessions (${entry.sessions_after} sessions so far)`;
|
|
12776
|
+
return [markdown ? `- *${line}*` : line];
|
|
12777
|
+
}
|
|
12778
|
+
if (entry.after === undefined || !Number.isFinite(entry.after))
|
|
12779
|
+
return [];
|
|
12780
|
+
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}`;
|
|
12781
|
+
return [markdown ? `- ${line}` : line];
|
|
12782
|
+
});
|
|
12783
|
+
if (rows.length === 0)
|
|
12784
|
+
return [];
|
|
12785
|
+
return [markdown ? "### Confirmed fixes" : "confirmed fixes", ...rows];
|
|
12786
|
+
}
|
|
12787
|
+
function renderLearnRepos(repos, markdown) {
|
|
12788
|
+
return repos.map((repo) => `${markdown ? "- " : ""}${repo.repo} · ${repo.sessions} sessions · dumbzone ${repo.dumbzone_pct}% · median context ~${humanTokens(repo.median_context)}`);
|
|
12789
|
+
}
|
|
12337
12790
|
function readLearnDiff(current) {
|
|
12338
12791
|
const dir = join(cavemanHome(), "reports");
|
|
12339
12792
|
let files;
|
|
@@ -12466,6 +12919,16 @@ function proxyExecLearnAsync(proxyArgs, onProgress) {
|
|
|
12466
12919
|
});
|
|
12467
12920
|
});
|
|
12468
12921
|
}
|
|
12922
|
+
export function formatLearnProxyJSON(raw, tty = !!process.stdout.isTTY) {
|
|
12923
|
+
if (!tty)
|
|
12924
|
+
return raw;
|
|
12925
|
+
try {
|
|
12926
|
+
return `${JSON.stringify(JSON.parse(raw), null, 2)}\n`;
|
|
12927
|
+
}
|
|
12928
|
+
catch {
|
|
12929
|
+
return raw;
|
|
12930
|
+
}
|
|
12931
|
+
}
|
|
12469
12932
|
export function learnReportOpener(report, platform = process.platform) {
|
|
12470
12933
|
if (platform === "darwin")
|
|
12471
12934
|
return { command: "open", args: [report] };
|
|
@@ -12519,13 +12982,21 @@ function renderLearnApply(raw, dryRun) {
|
|
|
12519
12982
|
return `${lines.join("\n")}\n`;
|
|
12520
12983
|
}
|
|
12521
12984
|
function learnUsage() {
|
|
12522
|
-
console.log(`${invokedAs()} learn [--all|--plain|--json|--md] [--since 30d] [--sources codex,
|
|
12985
|
+
console.log(`${invokedAs()} learn [--all|--plain|--json|--md] [--since 30d] [--sources claude,codex,gemini,opencode,aider]
|
|
12523
12986
|
default interactive setup score + grouped top moves
|
|
12524
12987
|
--plain compact text; no animation or keyboard menu
|
|
12525
12988
|
--all every finding, internal id, basis, and suggestion
|
|
12526
12989
|
--json|--md machine-readable or detailed Markdown output
|
|
12527
12990
|
implement open Claude Code or Codex to review and fix findings
|
|
12528
|
-
apply prepare one finding for consent-gated editing
|
|
12991
|
+
apply prepare one finding for consent-gated editing
|
|
12992
|
+
|
|
12993
|
+
advanced:
|
|
12994
|
+
applied <sink_id> [--fix-kind <kind>] [--note <text>]
|
|
12995
|
+
record an approved, re-measured fix
|
|
12996
|
+
simulate <sink_id...>
|
|
12997
|
+
sum counterfactual scale over scanned history
|
|
12998
|
+
--repo <substring>
|
|
12999
|
+
filter sessions before analysis`);
|
|
12529
13000
|
}
|
|
12530
13001
|
function learnImplementUsage() {
|
|
12531
13002
|
console.log(`${invokedAs()} learn implement [claude|codex] [--prompt "<focus>"]
|
|
@@ -12638,6 +13109,11 @@ async function learn(rest) {
|
|
|
12638
13109
|
return learnUsage();
|
|
12639
13110
|
if (sub === "implement")
|
|
12640
13111
|
return learnImplement(rest.slice(1));
|
|
13112
|
+
if (sub === "applied" || sub === "simulate") {
|
|
13113
|
+
const rawText = proxyExecLearn(["learn", ...rest], false);
|
|
13114
|
+
process.stdout.write(formatLearnProxyJSON(rawText));
|
|
13115
|
+
return;
|
|
13116
|
+
}
|
|
12641
13117
|
if (sub === "apply") {
|
|
12642
13118
|
const json = rest.includes("--json");
|
|
12643
13119
|
const rawText = proxyExecLearn(["learn", ...rest], false);
|
|
@@ -12654,6 +13130,7 @@ async function learn(rest) {
|
|
|
12654
13130
|
const json = rest.includes("--json");
|
|
12655
13131
|
const markdown = rest.includes("--md");
|
|
12656
13132
|
const verbose = rest.includes("--all") || rest.includes("--verbose");
|
|
13133
|
+
const all = rest.includes("--all");
|
|
12657
13134
|
const tui = learnTuiEnabled(rest);
|
|
12658
13135
|
const forwarded = rest.filter((arg) => !["--json", "--md", "--all", "--verbose", "--plain"].includes(arg));
|
|
12659
13136
|
const reportBefore = learnReportMtime();
|
|
@@ -12691,6 +13168,7 @@ async function learn(rest) {
|
|
|
12691
13168
|
process.stdout.write(renderLearnPlan(plan, {
|
|
12692
13169
|
report,
|
|
12693
13170
|
verbose: true,
|
|
13171
|
+
all: true,
|
|
12694
13172
|
...(diff ? { diff } : {}),
|
|
12695
13173
|
}));
|
|
12696
13174
|
return;
|
|
@@ -12717,6 +13195,7 @@ async function learn(rest) {
|
|
|
12717
13195
|
markdown,
|
|
12718
13196
|
report: learnReportPath(),
|
|
12719
13197
|
verbose,
|
|
13198
|
+
all,
|
|
12720
13199
|
...(diff ? { diff } : {}),
|
|
12721
13200
|
}));
|
|
12722
13201
|
}
|
|
@@ -13081,6 +13560,13 @@ function usageSecretDir() {
|
|
|
13081
13560
|
}
|
|
13082
13561
|
function readStdin() {
|
|
13083
13562
|
return new Promise((resolve, reject) => {
|
|
13563
|
+
// No pipe, no input. On a TTY stdin never ends, so `caveman compress` or
|
|
13564
|
+
// `toon encode` typed without a redirect sat there forever looking like a
|
|
13565
|
+
// prompt with nothing to type into.
|
|
13566
|
+
if (process.stdin.isTTY) {
|
|
13567
|
+
reject(new Error("no input on stdin — pipe a file in, e.g. `cat file | caveman …`"));
|
|
13568
|
+
return;
|
|
13569
|
+
}
|
|
13084
13570
|
const chunks = [];
|
|
13085
13571
|
process.stdin.on("data", (chunk) => chunks.push(chunk));
|
|
13086
13572
|
process.stdin.on("end", () => resolve(Buffer.concat(chunks)));
|
|
@@ -13474,7 +13960,7 @@ async function status(argv) {
|
|
|
13474
13960
|
},
|
|
13475
13961
|
next,
|
|
13476
13962
|
};
|
|
13477
|
-
const native = ["claude", "codex", "hermes", "gemini", "opencode", "aider"].map((agent) => {
|
|
13963
|
+
const native = ["claude", "codex", "hermes", "gemini", "opencode", "pi", "aider"].map((agent) => {
|
|
13478
13964
|
const integration = nativeIntegrationStatus(agent);
|
|
13479
13965
|
return {
|
|
13480
13966
|
...integration,
|
|
@@ -14819,7 +15305,9 @@ more
|
|
|
14819
15305
|
caveman tools local, no account · caveman help tools
|
|
14820
15306
|
caveman cloud connected · caveman help cloud`;
|
|
14821
15307
|
function renderedAgentList() {
|
|
14822
|
-
|
|
15308
|
+
// 8 fits todays registry on one line; "+N more" would render longer than
|
|
15309
|
+
// the ids it hides.
|
|
15310
|
+
const visible = AGENTS.slice(0, 8).map((agent) => agent.id);
|
|
14823
15311
|
const remaining = AGENTS.length - visible.length;
|
|
14824
15312
|
return `${visible.join(" | ")}${remaining > 0 ? ` | +${remaining} more — ${invokedAs()} run` : ""}`;
|
|
14825
15313
|
}
|