@caveman-ai/cli 4.0.1 → 4.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-skills.generated.js +1 -1
- package/dist/agents.generated.js +28 -27
- package/dist/binaries.generated.js +1 -1
- package/dist/caveman-pi-extension.mjs +302 -10
- package/dist/codemode.js +1402 -0
- package/dist/index.js +1453 -186
- package/dist/learn-tui.js +49 -47
- package/dist/modules/doctor.js +3 -0
- package/dist/provider-routing.js +11 -5
- package/dist/reserved-verbs.generated.js +0 -1
- package/dist/verified-methods.mirror.js +3 -3
- package/package.json +4 -4
package/dist/index.js
CHANGED
|
@@ -6,6 +6,7 @@ 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";
|
|
7
7
|
import { connect as netConnect, createServer as netCreateServer, isIP } from "node:net";
|
|
8
8
|
import { request as httpRequest } from "node:http";
|
|
9
|
+
import { applyKiloCodemodeOverlay, applyOpenCodeCodemodeOverlay, buildHermesEphemeralCodemodeHome, discoverCodemodeServers, discoverKiloOwnServerNames, discoverOpenCodeOwnServerNames, NATIVE_CODEMODE_AGENTS, patchEphemeralOpenClawCodemode, patchEphemeralQwenCodemode, stripExternalCodexMcpTables, syncBackHermesEphemeralHome, writeEphemeralCodemodeConfig, writeGeminiCodemodeSettingsOverlay, } from "./codemode.js";
|
|
9
10
|
import { request as httpsRequest } from "node:https";
|
|
10
11
|
import { createHash, createHmac, createPublicKey, randomBytes, randomUUID, verify as edVerify } from "node:crypto";
|
|
11
12
|
import { fileURLToPath } from "node:url";
|
|
@@ -44,15 +45,19 @@ import { endRuntimes, stopRuntime } from "./modules/stop.js";
|
|
|
44
45
|
import { foundKeys, providersAdd, providersCloud, providersLocal, providersLogin, providersRemove } from "./modules/provider-logins.js";
|
|
45
46
|
export const overlayBuilders = {};
|
|
46
47
|
const wrapTempDirs = new Set();
|
|
48
|
+
const hermesEphemeralSyncPairs = new Map();
|
|
47
49
|
// The standalone proxy listens here; `caveman start` launches it and
|
|
48
50
|
// `caveman wrap` points agents at it.
|
|
49
51
|
const PROXY_ADDR = "127.0.0.1:8787";
|
|
50
52
|
const PROXY_URL = `http://${PROXY_ADDR}`;
|
|
51
53
|
// Restores Claude Code's tool search after we take over ANTHROPIC_BASE_URL.
|
|
52
|
-
// "
|
|
53
|
-
//
|
|
54
|
-
//
|
|
55
|
-
|
|
54
|
+
// "true" matches Claude Code's own default when the variable is unset. "auto"
|
|
55
|
+
// would gate it on a tool-catalog size threshold, which hosts that connect MCP
|
|
56
|
+
// servers after the first request (Agent SDK apps) cross mid-session: early
|
|
57
|
+
// turns inline every schema and the flip to deferred busts the prompt cache.
|
|
58
|
+
const TOOL_SEARCH_DEFAULT = "true";
|
|
59
|
+
// Earlier releases wrote "auto"; disable still withdraws it as ours.
|
|
60
|
+
const LEGACY_TOOL_SEARCH_DEFAULTS = ["auto"];
|
|
56
61
|
// The agent traffic target (wrap, `enable <agent>`, module wiring), resolved per
|
|
57
62
|
// invocation. Signing in never moves agent traffic through a Caveman hop: the
|
|
58
63
|
// managed gateway is the target only when chosen explicitly. Precedence:
|
|
@@ -233,7 +238,7 @@ function agentTraffic() {
|
|
|
233
238
|
return { target: "local", line: "agent traffic: local runtime" };
|
|
234
239
|
}
|
|
235
240
|
// Known agents `caveman wrap` can launch by short id come from the agent-profile
|
|
236
|
-
// registry (
|
|
241
|
+
// registry (agents/profiles/*.json, compiled to agents.generated.ts). The
|
|
237
242
|
// data drives detection, the interactive picker, the install hint, and — crucially
|
|
238
243
|
// — HOW each agent is pointed at the gateway (env vs inline-config injection). So
|
|
239
244
|
// adding an agent is a new profile file, not a code change. Any other command
|
|
@@ -475,25 +480,12 @@ const LEGACY_HANDLERS = {
|
|
|
475
480
|
update: (argv) => update(argv),
|
|
476
481
|
opportunities: (argv) => argv[0] === "list" ? get("/api/v1/opportunities").then(print) : commandUsage("opportunities list"),
|
|
477
482
|
snippets,
|
|
478
|
-
|
|
479
|
-
if (argv[0] === "up")
|
|
480
|
-
return shellHint("make dev");
|
|
481
|
-
if (argv[0] === "down")
|
|
482
|
-
return shellHint("make down");
|
|
483
|
-
if (argv[0] === "reset")
|
|
484
|
-
return shellHint("make reset-local");
|
|
485
|
-
return commandUsage("dev up|down|reset");
|
|
486
|
-
},
|
|
487
|
-
deploy: (argv) => {
|
|
488
|
-
if (argv[0] === "aws")
|
|
489
|
-
return shellHint("make deploy-aws");
|
|
490
|
-
if (argv[0] === "status")
|
|
491
|
-
return get("/api/v1/system/status").then(print);
|
|
492
|
-
return commandUsage("deploy aws|status");
|
|
493
|
-
},
|
|
483
|
+
deploy: (argv) => argv[0] === "status" ? get("/api/v1/system/status").then(print) : commandUsage("deploy status"),
|
|
494
484
|
start: (argv) => start(argv),
|
|
495
485
|
wrap,
|
|
496
486
|
run: wrap,
|
|
487
|
+
// Unprinted (porcelain caps): stdio Code-Mode MCP gateway bridging existing MCP servers behind 3 meta-tools.
|
|
488
|
+
codemode: codemodeCmd,
|
|
497
489
|
status,
|
|
498
490
|
explore,
|
|
499
491
|
verify: verifyFirstRequest,
|
|
@@ -674,6 +666,10 @@ setModuleHost({
|
|
|
674
666
|
}));
|
|
675
667
|
},
|
|
676
668
|
agentAsk: (agent) => agent === "codex" && readNativeJournal("codex") && !codexHooksTrusted() ? CODEX_TRUST_ASK : undefined,
|
|
669
|
+
recoveryStoreProblem: () => {
|
|
670
|
+
const store = readRecoveryStore(true);
|
|
671
|
+
return store?.writes_refused && store.reason ? `${store.reason} — new input passes through uncompressed${store.fix ? ` · fix: ${store.fix}` : ""}` : undefined;
|
|
672
|
+
},
|
|
677
673
|
runtimeDown: async () => {
|
|
678
674
|
const wired = ["claude", "codex", "hermes", "gemini", "opencode", "pi", "aider"].filter((agent) => readNativeJournal(agent));
|
|
679
675
|
return wired.length && await agentRuntimeState() === "down" ? agentRuntimeLine("down", wired) : undefined;
|
|
@@ -817,7 +813,7 @@ const TELEMETRY_DISCLOSURE_LINE = "usage stats on — commands, agent sessions,
|
|
|
817
813
|
const TELEMETRY_TOKEN_READ_TIMEOUT_MS = Number(process.env.CAVEMAN_TELEMETRY_TOKEN_READ_TIMEOUT_MS) || 400;
|
|
818
814
|
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.";
|
|
819
815
|
const TELEMETRY_COMMAND_ALLOWLIST = [
|
|
820
|
-
"agent", "audit", "billing", "browse", "compress", "convert", "costs", "deploy", "
|
|
816
|
+
"agent", "audit", "billing", "browse", "codemode", "compress", "convert", "costs", "deploy", "doctor", "evals", "experiments",
|
|
821
817
|
"explore", "help", "hooks", "init", "keys", "learn", "login", "logout", "mcp", "mem", "opportunities", "plan",
|
|
822
818
|
"projects", "providers", "receipts", "retrieve", "score", "sdk", "setup", "shrink", "shrink-hook", "skills",
|
|
823
819
|
"run", "snippets", "start", "stats", "status", "sync", "telemetry", "toon", "traces", "trial", "unknown", "update", "usage", "verify", "version", "welcome", "whoami", "wrap",
|
|
@@ -825,9 +821,9 @@ const TELEMETRY_COMMAND_ALLOWLIST = [
|
|
|
825
821
|
];
|
|
826
822
|
const TELEMETRY_COMMANDS = new Set(TELEMETRY_COMMAND_ALLOWLIST);
|
|
827
823
|
const TELEMETRY_SUBCOMMANDS = new Set([
|
|
828
|
-
"act", "apply", "
|
|
824
|
+
"act", "apply", "charges", "create", "decode", "encode", "eval", "export", "forget", "import",
|
|
829
825
|
"catalog", "implement", "install", "link", "list", "off", "on", "recall", "recover", "refresh", "remember", "report", "reset", "revoke",
|
|
830
|
-
"run", "show", "snippet", "status", "uninstall", "unlink", "
|
|
826
|
+
"run", "show", "snippet", "status", "uninstall", "unlink", "verify",
|
|
831
827
|
]);
|
|
832
828
|
const TELEMETRY_START_MS = Date.now();
|
|
833
829
|
let telemetryCommandSent = false;
|
|
@@ -4529,22 +4525,23 @@ function capabilityInputValue(key, value) {
|
|
|
4529
4525
|
// `config get` output are unchanged; anything unrecognized returns undefined,
|
|
4530
4526
|
// which leaves the key at its previous (default "auto") value rather than
|
|
4531
4527
|
// silently inventing a surface.
|
|
4532
|
-
if (key === "execute.mcp" && (value === "auto" || value === "marker-only"))
|
|
4528
|
+
if (key === "execute.mcp" && (value === "auto" || value === "codemode" || value === "marker-only"))
|
|
4533
4529
|
return value;
|
|
4534
4530
|
return wrapBoolValue(value);
|
|
4535
4531
|
}
|
|
4536
|
-
// mcpSurfaceMode collapses the stored execute.mcp value into the
|
|
4537
|
-
//
|
|
4538
|
-
// reach it. It decides how much surface we INJECT — never what we tell the
|
|
4532
|
+
// mcpSurfaceMode collapses the stored execute.mcp value into the mode the wrap
|
|
4533
|
+
// path acts on. It decides how much surface we INJECT — never what we tell the
|
|
4539
4534
|
// proxy about recovery, which is answered from real install evidence.
|
|
4540
4535
|
function mcpSurfaceMode(value) {
|
|
4541
4536
|
if (value === false)
|
|
4542
4537
|
return "off";
|
|
4538
|
+
if (value === "codemode")
|
|
4539
|
+
return "codemode";
|
|
4543
4540
|
if (value === "marker-only")
|
|
4544
4541
|
return "marker-only";
|
|
4545
4542
|
return "auto";
|
|
4546
4543
|
}
|
|
4547
|
-
const MCP_SURFACE_VALUES = "auto | marker-only | true | false";
|
|
4544
|
+
const MCP_SURFACE_VALUES = "auto | codemode | marker-only | true | false";
|
|
4548
4545
|
function nestedCapabilityValue(doc, key) {
|
|
4549
4546
|
const [group, first, second] = key.split(".");
|
|
4550
4547
|
const block = objectValue(doc[group]);
|
|
@@ -4552,11 +4549,22 @@ function nestedCapabilityValue(doc, key) {
|
|
|
4552
4549
|
return block[first];
|
|
4553
4550
|
return objectValue(block[first])[second];
|
|
4554
4551
|
}
|
|
4552
|
+
// proxyYamlMode reads the proxy's own TOP-LEVEL `mode:` out of caveman.yaml.
|
|
4553
|
+
// The pattern is anchored at column 0 on purpose (#1457). `^\s*mode\s*:` with
|
|
4554
|
+
// /m matched the key at ANY indentation, and caveman.yaml legitimately carries
|
|
4555
|
+
// a second, nested one — `middleware.mode`, the documented "proxy records while
|
|
4556
|
+
// the middleware compresses" shape — so the nested value was read as the
|
|
4557
|
+
// proxy's. The proxy itself resolves keys by name (yaml.v3), which made the two
|
|
4558
|
+
// disagree about one file in both directions: a nested-only mode was adopted as
|
|
4559
|
+
// the proxy's, and a nested key written ABOVE a real top-level one won on
|
|
4560
|
+
// textual order, which also surfaced as a `caveman status` mode mismatch that
|
|
4561
|
+
// was not real. yamlScopedBaseUrl() below tracks indentation deliberately and
|
|
4562
|
+
// is unaffected; this key is top-level or it is not ours to read.
|
|
4555
4563
|
function proxyYamlMode() {
|
|
4556
4564
|
const path = process.env.CAVEMAN_CONFIG ?? join(cavemanHome(), "caveman.yaml");
|
|
4557
4565
|
try {
|
|
4558
4566
|
const raw = readFileSync(path, "utf8");
|
|
4559
|
-
const match = raw.match(
|
|
4567
|
+
const match = raw.match(/^mode[ \t]*:[ \t]*["']?([^#\s"']+)/m);
|
|
4560
4568
|
return match?.[1];
|
|
4561
4569
|
}
|
|
4562
4570
|
catch {
|
|
@@ -4838,6 +4846,7 @@ function defaultWrapOptions() {
|
|
|
4838
4846
|
delegate: cfg.delegate,
|
|
4839
4847
|
minimal: false,
|
|
4840
4848
|
autoRecall: cfg.autoRecall,
|
|
4849
|
+
codemode: cfg.mcp === "codemode",
|
|
4841
4850
|
command: [],
|
|
4842
4851
|
};
|
|
4843
4852
|
if (cfg.pixelModels !== undefined)
|
|
@@ -4952,6 +4961,14 @@ export const OFF_STATES = {
|
|
|
4952
4961
|
},
|
|
4953
4962
|
// The proxy's cache tripwire: the client re-sent bytes the provider had
|
|
4954
4963
|
// cached and caveman forwarded them differently. Never expected; a bug.
|
|
4964
|
+
// The recovery store (ccr.db) refuses new recoveries: it is damaged, or full
|
|
4965
|
+
// with nothing old enough to expire. Every lossy compression needs one, so
|
|
4966
|
+
// inputs pass through uncompressed until the fix (#1369, #1370).
|
|
4967
|
+
recoveryStore: (reason, fix) => ({
|
|
4968
|
+
id: "recovery-store",
|
|
4969
|
+
line: `${reason} — new input passes through uncompressed`,
|
|
4970
|
+
...(fix ? { fix } : {}),
|
|
4971
|
+
}),
|
|
4955
4972
|
cavemanCacheBust: (count) => ({
|
|
4956
4973
|
id: "cache-bust",
|
|
4957
4974
|
line: `caveman changed bytes the provider had already cached on ${count} request${count === 1 ? "" : "s"} today — those turns paid to re-cache their prompt; this is a caveman bug`,
|
|
@@ -4964,6 +4981,7 @@ const OFF_STATE_PRECEDENCE = [
|
|
|
4964
4981
|
"running-mode-mismatch",
|
|
4965
4982
|
"invalid-mode",
|
|
4966
4983
|
"user-record",
|
|
4984
|
+
"recovery-store",
|
|
4967
4985
|
"mcp-missing",
|
|
4968
4986
|
"mem-missing",
|
|
4969
4987
|
"zdr",
|
|
@@ -5559,6 +5577,36 @@ function readProxyObserveSummary(sinceISO) {
|
|
|
5559
5577
|
return null;
|
|
5560
5578
|
}
|
|
5561
5579
|
}
|
|
5580
|
+
function readRecoveryStore(check) {
|
|
5581
|
+
if (!probeProxyVersion()?.capabilities.includes("recovery_store_v1"))
|
|
5582
|
+
return undefined;
|
|
5583
|
+
const bin = cavemanBin("caveman-proxy", "CAVEMAN_PROXY_BIN");
|
|
5584
|
+
let out;
|
|
5585
|
+
try {
|
|
5586
|
+
out = execFileSync(bin, ["recovery-store", check ? "check" : "status"], {
|
|
5587
|
+
encoding: "utf8",
|
|
5588
|
+
env: process.env,
|
|
5589
|
+
timeout: check ? 120_000 : 10_000,
|
|
5590
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
5591
|
+
});
|
|
5592
|
+
}
|
|
5593
|
+
catch (error) {
|
|
5594
|
+
out = String(error.stdout ?? "");
|
|
5595
|
+
}
|
|
5596
|
+
try {
|
|
5597
|
+
const parsed = JSON.parse(out);
|
|
5598
|
+
if (parsed?.schema !== "caveman.recovery_store.v1")
|
|
5599
|
+
return undefined;
|
|
5600
|
+
// The fix names the subcommand; spell out the binary, which is not on PATH.
|
|
5601
|
+
const shown = /[^\w@%+=:,./\\-]/.test(bin) ? quoteHookPath(bin) : bin;
|
|
5602
|
+
if (parsed.fix)
|
|
5603
|
+
parsed.fix = parsed.fix.replace("caveman-proxy recovery-store", `${shown} recovery-store`);
|
|
5604
|
+
return parsed;
|
|
5605
|
+
}
|
|
5606
|
+
catch {
|
|
5607
|
+
return undefined;
|
|
5608
|
+
}
|
|
5609
|
+
}
|
|
5562
5610
|
// PROXY_RECENT_ROW_CAP mirrors the store's hard cap on `stats --recent N`: asking
|
|
5563
5611
|
// for more rows than this silently returns this many, so a full page back is
|
|
5564
5612
|
// indistinguishable from a truncated window.
|
|
@@ -5743,6 +5791,45 @@ function printSessionSavings(kind, sinceISO, agentId) {
|
|
|
5743
5791
|
// compression-first: it starts the standalone proxy in `compress` mode unless
|
|
5744
5792
|
// config/env or --off selects record mode. Known agents (claude, codex, …) are launchable by short id
|
|
5745
5793
|
// and get detected; any other command still runs verbatim.
|
|
5794
|
+
async function codemodeCmd(rest) {
|
|
5795
|
+
const probed = probeMcpBinary();
|
|
5796
|
+
if (!probed) {
|
|
5797
|
+
console.error("caveman codemode: caveman-mcp binary not found. Run `caveman setup --install` first.");
|
|
5798
|
+
process.exit(1);
|
|
5799
|
+
}
|
|
5800
|
+
if (!probed.probe.current || !probed.probe.capabilities.includes("codemode")) {
|
|
5801
|
+
console.error(`caveman codemode: caveman-mcp (${probed.probe.version || "unknown"}) lacks Code Mode support. Run \`caveman setup --install\` to upgrade.`);
|
|
5802
|
+
process.exit(1);
|
|
5803
|
+
}
|
|
5804
|
+
const toolsOnlyIdx = rest.indexOf("--tools-only");
|
|
5805
|
+
const subArgs = toolsOnlyIdx >= 0
|
|
5806
|
+
? ["tools", ...rest.filter((_, idx) => idx !== toolsOnlyIdx)]
|
|
5807
|
+
: ["codemode", ...rest];
|
|
5808
|
+
const invocation = portableInvocation(probed.binary, subArgs);
|
|
5809
|
+
const res = spawnSync(invocation.command, invocation.args, {
|
|
5810
|
+
stdio: "inherit",
|
|
5811
|
+
windowsHide: true,
|
|
5812
|
+
});
|
|
5813
|
+
if (res.error) {
|
|
5814
|
+
console.error(`caveman codemode: failed to run ${probed.binary}: ${res.error.message}`);
|
|
5815
|
+
process.exit(127);
|
|
5816
|
+
}
|
|
5817
|
+
process.exitCode = res.status ?? (res.signal ? signalExitCode(res.signal) : 1);
|
|
5818
|
+
}
|
|
5819
|
+
const HERMES_NON_CHAT_SUBCOMMANDS = new Set([
|
|
5820
|
+
"status", "model", "mcp", "config", "cron", "profile", "plugins", "skills",
|
|
5821
|
+
"sessions", "version", "doctor", "setup", "login", "logout", "gateway", "acp",
|
|
5822
|
+
"insights", "memory", "tools", "update", "uninstall", "security", "backup", "restore",
|
|
5823
|
+
]);
|
|
5824
|
+
function hermesNeedsCustomProviderArgs(userArgs) {
|
|
5825
|
+
if (userArgs.length === 0)
|
|
5826
|
+
return true;
|
|
5827
|
+
if (HERMES_NON_CHAT_SUBCOMMANDS.has(userArgs[0]))
|
|
5828
|
+
return false;
|
|
5829
|
+
if (userArgs.some((a) => a === "--help" || a === "-h" || a === "--version" || a === "-V"))
|
|
5830
|
+
return false;
|
|
5831
|
+
return true;
|
|
5832
|
+
}
|
|
5746
5833
|
async function wrap(rest) {
|
|
5747
5834
|
pendingRunOffStates.length = 0;
|
|
5748
5835
|
const parsed = parseWrapArgs(rest);
|
|
@@ -5762,7 +5849,12 @@ async function wrap(rest) {
|
|
|
5762
5849
|
const requested = rest[0];
|
|
5763
5850
|
const agent = findAgent(requested);
|
|
5764
5851
|
const bin = agent ? binOf(agent) : requested;
|
|
5765
|
-
const
|
|
5852
|
+
const userArgs = rest.slice(1);
|
|
5853
|
+
const extra = agent
|
|
5854
|
+
? agent.id === "hermes" && !hermesNeedsCustomProviderArgs(userArgs)
|
|
5855
|
+
? userArgs
|
|
5856
|
+
: [...agent.args, ...userArgs]
|
|
5857
|
+
: userArgs;
|
|
5766
5858
|
const resolved = which(bin);
|
|
5767
5859
|
if (!resolved) {
|
|
5768
5860
|
wrapNotFoundUI(requested, agent);
|
|
@@ -6140,6 +6232,36 @@ function parseWrapArgs(rest) {
|
|
|
6140
6232
|
cmd.shift();
|
|
6141
6233
|
continue;
|
|
6142
6234
|
}
|
|
6235
|
+
if (a === "--codemode") {
|
|
6236
|
+
out.codemode = true;
|
|
6237
|
+
cmd.shift();
|
|
6238
|
+
continue;
|
|
6239
|
+
}
|
|
6240
|
+
if (a === "--trust-workspace-mcp") {
|
|
6241
|
+
out.trustWorkspaceMcp = true;
|
|
6242
|
+
cmd.shift();
|
|
6243
|
+
continue;
|
|
6244
|
+
}
|
|
6245
|
+
if (a === "--shrink-tools") {
|
|
6246
|
+
out.shrinkTools = true;
|
|
6247
|
+
cmd.shift();
|
|
6248
|
+
continue;
|
|
6249
|
+
}
|
|
6250
|
+
if (a === "--defer-mcp-tools") {
|
|
6251
|
+
out.deferMcpTools = true;
|
|
6252
|
+
cmd.shift();
|
|
6253
|
+
continue;
|
|
6254
|
+
}
|
|
6255
|
+
if (a === "--canonical-tools") {
|
|
6256
|
+
out.canonicalTools = true;
|
|
6257
|
+
cmd.shift();
|
|
6258
|
+
continue;
|
|
6259
|
+
}
|
|
6260
|
+
if (a === "--turn-effort") {
|
|
6261
|
+
out.turnEffort = true;
|
|
6262
|
+
cmd.shift();
|
|
6263
|
+
continue;
|
|
6264
|
+
}
|
|
6143
6265
|
if (deletedFlags.has(a ?? "")) {
|
|
6144
6266
|
console.error(`caveman wrap: ${a} moved to capability config — inspect with \`${invokedAs()} tools config get\``);
|
|
6145
6267
|
process.exit(2);
|
|
@@ -6172,11 +6294,16 @@ function wrapUsage(stream = "stderr") {
|
|
|
6172
6294
|
else
|
|
6173
6295
|
console.error(line);
|
|
6174
6296
|
};
|
|
6175
|
-
write(`usage: ${invokedCommand("wrap")} [--off|--pixel] [--workflow <slug>] <agent> [args...]`);
|
|
6176
|
-
write(" (default)
|
|
6177
|
-
write(" --off
|
|
6178
|
-
write(" --pixel
|
|
6179
|
-
write(" --
|
|
6297
|
+
write(`usage: ${invokedCommand("wrap")} [--off|--pixel] [--codemode] [--shrink-tools] [--defer-mcp-tools] [--canonical-tools] [--turn-effort] [--workflow <slug>] <agent> [args...]`);
|
|
6298
|
+
write(" (default) ephemeral stack: S4 compression + TOON best-of + recovery/output shrink where host supports a temp pack");
|
|
6299
|
+
write(" --off byte-safe pass-through metering only — nothing is rewritten");
|
|
6300
|
+
write(" --pixel lossy text→PNG pixel mode (model-gated); originals recoverable via caveman_retrieve");
|
|
6301
|
+
write(" --codemode opt-in QuickJS Code-Mode MCP gateway (4 read/write-split meta-tools + CCR recovery + repo/pr/browse); Claude Code, Codex, OpenCode & Hermes also ship native codemodes");
|
|
6302
|
+
write(" --shrink-tools opt-in caveman-shrink compression on tools[] schemas in the local proxy");
|
|
6303
|
+
write(" --defer-mcp-tools opt-in provider-native defer_loading on non-core MCP tools (Anthropic + OpenAI Responses)");
|
|
6304
|
+
write(" --canonical-tools opt-in deterministic tools[] sorting so MCP reconnect shuffles never bust the prompt cache");
|
|
6305
|
+
write(" --turn-effort opt-in cache-safe per-message reasoning effort stepping (Claude 5+/Opus 5.5 marks & GPT-6 configuration_update; 0 cache bust)");
|
|
6306
|
+
write(" --workflow label this session's traffic (x-cave-workflow) so it groups by name in the dashboard");
|
|
6180
6307
|
write(`Capability groups: think / remember / execute — inspect with \`${invokedAs()} tools config get\`.`);
|
|
6181
6308
|
write("Auth passes through untouched: API keys AND subscription OAuth logins (Claude Pro/Max) both work.");
|
|
6182
6309
|
write("Subscription logins compress locally too, no account needed (live zone only — compressed turns are re-sent byte-identically so the provider cache stays warm;");
|
|
@@ -6190,7 +6317,7 @@ function normalizeAgentShortcutWrapArgs(input) {
|
|
|
6190
6317
|
const agentArgs = [];
|
|
6191
6318
|
for (let i = 1; i < input.length; i++) {
|
|
6192
6319
|
const item = input[i];
|
|
6193
|
-
if (item === "--off" || item === "--pixel") {
|
|
6320
|
+
if (item === "--off" || item === "--pixel" || item === "--codemode" || item === "--trust-workspace-mcp" || item === "--shrink-tools" || item === "--defer-mcp-tools" || item === "--canonical-tools" || item === "--turn-effort") {
|
|
6194
6321
|
wrapFlags.push(item);
|
|
6195
6322
|
continue;
|
|
6196
6323
|
}
|
|
@@ -6238,7 +6365,8 @@ async function agentShortcut(rest) {
|
|
|
6238
6365
|
process.exitCode = 127;
|
|
6239
6366
|
return;
|
|
6240
6367
|
}
|
|
6241
|
-
const
|
|
6368
|
+
const helpArgs = agent.id === "hermes" ? rest.slice(1) : [...agent.args, ...rest.slice(1)];
|
|
6369
|
+
const invocation = portableInvocation(bin, helpArgs);
|
|
6242
6370
|
const result = spawnSync(invocation.command, invocation.args, { stdio: "inherit" });
|
|
6243
6371
|
if (result.error)
|
|
6244
6372
|
throw new Error(`failed to exec ${bin}: ${result.error.message}`);
|
|
@@ -6342,7 +6470,11 @@ async function agentShortcut(rest) {
|
|
|
6342
6470
|
maybeWarnHermesMissingKey(agent, gatewayURL());
|
|
6343
6471
|
const stopProxyKeepalive = startProxyKeepalive();
|
|
6344
6472
|
const code = await new Promise((resolve, reject) => {
|
|
6345
|
-
|
|
6473
|
+
// Native Hermes installs already own model.provider/base_url in config.yaml
|
|
6474
|
+
// (including openai-codex OAuth on /chatgpt); prepending `--provider custom`
|
|
6475
|
+
// would override that OAuth provider and break Hermes subcommands.
|
|
6476
|
+
const launchArgs = native === "hermes" ? rest.slice(1) : [...agent.args, ...rest.slice(1)];
|
|
6477
|
+
const invocation = portableInvocation(bin, launchArgs);
|
|
6346
6478
|
let child;
|
|
6347
6479
|
try {
|
|
6348
6480
|
child = spawn(invocation.command, invocation.args, { stdio: "inherit" });
|
|
@@ -6524,14 +6656,42 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscriptionOver
|
|
|
6524
6656
|
// detail itself — i.e. it has the caveman MCP retrieve tool installed (run
|
|
6525
6657
|
// `caveman mcp install <agent>`). When it does, signal the proxy to use MCP
|
|
6526
6658
|
// recovery (which lets it compress streams); otherwise streams pass through.
|
|
6527
|
-
const
|
|
6528
|
-
|
|
6659
|
+
const codemodeSupportedAgents = new Set(["claude", "codex", "gemini", "qwen", "opencode", "openclaw", "kilo", "hermes", "pi"]);
|
|
6660
|
+
const codemodeRequested = Boolean(!direct && opts.codemode && agent && codemodeSupportedAgents.has(agent.id));
|
|
6661
|
+
const ephemeralMcp = !direct && agent && (agent.id === "claude" || agent.id === "codex" || codemodeRequested)
|
|
6662
|
+
&& !opts.minimal && (opts.mcpMode === "auto" || opts.mcpMode === "codemode" || opts.codemode) && wrapRecoveryEligible(opts)
|
|
6529
6663
|
? probeMcpBinary()
|
|
6530
6664
|
: null;
|
|
6531
6665
|
if (ephemeralMcp && !ephemeralMcp.probe.current)
|
|
6532
6666
|
queueStaleMcpBinary(ephemeralMcp.probe);
|
|
6533
6667
|
const ephemeralMcpBinary = ephemeralMcp?.probe.current ? ephemeralMcp.binary : undefined;
|
|
6534
|
-
|
|
6668
|
+
let codemodeLaunch;
|
|
6669
|
+
let codemodeVerifiedRecovery = false;
|
|
6670
|
+
if (codemodeRequested) {
|
|
6671
|
+
if (ephemeralMcp) {
|
|
6672
|
+
if (ephemeralMcp.probe.current && ephemeralMcp.probe.capabilities.includes("codemode")) {
|
|
6673
|
+
codemodeLaunch = mcpServerLaunch(ephemeralMcp.binary, []);
|
|
6674
|
+
// Kilo and Qwen can apply policy after user-owned config; they prove
|
|
6675
|
+
// recovery in band rather than via a proxy-wide recovery assertion.
|
|
6676
|
+
codemodeVerifiedRecovery = agent.id !== "kilo" && agent.id !== "qwen";
|
|
6677
|
+
}
|
|
6678
|
+
else {
|
|
6679
|
+
queueStaleMcpBinary(ephemeralMcp.probe);
|
|
6680
|
+
process.stderr.write(`${mark("warn")} caveman-mcp (${ephemeralMcp.probe.version}) lacks Code Mode support; run \`caveman setup --install\` — launching without --codemode\n`);
|
|
6681
|
+
}
|
|
6682
|
+
}
|
|
6683
|
+
else {
|
|
6684
|
+
process.stderr.write(`${mark("warn")} caveman-mcp not found; run \`caveman setup --install\` — launching without --codemode\n`);
|
|
6685
|
+
}
|
|
6686
|
+
}
|
|
6687
|
+
const codemodeEnabled = Boolean(codemodeRequested && codemodeLaunch);
|
|
6688
|
+
const trustWorkspaceMcp = Boolean(opts.trustWorkspaceMcp || process.env.CAVEMAN_TRUST_WORKSPACE_MCP === "1");
|
|
6689
|
+
const codemodeServers = codemodeEnabled
|
|
6690
|
+
? discoverCodemodeServers(process.cwd(), homedir(), process.env, trustWorkspaceMcp)
|
|
6691
|
+
: {};
|
|
6692
|
+
const mcpRecovery = !direct && (Boolean(ephemeralMcpBinary && (agent?.id === "claude" || agent?.id === "codex"))
|
|
6693
|
+
|| codemodeVerifiedRecovery
|
|
6694
|
+
|| wrapMcpRecoveryAvailable(agent, opts, cmdArgs));
|
|
6535
6695
|
const delegateAlreadyInstalled = Boolean(!direct && agent && mcpServerInstalled(agent.id, "caveman-delegate"));
|
|
6536
6696
|
const ephemeralDelegateMcp = !direct && agent && (agent.id === "claude" || agent.id === "codex")
|
|
6537
6697
|
&& !opts.minimal && opts.delegate && !delegateAlreadyInstalled
|
|
@@ -6568,7 +6728,33 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscriptionOver
|
|
|
6568
6728
|
: null;
|
|
6569
6729
|
}
|
|
6570
6730
|
}
|
|
6731
|
+
if (proxyReady && !direct) {
|
|
6732
|
+
const startOnlyFlags = [];
|
|
6733
|
+
if (opts.shrinkTools)
|
|
6734
|
+
startOnlyFlags.push("--shrink-tools");
|
|
6735
|
+
if (opts.deferMcpTools)
|
|
6736
|
+
startOnlyFlags.push("--defer-mcp-tools");
|
|
6737
|
+
if (opts.canonicalTools)
|
|
6738
|
+
startOnlyFlags.push("--canonical-tools");
|
|
6739
|
+
if (opts.turnEffort)
|
|
6740
|
+
startOnlyFlags.push("--turn-effort");
|
|
6741
|
+
if (startOnlyFlags.length > 0) {
|
|
6742
|
+
process.stderr.write(`${mark("warn")} Caveman proxy is already running on ${host}:${port}; ${startOnlyFlags.join(", ")} only take effect when starting the proxy (run \`caveman stop\` first to restart with those flags)\n`);
|
|
6743
|
+
}
|
|
6744
|
+
}
|
|
6571
6745
|
if (!proxyReady && !direct) {
|
|
6746
|
+
if (opts.shrinkTools && !process.env.CAVEMAN_TOOLSCHEMA_STRIP) {
|
|
6747
|
+
process.env.CAVEMAN_TOOLSCHEMA_STRIP = "shrink";
|
|
6748
|
+
}
|
|
6749
|
+
if (opts.deferMcpTools && !process.env.CAVEMAN_DEFER_MCP_TOOLS) {
|
|
6750
|
+
process.env.CAVEMAN_DEFER_MCP_TOOLS = "1";
|
|
6751
|
+
}
|
|
6752
|
+
if (opts.canonicalTools && !process.env.CAVEMAN_CANONICAL_TOOLS) {
|
|
6753
|
+
process.env.CAVEMAN_CANONICAL_TOOLS = "1";
|
|
6754
|
+
}
|
|
6755
|
+
if (opts.turnEffort && !process.env.CAVEMAN_TURN_EFFORT) {
|
|
6756
|
+
process.env.CAVEMAN_TURN_EFFORT = "1";
|
|
6757
|
+
}
|
|
6572
6758
|
if (local && !opts.noProxy) {
|
|
6573
6759
|
proxyStarted = codexSubscription
|
|
6574
6760
|
? await startWrapProxy(effectiveMode, desiredRecoveryViaMCP, false, undefined, undefined, gw, "codex-subscription", observeEstimate)
|
|
@@ -6716,14 +6902,73 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscriptionOver
|
|
|
6716
6902
|
env = direct
|
|
6717
6903
|
? { ...process.env }
|
|
6718
6904
|
: agent?.id === "codex"
|
|
6719
|
-
? buildCodexEphemeralWrapEnv(gw, codexSubscription, ephemeralMcpBinary, ephemeralDelegateMcp)
|
|
6905
|
+
? buildCodexEphemeralWrapEnv(gw, codexSubscription, ephemeralMcpBinary, ephemeralDelegateMcp, codemodeEnabled && codemodeLaunch ? { launch: codemodeLaunch, servers: codemodeServers, workspace: process.cwd() } : null)
|
|
6720
6906
|
: buildWrapEnv(agent, gw, opts.mcpMode, cmdArgs, runtime.owner === "unknown" ? undefined : runtime);
|
|
6721
6907
|
if (!direct && agent?.id === "claude") {
|
|
6722
|
-
const
|
|
6723
|
-
|
|
6908
|
+
const codemodeSpec = codemodeEnabled && codemodeLaunch ? { launch: codemodeLaunch, servers: codemodeServers, workspace: process.cwd() } : null;
|
|
6909
|
+
const pluginDir = buildClaudeEphemeralPlugin(ephemeralMcpBinary, includeShrink, Boolean(opts.autoRecall), ephemeralDelegateMcp, codemodeSpec);
|
|
6910
|
+
if (codemodeSpec) {
|
|
6911
|
+
// Strict MCP config isolates Claude to the 3 Code-Mode meta-tools while
|
|
6912
|
+
// caveman-mcp codemode bridges all discovered MCP servers behind them.
|
|
6913
|
+
childArgs = ["--plugin-dir", pluginDir, "--strict-mcp-config", "--mcp-config", join(pluginDir, ".mcp.json"), ...cmdArgs];
|
|
6914
|
+
}
|
|
6915
|
+
else {
|
|
6916
|
+
childArgs = ["--plugin-dir", pluginDir, ...cmdArgs];
|
|
6917
|
+
}
|
|
6724
6918
|
}
|
|
6725
|
-
if (!direct &&
|
|
6919
|
+
if (!direct && codemodeEnabled) {
|
|
6920
|
+
const bridgedCount = Object.keys(codemodeServers).length;
|
|
6921
|
+
const nativeNote = agent && NATIVE_CODEMODE_AGENTS.has(agent.id)
|
|
6922
|
+
? ` (opt-in alongside ${agent.display_name}'s native codemode)`
|
|
6923
|
+
: "";
|
|
6924
|
+
process.stderr.write(dim(`→ codemode active (${agent?.id}) · QuickJS sandbox bridging ${bridgedCount} MCP server${bridgedCount === 1 ? "" : "s"} + built-ins (repo, pr, browse) behind 4 read/write-split meta-tools + CCR recovery${nativeNote}\n`));
|
|
6925
|
+
}
|
|
6926
|
+
if (!direct && agent?.id === "pi") {
|
|
6726
6927
|
childArgs = buildPiWrapArgs(cmdArgs, env, gw);
|
|
6928
|
+
if (codemodeEnabled && codemodeLaunch) {
|
|
6929
|
+
const cmDir = mkdtempSync(join(tmpdir(), "caveman-wrap-pi-cm-"));
|
|
6930
|
+
wrapTempDirs.add(cmDir);
|
|
6931
|
+
env.CAVEMAN_PI_CODEMODE = "1";
|
|
6932
|
+
env.CAVEMAN_PI_CODEMODE_CONFIG = writeEphemeralCodemodeConfig(cmDir, codemodeServers);
|
|
6933
|
+
env.CAVEMAN_PI_CODEMODE_WORKSPACE = process.cwd();
|
|
6934
|
+
if (!env.CAVEMAN_MCP_BIN) {
|
|
6935
|
+
env.CAVEMAN_MCP_BIN = codemodeLaunch.command;
|
|
6936
|
+
if (codemodeLaunch.args.length > 0 && !env.CAVEMAN_MCP_PREFIX_ARGS) {
|
|
6937
|
+
env.CAVEMAN_MCP_PREFIX_ARGS = JSON.stringify(codemodeLaunch.args);
|
|
6938
|
+
}
|
|
6939
|
+
}
|
|
6940
|
+
}
|
|
6941
|
+
}
|
|
6942
|
+
if (!direct && codemodeEnabled && codemodeLaunch && agent && agent.id !== "claude" && agent.id !== "codex" && agent.id !== "pi") {
|
|
6943
|
+
const cmDir = mkdtempSync(join(tmpdir(), `caveman-wrap-${agent.id}-cm-`));
|
|
6944
|
+
wrapTempDirs.add(cmDir);
|
|
6945
|
+
const cfgPath = writeEphemeralCodemodeConfig(cmDir, codemodeServers);
|
|
6946
|
+
const cmEntry = {
|
|
6947
|
+
command: codemodeLaunch.command,
|
|
6948
|
+
args: [...codemodeLaunch.args, "codemode", "--config", cfgPath, "--workspace", process.cwd()],
|
|
6949
|
+
};
|
|
6950
|
+
if (agent.id === "gemini") {
|
|
6951
|
+
env.GEMINI_CLI_SYSTEM_SETTINGS_PATH = writeGeminiCodemodeSettingsOverlay(cmDir, process.env.GEMINI_CLI_SYSTEM_SETTINGS_PATH ?? "", cmEntry);
|
|
6952
|
+
}
|
|
6953
|
+
else if (agent.id === "qwen" && env.QWEN_CODE_SYSTEM_SETTINGS_PATH) {
|
|
6954
|
+
patchEphemeralQwenCodemode(env.QWEN_CODE_SYSTEM_SETTINGS_PATH, cmEntry);
|
|
6955
|
+
env.QWEN_CODE_LEGACY_MCP_BLOCKING = "1";
|
|
6956
|
+
}
|
|
6957
|
+
else if (agent.id === "opencode") {
|
|
6958
|
+
env.OPENCODE_CONFIG_CONTENT = applyOpenCodeCodemodeOverlay(env.OPENCODE_CONFIG_CONTENT, discoverOpenCodeOwnServerNames(process.cwd(), homedir(), process.env, trustWorkspaceMcp), cmEntry);
|
|
6959
|
+
}
|
|
6960
|
+
else if (agent.id === "kilo") {
|
|
6961
|
+
env.KILO_CONFIG_CONTENT = applyKiloCodemodeOverlay(env.KILO_CONFIG_CONTENT, cmEntry, discoverKiloOwnServerNames(process.cwd(), homedir(), process.env, trustWorkspaceMcp));
|
|
6962
|
+
}
|
|
6963
|
+
else if (agent.id === "openclaw" && env.OPENCLAW_CONFIG_PATH) {
|
|
6964
|
+
patchEphemeralOpenClawCodemode(env.OPENCLAW_CONFIG_PATH, cmEntry);
|
|
6965
|
+
}
|
|
6966
|
+
else if (agent.id === "hermes") {
|
|
6967
|
+
const srcHermesHome = hermesHome();
|
|
6968
|
+
hermesEphemeralSyncPairs.set(cmDir, srcHermesHome);
|
|
6969
|
+
env.HERMES_HOME = buildHermesEphemeralCodemodeHome(srcHermesHome, cmDir, cmEntry);
|
|
6970
|
+
}
|
|
6971
|
+
}
|
|
6727
6972
|
if (!direct && agent?.id === "aider")
|
|
6728
6973
|
childArgs = routedAiderArgs(cmdArgs);
|
|
6729
6974
|
}
|
|
@@ -6744,6 +6989,8 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscriptionOver
|
|
|
6744
6989
|
Object.assign(env, claudeCaveBuildEnv());
|
|
6745
6990
|
if (!direct)
|
|
6746
6991
|
maybeWarnHermesMissingKey(agent, gw);
|
|
6992
|
+
if (!direct)
|
|
6993
|
+
maybeWarnGeminiHeadlessAuth(agent, childArgs);
|
|
6747
6994
|
if (direct) {
|
|
6748
6995
|
// buildWrapEnv writes the agent-attributed `${gw}/w/<agent>` form, and an
|
|
6749
6996
|
// outer routed wrap may leak the bare form; a direct launch strips both.
|
|
@@ -6880,6 +7127,43 @@ function firstEnvSecret(env, keys) {
|
|
|
6880
7127
|
}
|
|
6881
7128
|
return undefined;
|
|
6882
7129
|
}
|
|
7130
|
+
// Wrap writes no user config, so where Gemini would reject the `gateway` auth
|
|
7131
|
+
// type our route makes it pick (see geminiEnvSelectsAuth), a headless launch
|
|
7132
|
+
// names the fix instead. Headless mirrors Gemini's isHeadlessMode.
|
|
7133
|
+
// ponytail: a positional query and system-level settings files are not read;
|
|
7134
|
+
// a miss only means Gemini's own error shows without this line.
|
|
7135
|
+
function maybeWarnGeminiHeadlessAuth(agent, args) {
|
|
7136
|
+
if (agent?.id !== "gemini")
|
|
7137
|
+
return;
|
|
7138
|
+
const flag = (names) => args.some((arg) => names.some((name) => arg === name || arg.startsWith(`${name}=`)));
|
|
7139
|
+
// Interactive and ACP sessions pick auth their own way; subcommands and
|
|
7140
|
+
// version/help never authenticate.
|
|
7141
|
+
if (flag(["-i", "--prompt-interactive", "--acp", "--experimental-acp", "-v", "--version", "-h", "--help"]))
|
|
7142
|
+
return;
|
|
7143
|
+
if (["mcp", "extensions", "skills", "hooks"].includes(args[0] ?? ""))
|
|
7144
|
+
return;
|
|
7145
|
+
const headless = process.env.CI === "true" || process.env.GITHUB_ACTIONS === "true"
|
|
7146
|
+
|| !process.stdin.isTTY || !process.stdout.isTTY || flag(["-p", "--prompt"]);
|
|
7147
|
+
if (!headless)
|
|
7148
|
+
return;
|
|
7149
|
+
for (const file of [geminiSettingsPath(), join(process.cwd(), ".gemini", "settings.json")]) {
|
|
7150
|
+
try {
|
|
7151
|
+
if (getObject(readJson5Lenient(file), ["security", "auth"])?.selectedType)
|
|
7152
|
+
return;
|
|
7153
|
+
}
|
|
7154
|
+
catch {
|
|
7155
|
+
// Missing or unreadable: no auth type chosen there.
|
|
7156
|
+
}
|
|
7157
|
+
}
|
|
7158
|
+
let dotenv = "";
|
|
7159
|
+
try {
|
|
7160
|
+
dotenv = readFileSync(join(geminiConfigDir(), ".env"), "utf8");
|
|
7161
|
+
}
|
|
7162
|
+
catch { /* no global .env */ }
|
|
7163
|
+
if (geminiEnvSelectsAuth(dotenv))
|
|
7164
|
+
return;
|
|
7165
|
+
process.stderr.write(`caveman: headless Gemini CLI needs an auth type of your own or it exits "Invalid auth method selected."; add "security": {"auth": {"selectedType": "${GEMINI_PINNED_AUTH}"}} to ${geminiSettingsPath()}\n`);
|
|
7166
|
+
}
|
|
6883
7167
|
function maybeWarnHermesMissingKey(agent, gw = gatewayURL()) {
|
|
6884
7168
|
if (agent?.id !== "hermes")
|
|
6885
7169
|
return;
|
|
@@ -6928,6 +7212,11 @@ function hermesHostDerivedApiKeyEnvName(gw) {
|
|
|
6928
7212
|
}
|
|
6929
7213
|
function applyHermesAuthEnv(env, gw, modeGw = gw) {
|
|
6930
7214
|
delete env.CUSTOM_API_KEY;
|
|
7215
|
+
// Hermes OpenAI-compatible auxiliary clients (summary/compression/vision)
|
|
7216
|
+
// append /chat/completions to OPENAI_BASE_URL / OPENAI_API_BASE and expect /v1.
|
|
7217
|
+
const v1Base = appendUrlPath(gw, "/v1");
|
|
7218
|
+
env.OPENAI_BASE_URL = v1Base;
|
|
7219
|
+
env.OPENAI_API_BASE = v1Base;
|
|
6931
7220
|
if (wrapMode(modeGw) !== "managed")
|
|
6932
7221
|
return;
|
|
6933
7222
|
const key = firstEnvSecret(env, ["CAVE_API_KEY"]) ?? connectedGatewayAPIKey();
|
|
@@ -7694,6 +7983,34 @@ export function hookExecutableInvocation(executable, script, platform = process.
|
|
|
7694
7983
|
// required invocation operator. POSIX hook commands keep their exact shape.
|
|
7695
7984
|
return platform === "win32" && powershell ? `& ${invocation}` : invocation;
|
|
7696
7985
|
}
|
|
7986
|
+
// hostShellInvocation renders the same invocation for a command string we hand
|
|
7987
|
+
// BACK to the host for the host's own shell to run — a `shrink` rewrite, not a
|
|
7988
|
+
// hook the host dispatches itself. That shell differs per host on Windows: Git
|
|
7989
|
+
// Bash under Claude Code, PowerShell under the opencode plugin, cmd.exe under
|
|
7990
|
+
// Gemini CLI, and the three share no quoting syntax. A quoted path is only a
|
|
7991
|
+
// string literal in PowerShell, so the quoted prefix died with
|
|
7992
|
+
// `ParserError: Unexpected token 'shrink'` before the command ran (#1263);
|
|
7993
|
+
// single quotes are literal characters in cmd.exe; and the `&` call operator
|
|
7994
|
+
// PowerShell needs is a syntax error in bash. An unquoted, forward-slashed path
|
|
7995
|
+
// is the one form all three execute, so emit that when every component allows
|
|
7996
|
+
// it and return null when one does not — a path with a space has no portable
|
|
7997
|
+
// form at all, and the caller then declines the rewrite, which leaves the
|
|
7998
|
+
// command running exactly as the host sent it. POSIX hosts all run an sh-family
|
|
7999
|
+
// shell, where the quoted form is both correct and space-safe: unchanged there.
|
|
8000
|
+
const BARE_HOST_SHELL_PATH = /^[A-Za-z0-9_:./-]+$/;
|
|
8001
|
+
export function hostShellInvocation(executable, script, platform = process.platform) {
|
|
8002
|
+
const parts = script ? [executable, script] : [executable];
|
|
8003
|
+
if (platform !== "win32")
|
|
8004
|
+
return parts.map((part) => quoteHookPath(part, platform)).join(" ");
|
|
8005
|
+
const bare = [];
|
|
8006
|
+
for (const part of parts) {
|
|
8007
|
+
const normalized = normalizeHookPath(part, platform);
|
|
8008
|
+
if (!BARE_HOST_SHELL_PATH.test(normalized))
|
|
8009
|
+
return null;
|
|
8010
|
+
bare.push(normalized);
|
|
8011
|
+
}
|
|
8012
|
+
return bare.join(" ");
|
|
8013
|
+
}
|
|
7697
8014
|
function nativeHookCommand(agentId) {
|
|
7698
8015
|
const fastHook = join(dirname(fileURLToPath(import.meta.url)), "native-hook-fast.js");
|
|
7699
8016
|
const explicitProxy = process.env.CAVEMAN_PROXY_BIN;
|
|
@@ -7820,7 +8137,7 @@ function canonicalManagedHookEntry(entry) {
|
|
|
7820
8137
|
const clone = JSON.parse(JSON.stringify(entry));
|
|
7821
8138
|
const hooks = clone.hooks;
|
|
7822
8139
|
hooks[0].command = identity;
|
|
7823
|
-
return
|
|
8140
|
+
return canonicalize(clone);
|
|
7824
8141
|
}
|
|
7825
8142
|
// Why: `think.shrink` (and its `CAVEMAN_SHRINK` env form) is the persisted
|
|
7826
8143
|
// switch for the command-output rewrite, but only the ephemeral launcher ever
|
|
@@ -7996,6 +8313,37 @@ function generatedArtifactTargetsExist(text) {
|
|
|
7996
8313
|
const tokens = generatedInvocation(text);
|
|
7997
8314
|
return tokens === undefined || invocationTargetsExist(tokens);
|
|
7998
8315
|
}
|
|
8316
|
+
// Same question as managedHookTargetsExist below, asked of an MCP registration
|
|
8317
|
+
// instead of a hook: the recovery tool is only real while the command the host
|
|
8318
|
+
// will launch still exists and can be executed. probeMcpBinary() answers a
|
|
8319
|
+
// DIFFERENT question — whether some compatible caveman-mcp is resolvable on
|
|
8320
|
+
// this machine right now — so an install whose registered binary was removed,
|
|
8321
|
+
// or left non-executable, kept attesting recovery while an actual launch raised
|
|
8322
|
+
// FileNotFoundError or PermissionError (#1392). That is the MCP twin of the
|
|
8323
|
+
// disappearing hook/plugin targets in #1137.
|
|
8324
|
+
//
|
|
8325
|
+
// Existence and permission only: a registration may have been edited by the
|
|
8326
|
+
// user, and probing it must never run it, nor adopt it as owned. Registrations
|
|
8327
|
+
// journaled as config text (codex tables, the hermes mcp_servers block) carry
|
|
8328
|
+
// no structured command and are not inspected here.
|
|
8329
|
+
function journaledMcpTargetsExist(journal) {
|
|
8330
|
+
// Same filter the ownership checks apply: a deleted Claude profile's entry
|
|
8331
|
+
// has nothing left to launch, and a stale path in one must not report the
|
|
8332
|
+
// remaining profiles degraded.
|
|
8333
|
+
for (const operation of (journal?.operations ?? []).filter((item) => !claudeProfileGone(item))) {
|
|
8334
|
+
const installed = operation.owned?.installed_mcp;
|
|
8335
|
+
if (!installed || typeof installed !== "object" || Array.isArray(installed))
|
|
8336
|
+
continue;
|
|
8337
|
+
const { command, args } = installed;
|
|
8338
|
+
const strings = (value) => Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
|
|
8339
|
+
// claude: { command: "<bin>", args: [] } · gemini: { command, args }
|
|
8340
|
+
// opencode: { type: "local", command: ["<bin>"] }
|
|
8341
|
+
const tokens = Array.isArray(command) ? strings(command) : typeof command === "string" ? [command, ...strings(args)] : [];
|
|
8342
|
+
if (tokens.length > 0 && !invocationTargetsExist(tokens))
|
|
8343
|
+
return false;
|
|
8344
|
+
}
|
|
8345
|
+
return true;
|
|
8346
|
+
}
|
|
7999
8347
|
// A managed hook is only healthy while the files its command runs still exist.
|
|
8000
8348
|
// Identity is judged by basename, so a hook rendered into a directory that has
|
|
8001
8349
|
// since been deleted (an nvm Node upgrade, #1137) kept matching the expected
|
|
@@ -8047,7 +8395,7 @@ function nativeHookEntriesHealthy(root, agentId) {
|
|
|
8047
8395
|
});
|
|
8048
8396
|
});
|
|
8049
8397
|
}
|
|
8050
|
-
function buildCodexEphemeralHome(gw, subscription, mcpBinary, delegateMcp) {
|
|
8398
|
+
function buildCodexEphemeralHome(gw, subscription, mcpBinary, delegateMcp, codemodeSpec = null) {
|
|
8051
8399
|
const sourceHome = codexHomeDir();
|
|
8052
8400
|
const outDir = mkdtempSync(join(tmpdir(), "caveman-wrap-"));
|
|
8053
8401
|
wrapTempDirs.add(outDir);
|
|
@@ -8065,14 +8413,21 @@ function buildCodexEphemeralHome(gw, subscription, mcpBinary, delegateMcp) {
|
|
|
8065
8413
|
catch {
|
|
8066
8414
|
sourceConfig = "";
|
|
8067
8415
|
}
|
|
8068
|
-
const
|
|
8416
|
+
const baseStripped = stripCodexCavemanMcpToml(stripCodexCavemanProviderToml(sourceConfig));
|
|
8417
|
+
const stripped = codemodeSpec ? stripExternalCodexMcpTables(baseStripped) : baseStripped;
|
|
8069
8418
|
const providerLines = codexCavemanProviderToml(gw, subscription).split("\n");
|
|
8070
8419
|
const providerRoot = providerLines.shift();
|
|
8071
8420
|
const providerTables = providerLines.join("\n");
|
|
8072
8421
|
const recoveryEnv = codexRecoveryEnv();
|
|
8073
|
-
|
|
8074
|
-
|
|
8075
|
-
|
|
8422
|
+
let mcp = "\n";
|
|
8423
|
+
if (codemodeSpec) {
|
|
8424
|
+
const cfgPath = writeEphemeralCodemodeConfig(outDir, codemodeSpec.servers);
|
|
8425
|
+
const cmArgs = [...codemodeSpec.launch.args, "codemode", "--config", cfgPath, "--workspace", codemodeSpec.workspace];
|
|
8426
|
+
mcp = `\n\n[mcp_servers.caveman-codemode]\ncommand = ${JSON.stringify(codemodeSpec.launch.command)}\nargs = [${cmArgs.map((arg) => JSON.stringify(arg)).join(", ")}]\n${recoveryEnv ? `${recoveryEnv}\n` : ""}`;
|
|
8427
|
+
}
|
|
8428
|
+
else if (mcpBinary) {
|
|
8429
|
+
mcp = `\n\n[mcp_servers.caveman]\ncommand = ${JSON.stringify(mcpBinary)}\n${recoveryEnv ? `${recoveryEnv}\n` : ""}`;
|
|
8430
|
+
}
|
|
8076
8431
|
const delegateArgs = delegateMcp?.args.length
|
|
8077
8432
|
? `\nargs = [${delegateMcp.args.map((arg) => JSON.stringify(arg)).join(", ")}]`
|
|
8078
8433
|
: "";
|
|
@@ -8088,17 +8443,17 @@ function buildCodexEphemeralHome(gw, subscription, mcpBinary, delegateMcp) {
|
|
|
8088
8443
|
linkCodexReadOnly(sourceHome, outDir, "AGENTS.md");
|
|
8089
8444
|
return outDir;
|
|
8090
8445
|
}
|
|
8091
|
-
function buildCodexEphemeralWrapEnv(gw, subscription, mcpBinary, delegateMcp) {
|
|
8446
|
+
function buildCodexEphemeralWrapEnv(gw, subscription, mcpBinary, delegateMcp, codemodeSpec = null) {
|
|
8092
8447
|
const env = { ...process.env };
|
|
8093
8448
|
for (const key of WRAP_BASE_URL_ENV_VARS)
|
|
8094
8449
|
delete env[key];
|
|
8095
8450
|
// The ephemeral CODEX_HOME points Codex at the same loopback gateway, so it
|
|
8096
8451
|
// needs the same proxy exemption the base-url wrap path gets.
|
|
8097
8452
|
Object.assign(env, gatewayNoProxyEnv(gw));
|
|
8098
|
-
env.CODEX_HOME = buildCodexEphemeralHome(gw, subscription, mcpBinary, delegateMcp);
|
|
8453
|
+
env.CODEX_HOME = buildCodexEphemeralHome(gw, subscription, mcpBinary, delegateMcp, codemodeSpec);
|
|
8099
8454
|
return env;
|
|
8100
8455
|
}
|
|
8101
|
-
function buildClaudeEphemeralPlugin(mcpBinary, includeShrink, includeRecall, delegateMcp) {
|
|
8456
|
+
function buildClaudeEphemeralPlugin(mcpBinary, includeShrink, includeRecall, delegateMcp, codemodeSpec = null) {
|
|
8102
8457
|
const dir = mkdtempSync(join(tmpdir(), "caveman-wrap-claude-"));
|
|
8103
8458
|
wrapTempDirs.add(dir);
|
|
8104
8459
|
mkdirSync(join(dir, ".claude-plugin"), { recursive: true });
|
|
@@ -8109,10 +8464,18 @@ function buildClaudeEphemeralPlugin(mcpBinary, includeShrink, includeRecall, del
|
|
|
8109
8464
|
description: "Ephemeral Caveman local-engine pack",
|
|
8110
8465
|
}, null, 2) + "\n", { mode: 0o600 });
|
|
8111
8466
|
writeFileSync(join(dir, "hooks", "hooks.json"), JSON.stringify(nativeHooksDocument("claude", includeShrink, {}, includeRecall), null, 2) + "\n", { mode: 0o600 });
|
|
8112
|
-
if (mcpBinary || delegateMcp) {
|
|
8467
|
+
if (codemodeSpec || mcpBinary || delegateMcp) {
|
|
8113
8468
|
const mcpServers = {};
|
|
8114
|
-
if (
|
|
8469
|
+
if (codemodeSpec) {
|
|
8470
|
+
const cfgPath = writeEphemeralCodemodeConfig(dir, codemodeSpec.servers);
|
|
8471
|
+
mcpServers["caveman-codemode"] = {
|
|
8472
|
+
command: codemodeSpec.launch.command,
|
|
8473
|
+
args: [...codemodeSpec.launch.args, "codemode", "--config", cfgPath, "--workspace", codemodeSpec.workspace],
|
|
8474
|
+
};
|
|
8475
|
+
}
|
|
8476
|
+
else if (mcpBinary) {
|
|
8115
8477
|
mcpServers.caveman = { command: mcpBinary, args: [] };
|
|
8478
|
+
}
|
|
8116
8479
|
if (delegateMcp)
|
|
8117
8480
|
mcpServers["caveman-delegate"] = delegateMcp;
|
|
8118
8481
|
writeFileSync(join(dir, ".mcp.json"), JSON.stringify({
|
|
@@ -8197,6 +8560,7 @@ const HERMES_NATIVE_PLUGIN_END = "# <<< caveman:native-hermes-plugin";
|
|
|
8197
8560
|
const HERMES_NATIVE_MCP_BEGIN = "# >>> caveman:native-hermes-mcp";
|
|
8198
8561
|
const HERMES_NATIVE_MCP_END = "# <<< caveman:native-hermes-mcp";
|
|
8199
8562
|
const HERMES_NATIVE_PLUGIN_NAME = "caveman_native";
|
|
8563
|
+
const HERMES_NATIVE_MCP_SERVER = "caveman-native";
|
|
8200
8564
|
const GEMINI_NATIVE_ENV_BEGIN = "# >>> caveman:native-routing";
|
|
8201
8565
|
const GEMINI_NATIVE_ENV_END = "# <<< caveman:native-routing";
|
|
8202
8566
|
const AIDER_NATIVE_ROUTE_BEGIN = "# >>> caveman:native-aider-routing";
|
|
@@ -8412,9 +8776,17 @@ function nativeProxyBinaryRequired(gw) {
|
|
|
8412
8776
|
// several times, and a hung host would cost the full timeout every time.
|
|
8413
8777
|
const nativeHostProbes = new Map();
|
|
8414
8778
|
function nativeHostProbe(agent) {
|
|
8415
|
-
|
|
8779
|
+
return nativeBinaryProbe(binOf(agent))
|
|
8780
|
+
?? { binary: null, launchable: false, version: null, error: "binary_not_found" };
|
|
8781
|
+
}
|
|
8782
|
+
// One named binary, or null when it is not installed — so a caller that cares
|
|
8783
|
+
// about EVERY published name (opencodePluginMajors) can ask per name instead of
|
|
8784
|
+
// only about binOf's first hit. Shares the probe cache, keyed on the resolved
|
|
8785
|
+
// path, so two names resolving to the same file cost one spawn.
|
|
8786
|
+
function nativeBinaryProbe(name) {
|
|
8787
|
+
const binary = which(name);
|
|
8416
8788
|
if (!binary)
|
|
8417
|
-
return
|
|
8789
|
+
return null;
|
|
8418
8790
|
let probe = nativeHostProbes.get(binary);
|
|
8419
8791
|
if (!probe)
|
|
8420
8792
|
nativeHostProbes.set(binary, probe = probeNativeHost(binary));
|
|
@@ -8798,6 +9170,31 @@ function geminiRouteShadow() {
|
|
|
8798
9170
|
return null;
|
|
8799
9171
|
}
|
|
8800
9172
|
}
|
|
9173
|
+
// Gemini CLI resolves an unset (or empty) auth type from env: GOOGLE_GENAI_USE_GCA,
|
|
9174
|
+
// then GOOGLE_GENAI_USE_VERTEXAI, then GOOGLE_GEMINI_BASE_URL -> `gateway`, a type
|
|
9175
|
+
// its own headless validator rejects ("Invalid auth method selected.", exit 41;
|
|
9176
|
+
// google-gemini/gemini-cli#27550, closed not planned). Our route always sets the
|
|
9177
|
+
// base URL, so the API-key type is pinned unless one of these switches is on:
|
|
9178
|
+
// GCA and Vertex resolve before the base URL, and Cloud Shell / compute ADC users
|
|
9179
|
+
// get their type written by Gemini itself. The shell wins over the .env file and
|
|
9180
|
+
// the last line wins within it, as in Gemini.
|
|
9181
|
+
const GEMINI_PINNED_AUTH = "gemini-api-key";
|
|
9182
|
+
const GEMINI_PINNED_AUTH_NOTE = `auth: security.auth.selectedType = ${GEMINI_PINNED_AUTH} (Gemini CLI rejects the gateway type it picks for a routed base URL; /auth in Gemini changes it)`;
|
|
9183
|
+
function geminiEnvSelectsAuth(dotenv) {
|
|
9184
|
+
return ["GOOGLE_GENAI_USE_GCA", "GOOGLE_GENAI_USE_VERTEXAI", "CLOUD_SHELL", "GEMINI_CLI_USE_COMPUTE_ADC"].some((key) => {
|
|
9185
|
+
const line = dotenv.split(/\r?\n/).findLast((item) => new RegExp(`^\\s*(?:export\\s+)?${key}\\s*=`).test(item));
|
|
9186
|
+
return (process.env[key] ?? configValue(line?.slice(line.indexOf("=") + 1))) === "true";
|
|
9187
|
+
});
|
|
9188
|
+
}
|
|
9189
|
+
// An install from before the pin existed journals no `selected_auth` at all
|
|
9190
|
+
// (an install that chose not to pin records null): enable and doctor --fix
|
|
9191
|
+
// re-wire it so the pin is decided once.
|
|
9192
|
+
function geminiAuthUndecided(agent) {
|
|
9193
|
+
if (agent !== "gemini")
|
|
9194
|
+
return false;
|
|
9195
|
+
const operation = readNativeJournal("gemini")?.operations.find((item) => item.kind === "gemini-settings");
|
|
9196
|
+
return Boolean(operation && !("selected_auth" in (operation.owned ?? {})));
|
|
9197
|
+
}
|
|
8801
9198
|
function geminiNativeMutations(gw, mcpBinary) {
|
|
8802
9199
|
if (wrapMode(gw) === "managed") {
|
|
8803
9200
|
throw new Error("managed Gemini CLI routing is unsupported because Gemini CLI cannot send separate Caveman and upstream credentials");
|
|
@@ -8806,6 +9203,20 @@ function geminiNativeMutations(gw, mcpBinary) {
|
|
|
8806
9203
|
const settingsBefore = fileBytes(settingsPath);
|
|
8807
9204
|
const settings = parseJsonFileObject(settingsPath, settingsBefore);
|
|
8808
9205
|
assertNativeHooksShape(settingsPath, settings, "gemini");
|
|
9206
|
+
const envPath = join(geminiConfigDir(), ".env");
|
|
9207
|
+
const envBefore = fileBytes(envPath);
|
|
9208
|
+
// Pin the API-key type only where the user chose none (see geminiEnvSelectsAuth);
|
|
9209
|
+
// a non-object security/auth value is left as is.
|
|
9210
|
+
const security = settings.security === undefined ? {} : asJsonObject(settings.security);
|
|
9211
|
+
const auth = security && (security.auth === undefined ? {} : asJsonObject(security.auth));
|
|
9212
|
+
const selectedAuth = auth && !auth.selectedType && !geminiEnvSelectsAuth(envBefore?.toString("utf8") ?? "")
|
|
9213
|
+
? GEMINI_PINNED_AUTH
|
|
9214
|
+
: null;
|
|
9215
|
+
if (selectedAuth) {
|
|
9216
|
+
auth.selectedType = selectedAuth;
|
|
9217
|
+
security.auth = auth;
|
|
9218
|
+
settings.security = security;
|
|
9219
|
+
}
|
|
8809
9220
|
if (settings.mcpServers !== undefined && (typeof settings.mcpServers !== "object" || settings.mcpServers === null || Array.isArray(settings.mcpServers))) {
|
|
8810
9221
|
throw new Error(`${settingsPath} mcpServers must be a JSON object; refusing to overwrite it`);
|
|
8811
9222
|
}
|
|
@@ -8817,8 +9228,6 @@ function geminiNativeMutations(gw, mcpBinary) {
|
|
|
8817
9228
|
servers.caveman = installedMcp;
|
|
8818
9229
|
settings.mcpServers = servers;
|
|
8819
9230
|
const withHooks = nativeHooksDocument("gemini", nativeShrinkEnabled(), settings);
|
|
8820
|
-
const envPath = join(geminiConfigDir(), ".env");
|
|
8821
|
-
const envBefore = fileBytes(envPath);
|
|
8822
9231
|
const route = appendUrlPath(gw, "/w/gemini");
|
|
8823
9232
|
const nativeEnv = geminiNativeEnv(envBefore?.toString("utf8") ?? "", route);
|
|
8824
9233
|
// The block goes last in the file, so it would win over the user's own.
|
|
@@ -8831,7 +9240,7 @@ function geminiNativeMutations(gw, mcpBinary) {
|
|
|
8831
9240
|
before: settingsBefore,
|
|
8832
9241
|
after: jsonBytes(withHooks, settingsBefore),
|
|
8833
9242
|
kind: "gemini-settings",
|
|
8834
|
-
owned: { installed_mcp: installedMcp, previous_mcp: previousMcp ?? null },
|
|
9243
|
+
owned: { installed_mcp: installedMcp, previous_mcp: previousMcp ?? null, selected_auth: selectedAuth },
|
|
8835
9244
|
},
|
|
8836
9245
|
{
|
|
8837
9246
|
file: envPath,
|
|
@@ -8842,9 +9251,15 @@ function geminiNativeMutations(gw, mcpBinary) {
|
|
|
8842
9251
|
},
|
|
8843
9252
|
];
|
|
8844
9253
|
}
|
|
8845
|
-
// OpenCode reads
|
|
8846
|
-
//
|
|
9254
|
+
// OpenCode reads OPENCODE_CONFIG_DIR when that is set to a nonempty value,
|
|
9255
|
+
// else $XDG_CONFIG_HOME/opencode, else ~/.config/opencode on every platform,
|
|
9256
|
+
// and opencode.jsonc over opencode.json when both are there. Skipping the
|
|
9257
|
+
// variable installed into a root the host never reads, while still reporting
|
|
9258
|
+
// success (#1441); the installer and the mode plugin resolve it the same way.
|
|
8847
9259
|
function opencodeConfigDir() {
|
|
9260
|
+
const selected = process.env.OPENCODE_CONFIG_DIR ?? "";
|
|
9261
|
+
if (selected.trim())
|
|
9262
|
+
return resolve(selected);
|
|
8848
9263
|
return join(process.env.XDG_CONFIG_HOME || join(homedir(), ".config"), "opencode");
|
|
8849
9264
|
}
|
|
8850
9265
|
function opencodeConfigPath() {
|
|
@@ -8854,12 +9269,30 @@ function opencodeConfigPath() {
|
|
|
8854
9269
|
function opencodeNativePluginPath() {
|
|
8855
9270
|
return join(opencodeConfigDir(), "plugins", "caveman-native.js");
|
|
8856
9271
|
}
|
|
8857
|
-
|
|
9272
|
+
// The plugin APIs this machine has to satisfy, ascending and deduplicated.
|
|
9273
|
+
//
|
|
9274
|
+
// Asking which major "the" host is was the wrong question: the generated plugin
|
|
9275
|
+
// lives at ONE path every opencode on the machine reads, and @opencode/cli
|
|
9276
|
+
// publishes `opencode` and `opencode2` from the same package, so two majors run
|
|
9277
|
+
// side by side routinely. A 1.x kept on PATH for other projects won binOf's
|
|
9278
|
+
// first-found probe, the gate read major 1, and OpenCode 2 refused the V1 hook
|
|
9279
|
+
// map outright: PluginModule.LoadError, missing "default" (#1316).
|
|
9280
|
+
//
|
|
9281
|
+
// Empty means no installed binary named a readable version — evidence of
|
|
9282
|
+
// neither major, not of absence.
|
|
9283
|
+
function opencodePluginMajors() {
|
|
8858
9284
|
const profile = AGENTS.find((agent) => agent.id === "opencode");
|
|
8859
|
-
|
|
8860
|
-
|
|
8861
|
-
const
|
|
8862
|
-
|
|
9285
|
+
if (!profile)
|
|
9286
|
+
return [];
|
|
9287
|
+
const majors = new Set();
|
|
9288
|
+
for (const name of profile.binary_names) {
|
|
9289
|
+
const probe = nativeBinaryProbe(name);
|
|
9290
|
+
// A failed probe's text is its error output, not a version.
|
|
9291
|
+
const semver = probe?.launchable ? parsedSemver(probe.version) : undefined;
|
|
9292
|
+
if (semver)
|
|
9293
|
+
majors.add(semver[0]);
|
|
9294
|
+
}
|
|
9295
|
+
return [...majors].sort((a, b) => a - b);
|
|
8863
9296
|
}
|
|
8864
9297
|
function opencodeNativePluginSource() {
|
|
8865
9298
|
// OpenCode 2 replaced the plugin API: a V1 hook map no longer loads
|
|
@@ -8872,12 +9305,14 @@ function opencodeNativePluginSource() {
|
|
|
8872
9305
|
// V2 { id, setup } beside it. 1.x also calls setup, with a context that has
|
|
8873
9306
|
// no session or event API, so setup returns there. Checked against real
|
|
8874
9307
|
// OpenCode 1.18.35 and 2.0.22; 1.0-1.3 call every export and cannot load it.
|
|
8875
|
-
|
|
8876
|
-
|
|
9308
|
+
//
|
|
9309
|
+
// Two installed majors take that same file, for the same reason: they share
|
|
9310
|
+
// this one plugins directory, so a file pinned to either API is one the other
|
|
9311
|
+
// host refuses to load (#1316).
|
|
9312
|
+
const majors = opencodePluginMajors();
|
|
9313
|
+
if (majors.length !== 1)
|
|
8877
9314
|
return opencodeNativePluginSourceBoth();
|
|
8878
|
-
|
|
8879
|
-
return opencodeNativePluginSourceV1();
|
|
8880
|
-
return opencodeNativePluginSourceV2();
|
|
9315
|
+
return majors[0] < 2 ? opencodeNativePluginSourceV1() : opencodeNativePluginSourceV2();
|
|
8881
9316
|
}
|
|
8882
9317
|
function opencodeNativePluginSourceBoth() {
|
|
8883
9318
|
const v2 = opencodeNativePluginSourceV2();
|
|
@@ -8898,11 +9333,18 @@ const prefix = ${JSON.stringify(pre)};
|
|
|
8898
9333
|
const contexts = new Map();
|
|
8899
9334
|
const pending = new Map();
|
|
8900
9335
|
|
|
8901
|
-
|
|
9336
|
+
// A host process can serve a project that is not its own launch directory, so
|
|
9337
|
+
// the served project travels with every call: in the payload, which
|
|
9338
|
+
// nativeRuntimeRequest reads as the session cwd, and as the child's working
|
|
9339
|
+
// directory, so anything it resolves relatively resolves there (#1443).
|
|
9340
|
+
let projectDir;
|
|
9341
|
+
|
|
9342
|
+
function call(event, payload = {}, cwd = projectDir) {
|
|
8902
9343
|
try {
|
|
8903
9344
|
const raw = execFileSync(command, [...prefix, "native-hook", "opencode", event], {
|
|
8904
|
-
input: JSON.stringify({ event_name: event, ...payload }),
|
|
9345
|
+
input: JSON.stringify({ event_name: event, ...(cwd ? { cwd } : {}), ...payload }),
|
|
8905
9346
|
encoding: "utf8",
|
|
9347
|
+
cwd: cwd || undefined,
|
|
8906
9348
|
timeout: 2000,
|
|
8907
9349
|
maxBuffer: 2 * 1024 * 1024,
|
|
8908
9350
|
// A host with no console of its own — OpenCode under a multiplexer or a
|
|
@@ -8975,7 +9417,7 @@ function sessionContext(sessionID) {
|
|
|
8975
9417
|
return contexts.get(sessionID);
|
|
8976
9418
|
}
|
|
8977
9419
|
|
|
8978
|
-
|
|
9420
|
+
const hostHooks = {
|
|
8979
9421
|
event: async ({ event }) => {
|
|
8980
9422
|
const type = event?.type;
|
|
8981
9423
|
const props = event?.properties ?? {};
|
|
@@ -9029,6 +9471,7 @@ export const CavemanNative = async () => ({
|
|
|
9029
9471
|
const raw = execFileSync(command, [...prefix, "shrink-hook"], {
|
|
9030
9472
|
input: JSON.stringify({ tool_name: "Bash", tool_input: { command: output.args.command } }),
|
|
9031
9473
|
encoding: "utf8",
|
|
9474
|
+
cwd: projectDir || undefined,
|
|
9032
9475
|
timeout: 750,
|
|
9033
9476
|
windowsHide: true,
|
|
9034
9477
|
});
|
|
@@ -9059,7 +9502,15 @@ export const CavemanNative = async () => ({
|
|
|
9059
9502
|
contexts.clear();
|
|
9060
9503
|
pending.clear();
|
|
9061
9504
|
},
|
|
9062
|
-
}
|
|
9505
|
+
};
|
|
9506
|
+
|
|
9507
|
+
// OpenCode's V1 plugin context names the served project \`directory\`. A host
|
|
9508
|
+
// that supplies none (or a caller that supplies no context at all) leaves
|
|
9509
|
+
// projectDir unset and every child inherits this process's cwd, as before.
|
|
9510
|
+
export const CavemanNative = async (ctx) => {
|
|
9511
|
+
if (typeof ctx?.directory === "string" && ctx.directory) projectDir = ctx.directory;
|
|
9512
|
+
return hostHooks;
|
|
9513
|
+
};
|
|
9063
9514
|
`;
|
|
9064
9515
|
}
|
|
9065
9516
|
function opencodeNativePluginSourceV2() {
|
|
@@ -9073,11 +9524,18 @@ import { createHash } from "node:crypto";
|
|
|
9073
9524
|
const command = ${JSON.stringify(cmd)};
|
|
9074
9525
|
const prefix = ${JSON.stringify(pre)};
|
|
9075
9526
|
|
|
9076
|
-
|
|
9527
|
+
// A host process can serve a project that is not its own launch directory, so
|
|
9528
|
+
// the served project travels with every call: in the payload, which
|
|
9529
|
+
// nativeRuntimeRequest reads as the session cwd, and as the child's working
|
|
9530
|
+
// directory, so anything it resolves relatively resolves there (#1443).
|
|
9531
|
+
let projectDir;
|
|
9532
|
+
|
|
9533
|
+
function call(event, payload = {}, cwd = projectDir) {
|
|
9077
9534
|
try {
|
|
9078
9535
|
const raw = execFileSync(command, [...prefix, "native-hook", "opencode", event], {
|
|
9079
|
-
input: JSON.stringify({ event_name: event, ...payload }),
|
|
9536
|
+
input: JSON.stringify({ event_name: event, ...(cwd ? { cwd } : {}), ...payload }),
|
|
9080
9537
|
encoding: "utf8",
|
|
9538
|
+
cwd: cwd || undefined,
|
|
9081
9539
|
timeout: 2000,
|
|
9082
9540
|
maxBuffer: 2 * 1024 * 1024,
|
|
9083
9541
|
// A host with no console of its own — OpenCode under a multiplexer or a
|
|
@@ -9144,13 +9602,19 @@ export default {
|
|
|
9144
9602
|
id: "caveman-native",
|
|
9145
9603
|
async setup(ctx) {
|
|
9146
9604
|
// Per-plugin-instance state: one setup() runs per location, so two
|
|
9147
|
-
// projects never share session context through module scope.
|
|
9605
|
+
// projects never share session context through module scope. The served
|
|
9606
|
+
// project directory is per-instance for the same reason, so it is passed
|
|
9607
|
+
// to each child explicitly rather than parked in module scope (#1443).
|
|
9148
9608
|
const contexts = new Map();
|
|
9149
9609
|
const pending = new Map();
|
|
9610
|
+
const projectCwd = typeof ctx.location?.directory === "string" && ctx.location.directory
|
|
9611
|
+
? ctx.location.directory
|
|
9612
|
+
: undefined;
|
|
9613
|
+
const emit = (event, payload = {}) => call(event, payload, projectCwd);
|
|
9150
9614
|
|
|
9151
9615
|
function sessionContext(sessionID) {
|
|
9152
9616
|
if (!contexts.has(sessionID)) {
|
|
9153
|
-
const out =
|
|
9617
|
+
const out = emit("SessionStart", { session_id: sessionID, surface: "cli" });
|
|
9154
9618
|
const context = out?.hookSpecificOutput?.additionalContext;
|
|
9155
9619
|
contexts.set(sessionID, typeof context === "string" ? context : "");
|
|
9156
9620
|
}
|
|
@@ -9167,8 +9631,16 @@ export default {
|
|
|
9167
9631
|
});
|
|
9168
9632
|
|
|
9169
9633
|
function sameLocation(event) {
|
|
9170
|
-
|
|
9171
|
-
|
|
9634
|
+
// OpenCode keeps routing metadata separate from the public event: the bus
|
|
9635
|
+
// resolves a locationless session event through that session's owner and
|
|
9636
|
+
// then filters each location subscription with the routing snapshot. So
|
|
9637
|
+
// an event delivered to THIS instance with no public location is already
|
|
9638
|
+
// ours — session.deleted publishes only { sessionID } — and dropping it
|
|
9639
|
+
// skipped SessionEnd and leaked the cached context until disposal
|
|
9640
|
+
// (#1444). A location that is present and different is somebody else's.
|
|
9641
|
+
if (!event.location) return true;
|
|
9642
|
+
return event.location.directory === ctx.location.directory &&
|
|
9643
|
+
event.location.workspaceID === ctx.location.workspaceID;
|
|
9172
9644
|
}
|
|
9173
9645
|
|
|
9174
9646
|
function handleEvent(event) {
|
|
@@ -9177,16 +9649,16 @@ export default {
|
|
|
9177
9649
|
const sessionID = event.data?.sessionID;
|
|
9178
9650
|
if (typeof sessionID !== "string" || !sessionID) return;
|
|
9179
9651
|
if (type === "session.created") sessionContext(sessionID);
|
|
9180
|
-
if (type === "session.idle")
|
|
9652
|
+
if (type === "session.idle") emit("Stop", { session_id: sessionID });
|
|
9181
9653
|
// "session.compacted" is the V1 event name; V2 reports compaction
|
|
9182
9654
|
// through "session.compaction.ended". Handle both.
|
|
9183
9655
|
if (type === "session.compaction.ended" || type === "session.compacted") {
|
|
9184
|
-
const out =
|
|
9656
|
+
const out = emit("PostCompact", { session_id: sessionID });
|
|
9185
9657
|
const context = out?.hookSpecificOutput?.additionalContext;
|
|
9186
9658
|
if (typeof context === "string" && context) contexts.set(sessionID, context);
|
|
9187
9659
|
}
|
|
9188
9660
|
if (type === "session.deleted") {
|
|
9189
|
-
|
|
9661
|
+
emit("SessionEnd", { session_id: sessionID });
|
|
9190
9662
|
contexts.delete(sessionID);
|
|
9191
9663
|
pending.delete(sessionID);
|
|
9192
9664
|
}
|
|
@@ -9194,7 +9666,7 @@ export default {
|
|
|
9194
9666
|
|
|
9195
9667
|
await ctx.session.hook("prompt", (event) => {
|
|
9196
9668
|
const prompt = event.prompt ?? {};
|
|
9197
|
-
const decision =
|
|
9669
|
+
const decision = emit("UserPromptSubmit", {
|
|
9198
9670
|
session_id: event.sessionID,
|
|
9199
9671
|
prompt: digest(prompt),
|
|
9200
9672
|
task_type: taskType(prompt),
|
|
@@ -9216,13 +9688,13 @@ export default {
|
|
|
9216
9688
|
});
|
|
9217
9689
|
|
|
9218
9690
|
await ctx.session.hook("compaction", (event) => {
|
|
9219
|
-
|
|
9691
|
+
emit("PreCompact", { session_id: event.sessionID });
|
|
9220
9692
|
const stable = sessionContext(event.sessionID);
|
|
9221
9693
|
if (stable) event.system.push({ type: "text", text: stable });
|
|
9222
9694
|
});
|
|
9223
9695
|
|
|
9224
9696
|
await ctx.tool.hook("execute.before", (event) => {
|
|
9225
|
-
const decision =
|
|
9697
|
+
const decision = emit("PreToolUse", {
|
|
9226
9698
|
session_id: event.sessionID,
|
|
9227
9699
|
tool_name: event.tool,
|
|
9228
9700
|
tool_input: event.input,
|
|
@@ -9239,6 +9711,7 @@ export default {
|
|
|
9239
9711
|
const raw = execFileSync(command, [...prefix, "shrink-hook"], {
|
|
9240
9712
|
input: JSON.stringify({ tool_name: "Bash", tool_input: { command: input.command } }),
|
|
9241
9713
|
encoding: "utf8",
|
|
9714
|
+
cwd: projectCwd || undefined,
|
|
9242
9715
|
timeout: 750,
|
|
9243
9716
|
windowsHide: true,
|
|
9244
9717
|
});
|
|
@@ -9250,7 +9723,7 @@ export default {
|
|
|
9250
9723
|
|
|
9251
9724
|
await ctx.tool.hook("execute.after", (event) => {
|
|
9252
9725
|
if (event.status !== "completed") return;
|
|
9253
|
-
const decision =
|
|
9726
|
+
const decision = emit("PostToolUse", {
|
|
9254
9727
|
session_id: event.sessionID,
|
|
9255
9728
|
tool_name: event.tool,
|
|
9256
9729
|
tool_input: event.input,
|
|
@@ -9264,7 +9737,7 @@ export default {
|
|
|
9264
9737
|
|
|
9265
9738
|
return () => {
|
|
9266
9739
|
controller.abort();
|
|
9267
|
-
for (const sessionID of contexts.keys())
|
|
9740
|
+
for (const sessionID of contexts.keys()) emit("SessionEnd", { session_id: sessionID });
|
|
9268
9741
|
contexts.clear();
|
|
9269
9742
|
pending.clear();
|
|
9270
9743
|
};
|
|
@@ -9999,15 +10472,31 @@ function insertHermesNativeListEntry(lines, sectionName, childName, begin, end,
|
|
|
9999
10472
|
lines.push(...whole);
|
|
10000
10473
|
return whole.join("\n");
|
|
10001
10474
|
}
|
|
10475
|
+
// Hermes provider ids that carry their OWN OAuth credential and the ChatGPT
|
|
10476
|
+
// Responses transport. Rewriting one to the generic `custom` provider drops
|
|
10477
|
+
// both: the installed resolver then picks chat_completions with
|
|
10478
|
+
// `no-key-required` and every request 401s (#1391). These keep their provider
|
|
10479
|
+
// and ride the proxy's existing ChatGPT handler instead.
|
|
10480
|
+
const HERMES_CHATGPT_OAUTH_PROVIDERS = new Set(["openai-codex"]);
|
|
10481
|
+
// `/chatgpt` is the ChatGPT mux handler, which takes its suffix verbatim — the
|
|
10482
|
+
// Responses operation is `/chatgpt/responses`, so this must NOT gain a "/v1".
|
|
10483
|
+
// Same reasoning as codexGatewayBase().
|
|
10484
|
+
function hermesGatewayBase(gw, keptProvider) {
|
|
10485
|
+
return appendUrlPath(gw, keptProvider && HERMES_CHATGPT_OAUTH_PROVIDERS.has(keptProvider) ? "/chatgpt" : "/w/hermes/v1");
|
|
10486
|
+
}
|
|
10002
10487
|
function hermesNativeConfig(source, gw, mcpBinary) {
|
|
10003
10488
|
for (const marker of [HERMES_NATIVE_ROUTE_BEGIN, HERMES_NATIVE_ROUTE_END, HERMES_NATIVE_PLUGIN_BEGIN, HERMES_NATIVE_PLUGIN_END, HERMES_NATIVE_MCP_BEGIN, HERMES_NATIVE_MCP_END]) {
|
|
10004
10489
|
if (source.includes(marker))
|
|
10005
10490
|
throw new Error("existing Hermes Caveman native block is unjournaled; run `caveman doctor hermes`");
|
|
10006
10491
|
}
|
|
10492
|
+
const nativePluginMembership = hermesNamedPluginMembership(source, HERMES_NATIVE_PLUGIN_NAME);
|
|
10493
|
+
if (nativePluginMembership === "disabled") {
|
|
10494
|
+
throw new Error(`Hermes plugin ${HERMES_NATIVE_PLUGIN_NAME} is explicitly disabled in plugins.disabled; remove that entry before enabling Caveman`);
|
|
10495
|
+
}
|
|
10007
10496
|
const lines = yamlLines(source);
|
|
10008
10497
|
let model = topLevelSection(lines, "model");
|
|
10009
10498
|
if (!model) {
|
|
10010
|
-
lines.
|
|
10499
|
+
lines.splice(yamlBodyStart(lines), 0, "model:");
|
|
10011
10500
|
model = topLevelSection(lines, "model");
|
|
10012
10501
|
}
|
|
10013
10502
|
const routeIndexes = [];
|
|
@@ -10024,10 +10513,17 @@ function hermesNativeConfig(source, gw, mcpBinary) {
|
|
|
10024
10513
|
const insertAt = routeIndexes[0] ?? model.start + 1;
|
|
10025
10514
|
for (const index of [...routeIndexes].sort((a, b) => b - a))
|
|
10026
10515
|
lines.splice(index, 1);
|
|
10516
|
+
// A named OAuth provider selects a credential and a transport that the
|
|
10517
|
+
// generic custom route cannot carry, so keep it and route to the handler
|
|
10518
|
+
// that speaks it. `api_mode` is not a route key, so it already survives.
|
|
10519
|
+
const providerLine = previousRouteLines.find((line) => /^ provider:/.test(line));
|
|
10520
|
+
const previousProvider = providerLine ? configValue(providerLine.slice(providerLine.indexOf(":") + 1)) : undefined;
|
|
10521
|
+
const keptProvider = previousProvider && HERMES_CHATGPT_OAUTH_PROVIDERS.has(previousProvider) ? previousProvider : null;
|
|
10522
|
+
const route = hermesGatewayBase(gw, keptProvider);
|
|
10027
10523
|
const routeBlock = [
|
|
10028
10524
|
` ${HERMES_NATIVE_ROUTE_BEGIN}`,
|
|
10029
|
-
' provider: "custom"',
|
|
10030
|
-
` base_url: ${yamlQuote(
|
|
10525
|
+
keptProvider ? ` provider: ${keptProvider}` : ' provider: "custom"',
|
|
10526
|
+
` base_url: ${yamlQuote(route)}`,
|
|
10031
10527
|
` ${HERMES_NATIVE_ROUTE_END}`,
|
|
10032
10528
|
];
|
|
10033
10529
|
lines.splice(insertAt, 0, ...routeBlock);
|
|
@@ -10044,8 +10540,9 @@ function hermesNativeConfig(source, gw, mcpBinary) {
|
|
|
10044
10540
|
}
|
|
10045
10541
|
}
|
|
10046
10542
|
if (enabled >= 0) {
|
|
10047
|
-
if (
|
|
10048
|
-
const
|
|
10543
|
+
if (nativePluginMembership !== "enabled") {
|
|
10544
|
+
const pad = " ".repeat(yamlListItemIndent(lines, enabled, plugins.end) ?? 4);
|
|
10545
|
+
const block = [`${pad}${HERMES_NATIVE_PLUGIN_BEGIN}`, `${pad}- ${HERMES_NATIVE_PLUGIN_NAME}`, `${pad}${HERMES_NATIVE_PLUGIN_END}`];
|
|
10049
10546
|
lines.splice(enabled + 1, 0, ...block);
|
|
10050
10547
|
pluginBlock = block.join("\n");
|
|
10051
10548
|
}
|
|
@@ -10065,16 +10562,19 @@ function hermesNativeConfig(source, gw, mcpBinary) {
|
|
|
10065
10562
|
}
|
|
10066
10563
|
const mcpBlockLines = [
|
|
10067
10564
|
` ${HERMES_NATIVE_MCP_BEGIN}`,
|
|
10068
|
-
|
|
10565
|
+
` ${HERMES_NATIVE_MCP_SERVER}:`,
|
|
10069
10566
|
` command: ${yamlQuote(mcpBinary)}`,
|
|
10070
10567
|
" enabled: true",
|
|
10071
10568
|
` ${HERMES_NATIVE_MCP_END}`,
|
|
10072
10569
|
];
|
|
10073
|
-
const mcpBlock = insertHermesNativeListEntry(lines, "mcp_servers",
|
|
10570
|
+
const mcpBlock = insertHermesNativeListEntry(lines, "mcp_servers", HERMES_NATIVE_MCP_SERVER, HERMES_NATIVE_MCP_BEGIN, HERMES_NATIVE_MCP_END, mcpBlockLines);
|
|
10074
10571
|
return {
|
|
10075
10572
|
text: yamlText(lines),
|
|
10076
10573
|
owned: {
|
|
10077
|
-
route
|
|
10574
|
+
route,
|
|
10575
|
+
// Absent in journals written before #1391; doctor reads that as the
|
|
10576
|
+
// generic route, which is what those installs actually carry.
|
|
10577
|
+
provider: keptProvider ?? "custom",
|
|
10078
10578
|
route_block: routeBlock.join("\n"),
|
|
10079
10579
|
previous_route_lines: previousRouteLines,
|
|
10080
10580
|
plugin_block: pluginBlock,
|
|
@@ -10572,8 +11072,9 @@ function enableNative(argv, { quiet = false } = {}) {
|
|
|
10572
11072
|
// is not the current target); it is re-wired below, outside the lock.
|
|
10573
11073
|
// Module apply (quiet) writes only the files its plan showed, so the
|
|
10574
11074
|
// voice skills ride along with an explicit `caveman enable` only.
|
|
10575
|
-
// A Claude profile the journal does not cover is re-wired the same way
|
|
10576
|
-
|
|
11075
|
+
// A Claude profile the journal does not cover is re-wired the same way,
|
|
11076
|
+
// and so is a Gemini install that predates the auth pin.
|
|
11077
|
+
if (agentStaleRoute(agent) || existing.unwired_profiles.length > 0 || geminiAuthUndecided(agent)) {
|
|
10577
11078
|
if (!quiet)
|
|
10578
11079
|
installNativeVoiceSkills(agent);
|
|
10579
11080
|
return "stale";
|
|
@@ -10599,6 +11100,8 @@ function enableNative(argv, { quiet = false } = {}) {
|
|
|
10599
11100
|
process.stderr.write(` ${mutation.kind}: ${mutation.file}\n`);
|
|
10600
11101
|
if (typeof route === "string")
|
|
10601
11102
|
process.stderr.write(` routing: ${route}\n`);
|
|
11103
|
+
if (mutations.some((item) => typeof item.owned?.selected_auth === "string"))
|
|
11104
|
+
process.stderr.write(` ${GEMINI_PINNED_AUTH_NOTE}\n`);
|
|
10602
11105
|
process.stderr.write(agent === "aider" ? " recovery MCP: unavailable in Aider\n" : ` recovery MCP: ${mcpBinary}\n`);
|
|
10603
11106
|
process.stderr.write(agent === "aider"
|
|
10604
11107
|
? ` Core: read-only ${aiderCorePath()}; lifecycle/tool interception unavailable; Ledger observational\n`
|
|
@@ -10643,9 +11146,13 @@ function enableNative(argv, { quiet = false } = {}) {
|
|
|
10643
11146
|
setNativeOptOut(agent, false);
|
|
10644
11147
|
if (outcome === "stale") {
|
|
10645
11148
|
const was = agentStaleRoute(agent);
|
|
11149
|
+
const authUndecided = geminiAuthUndecided(agent);
|
|
10646
11150
|
repairNativeAgent(agent, { quiet: true });
|
|
10647
11151
|
if (!quiet)
|
|
10648
|
-
process.stderr.write(`${mark("ok")} ${profile.display_name}: ${was ? `routing: ${was} → ${new URL(gw).origin}` : "native Caveman now covers every profile"}\n`);
|
|
11152
|
+
process.stderr.write(`${mark("ok")} ${profile.display_name}: ${was ? `routing: ${was} → ${new URL(gw).origin}` : authUndecided ? "native Caveman wiring refreshed" : "native Caveman now covers every profile"}\n`);
|
|
11153
|
+
const pinned = readNativeJournal(agent)?.operations.find((item) => item.kind === "gemini-settings")?.owned?.selected_auth;
|
|
11154
|
+
if (!quiet && authUndecided && typeof pinned === "string")
|
|
11155
|
+
process.stderr.write(dim(`→ ${GEMINI_PINNED_AUTH_NOTE}\n`));
|
|
10649
11156
|
}
|
|
10650
11157
|
ensureLocalProxyForNative(agent, gw);
|
|
10651
11158
|
if (quiet || outcome === "stale")
|
|
@@ -10775,7 +11282,7 @@ function restoreNativeOperation(operation) {
|
|
|
10775
11282
|
// Symmetric to the enable-side ENABLE_TOOL_SEARCH write: only withdraw the
|
|
10776
11283
|
// value we introduced ourselves and only while it is still untouched, so a
|
|
10777
11284
|
// user who set their own afterwards keeps it.
|
|
10778
|
-
if (beforeEnv.ENABLE_TOOL_SEARCH === undefined && currentEnv.ENABLE_TOOL_SEARCH === TOOL_SEARCH_DEFAULT) {
|
|
11285
|
+
if (beforeEnv.ENABLE_TOOL_SEARCH === undefined && (currentEnv.ENABLE_TOOL_SEARCH === TOOL_SEARCH_DEFAULT || LEGACY_TOOL_SEARCH_DEFAULTS.includes(String(currentEnv.ENABLE_TOOL_SEARCH)))) {
|
|
10779
11286
|
delete currentEnv.ENABLE_TOOL_SEARCH;
|
|
10780
11287
|
}
|
|
10781
11288
|
// Auto's picker keys this enable added, each only while it is still ours.
|
|
@@ -10841,6 +11348,18 @@ function restoreNativeOperation(operation) {
|
|
|
10841
11348
|
currentRoot.mcpServers = servers;
|
|
10842
11349
|
else
|
|
10843
11350
|
delete currentRoot.mcpServers;
|
|
11351
|
+
// Withdraw the pinned auth type only while it is still ours; a type the
|
|
11352
|
+
// user picked since (Gemini's /auth rewrites it) outlives disable.
|
|
11353
|
+
const selected = operation.owned?.selected_auth;
|
|
11354
|
+
const security = asJsonObject(currentRoot.security);
|
|
11355
|
+
const auth = asJsonObject(security?.auth);
|
|
11356
|
+
if (typeof selected === "string" && auth?.selectedType === selected) {
|
|
11357
|
+
delete auth.selectedType;
|
|
11358
|
+
if (Object.keys(auth).length === 0 && !getObject(beforeRoot, ["security", "auth"]))
|
|
11359
|
+
delete security.auth;
|
|
11360
|
+
if (Object.keys(security).length === 0 && !asJsonObject(beforeRoot.security))
|
|
11361
|
+
delete currentRoot.security;
|
|
11362
|
+
}
|
|
10844
11363
|
return jsonBytes(currentRoot, current);
|
|
10845
11364
|
}
|
|
10846
11365
|
if (operation.kind === "gemini-env") {
|
|
@@ -10935,18 +11454,33 @@ function restoreNativeOperation(operation) {
|
|
|
10935
11454
|
if (typeof routeBlock !== "string" || !Array.isArray(previousRouteLines)) {
|
|
10936
11455
|
throw new Error("Hermes integration journal lacks owned routing block");
|
|
10937
11456
|
}
|
|
10938
|
-
|
|
10939
|
-
|
|
10940
|
-
|
|
10941
|
-
|
|
10942
|
-
|
|
10943
|
-
|
|
10944
|
-
|
|
10945
|
-
|
|
10946
|
-
|
|
10947
|
-
|
|
11457
|
+
// The blocks are still there verbatim: restore byte for byte, as before.
|
|
11458
|
+
// A reserialised document (#1410) has the same VALUES under different
|
|
11459
|
+
// layout, and the markers are gone with the comments — so prove ownership
|
|
11460
|
+
// by value and then remove the settings by key. Anything that proof does
|
|
11461
|
+
// not cover keeps refusing: a changed owned value, a duplicate key, or a
|
|
11462
|
+
// shape the scoped reader will not decode.
|
|
11463
|
+
if (text.includes(routeBlock)) {
|
|
11464
|
+
text = text.replace(routeBlock, previousRouteLines.filter((line) => typeof line === "string").join("\n"));
|
|
11465
|
+
for (const key of ["plugin_block", "mcp_block"]) {
|
|
11466
|
+
const block = operation.owned?.[key];
|
|
11467
|
+
if (block === null || block === undefined)
|
|
11468
|
+
continue;
|
|
11469
|
+
if (typeof block !== "string" || !text.includes(block))
|
|
11470
|
+
throw new Error(`Hermes ${key.replace("_block", "")} block changed after enable; refusing destructive disable`);
|
|
11471
|
+
text = text.replace(block, "");
|
|
11472
|
+
}
|
|
11473
|
+
return Buffer.from(text);
|
|
10948
11474
|
}
|
|
10949
|
-
|
|
11475
|
+
if (!hermesRouteOwned(text, operation.owned))
|
|
11476
|
+
throw new Error("Hermes routing block changed after enable; refusing destructive disable");
|
|
11477
|
+
// An absent block is a journal that never wrote one: nothing of ours to
|
|
11478
|
+
// prove and nothing to remove, exactly as the literal loop above skips it.
|
|
11479
|
+
if (operation.owned?.plugin_block !== undefined && !hermesPluginOwned(text, operation.owned))
|
|
11480
|
+
throw new Error("Hermes plugin block changed after enable; refusing destructive disable");
|
|
11481
|
+
if (operation.owned?.mcp_block !== undefined && !hermesMcpOwned(text, operation.owned))
|
|
11482
|
+
throw new Error("Hermes mcp block changed after enable; refusing destructive disable");
|
|
11483
|
+
return Buffer.from(hermesRestoreOwnedByValue(text, operation.owned));
|
|
10950
11484
|
}
|
|
10951
11485
|
const rootBlock = operation.owned?.root_block;
|
|
10952
11486
|
const tablesBlock = operation.owned?.tables_block;
|
|
@@ -11410,10 +11944,15 @@ function nativeIntegrationStatus(agent, { probe = true } = {}) {
|
|
|
11410
11944
|
owned = CODEX_NATIVE_TABLES.every((table) => tables.get(table) === true) && codexNativeRouted(lines) && text.indexOf("\uFEFF", 1) === -1;
|
|
11411
11945
|
}
|
|
11412
11946
|
else if (operation.kind === "hermes-config") {
|
|
11947
|
+
// By name and value, like codex-config above and for the same reason:
|
|
11948
|
+
// a YAML round-trip that changes no value at all drops our marker
|
|
11949
|
+
// comments and renormalises quoting, and a literal read called that
|
|
11950
|
+
// drift (#1410).
|
|
11413
11951
|
const text = current.toString("utf8");
|
|
11414
|
-
owned = typeof operation.owned?.route_block === "string"
|
|
11415
|
-
&& (
|
|
11416
|
-
&& (
|
|
11952
|
+
owned = typeof operation.owned?.route_block === "string"
|
|
11953
|
+
&& hermesRouteOwned(text, operation.owned)
|
|
11954
|
+
&& hermesPluginOwned(text, operation.owned)
|
|
11955
|
+
&& hermesMcpOwned(text, operation.owned);
|
|
11417
11956
|
}
|
|
11418
11957
|
else if (operation.kind === "gemini-settings") {
|
|
11419
11958
|
const root = parseJsonFileObject(operation.file, current);
|
|
@@ -11473,11 +12012,16 @@ function nativeIntegrationStatus(agent, { probe = true } = {}) {
|
|
|
11473
12012
|
const coreResolution = runtimeConfig.resolution.values["think.core"];
|
|
11474
12013
|
const coreConfigured = coreResolution.value === true;
|
|
11475
12014
|
const mcp = probeMcpBinary();
|
|
11476
|
-
const expectedRoute = agent === "codex"
|
|
11477
|
-
? codexGatewayBase(gatewayURL(), detectCodexWrapAuthMode() === "subscription")
|
|
11478
|
-
: appendUrlPath(gatewayURL(), agent === "claude" ? "/w/claude" : agent === "hermes" ? "/w/hermes/v1" : agent === "gemini" ? "/w/gemini" : agent === "pi" ? "/w/pi" : "/w/aider/openai/v1");
|
|
11479
12015
|
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";
|
|
11480
12016
|
const routeOperation = journal?.operations.find((operation) => operation.kind === routeKind);
|
|
12017
|
+
// Hermes has two routes: the generic one, and `/chatgpt` for an install that
|
|
12018
|
+
// kept a named OAuth provider. The journal records which, so doctor expects
|
|
12019
|
+
// the route this install actually wrote rather than one of them always.
|
|
12020
|
+
const expectedRoute = agent === "codex"
|
|
12021
|
+
? codexGatewayBase(gatewayURL(), detectCodexWrapAuthMode() === "subscription")
|
|
12022
|
+
: agent === "hermes"
|
|
12023
|
+
? hermesGatewayBase(gatewayURL(), typeof routeOperation?.owned?.provider === "string" ? routeOperation.owned.provider : null)
|
|
12024
|
+
: appendUrlPath(gatewayURL(), agent === "claude" ? "/w/claude" : agent === "gemini" ? "/w/gemini" : agent === "pi" ? "/w/pi" : "/w/aider/openai/v1");
|
|
11481
12025
|
// Pi's artifact encodes no route: the extension resolves the gateway at
|
|
11482
12026
|
// runtime through the same env → config → default chain as gatewayURL(), so
|
|
11483
12027
|
// route drift between enable and now cannot happen. What CAN drift is the
|
|
@@ -11507,6 +12051,12 @@ function nativeIntegrationStatus(agent, { probe = true } = {}) {
|
|
|
11507
12051
|
// An unreadable version cannot vouch for a single-API file (an old V1 install
|
|
11508
12052
|
// on a 2.x host whose probe times out); repair rewrites it as the file both
|
|
11509
12053
|
// majors load, which reads current whatever the version.
|
|
12054
|
+
//
|
|
12055
|
+
// Neither can ONE readable version when the machine has two of them: the same
|
|
12056
|
+
// drift arrives sideways when a second bin shows up rather than when the first
|
|
12057
|
+
// one upgrades (`opencode` stays 1.19.3, `opencode2` is new, and the shared
|
|
12058
|
+
// plugins dir now has a host that refuses the installed file — #1316). So the
|
|
12059
|
+
// question is the full set of installed majors, exactly as it is for emission.
|
|
11510
12060
|
const opencodePluginApiCurrent = agent !== "opencode" || (() => {
|
|
11511
12061
|
const operation = journal?.operations.find((item) => item.kind === "opencode-plugin");
|
|
11512
12062
|
const current = operation ? fileBytes(operation.file)?.toString("utf8") : null;
|
|
@@ -11514,19 +12064,24 @@ function nativeIntegrationStatus(agent, { probe = true } = {}) {
|
|
|
11514
12064
|
return true;
|
|
11515
12065
|
const installedV2 = current.includes("async setup(ctx)");
|
|
11516
12066
|
const installedV1 = current.includes("export const CavemanNative");
|
|
12067
|
+
// Both markers (the dual file) or neither: nothing is pinned to one API.
|
|
11517
12068
|
if (installedV1 === installedV2)
|
|
11518
12069
|
return true;
|
|
11519
|
-
const
|
|
11520
|
-
if (
|
|
12070
|
+
const majors = opencodePluginMajors();
|
|
12071
|
+
if (majors.length !== 1)
|
|
11521
12072
|
return false;
|
|
11522
|
-
return (
|
|
12073
|
+
return (majors[0] >= 2) === installedV2;
|
|
11523
12074
|
})();
|
|
11524
12075
|
const routeHealthy = ownedHealthy && (agent === "opencode"
|
|
11525
12076
|
? Object.entries(opencodeNativeRoutes(gatewayURL())).every(([providerID, route]) => routeOperation?.owned?.routes?.[providerID] === route)
|
|
11526
12077
|
// Claude journals one route per profile; each has to be the current one.
|
|
11527
12078
|
: agent === "pi" ? piBundleCurrent : Boolean(routeOperation) && journal.operations.every((operation) => operation.kind !== routeKind || operation.owned?.route === expectedRoute));
|
|
11528
12079
|
const proxyHealthy = wrapMode(gatewayURL()) === "managed" || Boolean(probeProxyVersion()?.capabilities.includes("native_runtime_v1"));
|
|
11529
|
-
|
|
12080
|
+
// Recovery is real only when a current caveman-mcp is resolvable AND the
|
|
12081
|
+
// command the host will actually launch still exists. Both the component
|
|
12082
|
+
// below and this verdict read the one term, so they cannot disagree.
|
|
12083
|
+
const mcpLaunchable = Boolean(mcp?.probe.current) && journaledMcpTargetsExist(journal);
|
|
12084
|
+
const recoveryHealthy = agent === "aider" || mcpLaunchable;
|
|
11530
12085
|
const state = !available ? "unavailable" : transactionPending ? "degraded" : !installed ? "available" : !packCurrent || !ownedHealthy || !routeHealthy || !proxyHealthy || !recoveryHealthy || !opencodePluginApiCurrent || unwiredProfiles.length > 0 ? "degraded" : "installed";
|
|
11531
12086
|
const coreSupported = agent === "aider" ? ownedHealthy : ownedHealthy && Boolean(NATIVE_PACK.core);
|
|
11532
12087
|
// Codex runs none of the hooks until the user trusts them; Core rides on them.
|
|
@@ -11561,12 +12116,17 @@ function nativeIntegrationStatus(agent, { probe = true } = {}) {
|
|
|
11561
12116
|
if (own?.routed)
|
|
11562
12117
|
warnings.push(ownEndpointRoutedMessage(agent, own));
|
|
11563
12118
|
const fileText = checks.map((check) => fileBytes(check.file)?.toString("utf8") ?? "").join("\n");
|
|
12119
|
+
// Hermes reads its routing by PARSING the document, so it gets the config
|
|
12120
|
+
// file on its own rather than every journalled file concatenated: a `model:`
|
|
12121
|
+
// or `mcp_servers:` key appearing in the plugin manifest later must not be
|
|
12122
|
+
// able to answer for the one in config.yaml.
|
|
12123
|
+
const hermesRouteFileText = agent === "hermes" && routeOperation ? fileBytes(routeOperation.file)?.toString("utf8") ?? "" : "";
|
|
11564
12124
|
const components = {
|
|
11565
|
-
routing: routeHealthy && proxyHealthy && (agent === "claude" ? fileText.includes("ANTHROPIC_BASE_URL") : agent === "codex" ? fileText.includes("model_providers.caveman") : agent === "hermes" ?
|
|
12125
|
+
routing: routeHealthy && proxyHealthy && (agent === "claude" ? fileText.includes("ANTHROPIC_BASE_URL") : agent === "codex" ? fileText.includes("model_providers.caveman") : agent === "hermes" ? hermesRouteOwned(hermesRouteFileText, routeOperation?.owned) : 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)),
|
|
11566
12126
|
// A plugin the host cannot load runs no hooks, whatever its bytes hash to.
|
|
11567
12127
|
lifecycle_hooks: agent !== "aider" && ownedHealthy && opencodePluginApiCurrent && hooksTrusted,
|
|
11568
12128
|
core: coreActive,
|
|
11569
|
-
mcp_recovery: agent !== "aider" && ownedHealthy &&
|
|
12129
|
+
mcp_recovery: agent !== "aider" && ownedHealthy && mcpLaunchable,
|
|
11570
12130
|
// Codex is false for the same reason hermes is: no command rewrite happens.
|
|
11571
12131
|
// Since #1037 shrinkHook declines every Codex tool event, so Codex gets no
|
|
11572
12132
|
// shrink-hook entry; an older install's entry reads degraded until --fix.
|
|
@@ -11679,7 +12239,7 @@ async function nativeDoctor(argv) {
|
|
|
11679
12239
|
enableNative([target]);
|
|
11680
12240
|
fixResult = "enabled";
|
|
11681
12241
|
}
|
|
11682
|
-
else if (before.state === "installed" && !agentStaleRoute(target)) {
|
|
12242
|
+
else if (before.state === "installed" && !agentStaleRoute(target) && !geminiAuthUndecided(target)) {
|
|
11683
12243
|
fixResult = "not_needed";
|
|
11684
12244
|
}
|
|
11685
12245
|
else {
|
|
@@ -12103,6 +12663,11 @@ function applyConfigFileInjection(env, agent, inj, gw, modeGw = gw, mcpMode = "a
|
|
|
12103
12663
|
function cleanupWrapTempDirs() {
|
|
12104
12664
|
for (const dir of [...wrapTempDirs]) {
|
|
12105
12665
|
try {
|
|
12666
|
+
const syncTarget = hermesEphemeralSyncPairs.get(dir);
|
|
12667
|
+
if (syncTarget) {
|
|
12668
|
+
syncBackHermesEphemeralHome(dir, syncTarget);
|
|
12669
|
+
hermesEphemeralSyncPairs.delete(dir);
|
|
12670
|
+
}
|
|
12106
12671
|
rmSync(dir, { recursive: true, force: true });
|
|
12107
12672
|
}
|
|
12108
12673
|
catch {
|
|
@@ -13015,7 +13580,7 @@ function readLocalScanState() {
|
|
|
13015
13580
|
}
|
|
13016
13581
|
// dbFingerprint returns a stable identity for THIS local spend DB so the sync
|
|
13017
13582
|
// high-water mark is scoped to the specific database it was measured against.
|
|
13018
|
-
// If the DB is deleted and recreated (
|
|
13583
|
+
// If the DB is deleted and recreated (for example ~/.caveman is wiped),
|
|
13019
13584
|
// SQLite rowids restart at 1; without a per-DB fingerprint the stale watermark
|
|
13020
13585
|
// in ~/.caveman-cloud/sync.json would make `WHERE id > watermark` skip every new
|
|
13021
13586
|
// span forever. We persist a random UUID in a CLI-owned marker table on the
|
|
@@ -13192,7 +13757,7 @@ function localScanSyncLine(out) {
|
|
|
13192
13757
|
return `synced 30-day local scan · inferred token summary · separate from gateway spend and verified savings${destination}`;
|
|
13193
13758
|
}
|
|
13194
13759
|
// syncRequestSpan converts one local `requests` row into a caveman-jsonl span
|
|
13195
|
-
// line (Caveman
|
|
13760
|
+
// line (the Caveman Cloud importer's Span shape; timestamps are already in
|
|
13196
13761
|
// the ClickHouse layout because the proxy writes them that way). The basis and
|
|
13197
13762
|
// per-row inferred savings ride in attributes — the spans schema has no savings
|
|
13198
13763
|
// column, and imported rows must never look like verified ledger entries.
|
|
@@ -13850,8 +14415,9 @@ function nativeMcpRegistered(agent) {
|
|
|
13850
14415
|
if (agent === "codex")
|
|
13851
14416
|
return typeof operation.owned?.tables_block === "string" && codexNativeTables(codexTomlLines(current.toString("utf8")), operation.owned.tables_block).get("mcp_servers.caveman") === true;
|
|
13852
14417
|
// A null block: the user's own caveman-native entry was already there.
|
|
14418
|
+
// Read by value, so a reserialised config still counts (#1410).
|
|
13853
14419
|
if (agent === "hermes")
|
|
13854
|
-
return
|
|
14420
|
+
return hermesMcpOwned(current.toString("utf8"), operation.owned);
|
|
13855
14421
|
if (agent === "pi")
|
|
13856
14422
|
return current.toString("utf8").includes("caveman:native-pi");
|
|
13857
14423
|
const servers = objectValue(parseJsonFileObject(operation.file, current).mcpServers);
|
|
@@ -14000,6 +14566,36 @@ function stripMarkedBlock(text, begin, end) {
|
|
|
14000
14566
|
}
|
|
14001
14567
|
return { text: yamlText(kept), removed };
|
|
14002
14568
|
}
|
|
14569
|
+
// A YAML stream may open with `%`-directives and a `---` marker, which is what
|
|
14570
|
+
// Hermes itself writes. Content must go AFTER them: a directive that follows
|
|
14571
|
+
// content opens a second document, and `yaml.safe_load` then fails with
|
|
14572
|
+
// "expected a single document in the stream" (#1405). Leading comments are
|
|
14573
|
+
// skipped too, so a header comment keeps describing the file.
|
|
14574
|
+
function yamlBodyStart(lines) {
|
|
14575
|
+
let i = 0;
|
|
14576
|
+
while (i < lines.length && (/^\s*(?:#.*)?$/.test(lines[i]) || /^%/.test(lines[i])))
|
|
14577
|
+
i++;
|
|
14578
|
+
if (i < lines.length && /^---(?:\s|$)/.test(lines[i]))
|
|
14579
|
+
i++;
|
|
14580
|
+
return i;
|
|
14581
|
+
}
|
|
14582
|
+
// Indent of the sequence items already under `lines[keyAt]`, so an inserted
|
|
14583
|
+
// entry joins its siblings instead of opening a deeper block. Hermes writes
|
|
14584
|
+
// two-space items; a fixed four-space insert into one of those lists is a
|
|
14585
|
+
// "expected <block end>, but found '-'" parse error (#1405). null when the
|
|
14586
|
+
// list is empty or the shape is not a plain block sequence.
|
|
14587
|
+
function yamlListItemIndent(lines, keyAt, end) {
|
|
14588
|
+
for (let i = keyAt + 1; i < end; i++) {
|
|
14589
|
+
const line = lines[i];
|
|
14590
|
+
if (/^\s*(?:#.*)?$/.test(line))
|
|
14591
|
+
continue;
|
|
14592
|
+
const item = line.match(/^(\s+)- /);
|
|
14593
|
+
if (item)
|
|
14594
|
+
return item[1].length;
|
|
14595
|
+
return null;
|
|
14596
|
+
}
|
|
14597
|
+
return null;
|
|
14598
|
+
}
|
|
14003
14599
|
function topLevelSection(lines, key) {
|
|
14004
14600
|
const start = lines.findIndex((line) => new RegExp(`^${key}:\\s*(?:#.*)?$`).test(line));
|
|
14005
14601
|
if (start < 0)
|
|
@@ -14021,6 +14617,401 @@ function sectionHasChildKey(lines, section, key) {
|
|
|
14021
14617
|
}
|
|
14022
14618
|
return false;
|
|
14023
14619
|
}
|
|
14620
|
+
// #1410: Hermes ownership used to be keyed on the literal comment-delimited
|
|
14621
|
+
// blocks we wrote into config.yaml. Any YAML round-trip — an editor, a config
|
|
14622
|
+
// manager, `yaml.safe_dump` — drops comments and renormalises quoting and
|
|
14623
|
+
// indentation without changing one value, and every check then read the install
|
|
14624
|
+
// as gone: `doctor hermes` said `degraded`, and `doctor --fix` and `disable`
|
|
14625
|
+
// both refused to touch it, so the user could not uninstall. Codex's branch
|
|
14626
|
+
// already compares by name and value for exactly this reason (its own rewrites
|
|
14627
|
+
// of the file must not read as drift); the readers below let Hermes do the same.
|
|
14628
|
+
//
|
|
14629
|
+
// Only the scalar shapes a normaliser emits are decoded. A flow collection, a
|
|
14630
|
+
// block scalar, an anchor, an alias or a tag returns null, and every caller
|
|
14631
|
+
// reads null as "cannot prove ownership" — so an unparsed shape keeps today's
|
|
14632
|
+
// refusal rather than guessing at a destructive restore.
|
|
14633
|
+
function decodeYamlDoubleQuoted(body) {
|
|
14634
|
+
const simple = {
|
|
14635
|
+
"0": "\0", a: "\x07", b: "\b", t: "\t", "\t": "\t", n: "\n", v: "\v", f: "\f",
|
|
14636
|
+
r: "\r", e: "\x1b", " ": " ", '"': '"', "/": "/", "\\": "\\",
|
|
14637
|
+
N: "\u0085", _: " ", L: "
", P: "
",
|
|
14638
|
+
};
|
|
14639
|
+
let out = "";
|
|
14640
|
+
for (let i = 0; i < body.length; i++) {
|
|
14641
|
+
const ch = body[i];
|
|
14642
|
+
if (ch !== "\\") {
|
|
14643
|
+
out += ch;
|
|
14644
|
+
continue;
|
|
14645
|
+
}
|
|
14646
|
+
const esc = body[++i];
|
|
14647
|
+
if (esc === undefined)
|
|
14648
|
+
return null;
|
|
14649
|
+
if (esc === "x" || esc === "u" || esc === "U") {
|
|
14650
|
+
const width = esc === "x" ? 2 : esc === "u" ? 4 : 8;
|
|
14651
|
+
const hex = body.slice(i + 1, i + 1 + width);
|
|
14652
|
+
if (hex.length !== width || !/^[0-9a-fA-F]+$/.test(hex))
|
|
14653
|
+
return null;
|
|
14654
|
+
const code = parseInt(hex, 16);
|
|
14655
|
+
if (code > 0x10ffff)
|
|
14656
|
+
return null;
|
|
14657
|
+
out += String.fromCodePoint(code);
|
|
14658
|
+
i += width;
|
|
14659
|
+
continue;
|
|
14660
|
+
}
|
|
14661
|
+
const mapped = simple[esc];
|
|
14662
|
+
if (mapped === undefined)
|
|
14663
|
+
return null;
|
|
14664
|
+
out += mapped;
|
|
14665
|
+
}
|
|
14666
|
+
return out;
|
|
14667
|
+
}
|
|
14668
|
+
// The scalar of `key:` at lines[index], as a YAML loader would read it, plus the
|
|
14669
|
+
// index of the last line it spans. A quoted scalar may be folded across lines:
|
|
14670
|
+
// a plain line break folds to one space, a `\` at end of line inside double
|
|
14671
|
+
// quotes joins with none — both are shapes PyYAML emits past its 80-column
|
|
14672
|
+
// width. `null` means "not a scalar this reader decodes".
|
|
14673
|
+
function yamlScalarAfterKey(lines, index) {
|
|
14674
|
+
const line = lines[index];
|
|
14675
|
+
if (line === undefined)
|
|
14676
|
+
return { value: null, last: index };
|
|
14677
|
+
const raw = line.slice(line.indexOf(":") + 1);
|
|
14678
|
+
const head = raw.replace(/^[ \t]+/, "");
|
|
14679
|
+
// An empty value is YAML's null. Kept as "" so a caller comparing it against
|
|
14680
|
+
// a journalled route simply finds no match (an empty endpoint is restorable,
|
|
14681
|
+
// never owned), without being mistaken for an unreadable shape.
|
|
14682
|
+
if (head === "" || /^#/.test(head))
|
|
14683
|
+
return { value: "", last: index };
|
|
14684
|
+
if (/^[[{|>&*!]/.test(head))
|
|
14685
|
+
return { value: null, last: index };
|
|
14686
|
+
const quote = head[0];
|
|
14687
|
+
if (quote !== '"' && quote !== "'") {
|
|
14688
|
+
let plain = head.replace(/\s+#.*$/, "").trimEnd();
|
|
14689
|
+
const keyIndent = line.length - line.replace(/^[ \t]*/, "").length;
|
|
14690
|
+
let row = index;
|
|
14691
|
+
// A long plain scalar is folded onto more-indented continuation lines, each
|
|
14692
|
+
// break folding to one space — what PyYAML emits past its 80-column width
|
|
14693
|
+
// for a value with spaces in it, such as an executable path. A plain scalar
|
|
14694
|
+
// cannot contain ": ", so a line that reads as a key or a sequence item is
|
|
14695
|
+
// the next node and ends this one.
|
|
14696
|
+
while (row + 1 < lines.length) {
|
|
14697
|
+
const next = lines[row + 1];
|
|
14698
|
+
if (/^\s*(?:#.*)?$/.test(next))
|
|
14699
|
+
break;
|
|
14700
|
+
if (next.length - next.replace(/^[ \t]*/, "").length <= keyIndent)
|
|
14701
|
+
break;
|
|
14702
|
+
const body = next.trim();
|
|
14703
|
+
if (/^-(?:\s|$)/.test(body) || /:(?:\s|$)/.test(body))
|
|
14704
|
+
break;
|
|
14705
|
+
plain = `${plain} ${body.replace(/\s+#.*$/, "").trimEnd()}`;
|
|
14706
|
+
row += 1;
|
|
14707
|
+
}
|
|
14708
|
+
return { value: plain, last: row };
|
|
14709
|
+
}
|
|
14710
|
+
let body = "";
|
|
14711
|
+
let segment = head.slice(1);
|
|
14712
|
+
let at = index;
|
|
14713
|
+
// Bounded: a scalar may not outrun the document.
|
|
14714
|
+
for (;;) {
|
|
14715
|
+
let closed = -1;
|
|
14716
|
+
for (let i = 0; i < segment.length; i++) {
|
|
14717
|
+
if (quote === '"' && segment[i] === "\\") {
|
|
14718
|
+
i++;
|
|
14719
|
+
continue;
|
|
14720
|
+
}
|
|
14721
|
+
if (segment[i] !== quote)
|
|
14722
|
+
continue;
|
|
14723
|
+
if (quote === "'" && segment[i + 1] === "'") {
|
|
14724
|
+
i++;
|
|
14725
|
+
continue;
|
|
14726
|
+
}
|
|
14727
|
+
closed = i;
|
|
14728
|
+
break;
|
|
14729
|
+
}
|
|
14730
|
+
if (closed >= 0) {
|
|
14731
|
+
body += segment.slice(0, closed);
|
|
14732
|
+
break;
|
|
14733
|
+
}
|
|
14734
|
+
if (quote === '"' && /\\$/.test(segment))
|
|
14735
|
+
body += segment.slice(0, -1);
|
|
14736
|
+
else
|
|
14737
|
+
body += `${segment.replace(/[ \t]+$/, "")}\n`;
|
|
14738
|
+
at += 1;
|
|
14739
|
+
if (at >= lines.length)
|
|
14740
|
+
return { value: null, last: index };
|
|
14741
|
+
segment = lines[at].replace(/^[ \t]+/, "");
|
|
14742
|
+
}
|
|
14743
|
+
// A raw newline can only be a fold marker added above: YAML folds it to one
|
|
14744
|
+
// space. Escape decoding runs after, so a `\n` ESCAPE stays a newline.
|
|
14745
|
+
const folded = body.replace(/\n/g, " ");
|
|
14746
|
+
if (quote === "'")
|
|
14747
|
+
return { value: folded.replace(/''/g, "'"), last: at };
|
|
14748
|
+
const decoded = decodeYamlDoubleQuoted(folded);
|
|
14749
|
+
return { value: decoded, last: decoded === null ? index : at };
|
|
14750
|
+
}
|
|
14751
|
+
// Direct children of a block mapping: `{ key → scalar }` at the shallowest
|
|
14752
|
+
// indent in the section, so a reindented document reads the same as the one we
|
|
14753
|
+
// wrote. `null` when a key repeats (a duplicate key is the ambiguous shape
|
|
14754
|
+
// #1410 asks us to keep refusing) or when a child is not a scalar this reader
|
|
14755
|
+
// decodes.
|
|
14756
|
+
function yamlMappingChildren(lines, start, end) {
|
|
14757
|
+
let indent = null;
|
|
14758
|
+
for (let i = start; i < end; i++) {
|
|
14759
|
+
const line = lines[i];
|
|
14760
|
+
if (/^\s*(?:#.*)?$/.test(line))
|
|
14761
|
+
continue;
|
|
14762
|
+
const width = line.length - line.replace(/^[ \t]*/, "").length;
|
|
14763
|
+
if (indent === null || width < indent)
|
|
14764
|
+
indent = width;
|
|
14765
|
+
}
|
|
14766
|
+
if (indent === null)
|
|
14767
|
+
return new Map();
|
|
14768
|
+
const children = new Map();
|
|
14769
|
+
const key = new RegExp(`^[ \\t]{${indent}}(["']?)([^:"'\\s][^:"']*)\\1\\s*:(?=\\s|$)`);
|
|
14770
|
+
for (let i = start; i < end; i++) {
|
|
14771
|
+
const line = lines[i];
|
|
14772
|
+
if (/^\s*(?:#.*)?$/.test(line))
|
|
14773
|
+
continue;
|
|
14774
|
+
const width = line.length - line.replace(/^[ \t]*/, "").length;
|
|
14775
|
+
if (width !== indent)
|
|
14776
|
+
continue;
|
|
14777
|
+
const match = key.exec(line);
|
|
14778
|
+
if (!match)
|
|
14779
|
+
continue;
|
|
14780
|
+
const name = match[2];
|
|
14781
|
+
if (children.has(name))
|
|
14782
|
+
return null;
|
|
14783
|
+
const scalar = yamlScalarAfterKey(lines, i);
|
|
14784
|
+
if (scalar.value === null)
|
|
14785
|
+
return null;
|
|
14786
|
+
children.set(name, scalar.value);
|
|
14787
|
+
i = scalar.last;
|
|
14788
|
+
}
|
|
14789
|
+
return children;
|
|
14790
|
+
}
|
|
14791
|
+
// Span of the direct child `name` inside [start, end): its own line through the
|
|
14792
|
+
// last line indented deeper than it.
|
|
14793
|
+
function yamlChildSpan(lines, start, end, name) {
|
|
14794
|
+
let indent = null;
|
|
14795
|
+
for (let i = start; i < end; i++) {
|
|
14796
|
+
const line = lines[i];
|
|
14797
|
+
if (/^\s*(?:#.*)?$/.test(line))
|
|
14798
|
+
continue;
|
|
14799
|
+
const width = line.length - line.replace(/^[ \t]*/, "").length;
|
|
14800
|
+
if (indent === null || width < indent)
|
|
14801
|
+
indent = width;
|
|
14802
|
+
}
|
|
14803
|
+
if (indent === null)
|
|
14804
|
+
return null;
|
|
14805
|
+
const key = new RegExp(`^[ \\t]{${indent}}(["']?)${escapeRegExp(name)}\\1\\s*:(?=\\s|$)`);
|
|
14806
|
+
for (let i = start; i < end; i++) {
|
|
14807
|
+
if (/^\s*(?:#.*)?$/.test(lines[i]))
|
|
14808
|
+
continue;
|
|
14809
|
+
if (!key.test(lines[i]))
|
|
14810
|
+
continue;
|
|
14811
|
+
let last = i;
|
|
14812
|
+
for (let j = i + 1; j < end; j++) {
|
|
14813
|
+
const line = lines[j];
|
|
14814
|
+
if (/^\s*(?:#.*)?$/.test(line))
|
|
14815
|
+
continue;
|
|
14816
|
+
const width = line.length - line.replace(/^[ \t]*/, "").length;
|
|
14817
|
+
if (width <= indent)
|
|
14818
|
+
break;
|
|
14819
|
+
// A child's quoted scalar may be folded onto continuation lines, and one
|
|
14820
|
+
// of those can begin with `#`. Reading the value keeps those lines
|
|
14821
|
+
// attributed to their key; skipping them as comments left them outside
|
|
14822
|
+
// the span, so removing the block spliced out everything around an
|
|
14823
|
+
// orphaned fragment and produced a config that no longer parses.
|
|
14824
|
+
const scalar = /:(?:\s|$)/.test(line) ? yamlScalarAfterKey(lines, j) : null;
|
|
14825
|
+
last = scalar ? Math.max(j, scalar.last) : j;
|
|
14826
|
+
if (scalar)
|
|
14827
|
+
j = last;
|
|
14828
|
+
}
|
|
14829
|
+
return { start: i, end: last + 1 };
|
|
14830
|
+
}
|
|
14831
|
+
return null;
|
|
14832
|
+
}
|
|
14833
|
+
// What a Hermes config.yaml actually SAYS about the settings Caveman owns,
|
|
14834
|
+
// independent of how it is laid out. `model` and the `caveman-native` MCP entry
|
|
14835
|
+
// are read as values; plugin membership has its own layout-independent reader
|
|
14836
|
+
// in hermesPluginListContains.
|
|
14837
|
+
function hermesOwnedValues(text) {
|
|
14838
|
+
const lines = yamlLines(text);
|
|
14839
|
+
const model = topLevelSection(lines, "model");
|
|
14840
|
+
const servers = topLevelSection(lines, "mcp_servers");
|
|
14841
|
+
const native = servers ? yamlChildSpan(lines, servers.start + 1, servers.end, HERMES_NATIVE_MCP_SERVER) : null;
|
|
14842
|
+
return {
|
|
14843
|
+
model: model ? yamlMappingChildren(lines, model.start + 1, model.end) : null,
|
|
14844
|
+
mcp: native ? yamlMappingChildren(lines, native.start + 1, native.end) : null,
|
|
14845
|
+
};
|
|
14846
|
+
}
|
|
14847
|
+
// The `command` the journalled MCP block registered, read back out of the block
|
|
14848
|
+
// itself so no journal format change is needed: an install made before this fix
|
|
14849
|
+
// is checked by value too.
|
|
14850
|
+
function hermesJournaledMcpCommand(block) {
|
|
14851
|
+
const lines = yamlLines(block);
|
|
14852
|
+
for (let i = 0; i < lines.length; i++) {
|
|
14853
|
+
if (!/^\s*command\s*:/.test(lines[i]))
|
|
14854
|
+
continue;
|
|
14855
|
+
return yamlScalarAfterKey(lines, i).value;
|
|
14856
|
+
}
|
|
14857
|
+
return null;
|
|
14858
|
+
}
|
|
14859
|
+
// Does this config still carry Caveman's own Hermes routing, by value?
|
|
14860
|
+
function hermesRouteOwned(text, owned) {
|
|
14861
|
+
const route = owned?.route;
|
|
14862
|
+
if (typeof route !== "string")
|
|
14863
|
+
return false;
|
|
14864
|
+
// Journals written before #1391 carry no provider; those installs wrote the
|
|
14865
|
+
// generic one, which is what the enable path recorded from then on.
|
|
14866
|
+
const provider = typeof owned?.provider === "string" ? owned.provider : "custom";
|
|
14867
|
+
const values = hermesOwnedValues(text).model;
|
|
14868
|
+
return values?.get("base_url") === route && values.get("provider") === provider;
|
|
14869
|
+
}
|
|
14870
|
+
// Is the journalled `caveman-native` MCP server still registered, by value? A
|
|
14871
|
+
// null block means the user's own entry was already there, which disable never
|
|
14872
|
+
// owned and so never has to prove.
|
|
14873
|
+
function hermesMcpOwned(text, owned) {
|
|
14874
|
+
const block = owned?.mcp_block;
|
|
14875
|
+
if (block === null)
|
|
14876
|
+
return true;
|
|
14877
|
+
if (typeof block !== "string")
|
|
14878
|
+
return false;
|
|
14879
|
+
if (text.includes(block))
|
|
14880
|
+
return true;
|
|
14881
|
+
const command = hermesJournaledMcpCommand(block);
|
|
14882
|
+
if (command === null)
|
|
14883
|
+
return false;
|
|
14884
|
+
const values = hermesOwnedValues(text).mcp;
|
|
14885
|
+
return values?.get("command") === command && values.get("enabled") === "true";
|
|
14886
|
+
}
|
|
14887
|
+
// Is the journalled `caveman_native` plugin still enabled? Same null rule.
|
|
14888
|
+
//
|
|
14889
|
+
// This asks whether OUR entry is still in plugins.enabled, which is a different
|
|
14890
|
+
// question from whether Hermes would load the plugin: a user who ALSO lists the
|
|
14891
|
+
// name under plugins.disabled has not taken our entry away, and disable still
|
|
14892
|
+
// has to reverse it. So this reads the enabled list directly rather than going
|
|
14893
|
+
// through hermesNamedPluginMembership, whose disabled-first precedence answers
|
|
14894
|
+
// the load question. It inherits the exact-scalar, plugins-scoped matching
|
|
14895
|
+
// either way, so a `caveman_native_extra` entry no longer passes for ours.
|
|
14896
|
+
function hermesPluginOwned(text, owned) {
|
|
14897
|
+
const block = owned?.plugin_block;
|
|
14898
|
+
if (block === null)
|
|
14899
|
+
return true;
|
|
14900
|
+
if (typeof block !== "string")
|
|
14901
|
+
return false;
|
|
14902
|
+
return hermesPluginListContains(text, "enabled", HERMES_NATIVE_PLUGIN_NAME);
|
|
14903
|
+
}
|
|
14904
|
+
// Indent shared by the direct children of [start, end), or null when there are
|
|
14905
|
+
// none — the width an inserted sibling has to take in THIS document.
|
|
14906
|
+
function yamlChildIndent(lines, start, end) {
|
|
14907
|
+
let indent = null;
|
|
14908
|
+
for (let i = start; i < end; i++) {
|
|
14909
|
+
const line = lines[i];
|
|
14910
|
+
if (/^\s*(?:#.*)?$/.test(line))
|
|
14911
|
+
continue;
|
|
14912
|
+
const width = line.length - line.replace(/^[ \t]*/, "").length;
|
|
14913
|
+
if (indent === null || width < indent)
|
|
14914
|
+
indent = width;
|
|
14915
|
+
}
|
|
14916
|
+
return indent;
|
|
14917
|
+
}
|
|
14918
|
+
// Undo Caveman's Hermes settings on a document whose layout no longer matches
|
|
14919
|
+
// the journalled blocks (#1410). Only ever reached once hermesRouteOwned,
|
|
14920
|
+
// hermesPluginOwned and hermesMcpOwned have all proved, by value, that what is
|
|
14921
|
+
// in the file is still ours — so this removes Caveman's own settings and leaves
|
|
14922
|
+
// every unrelated sibling, comment and key where it is. Each removal mirrors
|
|
14923
|
+
// the shape of the block that was written: an entry we added to a list the user
|
|
14924
|
+
// already had takes the list with it only if we created the list too.
|
|
14925
|
+
function hermesRestoreOwnedByValue(text, owned) {
|
|
14926
|
+
const lines = yamlLines(text);
|
|
14927
|
+
const previous = (Array.isArray(owned?.previous_route_lines) ? owned.previous_route_lines : [])
|
|
14928
|
+
.filter((line) => typeof line === "string");
|
|
14929
|
+
// --- routing: our provider/base_url go, the user's come back ---
|
|
14930
|
+
const model = topLevelSection(lines, "model");
|
|
14931
|
+
if (!model)
|
|
14932
|
+
throw new Error("Hermes model section is gone; refusing destructive disable");
|
|
14933
|
+
const modelIndent = yamlChildIndent(lines, model.start + 1, model.end);
|
|
14934
|
+
if (modelIndent === null)
|
|
14935
|
+
throw new Error("Hermes model section is empty; refusing destructive disable");
|
|
14936
|
+
const ownedRouteRows = [];
|
|
14937
|
+
for (let i = model.start + 1; i < model.end; i++) {
|
|
14938
|
+
const line = lines[i];
|
|
14939
|
+
if (/^\s*(?:#.*)?$/.test(line))
|
|
14940
|
+
continue;
|
|
14941
|
+
const width = line.length - line.replace(/^[ \t]*/, "").length;
|
|
14942
|
+
if (width !== modelIndent)
|
|
14943
|
+
continue;
|
|
14944
|
+
if (!new RegExp(`^[ \\t]{${modelIndent}}(["']?)(provider|base_url)\\1\\s*:(?=\\s|$)`).test(line))
|
|
14945
|
+
continue;
|
|
14946
|
+
const scalar = yamlScalarAfterKey(lines, i);
|
|
14947
|
+
for (let row = i; row <= scalar.last; row++)
|
|
14948
|
+
ownedRouteRows.push(row);
|
|
14949
|
+
i = scalar.last;
|
|
14950
|
+
}
|
|
14951
|
+
if (ownedRouteRows.length === 0)
|
|
14952
|
+
throw new Error("Hermes routing keys are gone; refusing destructive disable");
|
|
14953
|
+
const pad = " ".repeat(modelIndent);
|
|
14954
|
+
const restoredRoute = previous.map((line) => {
|
|
14955
|
+
const parsed = /^\s*(["']?)([^:"']+)\1\s*:([\s\S]*)$/.exec(line);
|
|
14956
|
+
if (!parsed)
|
|
14957
|
+
throw new Error("Hermes integration journal holds an unreadable previous routing line");
|
|
14958
|
+
return `${pad}${parsed[2]}:${parsed[3]}`;
|
|
14959
|
+
});
|
|
14960
|
+
const insertAt = ownedRouteRows[0];
|
|
14961
|
+
for (const row of [...ownedRouteRows].reverse())
|
|
14962
|
+
lines.splice(row, 1);
|
|
14963
|
+
lines.splice(insertAt, 0, ...restoredRoute);
|
|
14964
|
+
// --- plugin membership ---
|
|
14965
|
+
const pluginBlock = owned?.plugin_block;
|
|
14966
|
+
if (typeof pluginBlock === "string") {
|
|
14967
|
+
const createdSection = /^plugins:/m.test(pluginBlock);
|
|
14968
|
+
const createdEnabled = createdSection || /^\s+enabled:/m.test(pluginBlock);
|
|
14969
|
+
const plugins = topLevelSection(lines, "plugins");
|
|
14970
|
+
if (!plugins)
|
|
14971
|
+
throw new Error("Hermes plugins section is gone; refusing destructive disable");
|
|
14972
|
+
let enabledAt = -1;
|
|
14973
|
+
for (let i = plugins.start + 1; i < plugins.end; i++) {
|
|
14974
|
+
if (/^\s+enabled\s*:(?=\s|$)/.test(lines[i])) {
|
|
14975
|
+
enabledAt = i;
|
|
14976
|
+
break;
|
|
14977
|
+
}
|
|
14978
|
+
}
|
|
14979
|
+
if (enabledAt < 0)
|
|
14980
|
+
throw new Error("Hermes plugins.enabled is gone; refusing destructive disable");
|
|
14981
|
+
let itemAt = -1;
|
|
14982
|
+
for (let i = enabledAt + 1; i < plugins.end; i++) {
|
|
14983
|
+
if (new RegExp(`^\\s*-\\s*(["']?)${escapeRegExp(HERMES_NATIVE_PLUGIN_NAME)}\\1\\s*(?:#.*)?$`).test(lines[i])) {
|
|
14984
|
+
itemAt = i;
|
|
14985
|
+
break;
|
|
14986
|
+
}
|
|
14987
|
+
}
|
|
14988
|
+
if (itemAt < 0)
|
|
14989
|
+
throw new Error("Hermes plugin entry is gone; refusing destructive disable");
|
|
14990
|
+
lines.splice(itemAt, 1);
|
|
14991
|
+
if (createdEnabled)
|
|
14992
|
+
lines.splice(enabledAt, 1);
|
|
14993
|
+
if (createdSection)
|
|
14994
|
+
lines.splice(plugins.start, 1);
|
|
14995
|
+
}
|
|
14996
|
+
// --- MCP registration ---
|
|
14997
|
+
const mcpBlock = owned?.mcp_block;
|
|
14998
|
+
if (typeof mcpBlock === "string") {
|
|
14999
|
+
const createdSection = /^mcp_servers:/m.test(mcpBlock);
|
|
15000
|
+
const servers = topLevelSection(lines, "mcp_servers");
|
|
15001
|
+
if (!servers)
|
|
15002
|
+
throw new Error("Hermes mcp_servers section is gone; refusing destructive disable");
|
|
15003
|
+
const native = yamlChildSpan(lines, servers.start + 1, servers.end, HERMES_NATIVE_MCP_SERVER);
|
|
15004
|
+
if (!native)
|
|
15005
|
+
throw new Error("Hermes MCP entry is gone; refusing destructive disable");
|
|
15006
|
+
lines.splice(native.start, native.end - native.start);
|
|
15007
|
+
if (createdSection)
|
|
15008
|
+
lines.splice(servers.start, 1);
|
|
15009
|
+
}
|
|
15010
|
+
// yamlText joins with \n. The literal path edits the raw string and so keeps
|
|
15011
|
+
// whatever the file used; this one must not quietly convert a Windows user's
|
|
15012
|
+
// config to LF on the way out.
|
|
15013
|
+
return text.includes("\r\n") ? yamlText(lines).replace(/\n/g, "\r\n") : yamlText(lines);
|
|
15014
|
+
}
|
|
14024
15015
|
function hermesMcpMarkers(serverName) {
|
|
14025
15016
|
return serverName === "caveman"
|
|
14026
15017
|
? { begin: HERMES_MCP_BEGIN, end: HERMES_MCP_END }
|
|
@@ -16816,13 +17807,15 @@ function shouldShrink(command) {
|
|
|
16816
17807
|
return false;
|
|
16817
17808
|
return SHRINK_ALLOW.has(first);
|
|
16818
17809
|
}
|
|
16819
|
-
//
|
|
16820
|
-
//
|
|
16821
|
-
|
|
17810
|
+
// cavemanHookTarget resolves what a hook runs to call back into this CLI, robust
|
|
17811
|
+
// to PATH: a resolved `caveman`/`cave`, else this very script's node. Rendering it
|
|
17812
|
+
// into a command string is the caller's job, because the two callers target
|
|
17813
|
+
// different shells (see hookExecutableInvocation vs hostShellInvocation).
|
|
17814
|
+
function cavemanHookTarget() {
|
|
16822
17815
|
// Never a package runner's cached copy when a lasting one exists.
|
|
16823
17816
|
const command = durableCaveman() ?? which("caveman") ?? which("cave");
|
|
16824
17817
|
if (!command)
|
|
16825
|
-
return
|
|
17818
|
+
return { executable: stableNodePath(), script: process.argv[1] };
|
|
16826
17819
|
// npm links `caveman` to a `#!/usr/bin/env node` script, and a host started
|
|
16827
17820
|
// from a GUI or launchd often has no node on PATH (nvm, volta, Homebrew):
|
|
16828
17821
|
// run it with this node, named as the lifecycle hooks name theirs (`--node`)
|
|
@@ -16833,9 +17826,20 @@ function cavemanBinForHook(powershell = process.platform === "win32") {
|
|
|
16833
17826
|
script = hookCommandBasename(process.execPath) === "node" && /\.[cm]?js$/.test(realpathSync(command));
|
|
16834
17827
|
}
|
|
16835
17828
|
catch { /* unresolvable: run it as found */ }
|
|
16836
|
-
return script
|
|
16837
|
-
|
|
16838
|
-
|
|
17829
|
+
return script ? { executable: stableNodePath(), script: command } : { executable: command };
|
|
17830
|
+
}
|
|
17831
|
+
// cavemanBinForHook is that invocation as the HOST will dispatch it — on native
|
|
17832
|
+
// Windows the hosts run command hooks through PowerShell, which needs `&`.
|
|
17833
|
+
function cavemanBinForHook(powershell = process.platform === "win32") {
|
|
17834
|
+
const target = cavemanHookTarget();
|
|
17835
|
+
return hookExecutableInvocation(target.executable, target.script, process.platform, powershell);
|
|
17836
|
+
}
|
|
17837
|
+
// cavemanBinForHostShell is that invocation for the host's OWN shell, which we do
|
|
17838
|
+
// not know. null = no portable form; the caller must decline rather than emit a
|
|
17839
|
+
// command one of the three Windows shells cannot parse (#1263).
|
|
17840
|
+
function cavemanBinForHostShell() {
|
|
17841
|
+
const target = cavemanHookTarget();
|
|
17842
|
+
return hostShellInvocation(target.executable, target.script, process.platform);
|
|
16839
17843
|
}
|
|
16840
17844
|
// shrinkHook is the settings-hook callback for the agents whose harness can
|
|
16841
17845
|
// deterministically rewrite a shell command before it runs: Claude Code (PreToolUse,
|
|
@@ -16881,9 +17885,16 @@ async function shrinkHook() {
|
|
|
16881
17885
|
const command = evt.tool_input?.command;
|
|
16882
17886
|
if (typeof command !== "string" || !shouldShrink(command))
|
|
16883
17887
|
process.exit(0);
|
|
16884
|
-
// updatedInput.command executes in host shell
|
|
16885
|
-
//
|
|
16886
|
-
|
|
17888
|
+
// updatedInput.command executes in the host's own shell — Git Bash under Claude
|
|
17889
|
+
// Code on Windows, PowerShell under the opencode plugin, cmd.exe under Gemini —
|
|
17890
|
+
// never the hook's explicit PowerShell shell, so this prefix is rendered bare
|
|
17891
|
+
// rather than quoted or `&`-prefixed. When no form serves all three (a space in
|
|
17892
|
+
// the path), there is no rewrite: the command runs as the host sent it, which is
|
|
17893
|
+
// the same safe direction as every other decline above.
|
|
17894
|
+
const prefix = cavemanBinForHostShell();
|
|
17895
|
+
if (!prefix)
|
|
17896
|
+
process.exit(0);
|
|
17897
|
+
const rewritten = `${prefix} shrink -- ${command.trim()}`;
|
|
16887
17898
|
// Gemini merges hookSpecificOutput.tool_input (snake_case, no event discriminator);
|
|
16888
17899
|
// Claude REPLACES via hookSpecificOutput.updatedInput (camelCase + hookEventName).
|
|
16889
17900
|
// Because Claude replaces, updatedInput must carry every field the host sent —
|
|
@@ -17615,7 +18626,8 @@ async function nativeHook(argv) {
|
|
|
17615
18626
|
confirmLearnNudge(learnNudgeToken);
|
|
17616
18627
|
});
|
|
17617
18628
|
}
|
|
17618
|
-
else if (normalizedEvent === "PostCompact" && agent !== "hermes" && compactContext) {
|
|
18629
|
+
else if (normalizedEvent === "PostCompact" && agent !== "hermes" && agent !== "codex" && compactContext) {
|
|
18630
|
+
// Codex PostCompact accepts only common fields; SessionStart source=compact restores Core.
|
|
17619
18631
|
process.stdout.write(JSON.stringify({
|
|
17620
18632
|
hookSpecificOutput: { hookEventName: normalizedEvent, additionalContext: compactContext },
|
|
17621
18633
|
}));
|
|
@@ -18241,7 +19253,25 @@ export function generatedPluginInvocation(onPath, currentScript, platform = proc
|
|
|
18241
19253
|
function cavemanInvocation() {
|
|
18242
19254
|
return generatedPluginInvocation(durableCaveman() ?? which("caveman") ?? which("cave") ?? undefined, process.argv[1] ?? "");
|
|
18243
19255
|
}
|
|
19256
|
+
// OpenCode 2 replaced the plugin API: its loader requires a default export
|
|
19257
|
+
// `{ id, setup | effect }` and REJECTS a bare V1 hook map with
|
|
19258
|
+
// "Plugin must export a default definition with an id and an effect or setup
|
|
19259
|
+
// function". A V1-only shrink plugin therefore never loaded on an OpenCode 2
|
|
19260
|
+
// host while the installer still reported the hook installed (#1445).
|
|
19261
|
+
//
|
|
19262
|
+
// `caveman enable opencode` already answers this for the native plugin; the
|
|
19263
|
+
// shrink plugin shares that one decision (opencodePluginMajors) so the two
|
|
19264
|
+
// generated files can never disagree about which API the host speaks.
|
|
18244
19265
|
function opencodePluginSource() {
|
|
19266
|
+
const majors = opencodePluginMajors();
|
|
19267
|
+
if (majors.length !== 1)
|
|
19268
|
+
return opencodeShrinkPluginSourceBoth();
|
|
19269
|
+
return majors[0] < 2 ? opencodeShrinkPluginSourceV1() : opencodeShrinkPluginSourceV2();
|
|
19270
|
+
}
|
|
19271
|
+
// The shared preamble: the marker, and one `rewrite()` both APIs call. Keeping
|
|
19272
|
+
// the subprocess in a single helper is what lets the "both" file carry two hook
|
|
19273
|
+
// shapes without two copies of the byte-safety contract.
|
|
19274
|
+
function opencodeShrinkPluginPreamble() {
|
|
18245
19275
|
const { cmd, pre } = cavemanInvocation();
|
|
18246
19276
|
const argv = JSON.stringify([...pre, "shrink-hook"]);
|
|
18247
19277
|
return `// caveman:shrink-plugin — GENERATED by \`caveman hooks install opencode\`.
|
|
@@ -18249,27 +19279,71 @@ function opencodePluginSource() {
|
|
|
18249
19279
|
// with \`caveman retrieve\`). Remove with \`caveman hooks uninstall opencode\`.
|
|
18250
19280
|
import { execFileSync } from "node:child_process";
|
|
18251
19281
|
|
|
19282
|
+
// Returns the rewritten command, or undefined to leave the original alone.
|
|
19283
|
+
function rewrite(command) {
|
|
19284
|
+
if (typeof command !== "string" || !command.trim()) return undefined;
|
|
19285
|
+
try {
|
|
19286
|
+
const res = execFileSync(${JSON.stringify(cmd)}, ${argv}, {
|
|
19287
|
+
input: JSON.stringify({ tool_name: "Bash", tool_input: { command } }),
|
|
19288
|
+
encoding: "utf8",
|
|
19289
|
+
windowsHide: true,
|
|
19290
|
+
});
|
|
19291
|
+
if (!res) return undefined;
|
|
19292
|
+
const rewritten = JSON.parse(res)?.hookSpecificOutput?.updatedInput?.command;
|
|
19293
|
+
return typeof rewritten === "string" && rewritten ? rewritten : undefined;
|
|
19294
|
+
} catch {
|
|
19295
|
+
// byte-safe: any failure leaves the original command untouched.
|
|
19296
|
+
return undefined;
|
|
19297
|
+
}
|
|
19298
|
+
}
|
|
19299
|
+
`;
|
|
19300
|
+
}
|
|
19301
|
+
// V1: a named factory returning a hook map, mutating output.args.command.
|
|
19302
|
+
function opencodeShrinkPluginHookMapV1() {
|
|
19303
|
+
return `
|
|
18252
19304
|
export const CavemanShrink = async () => ({
|
|
18253
19305
|
"tool.execute.before": async (input, output) => {
|
|
18254
19306
|
if (input?.tool !== "bash") return;
|
|
18255
|
-
const
|
|
18256
|
-
if (
|
|
18257
|
-
try {
|
|
18258
|
-
const res = execFileSync(${JSON.stringify(cmd)}, ${argv}, {
|
|
18259
|
-
input: JSON.stringify({ tool_name: "Bash", tool_input: { command } }),
|
|
18260
|
-
encoding: "utf8",
|
|
18261
|
-
windowsHide: true,
|
|
18262
|
-
});
|
|
18263
|
-
if (!res) return;
|
|
18264
|
-
const rewritten = JSON.parse(res)?.hookSpecificOutput?.updatedInput?.command;
|
|
18265
|
-
if (typeof rewritten === "string" && rewritten) output.args.command = rewritten;
|
|
18266
|
-
} catch {
|
|
18267
|
-
// byte-safe: any failure leaves the original command untouched.
|
|
18268
|
-
}
|
|
19307
|
+
const next = rewrite(output?.args?.command);
|
|
19308
|
+
if (next) output.args.command = next;
|
|
18269
19309
|
},
|
|
18270
19310
|
});
|
|
18271
19311
|
`;
|
|
18272
19312
|
}
|
|
19313
|
+
// V2: default { id, setup }, registering through ctx.tool.hook and mutating
|
|
19314
|
+
// event.input.command. V1 named this tool "bash"; V2 renamed the permission
|
|
19315
|
+
// action to "shell" — accept both, as the native V2 plugin does.
|
|
19316
|
+
function opencodeShrinkPluginDefinitionV2(extra = "") {
|
|
19317
|
+
return `
|
|
19318
|
+
export default {
|
|
19319
|
+
id: "caveman-shrink",
|
|
19320
|
+
${extra} async setup(ctx) {
|
|
19321
|
+
// A 1.x host also calls setup, with a context that has no tool hook API.
|
|
19322
|
+
if (!ctx?.tool?.hook) return;
|
|
19323
|
+
await ctx.tool.hook("execute.before", (event) => {
|
|
19324
|
+
if (event?.tool !== "bash" && event?.tool !== "shell") return;
|
|
19325
|
+
const input = event.input;
|
|
19326
|
+
if (!input || typeof input !== "object") return;
|
|
19327
|
+
const next = rewrite(input.command);
|
|
19328
|
+
if (next) input.command = next;
|
|
19329
|
+
});
|
|
19330
|
+
},
|
|
19331
|
+
};
|
|
19332
|
+
`;
|
|
19333
|
+
}
|
|
19334
|
+
function opencodeShrinkPluginSourceV1() {
|
|
19335
|
+
return `${opencodeShrinkPluginPreamble()}${opencodeShrinkPluginHookMapV1()}`;
|
|
19336
|
+
}
|
|
19337
|
+
function opencodeShrinkPluginSourceV2() {
|
|
19338
|
+
return `${opencodeShrinkPluginPreamble()}${opencodeShrinkPluginDefinitionV2()}`;
|
|
19339
|
+
}
|
|
19340
|
+
// An unreadable version is evidence of neither major, and two installed majors
|
|
19341
|
+
// share this one plugins directory, so both get the single file each host can
|
|
19342
|
+
// load: the V1 map behind `default.server` for OpenCode 1.4+, and the V2
|
|
19343
|
+
// { id, setup } beside it. Same rule, same reason as the native plugin (#1316).
|
|
19344
|
+
function opencodeShrinkPluginSourceBoth() {
|
|
19345
|
+
return `${opencodeShrinkPluginPreamble()}${opencodeShrinkPluginHookMapV1()}${opencodeShrinkPluginDefinitionV2(" server: CavemanShrink,\n")}`;
|
|
19346
|
+
}
|
|
18273
19347
|
function installShrinkPluginOpencode() {
|
|
18274
19348
|
const path = opencodePluginPath();
|
|
18275
19349
|
try {
|
|
@@ -18396,13 +19470,152 @@ def register(ctx):
|
|
|
18396
19470
|
# <<< caveman:shrink-plugin
|
|
18397
19471
|
`;
|
|
18398
19472
|
}
|
|
18399
|
-
function
|
|
18400
|
-
const
|
|
18401
|
-
|
|
18402
|
-
|
|
19473
|
+
function hermesFlowSequenceItems(raw) {
|
|
19474
|
+
const start = raw.indexOf("[");
|
|
19475
|
+
if (start < 0)
|
|
19476
|
+
return null;
|
|
19477
|
+
const items = [];
|
|
19478
|
+
let item = "";
|
|
19479
|
+
let quote = null;
|
|
19480
|
+
let escaped = false;
|
|
19481
|
+
let depth = 0;
|
|
19482
|
+
for (let i = start + 1; i < raw.length; i++) {
|
|
19483
|
+
const char = raw[i];
|
|
19484
|
+
if (quote) {
|
|
19485
|
+
if (quote === "'" && char === "'" && raw[i + 1] === "'") {
|
|
19486
|
+
item += "''";
|
|
19487
|
+
i++;
|
|
19488
|
+
continue;
|
|
19489
|
+
}
|
|
19490
|
+
item += char;
|
|
19491
|
+
if (quote === '"' && escaped) {
|
|
19492
|
+
escaped = false;
|
|
19493
|
+
continue;
|
|
19494
|
+
}
|
|
19495
|
+
if (quote === '"' && char === "\\") {
|
|
19496
|
+
escaped = true;
|
|
19497
|
+
continue;
|
|
19498
|
+
}
|
|
19499
|
+
if (char === quote)
|
|
19500
|
+
quote = null;
|
|
19501
|
+
continue;
|
|
19502
|
+
}
|
|
19503
|
+
if (char === "#" && (i === start + 1 || /\s/.test(raw[i - 1]))) {
|
|
19504
|
+
while (i < raw.length && raw[i] !== "\n")
|
|
19505
|
+
i++;
|
|
19506
|
+
continue;
|
|
19507
|
+
}
|
|
19508
|
+
if (char === "'" || char === '"') {
|
|
19509
|
+
quote = char;
|
|
19510
|
+
item += char;
|
|
19511
|
+
continue;
|
|
19512
|
+
}
|
|
19513
|
+
if (char === "[" || char === "{") {
|
|
19514
|
+
depth++;
|
|
19515
|
+
item += char;
|
|
19516
|
+
continue;
|
|
19517
|
+
}
|
|
19518
|
+
if (char === "]") {
|
|
19519
|
+
if (depth === 0) {
|
|
19520
|
+
items.push(item);
|
|
19521
|
+
return items.map(configValue).filter((value) => value !== undefined);
|
|
19522
|
+
}
|
|
19523
|
+
depth--;
|
|
19524
|
+
item += char;
|
|
19525
|
+
continue;
|
|
19526
|
+
}
|
|
19527
|
+
if (char === "}" && depth > 0) {
|
|
19528
|
+
depth--;
|
|
19529
|
+
item += char;
|
|
19530
|
+
continue;
|
|
19531
|
+
}
|
|
19532
|
+
if (char === "," && depth === 0) {
|
|
19533
|
+
items.push(item);
|
|
19534
|
+
item = "";
|
|
19535
|
+
continue;
|
|
19536
|
+
}
|
|
19537
|
+
item += char;
|
|
19538
|
+
}
|
|
19539
|
+
return null;
|
|
18403
19540
|
}
|
|
18404
|
-
function
|
|
18405
|
-
|
|
19541
|
+
function hermesPluginListContains(text, listName, name) {
|
|
19542
|
+
const lines = yamlLines(text);
|
|
19543
|
+
const plugins = topLevelSection(lines, "plugins");
|
|
19544
|
+
if (!plugins)
|
|
19545
|
+
return false;
|
|
19546
|
+
for (let i = plugins.start + 1; i < plugins.end; i++) {
|
|
19547
|
+
const match = lines[i].match(/^ (enabled|disabled):(?:\s*(.*))?$/);
|
|
19548
|
+
if (!match || match[1] !== listName)
|
|
19549
|
+
continue;
|
|
19550
|
+
const raw = (match[2] ?? "").replace(/\s+#.*$/, "").trim();
|
|
19551
|
+
if (raw.startsWith("[")) {
|
|
19552
|
+
let flow = raw;
|
|
19553
|
+
let items = hermesFlowSequenceItems(flow);
|
|
19554
|
+
for (let next = i + 1; items === null && next < plugins.end; next++) {
|
|
19555
|
+
flow += `\n${lines[next]}`;
|
|
19556
|
+
items = hermesFlowSequenceItems(flow);
|
|
19557
|
+
}
|
|
19558
|
+
return items?.includes(name) ?? false;
|
|
19559
|
+
}
|
|
19560
|
+
if (raw && !raw.startsWith("#"))
|
|
19561
|
+
return false;
|
|
19562
|
+
let sequenceIndent = null;
|
|
19563
|
+
for (let next = i + 1; next < plugins.end; next++) {
|
|
19564
|
+
const line = lines[next];
|
|
19565
|
+
if (/^ [A-Za-z0-9_-]+:\s*/.test(line))
|
|
19566
|
+
break;
|
|
19567
|
+
if (!line.trim() || /^\s*#/.test(line))
|
|
19568
|
+
continue;
|
|
19569
|
+
const item = line.match(/^(\s*)-\s*(.*?)\s*$/);
|
|
19570
|
+
if (!item) {
|
|
19571
|
+
if (sequenceIndent !== null && line.search(/\S/) > sequenceIndent)
|
|
19572
|
+
continue;
|
|
19573
|
+
break;
|
|
19574
|
+
}
|
|
19575
|
+
const indent = item[1].length;
|
|
19576
|
+
if (sequenceIndent === null)
|
|
19577
|
+
sequenceIndent = indent;
|
|
19578
|
+
if (indent === sequenceIndent && configValue(item[2]) === name)
|
|
19579
|
+
return true;
|
|
19580
|
+
}
|
|
19581
|
+
return false;
|
|
19582
|
+
}
|
|
19583
|
+
return false;
|
|
19584
|
+
}
|
|
19585
|
+
function hermesNamedPluginMembership(text, name) {
|
|
19586
|
+
if (hermesPluginListContains(text, "disabled", name))
|
|
19587
|
+
return "disabled";
|
|
19588
|
+
if (hermesPluginListContains(text, "enabled", name))
|
|
19589
|
+
return "enabled";
|
|
19590
|
+
return "not-enabled";
|
|
19591
|
+
}
|
|
19592
|
+
function hermesEnabledListIsInline(text) {
|
|
19593
|
+
const lines = yamlLines(text);
|
|
19594
|
+
const plugins = topLevelSection(lines, "plugins");
|
|
19595
|
+
return Boolean(plugins && lines.slice(plugins.start + 1, plugins.end).some((line) => /^ enabled:\s*\[/.test(line)));
|
|
19596
|
+
}
|
|
19597
|
+
function hermesPluginInstallConfigReady() {
|
|
19598
|
+
const path = hermesConfigPath();
|
|
19599
|
+
let existing = "";
|
|
19600
|
+
try {
|
|
19601
|
+
existing = readFileSync(path, "utf8");
|
|
19602
|
+
}
|
|
19603
|
+
catch (error) {
|
|
19604
|
+
if (error.code !== "ENOENT") {
|
|
19605
|
+
console.error(`${mark("warn")} cannot read ${path}: ${error.message}`);
|
|
19606
|
+
return false;
|
|
19607
|
+
}
|
|
19608
|
+
}
|
|
19609
|
+
const membership = hermesNamedPluginMembership(existing, HERMES_PLUGIN_NAME);
|
|
19610
|
+
if (membership === "disabled") {
|
|
19611
|
+
console.error(`${mark("warn")} ${path} explicitly disables ${HERMES_PLUGIN_NAME} in plugins.disabled; no hook was installed`);
|
|
19612
|
+
return false;
|
|
19613
|
+
}
|
|
19614
|
+
if (membership !== "enabled" && hermesEnabledListIsInline(existing)) {
|
|
19615
|
+
console.error(`${mark("warn")} ${path} uses inline plugins.enabled; refusing to claim the Hermes plugin is installed`);
|
|
19616
|
+
return false;
|
|
19617
|
+
}
|
|
19618
|
+
return true;
|
|
18406
19619
|
}
|
|
18407
19620
|
function enableHermesPluginInConfig() {
|
|
18408
19621
|
const path = hermesConfigPath();
|
|
@@ -18416,7 +19629,12 @@ function enableHermesPluginInConfig() {
|
|
|
18416
19629
|
return false;
|
|
18417
19630
|
}
|
|
18418
19631
|
}
|
|
18419
|
-
|
|
19632
|
+
const membership = hermesNamedPluginMembership(existing, HERMES_PLUGIN_NAME);
|
|
19633
|
+
if (membership === "disabled") {
|
|
19634
|
+
console.error(`${mark("warn")} ${path} explicitly disables ${HERMES_PLUGIN_NAME} in plugins.disabled; remove that entry before installing`);
|
|
19635
|
+
return false;
|
|
19636
|
+
}
|
|
19637
|
+
if (membership === "enabled")
|
|
18420
19638
|
return true;
|
|
18421
19639
|
const stripped = stripMarkedBlock(existing, HERMES_PLUGIN_ENABLE_BEGIN, HERMES_PLUGIN_ENABLE_END).text;
|
|
18422
19640
|
const lines = yamlLines(stripped);
|
|
@@ -18441,7 +19659,10 @@ function enableHermesPluginInConfig() {
|
|
|
18441
19659
|
return false;
|
|
18442
19660
|
}
|
|
18443
19661
|
if (enabledLine >= 0) {
|
|
18444
|
-
|
|
19662
|
+
// Same sibling-indent rule as hermesNativeConfig: a fixed four-space
|
|
19663
|
+
// entry in a two-space list is a parse error (#1405).
|
|
19664
|
+
const pad = " ".repeat(yamlListItemIndent(lines, enabledLine, plugins.end) ?? 4);
|
|
19665
|
+
lines.splice(enabledLine + 1, 0, `${pad}${HERMES_PLUGIN_ENABLE_BEGIN}`, `${pad}- ${HERMES_PLUGIN_NAME}`, `${pad}${HERMES_PLUGIN_ENABLE_END}`);
|
|
18445
19666
|
}
|
|
18446
19667
|
else {
|
|
18447
19668
|
lines.splice(plugins.start + 1, 0, ` ${HERMES_PLUGIN_ENABLE_BEGIN}`, " enabled:", ` - ${HERMES_PLUGIN_NAME}`, ` ${HERMES_PLUGIN_ENABLE_END}`);
|
|
@@ -18518,6 +19739,8 @@ function disableHermesPluginInConfig() {
|
|
|
18518
19739
|
}
|
|
18519
19740
|
}
|
|
18520
19741
|
function installShrinkPluginHermes() {
|
|
19742
|
+
if (!hermesPluginInstallConfigReady())
|
|
19743
|
+
return false;
|
|
18521
19744
|
try {
|
|
18522
19745
|
mkdirSync(hermesPluginDir(), { recursive: true });
|
|
18523
19746
|
writeFileSync(hermesPluginManifestPath(), hermesPluginManifestSource());
|
|
@@ -18529,6 +19752,7 @@ function installShrinkPluginHermes() {
|
|
|
18529
19752
|
}
|
|
18530
19753
|
if (!enableHermesPluginInConfig()) {
|
|
18531
19754
|
process.stderr.write(`${mark("warn")} Hermes plugin written to ${hermesPluginDir()}, but plugins.enabled was not updated; run ${cyan(`hermes plugins enable ${HERMES_PLUGIN_NAME}`)}\n`);
|
|
19755
|
+
return false;
|
|
18532
19756
|
}
|
|
18533
19757
|
return true;
|
|
18534
19758
|
}
|
|
@@ -18882,6 +20106,11 @@ function evalsRun(argv = []) {
|
|
|
18882
20106
|
// stats prints the local spend summary by delegating to the proxy binary, which
|
|
18883
20107
|
// owns the ~/.caveman/ SQLite store. The CLI carries no database dependency, so
|
|
18884
20108
|
// it reads through the same Go binary `caveman start` launches.
|
|
20109
|
+
// The report reads every request row in its window; CAVE_STATS_TIMEOUT_MS
|
|
20110
|
+
// overrides the 60s it may take.
|
|
20111
|
+
function statsTimeoutMs() {
|
|
20112
|
+
return Number(process.env.CAVE_STATS_TIMEOUT_MS) || 60_000;
|
|
20113
|
+
}
|
|
18885
20114
|
function stats(argv = []) {
|
|
18886
20115
|
if (argv.length === 1 && ["--help", "-h", "help"].includes(argv[0])) {
|
|
18887
20116
|
process.stdout.write(STATS_HELP);
|
|
@@ -18902,7 +20131,7 @@ function stats(argv = []) {
|
|
|
18902
20131
|
args.push("--write-report");
|
|
18903
20132
|
if (options.out)
|
|
18904
20133
|
args.push("--out", resolve(options.out));
|
|
18905
|
-
const out = execFileSync(bin, args, { encoding: "utf8", timeout:
|
|
20134
|
+
const out = execFileSync(bin, args, { encoding: "utf8", timeout: statsTimeoutMs(), maxBuffer: 32 * 1024 * 1024 });
|
|
18906
20135
|
const report = JSON.parse(out);
|
|
18907
20136
|
// Older companion binaries ignore --report. Keep their measurements
|
|
18908
20137
|
// readable, but never pretend they generated the new accounting report.
|
|
@@ -18924,6 +20153,17 @@ function stats(argv = []) {
|
|
|
18924
20153
|
}
|
|
18925
20154
|
}
|
|
18926
20155
|
catch (error) {
|
|
20156
|
+
// A report that ran out of time says so, with the size it had to read
|
|
20157
|
+
// and the narrower window that reads less (#1371).
|
|
20158
|
+
if (error.code === "ETIMEDOUT") {
|
|
20159
|
+
let size = "";
|
|
20160
|
+
try {
|
|
20161
|
+
size = ` (${Math.round(statSync(join(cavemanHome(), "caveman.db")).size / 1048576)} MB)`;
|
|
20162
|
+
}
|
|
20163
|
+
catch { /* no local store */ }
|
|
20164
|
+
console.error(`caveman stats timed out after ${Math.round(statsTimeoutMs() / 1000)}s reading the local stats database${size}. Try a shorter window: caveman stats --days 7`);
|
|
20165
|
+
process.exit(1);
|
|
20166
|
+
}
|
|
18927
20167
|
console.error(`failed to read stats via ${bin}: ${error.message}`);
|
|
18928
20168
|
process.exit(1);
|
|
18929
20169
|
}
|
|
@@ -19110,7 +20350,7 @@ async function trial(rest) {
|
|
|
19110
20350
|
// older proxies omit it and always scanned 30d).
|
|
19111
20351
|
function learnEmpty(plan) {
|
|
19112
20352
|
const since = learnSince(plan.window?.since || "30d");
|
|
19113
|
-
return `no Claude Code, Codex, Gemini CLI, opencode or
|
|
20353
|
+
return `no Claude Code, Codex, Gemini CLI, opencode, aider or Pi 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`;
|
|
19114
20354
|
}
|
|
19115
20355
|
// learnNoScoreYet explains why there is no score: the score needs the same
|
|
19116
20356
|
// text repeated in at least 3 sessions.
|
|
@@ -19302,6 +20542,7 @@ function learnSourceLine(plan, sessions) {
|
|
|
19302
20542
|
by.gemini ? `Gemini ${commaCount(by.gemini)}` : "",
|
|
19303
20543
|
by.opencode ? `opencode ${commaCount(by.opencode)}` : "",
|
|
19304
20544
|
by.aider ? `aider ${commaCount(by.aider)}` : "",
|
|
20545
|
+
by.pi ? `Pi ${commaCount(by.pi)}` : "",
|
|
19305
20546
|
].filter(Boolean);
|
|
19306
20547
|
return `${commaCount(sessions)} sessions read${sourceBits.length ? ` · ${sourceBits.join(" · ")}` : ""}`;
|
|
19307
20548
|
}
|
|
@@ -19854,7 +21095,7 @@ export function renderLearnReconcile(raw) {
|
|
|
19854
21095
|
return `${out.join("\n")}\n`;
|
|
19855
21096
|
}
|
|
19856
21097
|
function learnUsage() {
|
|
19857
|
-
console.log(`${invokedAs()} learn [--all|--plain|--json|--md] [--since 30d] [--sources claude,codex,gemini,opencode,aider]
|
|
21098
|
+
console.log(`${invokedAs()} learn [--all|--plain|--json|--md] [--since 30d] [--sources claude,codex,gemini,opencode,aider,pi]
|
|
19858
21099
|
shows where your agent's tokens go, and what to fix first
|
|
19859
21100
|
default interactive Setup Score + top findings
|
|
19860
21101
|
--plain short text; no animation or keyboard menu
|
|
@@ -20138,7 +21379,11 @@ function resolveCavememCommand() {
|
|
|
20138
21379
|
function cavememRun(memArgs, opts = {}) {
|
|
20139
21380
|
const { command, args: pre } = resolveCavememCommand();
|
|
20140
21381
|
try {
|
|
20141
|
-
return execFileSync(command, [...pre, ...memArgs], {
|
|
21382
|
+
return execFileSync(command, [...pre, ...memArgs], {
|
|
21383
|
+
encoding: "utf8",
|
|
21384
|
+
env: process.env,
|
|
21385
|
+
stdio: [opts.stdin ? "inherit" : "pipe", "pipe", "pipe"],
|
|
21386
|
+
});
|
|
20142
21387
|
}
|
|
20143
21388
|
catch (error) {
|
|
20144
21389
|
const e = error;
|
|
@@ -20154,6 +21399,23 @@ function cavememRun(memArgs, opts = {}) {
|
|
|
20154
21399
|
}
|
|
20155
21400
|
return null;
|
|
20156
21401
|
}
|
|
21402
|
+
// A cavemem older than `supersede --stdin` reads supersede's second argument as
|
|
21403
|
+
// the replacement TEXT, so handing one "--stdin" stores the literal flag,
|
|
21404
|
+
// expires the real memory and exits 0. The binary advertises the capability, so
|
|
21405
|
+
// ask before sending a replacement over stdin. Soft: an unreadable version
|
|
21406
|
+
// answers "no", which refuses rather than risking the write.
|
|
21407
|
+
function cavememSupersedeStdin() {
|
|
21408
|
+
const out = cavememRun(["version", "--json"], { soft: true });
|
|
21409
|
+
if (!out)
|
|
21410
|
+
return false;
|
|
21411
|
+
try {
|
|
21412
|
+
const { capabilities } = JSON.parse(out);
|
|
21413
|
+
return Array.isArray(capabilities) && capabilities.includes("supersede-stdin");
|
|
21414
|
+
}
|
|
21415
|
+
catch {
|
|
21416
|
+
return false;
|
|
21417
|
+
}
|
|
21418
|
+
}
|
|
20157
21419
|
// mem is the durable-memory command family (cavemem). remember/recall/recover/
|
|
20158
21420
|
// forget are mechanical store ops; the editing skill and the opt-in recall hook
|
|
20159
21421
|
// build on them. Memory edits to a user's config are NEVER done here — only the
|
|
@@ -20167,10 +21429,16 @@ function mem(rest) {
|
|
|
20167
21429
|
// fall back to dropping flag-looking args (remember takes none) for
|
|
20168
21430
|
// backward compatibility.
|
|
20169
21431
|
const args = rest.slice(1);
|
|
21432
|
+
// --stdin hands our stdin straight to cavemem, so the block reaches the
|
|
21433
|
+
// store byte for byte and never passes through a shell command line.
|
|
21434
|
+
if (args.length === 1 && args[0] === "--stdin") {
|
|
21435
|
+
process.stdout.write(cavememRun(["remember", "--stdin"], { stdin: true }) ?? "");
|
|
21436
|
+
return;
|
|
21437
|
+
}
|
|
20170
21438
|
const sep = args.indexOf("--");
|
|
20171
21439
|
const text = (sep >= 0 ? args.slice(sep + 1) : args.filter((a) => !a.startsWith("--"))).join(" ");
|
|
20172
21440
|
if (!text) {
|
|
20173
|
-
console.error(`usage: ${invokedCommand("mem")} remember [--] <text
|
|
21441
|
+
console.error(`usage: ${invokedCommand("mem")} remember [--] <text> | --stdin`);
|
|
20174
21442
|
process.exit(2);
|
|
20175
21443
|
}
|
|
20176
21444
|
process.stdout.write(cavememRun(["remember", text]) ?? "");
|
|
@@ -20213,10 +21481,21 @@ function mem(rest) {
|
|
|
20213
21481
|
// Same `--` end-of-options handling as remember: a replacement block that
|
|
20214
21482
|
// opens with a `---` rule must survive verbatim instead of filtering empty.
|
|
20215
21483
|
const rest2 = rest.slice(2);
|
|
21484
|
+
// --stdin hands our stdin straight to cavemem, exactly as remember does,
|
|
21485
|
+
// so a replacement bigger than one argv element (~128 KB on Linux,
|
|
21486
|
+
// ~32 KB of whole command line on Windows) reaches the store at all.
|
|
21487
|
+
if (id && rest2.length === 1 && rest2[0] === "--stdin") {
|
|
21488
|
+
if (!cavememSupersedeStdin()) {
|
|
21489
|
+
console.error("caveman: this cavemem build cannot read a replacement from stdin (no supersede-stdin capability); upgrade it, or pass the text as an argument");
|
|
21490
|
+
process.exit(1);
|
|
21491
|
+
}
|
|
21492
|
+
process.stdout.write(cavememRun(["supersede", id, "--stdin"], { stdin: true }) ?? "");
|
|
21493
|
+
return;
|
|
21494
|
+
}
|
|
20216
21495
|
const sep = rest2.indexOf("--");
|
|
20217
21496
|
const text = (sep >= 0 ? rest2.slice(sep + 1) : rest2.filter((a) => !a.startsWith("--"))).join(" ");
|
|
20218
21497
|
if (!id || !text) {
|
|
20219
|
-
console.error(`usage: ${invokedCommand("mem")} supersede <id> [--] <text
|
|
21498
|
+
console.error(`usage: ${invokedCommand("mem")} supersede <id> [--] <text> | <id> --stdin`);
|
|
20220
21499
|
process.exit(2);
|
|
20221
21500
|
}
|
|
20222
21501
|
process.stdout.write(cavememRun(["supersede", id, text]) ?? "");
|
|
@@ -20268,6 +21547,7 @@ function memRecover(handle) {
|
|
|
20268
21547
|
function memUsage() {
|
|
20269
21548
|
console.log(`caveman mem — durable agent memory (cavemem)
|
|
20270
21549
|
caveman mem remember <text> store a memory
|
|
21550
|
+
caveman mem remember --stdin store a memory read from stdin, byte for byte
|
|
20271
21551
|
caveman mem recall <query> [--limit N] recall memories (lexical, conservative threshold)
|
|
20272
21552
|
caveman mem supersede <id> <text> replace a current fact; preserve history
|
|
20273
21553
|
caveman mem history <id> show oldest-to-newest versions
|
|
@@ -20905,6 +22185,9 @@ async function status(argv) {
|
|
|
20905
22185
|
const cavemanBusts = Number(today?.caveman_cache_bust_requests ?? 0);
|
|
20906
22186
|
if (Number.isSafeInteger(cavemanBusts) && cavemanBusts > 0)
|
|
20907
22187
|
states.push(OFF_STATES.cavemanCacheBust(cavemanBusts));
|
|
22188
|
+
const recoveryStore = versionInfo ? readRecoveryStore(false) : undefined;
|
|
22189
|
+
if (recoveryStore?.writes_refused && recoveryStore.reason)
|
|
22190
|
+
states.push(OFF_STATES.recoveryStore(recoveryStore.reason, recoveryStore.fix));
|
|
20908
22191
|
const runningMode = runtime.owner !== "unknown" && runtime.mode ? runtime.mode : null;
|
|
20909
22192
|
const resolvedMode = gate.mode;
|
|
20910
22193
|
const snapshot = readLearnSnapshot();
|
|
@@ -22297,9 +23580,6 @@ function configPath() {
|
|
|
22297
23580
|
function print(value) {
|
|
22298
23581
|
console.log(JSON.stringify(value, null, 2));
|
|
22299
23582
|
}
|
|
22300
|
-
function shellHint(commandLine) {
|
|
22301
|
-
console.log(commandLine);
|
|
22302
|
-
}
|
|
22303
23583
|
export const HELP_SCREEN = `caveman
|
|
22304
23584
|
|
|
22305
23585
|
run
|
|
@@ -22544,19 +23824,6 @@ function which(cmd) {
|
|
|
22544
23824
|
}
|
|
22545
23825
|
return null;
|
|
22546
23826
|
}
|
|
22547
|
-
// dockerState reports whether the Docker daemon is reachable, so `caveman start`
|
|
22548
|
-
// can give an honest hint about the `make dev` path.
|
|
22549
|
-
function dockerState() {
|
|
22550
|
-
if (!which("docker"))
|
|
22551
|
-
return "absent";
|
|
22552
|
-
try {
|
|
22553
|
-
execFileSync("docker", ["info"], { stdio: "ignore", timeout: 4000 });
|
|
22554
|
-
return "running";
|
|
22555
|
-
}
|
|
22556
|
-
catch {
|
|
22557
|
-
return "stopped";
|
|
22558
|
-
}
|
|
22559
|
-
}
|
|
22560
23827
|
// portListening probes a TCP port with a short timeout — used to detect whether
|
|
22561
23828
|
// the proxy is already up, so start/wrap can say so without false positives.
|
|
22562
23829
|
function portListening(host, port) {
|