@caveman-ai/cli 1.3.1 → 1.3.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +41 -1
- package/dist/agent-skills.generated.js +1 -1
- package/dist/agents.generated.js +388 -11
- package/dist/binaries.generated.js +1 -1
- package/dist/caveman-pi-extension.mjs +332 -51
- package/dist/cloud-client.mjs +22 -0
- package/dist/cloud-mcp.mjs +75 -0
- package/dist/index.js +3014 -273
- package/dist/native-hook-fast.js +2 -2
- package/dist/openclaw-provider-compat.js +111 -0
- package/dist/provider-routing.js +140 -0
- package/dist/proxy-fetch.js +3 -1
- package/dist/stats-cli.js +105 -0
- package/dist/surface.json +299 -0
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,17 +1,18 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { execFileSync, spawn, spawnSync } from "node:child_process";
|
|
3
|
-
import { accessSync, appendFileSync, cpSync, existsSync, chmodSync, constants, copyFileSync, mkdirSync, mkdtempSync, lstatSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, symlinkSync, unlinkSync, writeFileSync, } from "node:fs";
|
|
3
|
+
import { accessSync, appendFileSync, closeSync, cpSync, existsSync, fchmodSync, fsyncSync, chmodSync, constants, copyFileSync, linkSync, mkdirSync, mkdtempSync, openSync, lstatSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, symlinkSync, unlinkSync, writeFileSync, } from "node:fs";
|
|
4
4
|
import { chmod, mkdir, open, readFile, rename, writeFile } from "node:fs/promises";
|
|
5
|
-
import { homedir, hostname, tmpdir } from "node:os";
|
|
6
|
-
import { basename, delimiter, dirname, extname, isAbsolute, join, resolve } from "node:path";
|
|
5
|
+
import { homedir, hostname, tmpdir, userInfo } from "node:os";
|
|
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
9
|
import { request as httpsRequest } from "node:https";
|
|
10
10
|
import { createHash, createHmac, createPublicKey, randomBytes, randomUUID, verify as edVerify } from "node:crypto";
|
|
11
11
|
import { fileURLToPath } from "node:url";
|
|
12
|
+
import { parseEnv } from "node:util";
|
|
12
13
|
import { PROFILES } from "./agents.generated.js";
|
|
13
14
|
import { BINARY_RELEASE, BINARY_RELEASE_BASE_DEFAULT, BINARY_SIGNING_PUBKEY, } from "./binaries.generated.js";
|
|
14
|
-
import { installProxyAwareFetch } from "./proxy-fetch.js";
|
|
15
|
+
import { installProxyAwareFetch, resolveProxyUrl } from "./proxy-fetch.js";
|
|
15
16
|
import { RECIPES } from "./recipes.generated.js";
|
|
16
17
|
import { PRACTICE_REGISTRY } from "./practices.generated.js";
|
|
17
18
|
import { RESERVED_VERBS } from "./reserved-verbs.generated.js";
|
|
@@ -21,6 +22,9 @@ import { NATIVE_CORE, NATIVE_PACK, NATIVE_SKILL_INSTRUCTIONS } from "./native-pa
|
|
|
21
22
|
import { serveAgentMcp, } from "./agent-mcp.js";
|
|
22
23
|
import { portableInvocation } from "./portable-command.js";
|
|
23
24
|
import { hardenedGitArgs, hardenedGitEnv } from "./git-safe.js";
|
|
25
|
+
import { publishedForwardHeadersOf, publishedUpstreamsOf, unforwardedProviderHeaders, verifiedProviderRoute } from "./provider-routing.js";
|
|
26
|
+
import { openClawRequestCompatibilityIssue, preserveOpenClawProviderCompat } from "./openclaw-provider-compat.js";
|
|
27
|
+
import { parseStatsOptions, renderStatsSummary, STATS_HELP, STATS_USAGE } from "./stats-cli.js";
|
|
24
28
|
export const overlayBuilders = {};
|
|
25
29
|
const wrapTempDirs = new Set();
|
|
26
30
|
// The standalone proxy listens here; `caveman start` launches it and
|
|
@@ -59,8 +63,13 @@ function gatewayUrlFromConfigFile() {
|
|
|
59
63
|
// adding an agent is a new profile file, not a code change. Any other command
|
|
60
64
|
// still runs verbatim with the generic provider base-URL injection.
|
|
61
65
|
const AGENTS = PROFILES;
|
|
62
|
-
// binOf
|
|
66
|
+
// binOf prefers the first installed published binary and falls back to the
|
|
67
|
+
// primary name for install hints. Some packages intentionally publish aliases.
|
|
63
68
|
function binOf(a) {
|
|
69
|
+
for (const name of a.binary_names) {
|
|
70
|
+
if (which(name))
|
|
71
|
+
return name;
|
|
72
|
+
}
|
|
64
73
|
return a.binary_names[0] ?? a.id;
|
|
65
74
|
}
|
|
66
75
|
// findAgent resolves a wrap target to a profile by id first, then by any of its
|
|
@@ -1035,7 +1044,7 @@ function exploreUsage() {
|
|
|
1035
1044
|
console.error(`usage: ${invokedCommand("explore")} install [--agent claude] [--user] [--dir <path>]`);
|
|
1036
1045
|
console.error(" legacy alias for tools skills install caveman-explore");
|
|
1037
1046
|
console.error(" --agent claude target Claude Code (default; codex is not wired yet)");
|
|
1038
|
-
console.error(" --user install
|
|
1047
|
+
console.error(" --user install in the Claude profile's skills directory for all repos");
|
|
1039
1048
|
console.error(" --dir <path> write SKILL.md into <path>");
|
|
1040
1049
|
process.exit(2);
|
|
1041
1050
|
}
|
|
@@ -1200,7 +1209,7 @@ function discoverSkillTargets(rest) {
|
|
|
1200
1209
|
targets.push({ name: profile.id, dir: "", agent: profile.id });
|
|
1201
1210
|
continue;
|
|
1202
1211
|
}
|
|
1203
|
-
const roots =
|
|
1212
|
+
const roots = profile.skills.user_dirs.map((path) => resolveSkillRoot(agentUserPath(profile.id, path)));
|
|
1204
1213
|
if (rest.includes("--project"))
|
|
1205
1214
|
roots.push(...(profile.skills.project_dirs ?? []).map(resolveSkillRoot));
|
|
1206
1215
|
for (const root of roots)
|
|
@@ -1469,8 +1478,8 @@ function skillsUsage() {
|
|
|
1469
1478
|
console.error(" add <source> install any Git/URL/local source through the official Skills CLI, then pixelize new Claude Code/Codex skills");
|
|
1470
1479
|
console.error(" accepts npx skills add flags such as --skill, --agent, --global, --list, --yes, and --all");
|
|
1471
1480
|
console.error(" --agent claude Claude Code (default) — writes .claude/skills/<name>/SKILL.md");
|
|
1472
|
-
console.error(" --agent codex Codex — writes
|
|
1473
|
-
console.error(" --user install
|
|
1481
|
+
console.error(" --agent codex Codex — writes skills/<name>/SKILL.md inside CODEX_HOME (default ~/.codex)");
|
|
1482
|
+
console.error(" --user install in the Claude profile's skills directory for all repos");
|
|
1474
1483
|
console.error(" --dir <path> single: write SKILL.md there; suite: write <path>/<name>/SKILL.md");
|
|
1475
1484
|
console.error(" --density LEVEL pixel pack geometry (default balanced): conservative|balanced|max");
|
|
1476
1485
|
console.error(" --no-pixel install plain SKILL.md without pixel conversion");
|
|
@@ -1671,12 +1680,12 @@ function skillDestination(name, rest, multiple, agent) {
|
|
|
1671
1680
|
return join(directDir, ...(multiple ? [name, "SKILL.md"] : ["SKILL.md"]));
|
|
1672
1681
|
if (agent === "claude") {
|
|
1673
1682
|
const root = rest.includes("--user")
|
|
1674
|
-
? join(
|
|
1683
|
+
? join(claudeConfigDir(), "skills")
|
|
1675
1684
|
: join(process.cwd(), ".claude", "skills");
|
|
1676
1685
|
return join(root, name, "SKILL.md");
|
|
1677
1686
|
}
|
|
1678
1687
|
if (agent === "codex")
|
|
1679
|
-
return join(
|
|
1688
|
+
return join(codexHomeDir(), "skills", name, "SKILL.md");
|
|
1680
1689
|
console.error(`caveman skills: --agent must be claude or codex (got ${agent})`);
|
|
1681
1690
|
process.exit(2);
|
|
1682
1691
|
}
|
|
@@ -1684,9 +1693,9 @@ function externalSkillRoots(args) {
|
|
|
1684
1693
|
const global = args.includes("--global") || args.includes("-g");
|
|
1685
1694
|
if (global) {
|
|
1686
1695
|
return [
|
|
1687
|
-
{ root: join(
|
|
1696
|
+
{ root: join(claudeConfigDir(), "skills"), agent: "claude" },
|
|
1688
1697
|
{ root: join(homedir(), ".agents", "skills"), agent: "codex" },
|
|
1689
|
-
{ root: join(
|
|
1698
|
+
{ root: join(codexHomeDir(), "skills"), agent: "codex" },
|
|
1690
1699
|
];
|
|
1691
1700
|
}
|
|
1692
1701
|
return [
|
|
@@ -1749,7 +1758,9 @@ function runExternalSkillAdd(rest) {
|
|
|
1749
1758
|
const noPixel = rest.includes("--no-pixel");
|
|
1750
1759
|
const args = stripCavemanSkillAddOptions(rest);
|
|
1751
1760
|
const listOnly = args.includes("--list") || args.includes("-l");
|
|
1752
|
-
|
|
1761
|
+
// Listing and plain installation delegate all path decisions upstream.
|
|
1762
|
+
// Resolving unrelated profiles here can reject an otherwise valid command.
|
|
1763
|
+
const roots = noPixel || listOnly ? [] : externalSkillRoots(args);
|
|
1753
1764
|
const before = noPixel || listOnly ? new Map() : snapshotExternalSkills(roots);
|
|
1754
1765
|
if (!noPixel && !listOnly && !args.includes("--copy"))
|
|
1755
1766
|
args.push("--copy");
|
|
@@ -1861,7 +1872,7 @@ async function skills(rest) {
|
|
|
1861
1872
|
installed.push({ name, dest, pixelResult });
|
|
1862
1873
|
}
|
|
1863
1874
|
const note = agent === "codex"
|
|
1864
|
-
?
|
|
1875
|
+
? `Codex auto-loads skill directories from ${join(codexHomeDir(), "skills")}.`
|
|
1865
1876
|
: "Claude Code auto-loads this skill when its description matches.";
|
|
1866
1877
|
const lines = installed.flatMap(({ name, dest, pixelResult }) => [
|
|
1867
1878
|
`${mark("ok")} ${name}: ${cyan(dest)}`,
|
|
@@ -1953,8 +1964,10 @@ async function start(argv = []) {
|
|
|
1953
1964
|
const subscriptionCompress = subscriptionCompressEnabled(startGate);
|
|
1954
1965
|
// A bare proxy has no active-agent identity, so it cannot prove that whichever
|
|
1955
1966
|
// subscription client arrives owns a compatible recovery tool. Keep the global
|
|
1956
|
-
// recovery signal off;
|
|
1957
|
-
//
|
|
1967
|
+
// recovery signal off; `caveman wrap <agent>` binds recovery to a checked agent
|
|
1968
|
+
// profile out of band, and for every other client the proxy reads the retrieve
|
|
1969
|
+
// tool out of the request itself. Inherited environment claims never cross this
|
|
1970
|
+
// boundary.
|
|
1958
1971
|
const mcpRecovery = startMcpRecoveryAvailable();
|
|
1959
1972
|
const env = {
|
|
1960
1973
|
...process.env,
|
|
@@ -2071,7 +2084,12 @@ function probeVersionedBinary(binary, requiredCapability) {
|
|
|
2071
2084
|
return { ...cached, current: cached.capabilities.includes(requiredCapability) };
|
|
2072
2085
|
let result = { version: "pre-versioned", capabilities: [] };
|
|
2073
2086
|
try {
|
|
2074
|
-
|
|
2087
|
+
// An npm-installed caveman-mcp on Windows is a `.cmd` shim, which Node
|
|
2088
|
+
// refuses to execFile directly (CVE-2024-27980). Route through the same
|
|
2089
|
+
// shim-aware invocation every other launch site uses; a shim that cannot
|
|
2090
|
+
// be launched safely throws and lands in the fail-closed branch below.
|
|
2091
|
+
const invocation = portableInvocation(binary, ["version", "--json"]);
|
|
2092
|
+
const raw = execFileSync(invocation.command, invocation.args, {
|
|
2075
2093
|
encoding: "utf8",
|
|
2076
2094
|
env: process.env,
|
|
2077
2095
|
timeout: versionedBinaryProbeTimeoutMs(),
|
|
@@ -2470,19 +2488,59 @@ function readPendingAgentNativeBundleRemoval(agent) {
|
|
|
2470
2488
|
throw new Error(`cannot read pending ${agent} agent-native removal journal: ${error.message}`);
|
|
2471
2489
|
}
|
|
2472
2490
|
}
|
|
2491
|
+
function mcpServerToolName(serverName) {
|
|
2492
|
+
if (serverName === "caveman")
|
|
2493
|
+
return "caveman_retrieve";
|
|
2494
|
+
if (serverName === "caveman-browse")
|
|
2495
|
+
return "caveman_browse";
|
|
2496
|
+
if (serverName === "caveman-cloud")
|
|
2497
|
+
return "caveman_context";
|
|
2498
|
+
if (serverName === "caveman-delegate")
|
|
2499
|
+
return "caveman_delegate";
|
|
2500
|
+
return undefined;
|
|
2501
|
+
}
|
|
2502
|
+
function parseMcpServerMarkerBytes(agent, serverName, bytes) {
|
|
2503
|
+
try {
|
|
2504
|
+
const value = JSON.parse(bytes.toString("utf8"));
|
|
2505
|
+
const expectedTool = mcpServerToolName(serverName);
|
|
2506
|
+
if (!expectedTool || value.tool !== expectedTool)
|
|
2507
|
+
return null;
|
|
2508
|
+
const hasConfigPath = Object.hasOwn(value, "config_path");
|
|
2509
|
+
const expectedKeys = hasConfigPath
|
|
2510
|
+
? ["args", "command", "config_path", "schema_version", "tool"]
|
|
2511
|
+
: ["args", "command", "tool"];
|
|
2512
|
+
if (Object.keys(value).sort().join("\0") !== expectedKeys.join("\0"))
|
|
2513
|
+
return null;
|
|
2514
|
+
if (typeof value.command !== "string" || !value.command.trim() || /[\r\n]/.test(value.command) || !Array.isArray(value.args) || !value.args.every((arg) => typeof arg === "string"))
|
|
2515
|
+
return null;
|
|
2516
|
+
if (hasConfigPath && (value.schema_version !== 1
|
|
2517
|
+
|| agent !== "kilo" && agent !== "qwen"
|
|
2518
|
+
|| typeof value.config_path !== "string"
|
|
2519
|
+
|| value.config_path !== canonicalMcpConfigPath(value.config_path)))
|
|
2520
|
+
return null;
|
|
2521
|
+
return {
|
|
2522
|
+
command: value.command,
|
|
2523
|
+
args: value.args,
|
|
2524
|
+
...(hasConfigPath ? { config_path: value.config_path, schema_version: 1 } : {}),
|
|
2525
|
+
};
|
|
2526
|
+
}
|
|
2527
|
+
catch {
|
|
2528
|
+
return null;
|
|
2529
|
+
}
|
|
2530
|
+
}
|
|
2473
2531
|
function readMcpServerMarker(agent, serverName) {
|
|
2474
2532
|
try {
|
|
2475
|
-
const
|
|
2476
|
-
if (
|
|
2533
|
+
const path = mcpServerMarkerPath(agent, serverName);
|
|
2534
|
+
if ((agent === "kilo" || agent === "qwen") && lstatSync(path).isSymbolicLink())
|
|
2477
2535
|
return null;
|
|
2478
|
-
return
|
|
2536
|
+
return parseMcpServerMarkerBytes(agent, serverName, readFileSync(path));
|
|
2479
2537
|
}
|
|
2480
2538
|
catch {
|
|
2481
2539
|
return null;
|
|
2482
2540
|
}
|
|
2483
2541
|
}
|
|
2484
2542
|
function claudeMcpRegistration(serverName) {
|
|
2485
|
-
const path =
|
|
2543
|
+
const path = claudeGlobalConfigPath();
|
|
2486
2544
|
const bytes = fileBytes(path);
|
|
2487
2545
|
if (!bytes)
|
|
2488
2546
|
return { present: false, command: "", args: [], exact_shape: false };
|
|
@@ -2516,7 +2574,7 @@ function installAgentNativeCloudMcp(agent, mcp) {
|
|
|
2516
2574
|
return;
|
|
2517
2575
|
}
|
|
2518
2576
|
const installed = agent === "claude"
|
|
2519
|
-
? installMcpJson(
|
|
2577
|
+
? installMcpJson(claudeGlobalConfigPath(), ["mcpServers", "caveman-cloud"], { command: mcp.command, args: mcp.args })
|
|
2520
2578
|
: installMcpForAgent(findAgent(agent), mcp, "caveman-cloud");
|
|
2521
2579
|
if (!installed)
|
|
2522
2580
|
throw new Error(`could not install caveman-cloud MCP for ${agent}`);
|
|
@@ -2524,7 +2582,7 @@ function installAgentNativeCloudMcp(agent, mcp) {
|
|
|
2524
2582
|
}
|
|
2525
2583
|
function uninstallAgentNativeCloudMcp(agent) {
|
|
2526
2584
|
const removed = agent === "claude"
|
|
2527
|
-
? removeMcpJson(
|
|
2585
|
+
? removeMcpJson(claudeGlobalConfigPath(), ["mcpServers", "caveman-cloud"])
|
|
2528
2586
|
: uninstallMcpForAgent(findAgent(agent), "caveman-cloud");
|
|
2529
2587
|
if (!removed)
|
|
2530
2588
|
throw new Error(`could not remove caveman-cloud MCP for ${agent}`);
|
|
@@ -2538,7 +2596,7 @@ function uninstallAgentNativeCloudMcp(agent) {
|
|
|
2538
2596
|
}
|
|
2539
2597
|
function agentNativeSkillFiles(agent) {
|
|
2540
2598
|
const names = AGENT_SKILL_SUITES["agent-native"] ?? [];
|
|
2541
|
-
const root = agent === "claude" ? join(
|
|
2599
|
+
const root = agent === "claude" ? join(claudeConfigDir(), "skills") : join(codexHomeDir(), "skills");
|
|
2542
2600
|
return names.map((name) => ({ name, file: join(root, name, "SKILL.md"), body: SKILLS[name] }));
|
|
2543
2601
|
}
|
|
2544
2602
|
function restoreAgentNativeBundleSkills(skills) {
|
|
@@ -2610,7 +2668,7 @@ function skillMatchesBefore(skill) {
|
|
|
2610
2668
|
function agentNativeCloudMcpHostAbsent(agent) {
|
|
2611
2669
|
if (agent === "claude")
|
|
2612
2670
|
return !claudeMcpRegistration("caveman-cloud").present;
|
|
2613
|
-
const config = fileBytes(join(
|
|
2671
|
+
const config = fileBytes(join(codexHomeDir(), "config.toml"))?.toString("utf8") ?? "";
|
|
2614
2672
|
return !config.includes("[mcp_servers.caveman-cloud]");
|
|
2615
2673
|
}
|
|
2616
2674
|
function agentNativeCloudMcpAbsent(agent) {
|
|
@@ -2715,7 +2773,7 @@ function preflightAgentNativeBundleComponents(agent, existingBundle) {
|
|
|
2715
2773
|
}
|
|
2716
2774
|
return;
|
|
2717
2775
|
}
|
|
2718
|
-
const config = fileBytes(join(
|
|
2776
|
+
const config = fileBytes(join(codexHomeDir(), "config.toml"))?.toString("utf8") ?? "";
|
|
2719
2777
|
if (!config.includes("[mcp_servers.caveman-cloud]"))
|
|
2720
2778
|
return;
|
|
2721
2779
|
if (!readMcpServerMarker("codex", "caveman-cloud")) {
|
|
@@ -3376,23 +3434,13 @@ export const OFF_STATES = {
|
|
|
3376
3434
|
},
|
|
3377
3435
|
runningModeMismatch: (running, resolvedMode) => ({
|
|
3378
3436
|
id: "running-mode-mismatch",
|
|
3379
|
-
line: `a caveman proxy is already running in ${running} mode
|
|
3380
|
-
fix: "
|
|
3381
|
-
}),
|
|
3382
|
-
runningModeHeld: (running, resolvedMode) => ({
|
|
3383
|
-
id: "running-mode-mismatch",
|
|
3384
|
-
line: `a caveman proxy is already running in ${running} mode — another live session holds it, so this session keeps that mode instead of restarting to ${resolvedMode}`,
|
|
3385
|
-
fix: "caveman run -- <your agent>",
|
|
3437
|
+
line: `a caveman proxy is already running in ${running} mode; keeping it running to protect existing sessions instead of switching to ${resolvedMode}`,
|
|
3438
|
+
fix: "restart the proxy explicitly after existing sessions finish, then retry",
|
|
3386
3439
|
}),
|
|
3387
3440
|
runningGateMismatch: {
|
|
3388
3441
|
id: "running-gate-mismatch",
|
|
3389
3442
|
line: "running caveman proxy has stale recovery state — launching this agent direct to avoid unsafe compression",
|
|
3390
|
-
fix: "
|
|
3391
|
-
},
|
|
3392
|
-
runningGateHeld: {
|
|
3393
|
-
id: "running-gate-mismatch",
|
|
3394
|
-
line: "another live session holds a caveman proxy with different recovery state — launching this agent direct to avoid unsafe compression",
|
|
3395
|
-
fix: "stop other wrapped sessions, then run this command again",
|
|
3443
|
+
fix: "restart the proxy explicitly after existing sessions finish, then retry",
|
|
3396
3444
|
},
|
|
3397
3445
|
foreignProcess: (host, port) => ({
|
|
3398
3446
|
id: "foreign-process",
|
|
@@ -4234,11 +4282,17 @@ async function wrap(rest) {
|
|
|
4234
4282
|
console.error("caveman wrap: --pixel not yet supported for codex subscription sessions");
|
|
4235
4283
|
process.exit(1);
|
|
4236
4284
|
}
|
|
4237
|
-
|
|
4238
|
-
|
|
4285
|
+
// Route-changing agent flags intentionally bypass Caveman. Decide before any
|
|
4286
|
+
// first-run install, proxy bootstrap, or welcome work so a direct launch has
|
|
4287
|
+
// no Caveman side effects beyond its explicit warning.
|
|
4288
|
+
const routeDecision = agent ? agentRouteOverride(agent, extra) : null;
|
|
4289
|
+
if (!routeDecision) {
|
|
4290
|
+
await bootstrapLocalWrapRuntime(parsed);
|
|
4291
|
+
await firstRunExperience();
|
|
4292
|
+
}
|
|
4239
4293
|
// `wrap` is a zero-commit trial. Native hooks/MCP/config live only in a temp
|
|
4240
4294
|
// host pack for this child; persistent integration requires an explicit install.
|
|
4241
|
-
await runWrapped(resolved, extra, agent, parsed, codexAuthMode === "subscription");
|
|
4295
|
+
await runWrapped(resolved, extra, agent, parsed, codexAuthMode === "subscription", routeDecision);
|
|
4242
4296
|
}
|
|
4243
4297
|
// ===========================================================================
|
|
4244
4298
|
// First-run experience. One-time (per machine) interactive moment on the first
|
|
@@ -4789,8 +4843,12 @@ async function agentShortcut(rest) {
|
|
|
4789
4843
|
// is the one-command compression path. If the proxy can't be reached, a TTY run
|
|
4790
4844
|
// offers to launch the agent directly (no Caveman, no compression this run) rather
|
|
4791
4845
|
// than wire it to a dead endpoint; non-TTY runs warn and route through as before.
|
|
4792
|
-
async function runWrapped(bin, cmdArgs, agent, opts = { mode: "compress", noProxy: false, toon: true, noShrink: false, mcpMode: "auto", noBrowse: false, delegate: false, minimal: false, command: [] }, codexSubscription = false) {
|
|
4793
|
-
const result = await spawnWrapped(bin, cmdArgs, agent, opts, gatewayURL(), codexSubscription);
|
|
4846
|
+
async function runWrapped(bin, cmdArgs, agent, opts = { mode: "compress", noProxy: false, toon: true, noShrink: false, mcpMode: "auto", noBrowse: false, delegate: false, minimal: false, command: [] }, codexSubscription = false, routeDecision) {
|
|
4847
|
+
const result = await spawnWrapped(bin, cmdArgs, agent, opts, gatewayURL(), codexSubscription, routeDecision);
|
|
4848
|
+
// Preflight route bypass is intentionally outside Caveman's lifecycle: no
|
|
4849
|
+
// savings read, sync, telemetry, or other post-child mutation.
|
|
4850
|
+
if (result.routeBypass)
|
|
4851
|
+
process.exit(result.code);
|
|
4794
4852
|
const summary = result.summaryKind && result.sessionStart
|
|
4795
4853
|
? printSessionSavings(result.summaryKind, result.sessionStart, agent?.id)
|
|
4796
4854
|
: null;
|
|
@@ -4851,7 +4909,7 @@ function routedAiderArgs(args) {
|
|
|
4851
4909
|
process.stderr.write(`caveman: aider model not set; routing with --model ${AIDER_ROUTED_DEFAULT_MODEL}\n`);
|
|
4852
4910
|
return ["--model", AIDER_ROUTED_DEFAULT_MODEL, ...args];
|
|
4853
4911
|
}
|
|
4854
|
-
async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = false) {
|
|
4912
|
+
async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = false, routeDecision) {
|
|
4855
4913
|
const { host, port } = gatewayHostPort(gw);
|
|
4856
4914
|
const local = wrapMode(gw) === "local";
|
|
4857
4915
|
let proxyStarted = false;
|
|
@@ -4860,14 +4918,23 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = f
|
|
|
4860
4918
|
// Gemini cannot preserve both contracts. Launch direct instead of routing a
|
|
4861
4919
|
// request that will 401 or misuse one credential as the other.
|
|
4862
4920
|
const managedGeminiUnsupported = !local && agent?.id === "gemini";
|
|
4863
|
-
|
|
4921
|
+
// `wrap` resolves this before first-run work and passes even a null decision.
|
|
4922
|
+
// Other callers resolve here. Never reread mutable settings across that boundary.
|
|
4923
|
+
const routeOverride = agent
|
|
4924
|
+
? routeDecision === undefined ? agentRouteOverride(agent, cmdArgs) : routeDecision
|
|
4925
|
+
: null;
|
|
4926
|
+
const routeBypass = routeOverride !== null;
|
|
4927
|
+
let direct = managedGeminiUnsupported || routeOverride !== null;
|
|
4864
4928
|
if (managedGeminiUnsupported) {
|
|
4865
4929
|
process.stderr.write("caveman: managed Gemini CLI wrap is unsupported because Gemini CLI cannot send separate Caveman and upstream credentials; launching directly\n");
|
|
4866
4930
|
}
|
|
4931
|
+
if (routeOverride && agent) {
|
|
4932
|
+
process.stderr.write(`caveman: ${routeOverrideLabel(agent)} ${routeOverride.surface} ${routeOverride.reason}; launching directly\n`);
|
|
4933
|
+
}
|
|
4867
4934
|
// The local proxy compresses with no account. When wrap runs the LOCAL
|
|
4868
4935
|
// proxy path we resolve the mode; managed gateway traffic is governed by the cloud
|
|
4869
4936
|
// policy engine, so we never resolve it here.
|
|
4870
|
-
const gateApplies = local && !opts.noProxy;
|
|
4937
|
+
const gateApplies = !direct && local && !opts.noProxy;
|
|
4871
4938
|
const entitlement = gateApplies ? readWrapEntitlement() : null;
|
|
4872
4939
|
const entitlementState = gateApplies ? readWrapEntitlementState() : null;
|
|
4873
4940
|
const gate = gateApplies ? resolveWrapGate(entitlement, new Date(), opts.mode) : null;
|
|
@@ -4889,20 +4956,20 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = f
|
|
|
4889
4956
|
// detail itself — i.e. it has the caveman MCP retrieve tool installed (run
|
|
4890
4957
|
// `caveman mcp install <agent>`). When it does, signal the proxy to use MCP
|
|
4891
4958
|
// recovery (which lets it compress streams); otherwise streams pass through.
|
|
4892
|
-
const ephemeralMcp = agent && (agent.id === "claude" || agent.id === "codex")
|
|
4959
|
+
const ephemeralMcp = !direct && agent && (agent.id === "claude" || agent.id === "codex")
|
|
4893
4960
|
&& !opts.minimal && opts.mcpMode === "auto" && wrapRecoveryEligible(opts)
|
|
4894
4961
|
? probeMcpBinary()
|
|
4895
4962
|
: null;
|
|
4896
4963
|
if (ephemeralMcp && !ephemeralMcp.probe.current)
|
|
4897
4964
|
queueStaleMcpBinary(ephemeralMcp.probe);
|
|
4898
4965
|
const ephemeralMcpBinary = ephemeralMcp?.probe.current ? ephemeralMcp.binary : undefined;
|
|
4899
|
-
const mcpRecovery = Boolean(ephemeralMcpBinary) || wrapMcpRecoveryAvailable(agent, opts);
|
|
4900
|
-
const delegateAlreadyInstalled = Boolean(agent && mcpServerInstalled(agent.id, "caveman-delegate"));
|
|
4901
|
-
const ephemeralDelegateMcp = agent && (agent.id === "claude" || agent.id === "codex")
|
|
4966
|
+
const mcpRecovery = !direct && (Boolean(ephemeralMcpBinary) || wrapMcpRecoveryAvailable(agent, opts, cmdArgs));
|
|
4967
|
+
const delegateAlreadyInstalled = Boolean(!direct && agent && mcpServerInstalled(agent.id, "caveman-delegate"));
|
|
4968
|
+
const ephemeralDelegateMcp = !direct && agent && (agent.id === "claude" || agent.id === "codex")
|
|
4902
4969
|
&& !opts.minimal && opts.delegate && !delegateAlreadyInstalled
|
|
4903
4970
|
? resolveDelegateMcpCommand()
|
|
4904
4971
|
: null;
|
|
4905
|
-
if (agent && (agent.id === "claude" || agent.id === "codex") && opts.delegate && !delegateAlreadyInstalled && !ephemeralDelegateMcp) {
|
|
4972
|
+
if (!direct && agent && (agent.id === "claude" || agent.id === "codex") && opts.delegate && !delegateAlreadyInstalled && !ephemeralDelegateMcp) {
|
|
4906
4973
|
process.stderr.write("caveman: delegate enabled but caveman-delegate server is unavailable; launching without delegate\n");
|
|
4907
4974
|
}
|
|
4908
4975
|
const desiredRecoveryViaMCP = observeEstimate ? false : mcpRecovery;
|
|
@@ -4910,7 +4977,7 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = f
|
|
|
4910
4977
|
const proxyVersion = gateApplies ? probeProxyVersion() : null;
|
|
4911
4978
|
let runtime = { owner: "unknown" };
|
|
4912
4979
|
let runtimeState = null;
|
|
4913
|
-
let proxyReady = await portListening(host, port);
|
|
4980
|
+
let proxyReady = direct ? false : await portListening(host, port);
|
|
4914
4981
|
if (proxyReady && gateApplies) {
|
|
4915
4982
|
runtime = readProxyRuntimeState(port, proxyVersion);
|
|
4916
4983
|
if (runtime.owner === "unknown") {
|
|
@@ -4919,70 +4986,21 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = f
|
|
|
4919
4986
|
: OFF_STATES.staleBinary("caveman-proxy", proxyVersion?.version ?? "unknown", cliVersion());
|
|
4920
4987
|
}
|
|
4921
4988
|
else if (!proxyRuntimeMatches(runtime, effectiveMode, desiredRecoveryViaMCP)) {
|
|
4922
|
-
|
|
4923
|
-
|
|
4924
|
-
|
|
4925
|
-
|
|
4926
|
-
|
|
4927
|
-
|
|
4928
|
-
|
|
4929
|
-
|
|
4930
|
-
|
|
4931
|
-
|
|
4932
|
-
|
|
4933
|
-
|
|
4934
|
-
process.kill(runtime.pid, "SIGTERM");
|
|
4935
|
-
const deadline = Date.now() + proxyRestartTimeoutMs();
|
|
4936
|
-
let successor = false;
|
|
4937
|
-
while (Date.now() < deadline) {
|
|
4938
|
-
await sleep(100);
|
|
4939
|
-
const generation = readRawProxyRunState(port);
|
|
4940
|
-
if (generation.owner !== "unknown" && generation.instance_token !== runtime.instance_token) {
|
|
4941
|
-
successor = true;
|
|
4942
|
-
break;
|
|
4943
|
-
}
|
|
4944
|
-
if (!(await portListening(host, port)))
|
|
4945
|
-
break;
|
|
4946
|
-
}
|
|
4947
|
-
proxyReady = await portListening(host, port);
|
|
4948
|
-
if (!proxyReady && !successor) {
|
|
4949
|
-
proxyStarted = await startWrapProxy(effectiveMode, desiredRecoveryViaMCP, codexSubscription ? false : observeEstimate ? false : opts.toon, opts.pixelModels, opts.pixelDensity, gw, codexSubscription ? "codex-subscription" : "standard", observeEstimate);
|
|
4950
|
-
proxyReady = await portListening(host, port);
|
|
4951
|
-
}
|
|
4952
|
-
runtime = proxyReady ? readProxyRuntimeState(port, proxyVersion) : { owner: "unknown" };
|
|
4953
|
-
if (runtime.owner === "unknown" || !proxyRuntimeMatches(runtime, effectiveMode, desiredRecoveryViaMCP)) {
|
|
4954
|
-
runtimeState = runtime.owner === "unknown"
|
|
4955
|
-
? OFF_STATES.foreignProcess(host, port)
|
|
4956
|
-
: !proxyRuntimeGateMatches(runtime, desiredRecoveryViaMCP)
|
|
4957
|
-
? OFF_STATES.runningGateMismatch
|
|
4958
|
-
: OFF_STATES.runningModeMismatch(runtime.mode ?? "unknown", effectiveMode);
|
|
4959
|
-
}
|
|
4960
|
-
}
|
|
4961
|
-
catch {
|
|
4962
|
-
runtime = readProxyRuntimeState(port, proxyVersion);
|
|
4963
|
-
runtimeState = runtime.owner === "unknown"
|
|
4964
|
-
? OFF_STATES.foreignProcess(host, port)
|
|
4965
|
-
: !proxyRuntimeMatches(runtime, effectiveMode, desiredRecoveryViaMCP)
|
|
4966
|
-
? !proxyRuntimeGateMatches(runtime, desiredRecoveryViaMCP)
|
|
4967
|
-
? OFF_STATES.runningGateMismatch
|
|
4968
|
-
: OFF_STATES.runningModeMismatch(runtime.mode ?? "unknown", effectiveMode)
|
|
4969
|
-
: null;
|
|
4970
|
-
}
|
|
4971
|
-
}
|
|
4972
|
-
else {
|
|
4973
|
-
runtime = readProxyRuntimeState(port, proxyVersion);
|
|
4974
|
-
runtimeState = runtime.owner === "unknown"
|
|
4975
|
-
? OFF_STATES.foreignProcess(host, port)
|
|
4976
|
-
: !proxyRuntimeMatches(runtime, effectiveMode, desiredRecoveryViaMCP)
|
|
4977
|
-
? !proxyRuntimeGateMatches(runtime, desiredRecoveryViaMCP)
|
|
4978
|
-
? OFF_STATES.runningGateMismatch
|
|
4979
|
-
: OFF_STATES.runningModeMismatch(runtime.mode ?? "unknown", effectiveMode)
|
|
4980
|
-
: null;
|
|
4981
|
-
}
|
|
4982
|
-
}
|
|
4989
|
+
// A missing wrapper marker does not prove this listener is unused:
|
|
4990
|
+
// native hooks, IDEs, and resumed sessions retain its base URL. Never
|
|
4991
|
+
// signal a shared proxy to change this new session's mode or recovery.
|
|
4992
|
+
// Re-read once in case another operator already replaced the generation.
|
|
4993
|
+
runtime = readProxyRuntimeState(port, proxyVersion);
|
|
4994
|
+
runtimeState = runtime.owner === "unknown"
|
|
4995
|
+
? OFF_STATES.foreignProcess(host, port)
|
|
4996
|
+
: !proxyRuntimeMatches(runtime, effectiveMode, desiredRecoveryViaMCP)
|
|
4997
|
+
? !proxyRuntimeGateMatches(runtime, desiredRecoveryViaMCP)
|
|
4998
|
+
? OFF_STATES.runningGateMismatch
|
|
4999
|
+
: OFF_STATES.runningModeMismatch(runtime.mode ?? "unknown", effectiveMode)
|
|
5000
|
+
: null;
|
|
4983
5001
|
}
|
|
4984
5002
|
}
|
|
4985
|
-
if (!proxyReady) {
|
|
5003
|
+
if (!proxyReady && !direct) {
|
|
4986
5004
|
if (local && !opts.noProxy) {
|
|
4987
5005
|
proxyStarted = codexSubscription
|
|
4988
5006
|
? await startWrapProxy(effectiveMode, desiredRecoveryViaMCP, false, undefined, undefined, gw, "codex-subscription", observeEstimate)
|
|
@@ -4990,19 +5008,25 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = f
|
|
|
4990
5008
|
}
|
|
4991
5009
|
proxyReady = await portListening(host, port);
|
|
4992
5010
|
if (proxyReady && gateApplies) {
|
|
4993
|
-
runtime = readProxyRuntimeState(port, proxyVersion);
|
|
5011
|
+
runtime = proxyStarted ? await awaitProxyRuntimeState(port, proxyVersion) : readProxyRuntimeState(port, proxyVersion);
|
|
4994
5012
|
if (runtime.owner === "unknown") {
|
|
4995
5013
|
runtimeState = proxyVersion?.capabilities.includes("run_state")
|
|
4996
5014
|
? OFF_STATES.foreignProcess(host, port)
|
|
4997
5015
|
: OFF_STATES.staleBinary("caveman-proxy", proxyVersion?.version ?? "unknown", cliVersion());
|
|
4998
5016
|
}
|
|
4999
5017
|
}
|
|
5000
|
-
if (!proxyReady
|
|
5018
|
+
if (!proxyReady) {
|
|
5001
5019
|
const startHint = codexSubscription || opts.mode === "record" ? "caveman start" : `CAVEMAN_MODE=${opts.mode} caveman start`;
|
|
5002
5020
|
if (codexSubscription && opts.noProxy) {
|
|
5003
5021
|
// Explicit proxy:false leaves subscription Codex in pass-through launch mode
|
|
5004
5022
|
// without extra status noise; useful for tests and managed launchers.
|
|
5005
5023
|
}
|
|
5024
|
+
else if (local && !opts.noProxy) {
|
|
5025
|
+
// A failed local optimization layer must not wire the agent to a dead
|
|
5026
|
+
// listener. Direct launch preserves the agent's own provider setup.
|
|
5027
|
+
direct = true;
|
|
5028
|
+
process.stderr.write(`${mark("warn")} Caveman proxy not reachable on ${host}:${port}; launching directly without compression or metering\n`);
|
|
5029
|
+
}
|
|
5006
5030
|
else if (interactive()) {
|
|
5007
5031
|
// The proxy is down and we couldn't bring it up. Launching the agent now
|
|
5008
5032
|
// would wire it to a dead endpoint (every request fails), so offer to run
|
|
@@ -5019,7 +5043,7 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = f
|
|
|
5019
5043
|
process.stderr.write(`${mark("warn")} cancelled — run ${cyan(startHint)}, then re-run your wrap\n`);
|
|
5020
5044
|
emitCommandRunOnce("error", "usage");
|
|
5021
5045
|
removeProxySessionMarker(sessionMarker);
|
|
5022
|
-
return { code: 130, proxyStarted };
|
|
5046
|
+
return { code: 130, proxyStarted, routeBypass };
|
|
5023
5047
|
}
|
|
5024
5048
|
}
|
|
5025
5049
|
else {
|
|
@@ -5028,10 +5052,21 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = f
|
|
|
5028
5052
|
}
|
|
5029
5053
|
}
|
|
5030
5054
|
}
|
|
5031
|
-
|
|
5055
|
+
// A foreign listener on the proxy port is the same failure as a gate
|
|
5056
|
+
// mismatch, with a worse consequence: launching routed would hand the
|
|
5057
|
+
// operator's provider keys to a process caveman does not own (#945).
|
|
5058
|
+
if (runtimeState?.id === "running-gate-mismatch" || runtimeState?.id === "running-mode-mismatch") {
|
|
5032
5059
|
process.stderr.write(`${mark("warn")} ${runtimeState.line}\n`);
|
|
5033
5060
|
direct = true;
|
|
5034
5061
|
}
|
|
5062
|
+
else if (proxyReady && gateApplies && !proxyStarted && runtime.owner === "unknown") {
|
|
5063
|
+
// A listener caveman did not start this run and cannot prove it owns: a
|
|
5064
|
+
// foreign process, or a proxy binary too old to answer. Routing anyway
|
|
5065
|
+
// would hand the operator's provider keys to that listener (#945).
|
|
5066
|
+
if (runtimeState)
|
|
5067
|
+
process.stderr.write(`${mark("warn")} ${runtimeState.line}\n`);
|
|
5068
|
+
direct = true;
|
|
5069
|
+
}
|
|
5035
5070
|
const subscriptionCompressionActive = !direct && proxyReady && subscriptionCompress && desiredRecoveryViaMCP
|
|
5036
5071
|
&& proxyRuntimeMatches(runtime, effectiveMode, desiredRecoveryViaMCP);
|
|
5037
5072
|
if (direct) {
|
|
@@ -5100,7 +5135,13 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = f
|
|
|
5100
5135
|
// Direct mode: inherit the shell env with NO profile injection, stripping only
|
|
5101
5136
|
// our own routing if it leaked in — so the agent talks straight to the provider
|
|
5102
5137
|
// with its own key. Any unrelated base URL the user set themselves stays put.
|
|
5103
|
-
|
|
5138
|
+
// Codex is excluded by design, and the README has said so all along: its runtime
|
|
5139
|
+
// rejects the rewrite (openai/codex#18491). No door actually implemented that, and
|
|
5140
|
+
// since #1037 shrinkHook declines every Codex tool event — so registering it here
|
|
5141
|
+
// bought nothing but a node spawn per tool call. The persistent `caveman enable
|
|
5142
|
+
// codex` door still writes the entry; removing it there needs a migration, since
|
|
5143
|
+
// nativeHookEntriesHealthy would read every existing install as degraded.
|
|
5144
|
+
const includeShrink = !opts.noShrink && wrapCompressEnabled(opts) && agent?.id !== "codex";
|
|
5104
5145
|
let childArgs = cmdArgs;
|
|
5105
5146
|
let env;
|
|
5106
5147
|
try {
|
|
@@ -5108,7 +5149,7 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = f
|
|
|
5108
5149
|
? { ...process.env }
|
|
5109
5150
|
: agent?.id === "codex"
|
|
5110
5151
|
? buildCodexEphemeralWrapEnv(gw, codexSubscription, ephemeralMcpBinary, includeShrink, ephemeralDelegateMcp)
|
|
5111
|
-
: buildWrapEnv(agent, gw, opts.mcpMode);
|
|
5152
|
+
: buildWrapEnv(agent, gw, opts.mcpMode, cmdArgs, runtime.owner === "unknown" ? undefined : runtime);
|
|
5112
5153
|
if (!direct && agent?.id === "claude") {
|
|
5113
5154
|
const pluginDir = buildClaudeEphemeralPlugin(ephemeralMcpBinary, includeShrink, Boolean(opts.autoRecall), ephemeralDelegateMcp);
|
|
5114
5155
|
childArgs = ["--plugin-dir", pluginDir, ...cmdArgs];
|
|
@@ -5124,13 +5165,24 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = f
|
|
|
5124
5165
|
childArgs = cmdArgs;
|
|
5125
5166
|
process.stderr.write(`${mark("warn")} temporary native pack unavailable: ${error.message}; launching ${agent?.display_name ?? bin} directly\n`);
|
|
5126
5167
|
}
|
|
5168
|
+
// Qwen's extension lock and Hermes's forced custom provider are routing
|
|
5169
|
+
// injection too. Remove them on direct fallback so the host keeps the user's
|
|
5170
|
+
// provider and policy. OpenClaw's `chat` is a command, not a routing override.
|
|
5171
|
+
if (direct && (agent?.id === "qwen" || agent?.id === "hermes")
|
|
5172
|
+
&& agent.args.every((arg, index) => childArgs[index] === arg)) {
|
|
5173
|
+
childArgs = childArgs.slice(agent.args.length);
|
|
5174
|
+
}
|
|
5127
5175
|
if (!direct && agent?.id === "claude")
|
|
5128
5176
|
Object.assign(env, claudeCaveBuildEnv());
|
|
5129
5177
|
if (!direct)
|
|
5130
5178
|
maybeWarnHermesMissingKey(agent, gw);
|
|
5131
5179
|
if (direct) {
|
|
5180
|
+
// buildWrapEnv writes the agent-attributed `${gw}/w/<agent>` form, and an
|
|
5181
|
+
// outer routed wrap may leak the bare form; a direct launch strips both.
|
|
5182
|
+
const gwPrefix = `${gw.replace(/\/+$/, "")}/`;
|
|
5132
5183
|
for (const k of WRAP_BASE_URL_ENV_VARS) {
|
|
5133
|
-
|
|
5184
|
+
const value = env[k];
|
|
5185
|
+
if (value !== undefined && (value === gw || value.startsWith(gwPrefix)))
|
|
5134
5186
|
delete env[k];
|
|
5135
5187
|
}
|
|
5136
5188
|
}
|
|
@@ -5215,7 +5267,7 @@ async function spawnWrapped(bin, cmdArgs, agent, opts, gw, codexSubscription = f
|
|
|
5215
5267
|
cleanupWrapTempDirs();
|
|
5216
5268
|
removeProxySessionMarker(sessionMarker);
|
|
5217
5269
|
}
|
|
5218
|
-
return { code, proxyStarted, sessionStart, summaryKind };
|
|
5270
|
+
return { code, proxyStarted, routeBypass, sessionStart, summaryKind };
|
|
5219
5271
|
}
|
|
5220
5272
|
export function claudeCaveBuildEnv() {
|
|
5221
5273
|
const lockPath = join(process.cwd(), ".caveman", "agent.lock.json");
|
|
@@ -5384,8 +5436,8 @@ async function startWrapProxy(mode, mcpRecovery, toon, pixelModels, pixelDensity
|
|
|
5384
5436
|
return false;
|
|
5385
5437
|
}
|
|
5386
5438
|
// startProxyKeepalive heartbeats the local proxy while the wrapped agent process
|
|
5387
|
-
// is alive,
|
|
5388
|
-
//
|
|
5439
|
+
// is alive, for compatibility with older proxies that still idle-exit (#860).
|
|
5440
|
+
// Current proxy versions never idle-exit. The proxy treats
|
|
5389
5441
|
// the beat as activity only — nothing is recorded. No immediate beat: launching
|
|
5390
5442
|
// is already activity, and short-lived runs should never touch the port. The
|
|
5391
5443
|
// timer is unref'd and every failure is ignored (fail-open, like the hooks).
|
|
@@ -5425,17 +5477,37 @@ function renderTemplate(s, gw = gatewayURL()) {
|
|
|
5425
5477
|
.replaceAll("{{cave_api_key}}", caveAPIKey)
|
|
5426
5478
|
.replaceAll("{{cave_org_id}}", orgIdFromConfigFile());
|
|
5427
5479
|
}
|
|
5480
|
+
const OPTIONAL_OPENAI_KEY_ENV_TEMPLATE = "{{cave_optional_openai_key_env}}";
|
|
5428
5481
|
// renderDeep applies renderTemplate to every string leaf of a JSON value — used to
|
|
5429
5482
|
// render an agent's inline-config template before it is stringified into an env var.
|
|
5430
|
-
|
|
5483
|
+
// Optional credential references disappear as whole object properties when their
|
|
5484
|
+
// source variable is unavailable. Secrets never enter generated JSON: the retained
|
|
5485
|
+
// value is the agent-native `$OPENAI_API_KEY` reference, not its expansion.
|
|
5486
|
+
function renderDeep(v, gw = gatewayURL(), env = process.env, options = {}) {
|
|
5487
|
+
if (v === OPTIONAL_OPENAI_KEY_ENV_TEMPLATE) {
|
|
5488
|
+
const key = env.OPENAI_API_KEY;
|
|
5489
|
+
const inherited = typeof key === "string" && !!key.trim() && !/[\r\n]/.test(key);
|
|
5490
|
+
return (options.optionalOpenAIKeyEnvAvailable ?? inherited)
|
|
5491
|
+
? options.optionalOpenAIKeyReference ?? "$OPENAI_API_KEY"
|
|
5492
|
+
: undefined;
|
|
5493
|
+
}
|
|
5431
5494
|
if (typeof v === "string")
|
|
5432
5495
|
return renderTemplate(v, gw);
|
|
5433
|
-
if (Array.isArray(v))
|
|
5434
|
-
return v.map((item) =>
|
|
5496
|
+
if (Array.isArray(v)) {
|
|
5497
|
+
return v.map((item) => {
|
|
5498
|
+
const rendered = renderDeep(item, gw, env, options);
|
|
5499
|
+
if (rendered === undefined)
|
|
5500
|
+
throw new Error("optional profile credentials cannot be array elements");
|
|
5501
|
+
return rendered;
|
|
5502
|
+
});
|
|
5503
|
+
}
|
|
5435
5504
|
if (v && typeof v === "object") {
|
|
5436
5505
|
const out = {};
|
|
5437
|
-
for (const [k, val] of Object.entries(v))
|
|
5438
|
-
|
|
5506
|
+
for (const [k, val] of Object.entries(v)) {
|
|
5507
|
+
const rendered = renderDeep(val, gw, env, options);
|
|
5508
|
+
if (rendered !== undefined)
|
|
5509
|
+
out[k] = rendered;
|
|
5510
|
+
}
|
|
5439
5511
|
return out;
|
|
5440
5512
|
}
|
|
5441
5513
|
return v;
|
|
@@ -5463,22 +5535,27 @@ function stripJson5Comments(s) {
|
|
|
5463
5535
|
continue;
|
|
5464
5536
|
}
|
|
5465
5537
|
if (ch === "/" && next === "/") {
|
|
5538
|
+
out += " ";
|
|
5466
5539
|
i += 2;
|
|
5467
|
-
while (i < s.length && s[i] !== "\n" && s[i] !== "\r")
|
|
5540
|
+
while (i < s.length && s[i] !== "\n" && s[i] !== "\r") {
|
|
5541
|
+
out += /\s/.test(s[i]) ? s[i] : " ";
|
|
5468
5542
|
i++;
|
|
5543
|
+
}
|
|
5469
5544
|
if (i < s.length)
|
|
5470
5545
|
out += s[i];
|
|
5471
5546
|
continue;
|
|
5472
5547
|
}
|
|
5473
5548
|
if (ch === "/" && next === "*") {
|
|
5549
|
+
out += " ";
|
|
5474
5550
|
i += 2;
|
|
5475
5551
|
while (i < s.length && !(s[i] === "*" && s[i + 1] === "/")) {
|
|
5476
|
-
|
|
5477
|
-
out += s[i];
|
|
5552
|
+
out += /\s/.test(s[i]) ? s[i] : " ";
|
|
5478
5553
|
i++;
|
|
5479
5554
|
}
|
|
5480
|
-
if (i < s.length)
|
|
5555
|
+
if (i < s.length) {
|
|
5556
|
+
out += " ";
|
|
5481
5557
|
i++;
|
|
5558
|
+
}
|
|
5482
5559
|
continue;
|
|
5483
5560
|
}
|
|
5484
5561
|
out += ch;
|
|
@@ -5517,8 +5594,7 @@ function stripTrailingCommas(s) {
|
|
|
5517
5594
|
}
|
|
5518
5595
|
return out;
|
|
5519
5596
|
}
|
|
5520
|
-
|
|
5521
|
-
const raw = readFileSync(path, "utf8");
|
|
5597
|
+
function parseJsonc(raw) {
|
|
5522
5598
|
try {
|
|
5523
5599
|
return JSON.parse(raw);
|
|
5524
5600
|
}
|
|
@@ -5526,21 +5602,47 @@ export function readJson5Lenient(path) {
|
|
|
5526
5602
|
return JSON.parse(stripTrailingCommas(stripJson5Comments(raw)));
|
|
5527
5603
|
}
|
|
5528
5604
|
}
|
|
5605
|
+
export function readJson5Lenient(path) {
|
|
5606
|
+
return parseJsonc(readFileSync(path, "utf8"));
|
|
5607
|
+
}
|
|
5529
5608
|
function isPlainObject(v) {
|
|
5530
5609
|
if (!v || typeof v !== "object" || Array.isArray(v))
|
|
5531
5610
|
return false;
|
|
5532
5611
|
const proto = Object.getPrototypeOf(v);
|
|
5533
5612
|
return proto === Object.prototype || proto === null;
|
|
5534
5613
|
}
|
|
5614
|
+
function isSafeObjectKey(key) {
|
|
5615
|
+
return key !== "__proto__" && key !== "constructor" && key !== "prototype";
|
|
5616
|
+
}
|
|
5535
5617
|
export function deepMerge(base, overlay) {
|
|
5536
|
-
if (isPlainObject(
|
|
5537
|
-
const out = {
|
|
5538
|
-
|
|
5539
|
-
|
|
5618
|
+
if (isPlainObject(overlay)) {
|
|
5619
|
+
const out = {};
|
|
5620
|
+
if (isPlainObject(base)) {
|
|
5621
|
+
for (const [k, v] of Object.entries(base)) {
|
|
5622
|
+
if (isSafeObjectKey(k))
|
|
5623
|
+
out[k] = isPlainObject(v) ? deepMerge({}, v) : v;
|
|
5624
|
+
}
|
|
5625
|
+
}
|
|
5626
|
+
for (const [k, v] of Object.entries(overlay)) {
|
|
5627
|
+
if (isSafeObjectKey(k))
|
|
5628
|
+
out[k] = deepMerge(out[k], v);
|
|
5629
|
+
}
|
|
5540
5630
|
return out;
|
|
5541
5631
|
}
|
|
5542
5632
|
return overlay;
|
|
5543
5633
|
}
|
|
5634
|
+
export function platformDefaultConfigPath(kind, platform = process.platform, _env = process.env) {
|
|
5635
|
+
if (kind !== "qwen-system-settings")
|
|
5636
|
+
return undefined;
|
|
5637
|
+
if (platform === "darwin")
|
|
5638
|
+
return "/Library/Application Support/QwenCode/settings.json";
|
|
5639
|
+
// Qwen 0.22.3 deliberately does not consult %ProgramData% here.
|
|
5640
|
+
if (platform === "win32")
|
|
5641
|
+
return "C:\\ProgramData\\qwen-code\\settings.json";
|
|
5642
|
+
if (platform === "linux")
|
|
5643
|
+
return "/etc/qwen-code/settings.json";
|
|
5644
|
+
return undefined;
|
|
5645
|
+
}
|
|
5544
5646
|
function baseConfigPath(base) {
|
|
5545
5647
|
const envPath = base.env_var ? process.env[base.env_var] : undefined;
|
|
5546
5648
|
if (envPath && envPath.trim())
|
|
@@ -5548,6 +5650,11 @@ function baseConfigPath(base) {
|
|
|
5548
5650
|
const stateDir = base.state_dir?.env_var ? process.env[base.state_dir.env_var] : undefined;
|
|
5549
5651
|
if (stateDir && stateDir.trim())
|
|
5550
5652
|
return join(expandTilde(stateDir), base.state_dir.filename);
|
|
5653
|
+
const platformDefault = base.platform_default
|
|
5654
|
+
? platformDefaultConfigPath(base.platform_default)
|
|
5655
|
+
: undefined;
|
|
5656
|
+
if (platformDefault)
|
|
5657
|
+
return platformDefault;
|
|
5551
5658
|
return expandTilde(base.path);
|
|
5552
5659
|
}
|
|
5553
5660
|
function readBaseConfig(inj) {
|
|
@@ -5579,9 +5686,9 @@ const OPENCLAW_API_BASE_PATH = {
|
|
|
5579
5686
|
"google-generative-ai": "/v1beta",
|
|
5580
5687
|
};
|
|
5581
5688
|
const OPENCLAW_WELL_KNOWN_PROVIDERS = {
|
|
5582
|
-
openai: { api: "openai-responses", apiKey: "${OPENAI_API_KEY}" },
|
|
5583
|
-
anthropic: { api: "anthropic-messages", apiKey: "${ANTHROPIC_API_KEY}" },
|
|
5584
|
-
google: { api: "google-generative-ai", apiKey: "${GEMINI_API_KEY}" },
|
|
5689
|
+
openai: { baseUrl: "https://api.openai.com/v1", api: "openai-responses", apiKey: "${OPENAI_API_KEY}" },
|
|
5690
|
+
anthropic: { baseUrl: "https://api.anthropic.com", api: "anthropic-messages", apiKey: "${ANTHROPIC_API_KEY}" },
|
|
5691
|
+
google: { baseUrl: "https://generativelanguage.googleapis.com/v1beta", api: "google-generative-ai", apiKey: "${GEMINI_API_KEY}" },
|
|
5585
5692
|
"openai-codex": { api: "openai-chatgpt-responses", auth: "oauth" },
|
|
5586
5693
|
};
|
|
5587
5694
|
const OPENCLAW_MODEL_DEFAULTS = {
|
|
@@ -5687,6 +5794,11 @@ function openClawProviderApi(providerId, provider, model) {
|
|
|
5687
5794
|
: undefined;
|
|
5688
5795
|
return modelApi || providerApi || wellKnownApi;
|
|
5689
5796
|
}
|
|
5797
|
+
function openClawEffectiveBaseUrl(api, baseUrl) {
|
|
5798
|
+
// OpenClaw normalizeModelCompat removes /v1 before the Anthropic SDK appends
|
|
5799
|
+
// /v1/messages. Pi passes its model base URL to that SDK unchanged.
|
|
5800
|
+
return api === "anthropic-messages" ? baseUrl?.replace(/\/v1\/?$/, "") : baseUrl;
|
|
5801
|
+
}
|
|
5690
5802
|
function openClawProviderModel(provider, modelId) {
|
|
5691
5803
|
const models = Array.isArray(provider.models) ? provider.models : [];
|
|
5692
5804
|
for (const item of models) {
|
|
@@ -5723,8 +5835,51 @@ function freshOpenClawModelRef(ctx) {
|
|
|
5723
5835
|
function appendUrlPath(base, path) {
|
|
5724
5836
|
return `${base.replace(/\/+$/, "")}${path}`;
|
|
5725
5837
|
}
|
|
5726
|
-
function
|
|
5727
|
-
return join(homedir(), ".
|
|
5838
|
+
export function claudeConfigDir(env = process.env) {
|
|
5839
|
+
return env.CLAUDE_CONFIG_DIR ? resolve(env.CLAUDE_CONFIG_DIR) : join(homedir(), ".claude");
|
|
5840
|
+
}
|
|
5841
|
+
export function claudeGlobalConfigPath(env = process.env) {
|
|
5842
|
+
// Claude keeps its default global/MCP config beside ~/.claude, but moves
|
|
5843
|
+
// that file inside a nonempty CLAUDE_CONFIG_DIR override.
|
|
5844
|
+
return env.CLAUDE_CONFIG_DIR ? join(claudeConfigDir(env), ".claude.json") : join(homedir(), ".claude.json");
|
|
5845
|
+
}
|
|
5846
|
+
export function geminiConfigDir(env = process.env) {
|
|
5847
|
+
// GEMINI_CLI_HOME replaces the home directory, not the .gemini directory.
|
|
5848
|
+
return resolve(env.GEMINI_CLI_HOME || homedir(), ".gemini");
|
|
5849
|
+
}
|
|
5850
|
+
function agentUserPath(agent, path) {
|
|
5851
|
+
const prefix = agent === "claude" ? "~/.claude/" : agent === "codex" ? "~/.codex/" : undefined;
|
|
5852
|
+
if (!prefix || !path.startsWith(prefix))
|
|
5853
|
+
return path;
|
|
5854
|
+
const root = agent === "claude" ? claudeConfigDir() : codexHomeDir();
|
|
5855
|
+
return join(root, path.slice(prefix.length));
|
|
5856
|
+
}
|
|
5857
|
+
export function codexHomeDir(env = process.env) {
|
|
5858
|
+
const configured = env.CODEX_HOME;
|
|
5859
|
+
if (!configured)
|
|
5860
|
+
return join(homedir(), ".codex");
|
|
5861
|
+
// Match Codex's own home resolver: a nonempty override may be relative, but
|
|
5862
|
+
// must already be a directory and is canonicalized before use. Never fall
|
|
5863
|
+
// back to another account's default home when the override is invalid.
|
|
5864
|
+
let metadata;
|
|
5865
|
+
try {
|
|
5866
|
+
metadata = statSync(configured);
|
|
5867
|
+
}
|
|
5868
|
+
catch (error) {
|
|
5869
|
+
if (error.code === "ENOENT") {
|
|
5870
|
+
throw new Error(`CODEX_HOME points to ${JSON.stringify(configured)}, but that path does not exist`);
|
|
5871
|
+
}
|
|
5872
|
+
throw new Error(`failed to read CODEX_HOME ${JSON.stringify(configured)}: ${error.message}`);
|
|
5873
|
+
}
|
|
5874
|
+
if (!metadata.isDirectory()) {
|
|
5875
|
+
throw new Error(`CODEX_HOME points to ${JSON.stringify(configured)}, but that path is not a directory`);
|
|
5876
|
+
}
|
|
5877
|
+
try {
|
|
5878
|
+
return realpathSync(configured);
|
|
5879
|
+
}
|
|
5880
|
+
catch (error) {
|
|
5881
|
+
throw new Error(`failed to canonicalize CODEX_HOME ${JSON.stringify(configured)}: ${error.message}`);
|
|
5882
|
+
}
|
|
5728
5883
|
}
|
|
5729
5884
|
function codexAuthPath() {
|
|
5730
5885
|
return join(codexHomeDir(), "auth.json");
|
|
@@ -5794,12 +5949,32 @@ function stripCodexCavemanProviderToml(text) {
|
|
|
5794
5949
|
}
|
|
5795
5950
|
return out.join("\n").trimEnd();
|
|
5796
5951
|
}
|
|
5952
|
+
// The api-key Codex route, in ONE place: the provider TOML writes it, the
|
|
5953
|
+
// install journal records it, and the doctor compares against it, and a route
|
|
5954
|
+
// only three of those four agree on reads as permanently degraded.
|
|
5955
|
+
const CODEX_API_KEY_ROUTE = "/w/codex/v1";
|
|
5956
|
+
function codexGatewayBase(gw, subscription) {
|
|
5957
|
+
// Codex's OpenAI-Responses client appends "/responses" onto base_url itself,
|
|
5958
|
+
// exactly as it does against the real api.openai.com, so what the proxy
|
|
5959
|
+
// receives is `<this path>/responses`. The openai adapter's Routes are a
|
|
5960
|
+
// closed, exact allowlist holding "/v1/responses" and never "/responses", so
|
|
5961
|
+
// the api-key route needs the "/v1" or every api-key Codex session 404s with
|
|
5962
|
+
// cave_route_not_found before one request reaches OpenAI (#1045). Same
|
|
5963
|
+
// convention aider already uses (`/w/aider/openai/v1`). The subscription
|
|
5964
|
+
// route is a different mux handler (`/chatgpt/`) that takes the suffix
|
|
5965
|
+
// verbatim, so it must NOT gain a "/v1".
|
|
5966
|
+
return appendUrlPath(gw, subscription ? "/chatgpt" : CODEX_API_KEY_ROUTE);
|
|
5967
|
+
}
|
|
5968
|
+
// Codex clears the stdio MCP environment, including these non-secret store
|
|
5969
|
+
// selectors. Forward their names so the proxy and recovery server share the
|
|
5970
|
+
// current launch's store without persisting provider credentials or stale paths.
|
|
5971
|
+
const CODEX_RECOVERY_ENV = 'env_vars = ["CAVEMAN_HOME", "CAVEMAN_CCR_DB"]';
|
|
5797
5972
|
function codexCavemanProviderToml(gw, subscription = true) {
|
|
5798
5973
|
return [
|
|
5799
5974
|
`model_provider = "caveman"`,
|
|
5800
5975
|
`[model_providers.caveman]`,
|
|
5801
5976
|
`name = "Caveman"`,
|
|
5802
|
-
`base_url = ${JSON.stringify(
|
|
5977
|
+
`base_url = ${JSON.stringify(codexGatewayBase(gw, subscription))}`,
|
|
5803
5978
|
`wire_api = "responses"`,
|
|
5804
5979
|
`requires_openai_auth = true`,
|
|
5805
5980
|
].join("\n");
|
|
@@ -5992,6 +6167,16 @@ function canonicalManagedHookEntry(entry) {
|
|
|
5992
6167
|
hooks[0].command = identity;
|
|
5993
6168
|
return JSON.stringify(clone);
|
|
5994
6169
|
}
|
|
6170
|
+
// Why: `think.shrink` (and its `CAVEMAN_SHRINK` env form) is the persisted
|
|
6171
|
+
// switch for the command-output rewrite, but only the ephemeral launcher ever
|
|
6172
|
+
// read it — every native writer passed a literal `true`, so `caveman enable` /
|
|
6173
|
+
// `doctor --fix` / `repairNativeAgent` reinstated `shrink-hook` no matter what
|
|
6174
|
+
// the config said and there was no persistent way to run the native
|
|
6175
|
+
// integration without it (#1049). Read in ONE place so the writers and the
|
|
6176
|
+
// health check that judges them cannot disagree about what is expected.
|
|
6177
|
+
function nativeShrinkEnabled() {
|
|
6178
|
+
return resolveCapabilities().values["think.shrink"].value;
|
|
6179
|
+
}
|
|
5995
6180
|
function nativeHooksDocument(agentId, includeShrink, base = {}, includeRecall = false) {
|
|
5996
6181
|
const root = JSON.parse(JSON.stringify(base));
|
|
5997
6182
|
const hooks = root.hooks && typeof root.hooks === "object" && !Array.isArray(root.hooks)
|
|
@@ -6003,21 +6188,46 @@ function nativeHooksDocument(agentId, includeShrink, base = {}, includeRecall =
|
|
|
6003
6188
|
? ["SessionStart", "UserPromptSubmit", "PreToolUse", "PermissionRequest", "PostToolUse", "PostToolUseFailure", "PreCompact", "PostCompact", "SubagentStart", "SubagentStop", "Stop", "SessionEnd"]
|
|
6004
6189
|
: ["SessionStart", "UserPromptSubmit", "PreToolUse", "PostToolUse", "PostToolUseFailure", "PreCompact", "SubagentStart", "SubagentStop", "Stop", "SessionEnd"];
|
|
6005
6190
|
const command = nativeHookCommand(agentId);
|
|
6191
|
+
const identity = `native-hook:${agentId}`;
|
|
6006
6192
|
for (const event of lifecycle) {
|
|
6007
|
-
|
|
6008
|
-
|
|
6009
|
-
|
|
6193
|
+
// Replace, never accumulate: a caveman native-hook entry for this agent
|
|
6194
|
+
// that points at another binary or adapter path (an upgrade, a moved
|
|
6195
|
+
// install, a dev build) is the SAME hook, so it goes before ours is added.
|
|
6196
|
+
// Matching on the exact command string alone appended a new set on every
|
|
6197
|
+
// path change and the host ran three caveman hooks per event.
|
|
6198
|
+
const list = (Array.isArray(hooks[event]) ? hooks[event] : [])
|
|
6199
|
+
.filter((entry) => managedHookIdentity(hookEntryCommand(entry) ?? "") !== identity);
|
|
6200
|
+
list.push(nativeHookEntry(command, agentId));
|
|
6010
6201
|
hooks[event] = list;
|
|
6011
6202
|
}
|
|
6012
|
-
|
|
6203
|
+
{
|
|
6013
6204
|
const shrinkEvent = agentId === "gemini" ? "BeforeTool" : "PreToolUse";
|
|
6014
6205
|
const list = Array.isArray(hooks[shrinkEvent]) ? hooks[shrinkEvent] : [];
|
|
6015
6206
|
const shrinkCommand = `${cavemanBinForHook()} shrink-hook`;
|
|
6016
|
-
|
|
6207
|
+
// Same replace-not-accumulate rule as the native hook: a shrink-hook entry
|
|
6208
|
+
// under another caveman path is ours. When the switch is OFF the rule has
|
|
6209
|
+
// to reach OUR path too (#1049): `base` is the host's live file, so a
|
|
6210
|
+
// standalone install, or any caveman old enough to predate the switch,
|
|
6211
|
+
// leaves an entry here that honoring the switch only on the entries we ADD
|
|
6212
|
+
// would merge straight through — the rewrite stays live on exactly the
|
|
6213
|
+
// machines that asked for it off, and the install is born degraded because
|
|
6214
|
+
// nativeHookEntriesHealthy rejects a managed entry the expected document
|
|
6215
|
+
// lacks. Withdrawing ours is not a claim on the user's other hooks:
|
|
6216
|
+
// managedHookIdentity only matches a caveman binary.
|
|
6217
|
+
for (let i = list.length - 1; i >= 0; i--) {
|
|
6218
|
+
const entry = list[i];
|
|
6219
|
+
const existing = entry ? hookEntryCommand(entry) : undefined;
|
|
6220
|
+
if (existing === undefined || managedHookIdentity(existing) !== "shrink-hook")
|
|
6221
|
+
continue;
|
|
6222
|
+
if (!includeShrink || existing !== shrinkCommand)
|
|
6223
|
+
list.splice(i, 1);
|
|
6224
|
+
}
|
|
6225
|
+
if (includeShrink && !list.some((entry) => hookEntryCommand(entry) === shrinkCommand)) {
|
|
6017
6226
|
list.push(agentId === "gemini"
|
|
6018
6227
|
? { matcher: "run_shell_command", ...nativeHookEntry(shrinkCommand, agentId) }
|
|
6019
6228
|
: nativeHookEntry(shrinkCommand, agentId));
|
|
6020
6229
|
}
|
|
6230
|
+
// The lifecycle loop above always writes this event, so the key exists either way.
|
|
6021
6231
|
hooks[shrinkEvent] = list;
|
|
6022
6232
|
}
|
|
6023
6233
|
if (agentId === "claude" && includeRecall) {
|
|
@@ -6038,6 +6248,8 @@ function assertNativeHooksShape(path, root, agentId) {
|
|
|
6038
6248
|
const hooks = root.hooks;
|
|
6039
6249
|
if (!hooks)
|
|
6040
6250
|
return;
|
|
6251
|
+
// `true` on purpose, unlike the writers: this only reads the event NAMES to
|
|
6252
|
+
// refuse a non-array, so the superset is the safer set to check.
|
|
6041
6253
|
const expected = nativeHooksDocument(agentId, true).hooks;
|
|
6042
6254
|
for (const event of Object.keys(expected)) {
|
|
6043
6255
|
if (hooks[event] !== undefined && !Array.isArray(hooks[event])) {
|
|
@@ -6051,7 +6263,7 @@ function nativeHookEntriesHealthy(root, agentId) {
|
|
|
6051
6263
|
: undefined;
|
|
6052
6264
|
if (!hooks)
|
|
6053
6265
|
return false;
|
|
6054
|
-
const expected = nativeHooksDocument(agentId,
|
|
6266
|
+
const expected = nativeHooksDocument(agentId, nativeShrinkEnabled()).hooks;
|
|
6055
6267
|
const required = Object.entries(expected).every(([event, expectedRaw]) => {
|
|
6056
6268
|
const actual = Array.isArray(hooks[event]) ? hooks[event] : [];
|
|
6057
6269
|
const actualEntries = new Set(actual.map(canonicalManagedHookEntry).filter(Boolean));
|
|
@@ -6095,7 +6307,7 @@ function buildCodexEphemeralHome(gw, subscription, mcpBinary, includeShrink, del
|
|
|
6095
6307
|
const providerRoot = providerLines.shift();
|
|
6096
6308
|
const providerTables = providerLines.join("\n");
|
|
6097
6309
|
const mcp = mcpBinary
|
|
6098
|
-
? `\n\n[mcp_servers.caveman]\ncommand = ${JSON.stringify(mcpBinary)}\n`
|
|
6310
|
+
? `\n\n[mcp_servers.caveman]\ncommand = ${JSON.stringify(mcpBinary)}\n${CODEX_RECOVERY_ENV}\n`
|
|
6099
6311
|
: "\n";
|
|
6100
6312
|
const delegateArgs = delegateMcp?.args.length
|
|
6101
6313
|
? `\nargs = [${delegateMcp.args.map((arg) => JSON.stringify(arg)).join(", ")}]`
|
|
@@ -6114,6 +6326,9 @@ function buildCodexEphemeralWrapEnv(gw, subscription, mcpBinary, includeShrink,
|
|
|
6114
6326
|
const env = { ...process.env };
|
|
6115
6327
|
for (const key of WRAP_BASE_URL_ENV_VARS)
|
|
6116
6328
|
delete env[key];
|
|
6329
|
+
// The ephemeral CODEX_HOME points Codex at the same loopback gateway, so it
|
|
6330
|
+
// needs the same proxy exemption the base-url wrap path gets.
|
|
6331
|
+
Object.assign(env, gatewayNoProxyEnv(gw));
|
|
6117
6332
|
env.CODEX_HOME = buildCodexEphemeralHome(gw, subscription, mcpBinary, includeShrink, delegateMcp);
|
|
6118
6333
|
return env;
|
|
6119
6334
|
}
|
|
@@ -6256,6 +6471,127 @@ function atomicWriteFile(path, bytes, mode = 0o600) {
|
|
|
6256
6471
|
throw error;
|
|
6257
6472
|
}
|
|
6258
6473
|
}
|
|
6474
|
+
function fsyncParentDirectory(path) {
|
|
6475
|
+
let fd;
|
|
6476
|
+
try {
|
|
6477
|
+
fd = openSync(dirname(path), constants.O_RDONLY);
|
|
6478
|
+
fsyncSync(fd);
|
|
6479
|
+
}
|
|
6480
|
+
catch {
|
|
6481
|
+
// Some platforms/filesystems reject directory fsync. File fsync + atomic
|
|
6482
|
+
// rename still provides strongest portable guarantee available to Node.
|
|
6483
|
+
}
|
|
6484
|
+
finally {
|
|
6485
|
+
if (fd !== undefined)
|
|
6486
|
+
try {
|
|
6487
|
+
closeSync(fd);
|
|
6488
|
+
}
|
|
6489
|
+
catch { /* best effort */ }
|
|
6490
|
+
}
|
|
6491
|
+
}
|
|
6492
|
+
function durableAtomicWriteFile(path, bytes, mode = 0o600) {
|
|
6493
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
6494
|
+
const temp = join(dirname(path), `.${basename(path)}.caveman-${process.pid}-${randomUUID()}.tmp`);
|
|
6495
|
+
let fd;
|
|
6496
|
+
try {
|
|
6497
|
+
fd = openSync(temp, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY, mode);
|
|
6498
|
+
writeFileSync(fd, bytes);
|
|
6499
|
+
fchmodSync(fd, mode);
|
|
6500
|
+
fsyncSync(fd);
|
|
6501
|
+
closeSync(fd);
|
|
6502
|
+
fd = undefined;
|
|
6503
|
+
renameSync(temp, path);
|
|
6504
|
+
fsyncParentDirectory(path);
|
|
6505
|
+
}
|
|
6506
|
+
catch (error) {
|
|
6507
|
+
if (fd !== undefined)
|
|
6508
|
+
try {
|
|
6509
|
+
closeSync(fd);
|
|
6510
|
+
}
|
|
6511
|
+
catch { /* original error wins */ }
|
|
6512
|
+
try {
|
|
6513
|
+
unlinkSync(temp);
|
|
6514
|
+
}
|
|
6515
|
+
catch { /* no partial */ }
|
|
6516
|
+
throw error;
|
|
6517
|
+
}
|
|
6518
|
+
}
|
|
6519
|
+
// Publish a fully-synced file without replacing an existing intent. Hard-linking
|
|
6520
|
+
// a same-directory temp gives O_EXCL semantics plus atomic visibility.
|
|
6521
|
+
function durableCreateFile(path, bytes, mode = 0o600) {
|
|
6522
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
6523
|
+
const temp = join(dirname(path), `.${basename(path)}.caveman-create-${process.pid}-${randomUUID()}.tmp`);
|
|
6524
|
+
try {
|
|
6525
|
+
durableAtomicWriteFile(temp, bytes, mode);
|
|
6526
|
+
linkSync(temp, path);
|
|
6527
|
+
fsyncParentDirectory(path);
|
|
6528
|
+
}
|
|
6529
|
+
finally {
|
|
6530
|
+
try {
|
|
6531
|
+
unlinkSync(temp);
|
|
6532
|
+
}
|
|
6533
|
+
catch { /* published or failed before temp creation */ }
|
|
6534
|
+
}
|
|
6535
|
+
}
|
|
6536
|
+
function optionalBytesEqual(left, right) {
|
|
6537
|
+
return left === null ? right === null : right !== null && left.equals(right);
|
|
6538
|
+
}
|
|
6539
|
+
function durableReplaceFileIfUnchanged(path, expected, next, mode = 0o600) {
|
|
6540
|
+
const current = fileBytes(path);
|
|
6541
|
+
if (!optionalBytesEqual(current, expected))
|
|
6542
|
+
throw new Error(`${path} changed during MCP update; refusing overwrite`);
|
|
6543
|
+
if (next === null) {
|
|
6544
|
+
if (current !== null) {
|
|
6545
|
+
const atDelete = fileBytes(path);
|
|
6546
|
+
if (!optionalBytesEqual(atDelete, expected))
|
|
6547
|
+
throw new Error(`${path} changed during MCP update; refusing removal`);
|
|
6548
|
+
unlinkSync(path);
|
|
6549
|
+
fsyncParentDirectory(path);
|
|
6550
|
+
}
|
|
6551
|
+
return;
|
|
6552
|
+
}
|
|
6553
|
+
// Prepare durable replacement first, then run final compare immediately
|
|
6554
|
+
// before rename. Per-agent lock serializes Caveman writers; this CAS catches
|
|
6555
|
+
// external edits observed before commit without erasing them.
|
|
6556
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
6557
|
+
const temp = join(dirname(path), `.${basename(path)}.caveman-cas-${process.pid}-${randomUUID()}.tmp`);
|
|
6558
|
+
let fd;
|
|
6559
|
+
try {
|
|
6560
|
+
fd = openSync(temp, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY, mode);
|
|
6561
|
+
writeFileSync(fd, next);
|
|
6562
|
+
fchmodSync(fd, mode);
|
|
6563
|
+
fsyncSync(fd);
|
|
6564
|
+
closeSync(fd);
|
|
6565
|
+
fd = undefined;
|
|
6566
|
+
const atCommit = fileBytes(path);
|
|
6567
|
+
if (!optionalBytesEqual(atCommit, expected))
|
|
6568
|
+
throw new Error(`${path} changed during MCP update; refusing overwrite`);
|
|
6569
|
+
renameSync(temp, path);
|
|
6570
|
+
fsyncParentDirectory(path);
|
|
6571
|
+
}
|
|
6572
|
+
catch (error) {
|
|
6573
|
+
if (fd !== undefined)
|
|
6574
|
+
try {
|
|
6575
|
+
closeSync(fd);
|
|
6576
|
+
}
|
|
6577
|
+
catch { /* original error wins */ }
|
|
6578
|
+
try {
|
|
6579
|
+
unlinkSync(temp);
|
|
6580
|
+
}
|
|
6581
|
+
catch { /* no partial */ }
|
|
6582
|
+
throw error;
|
|
6583
|
+
}
|
|
6584
|
+
}
|
|
6585
|
+
function durableUnlink(path) {
|
|
6586
|
+
try {
|
|
6587
|
+
unlinkSync(path);
|
|
6588
|
+
fsyncParentDirectory(path);
|
|
6589
|
+
}
|
|
6590
|
+
catch (error) {
|
|
6591
|
+
if (error.code !== "ENOENT")
|
|
6592
|
+
throw error;
|
|
6593
|
+
}
|
|
6594
|
+
}
|
|
6259
6595
|
function parseJsonFileObject(path, bytes) {
|
|
6260
6596
|
if (!bytes || bytes.length === 0)
|
|
6261
6597
|
return {};
|
|
@@ -6324,6 +6660,13 @@ function claudeNativeMutations(gw, mcpBinary) {
|
|
|
6324
6660
|
&& wrapMode(gw) === "local" && proxyAnthropicUpstreamIsFirstParty();
|
|
6325
6661
|
if (assumeFirstParty)
|
|
6326
6662
|
env[CLAUDE_ASSUME_FIRST_PARTY_ENV] = "1";
|
|
6663
|
+
// Native routing points every later turn at the same loopback gateway, so it
|
|
6664
|
+
// needs the wrap path's proxy exemption too (#1001). Never clobber a value the
|
|
6665
|
+
// user already carries in settings.
|
|
6666
|
+
for (const [key, value] of Object.entries(gatewayNoProxyEnv(gw))) {
|
|
6667
|
+
if (env[key] === undefined)
|
|
6668
|
+
env[key] = value;
|
|
6669
|
+
}
|
|
6327
6670
|
// Claude Code turns tool search (progressive MCP tool disclosure) OFF as soon
|
|
6328
6671
|
// as ANTHROPIC_BASE_URL is not a first-party Anthropic host, so pointing it at
|
|
6329
6672
|
// caveman would otherwise force every MCP tool schema inline on every request
|
|
@@ -6333,8 +6676,8 @@ function claudeNativeMutations(gw, mcpBinary) {
|
|
|
6333
6676
|
if (env.ENABLE_TOOL_SEARCH === undefined)
|
|
6334
6677
|
env.ENABLE_TOOL_SEARCH = TOOL_SEARCH_DEFAULT;
|
|
6335
6678
|
settings.env = env;
|
|
6336
|
-
const withHooks = nativeHooksDocument("claude",
|
|
6337
|
-
const mcpPath =
|
|
6679
|
+
const withHooks = nativeHooksDocument("claude", nativeShrinkEnabled(), settings);
|
|
6680
|
+
const mcpPath = claudeGlobalConfigPath();
|
|
6338
6681
|
const mcpBefore = fileBytes(mcpPath);
|
|
6339
6682
|
const mcpRoot = parseJsonFileObject(mcpPath, mcpBefore);
|
|
6340
6683
|
if (mcpRoot.mcpServers !== undefined && (typeof mcpRoot.mcpServers !== "object" || mcpRoot.mcpServers === null || Array.isArray(mcpRoot.mcpServers))) {
|
|
@@ -6400,8 +6743,8 @@ function geminiNativeMutations(gw, mcpBinary) {
|
|
|
6400
6743
|
const installedMcp = { command: mcpBinary, args: [] };
|
|
6401
6744
|
servers.caveman = installedMcp;
|
|
6402
6745
|
settings.mcpServers = servers;
|
|
6403
|
-
const withHooks = nativeHooksDocument("gemini",
|
|
6404
|
-
const envPath = join(
|
|
6746
|
+
const withHooks = nativeHooksDocument("gemini", nativeShrinkEnabled(), settings);
|
|
6747
|
+
const envPath = join(geminiConfigDir(), ".env");
|
|
6405
6748
|
const envBefore = fileBytes(envPath);
|
|
6406
6749
|
const route = appendUrlPath(gw, "/w/gemini");
|
|
6407
6750
|
const nativeEnv = geminiNativeEnv(envBefore?.toString("utf8") ?? "", route);
|
|
@@ -6750,15 +7093,23 @@ function aiderNativeMutations(gw) {
|
|
|
6750
7093
|
];
|
|
6751
7094
|
}
|
|
6752
7095
|
function codexNativeConfig(source, gw, subscription, mcpBinary) {
|
|
6753
|
-
|
|
7096
|
+
// Remove caveman's own marker blocks FIRST. The legacy table strippers below
|
|
7097
|
+
// skip every line after a caveman table until the next TOML header, and the
|
|
7098
|
+
// tables block ends with [mcp_servers.caveman] followed by the end marker, so
|
|
7099
|
+
// running them first ate "# <<< caveman:native-tables" and the block this
|
|
7100
|
+
// function had itself written failed its own re-parse as "corrupted" on the
|
|
7101
|
+
// next wrap (every `caveman codex` run fell back to session-only wrap and
|
|
7102
|
+
// doctor reported drift).
|
|
7103
|
+
let stripped = source;
|
|
6754
7104
|
for (const [begin, end] of [[CODEX_NATIVE_ROOT_BEGIN, CODEX_NATIVE_ROOT_END], [CODEX_NATIVE_TABLES_BEGIN, CODEX_NATIVE_TABLES_END]]) {
|
|
6755
7105
|
const start = stripped.indexOf(begin);
|
|
6756
7106
|
const finish = stripped.indexOf(end);
|
|
6757
|
-
if ((start === -1) !== (finish === -1))
|
|
7107
|
+
if ((start === -1) !== (finish === -1) || finish < start)
|
|
6758
7108
|
throw new Error("existing Codex Caveman block is corrupted; run `caveman doctor codex`");
|
|
6759
7109
|
if (start !== -1)
|
|
6760
7110
|
stripped = `${stripped.slice(0, start)}${stripped.slice(finish + end.length)}`.trim();
|
|
6761
7111
|
}
|
|
7112
|
+
stripped = stripCodexCavemanMcpToml(stripCodexCavemanProviderToml(stripped));
|
|
6762
7113
|
const rootBlock = `${CODEX_NATIVE_ROOT_BEGIN}\nmodel_provider = "caveman"\n${CODEX_NATIVE_ROOT_END}`;
|
|
6763
7114
|
const providerLines = codexCavemanProviderToml(gw, subscription).split("\n").slice(1).join("\n");
|
|
6764
7115
|
const tablesBlock = [
|
|
@@ -6767,6 +7118,7 @@ function codexNativeConfig(source, gw, subscription, mcpBinary) {
|
|
|
6767
7118
|
"",
|
|
6768
7119
|
"[mcp_servers.caveman]",
|
|
6769
7120
|
`command = ${JSON.stringify(mcpBinary)}`,
|
|
7121
|
+
CODEX_RECOVERY_ENV,
|
|
6770
7122
|
CODEX_NATIVE_TABLES_END,
|
|
6771
7123
|
].join("\n");
|
|
6772
7124
|
const middle = stripped ? `\n\n${stripped}` : "";
|
|
@@ -6777,12 +7129,12 @@ function codexNativeMutations(gw, mcpBinary) {
|
|
|
6777
7129
|
const hooksBefore = fileBytes(hooksPath);
|
|
6778
7130
|
const hooksRoot = parseJsonFileObject(hooksPath, hooksBefore);
|
|
6779
7131
|
assertNativeHooksShape(hooksPath, hooksRoot, "codex");
|
|
6780
|
-
const hooks = nativeHooksDocument("codex",
|
|
7132
|
+
const hooks = nativeHooksDocument("codex", nativeShrinkEnabled(), hooksRoot);
|
|
6781
7133
|
const configPath = join(codexHomeDir(), "config.toml");
|
|
6782
7134
|
const configBefore = fileBytes(configPath);
|
|
6783
7135
|
const subscription = detectCodexWrapAuthMode() === "subscription";
|
|
6784
7136
|
const native = codexNativeConfig(configBefore?.toString("utf8") ?? "", gw, subscription, mcpBinary);
|
|
6785
|
-
const route =
|
|
7137
|
+
const route = codexGatewayBase(gw, subscription);
|
|
6786
7138
|
return [
|
|
6787
7139
|
{ file: hooksPath, before: hooksBefore, after: Buffer.from(JSON.stringify(hooks, null, 2) + "\n"), kind: "codex-hooks" },
|
|
6788
7140
|
{
|
|
@@ -7011,7 +7363,7 @@ function hermesNativeConfig(source, gw, mcpBinary) {
|
|
|
7011
7363
|
const routeBlock = [
|
|
7012
7364
|
` ${HERMES_NATIVE_ROUTE_BEGIN}`,
|
|
7013
7365
|
' provider: "custom"',
|
|
7014
|
-
` base_url: ${yamlQuote(appendUrlPath(gw, "/w/hermes"))}`,
|
|
7366
|
+
` base_url: ${yamlQuote(appendUrlPath(gw, "/w/hermes/v1"))}`,
|
|
7015
7367
|
` ${HERMES_NATIVE_ROUTE_END}`,
|
|
7016
7368
|
];
|
|
7017
7369
|
lines.splice(insertAt, 0, ...routeBlock);
|
|
@@ -7058,7 +7410,7 @@ function hermesNativeConfig(source, gw, mcpBinary) {
|
|
|
7058
7410
|
return {
|
|
7059
7411
|
text: yamlText(lines),
|
|
7060
7412
|
owned: {
|
|
7061
|
-
route: appendUrlPath(gw, "/w/hermes"),
|
|
7413
|
+
route: appendUrlPath(gw, "/w/hermes/v1"),
|
|
7062
7414
|
route_block: routeBlock.join("\n"),
|
|
7063
7415
|
previous_route_lines: previousRouteLines,
|
|
7064
7416
|
plugin_block: pluginBlock,
|
|
@@ -7152,6 +7504,99 @@ function withIntegrationLock(agent, run) {
|
|
|
7152
7504
|
catch { /* best effort; future process can reclaim stale owner */ }
|
|
7153
7505
|
}
|
|
7154
7506
|
}
|
|
7507
|
+
function withMcpConfigLock(configPath, run) {
|
|
7508
|
+
const canonicalPath = canonicalMcpConfigPath(configPath);
|
|
7509
|
+
const key = createHash("sha256").update(canonicalPath).digest("hex").slice(0, 20);
|
|
7510
|
+
const lock = join(dirname(canonicalPath), `.caveman-mcp-${key}.lock`);
|
|
7511
|
+
const token = randomUUID();
|
|
7512
|
+
const claim = `${lock}.claim-${token}`;
|
|
7513
|
+
const owner = { schema_version: 1, pid: process.pid, token, config_path: canonicalPath, started_at: new Date().toISOString() };
|
|
7514
|
+
mkdirSync(dirname(lock), { recursive: true, mode: 0o700 });
|
|
7515
|
+
mkdirSync(claim, { mode: 0o700 });
|
|
7516
|
+
try {
|
|
7517
|
+
durableAtomicWriteFile(join(claim, "owner.json"), Buffer.from(JSON.stringify(owner) + "\n"));
|
|
7518
|
+
try {
|
|
7519
|
+
renameSync(claim, lock);
|
|
7520
|
+
fsyncParentDirectory(lock);
|
|
7521
|
+
}
|
|
7522
|
+
catch (error) {
|
|
7523
|
+
// Rename-to-existing differs by platform (EEXIST, ENOTEMPTY, EPERM,
|
|
7524
|
+
// EACCES). Existing published lock is authority regardless of errno.
|
|
7525
|
+
try {
|
|
7526
|
+
lstatSync(lock);
|
|
7527
|
+
}
|
|
7528
|
+
catch {
|
|
7529
|
+
throw error;
|
|
7530
|
+
}
|
|
7531
|
+
let stale = false;
|
|
7532
|
+
try {
|
|
7533
|
+
const lockStat = lstatSync(lock);
|
|
7534
|
+
const ownerPath = join(lock, "owner.json");
|
|
7535
|
+
const ownerStat = lstatSync(ownerPath);
|
|
7536
|
+
const existing = JSON.parse(readFileSync(ownerPath, "utf8"));
|
|
7537
|
+
const keys = ["config_path", "pid", "schema_version", "started_at", "token"];
|
|
7538
|
+
if (!lockStat.isDirectory() || lockStat.isSymbolicLink()
|
|
7539
|
+
|| !ownerStat.isFile() || ownerStat.isSymbolicLink()
|
|
7540
|
+
|| readdirSync(lock).sort().join("\0") !== "owner.json"
|
|
7541
|
+
|| Object.keys(existing).sort().join("\0") !== keys.join("\0")
|
|
7542
|
+
|| existing.schema_version !== 1
|
|
7543
|
+
|| typeof existing.pid !== "number" || !Number.isInteger(existing.pid) || existing.pid <= 1
|
|
7544
|
+
|| typeof existing.token !== "string"
|
|
7545
|
+
|| !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(existing.token)
|
|
7546
|
+
|| existing.config_path !== canonicalPath
|
|
7547
|
+
|| typeof existing.started_at !== "string"
|
|
7548
|
+
|| new Date(existing.started_at).toISOString() !== existing.started_at
|
|
7549
|
+
|| process.platform !== "win32" && ((lockStat.mode | ownerStat.mode) & 0o077) !== 0) {
|
|
7550
|
+
throw new Error("invalid MCP lock owner");
|
|
7551
|
+
}
|
|
7552
|
+
try {
|
|
7553
|
+
process.kill(existing.pid, 0);
|
|
7554
|
+
}
|
|
7555
|
+
catch (probeError) {
|
|
7556
|
+
stale = probeError.code === "ESRCH";
|
|
7557
|
+
}
|
|
7558
|
+
}
|
|
7559
|
+
catch {
|
|
7560
|
+
// Populated claim is durable before publication, so malformed or
|
|
7561
|
+
// ownerless lock can never be our crash residue. Never delete it.
|
|
7562
|
+
stale = false;
|
|
7563
|
+
}
|
|
7564
|
+
if (!stale)
|
|
7565
|
+
throw new Error(`MCP config change already running for ${canonicalPath}`);
|
|
7566
|
+
const quarantine = `${lock}.stale-${token}`;
|
|
7567
|
+
try {
|
|
7568
|
+
renameSync(lock, quarantine);
|
|
7569
|
+
renameSync(claim, lock);
|
|
7570
|
+
fsyncParentDirectory(lock);
|
|
7571
|
+
process.stderr.write(`${mark("warn")} reclaimed stale MCP config lock for ${canonicalPath}\n`);
|
|
7572
|
+
}
|
|
7573
|
+
catch {
|
|
7574
|
+
throw new Error(`MCP config change already running for ${canonicalPath}`);
|
|
7575
|
+
}
|
|
7576
|
+
finally {
|
|
7577
|
+
try {
|
|
7578
|
+
rmSync(quarantine, { recursive: true, force: true });
|
|
7579
|
+
}
|
|
7580
|
+
catch { /* isolated stale lock only */ }
|
|
7581
|
+
}
|
|
7582
|
+
}
|
|
7583
|
+
return run();
|
|
7584
|
+
}
|
|
7585
|
+
finally {
|
|
7586
|
+
try {
|
|
7587
|
+
rmSync(claim, { recursive: true, force: true });
|
|
7588
|
+
}
|
|
7589
|
+
catch { /* published or absent */ }
|
|
7590
|
+
try {
|
|
7591
|
+
const current = JSON.parse(readFileSync(join(lock, "owner.json"), "utf8"));
|
|
7592
|
+
if (current.token === token) {
|
|
7593
|
+
rmSync(lock, { recursive: true, force: true });
|
|
7594
|
+
fsyncParentDirectory(lock);
|
|
7595
|
+
}
|
|
7596
|
+
}
|
|
7597
|
+
catch { /* only owning token may remove a published lock */ }
|
|
7598
|
+
}
|
|
7599
|
+
}
|
|
7155
7600
|
function applyNativeMutations(agent, profile, mutations) {
|
|
7156
7601
|
const base = join(cavemanHome(), "integrations", "backups", agent, randomUUID());
|
|
7157
7602
|
mkdirSync(base, { recursive: true, mode: 0o700 });
|
|
@@ -7309,7 +7754,10 @@ function enableNative(argv) {
|
|
|
7309
7754
|
if (existing.installed) {
|
|
7310
7755
|
if (existing.state === "installed")
|
|
7311
7756
|
return "already";
|
|
7312
|
-
|
|
7757
|
+
// `--fix` on purpose: bare `caveman doctor <agent>` prints JSON that says
|
|
7758
|
+
// `degraded` and nothing that says how to leave that state, so pointing
|
|
7759
|
+
// at it alone dead-ends the user who followed this line here (#1049).
|
|
7760
|
+
throw new Error(`${profile.display_name} integration is degraded; run \`caveman doctor ${agent} --fix\` before changing it`);
|
|
7313
7761
|
}
|
|
7314
7762
|
const mutations = nativeMutationsFor(agent, gw, mcpBinary);
|
|
7315
7763
|
const route = mutations.find((item) => typeof item.owned?.route === "string")?.owned?.route;
|
|
@@ -7323,7 +7771,12 @@ function enableNative(argv) {
|
|
|
7323
7771
|
? ` Core: read-only ${aiderCorePath()}; lifecycle/tool interception unavailable; Ledger observational\n`
|
|
7324
7772
|
: agent === "pi"
|
|
7325
7773
|
? ` lifecycle/Core/tool rewrite: bundled Pi extension -> ${nativeHookCommand(agent)}\n`
|
|
7326
|
-
|
|
7774
|
+
// Codex gets the lifecycle line without the "tool rewrite" claim: since
|
|
7775
|
+
// #1037 shrink-hook declines every Codex tool event, so promising one here
|
|
7776
|
+
// would be the same false claim `doctor` used to report.
|
|
7777
|
+
: agent === "codex"
|
|
7778
|
+
? ` lifecycle/Core: ${nativeHookCommand(agent)}; command-output rewrite unavailable in Codex\n`
|
|
7779
|
+
: ` lifecycle/Core/tool rewrite: ${nativeHookCommand(agent)}${agent === "hermes" ? " via native plugin" : ` + ${cavemanBinForHook()} shrink-hook`}\n`);
|
|
7327
7780
|
applyNativeMutations(agent, profile, mutations);
|
|
7328
7781
|
return "enabled";
|
|
7329
7782
|
});
|
|
@@ -7360,6 +7813,8 @@ function removeNativeHookEntries(root, agent) {
|
|
|
7360
7813
|
: undefined;
|
|
7361
7814
|
if (!hooks)
|
|
7362
7815
|
return root;
|
|
7816
|
+
// `true` on purpose, unlike the writers: disable must withdraw a shrink entry
|
|
7817
|
+
// an earlier install wrote, whatever the config says now.
|
|
7363
7818
|
const expected = nativeHooksDocument(agent, true).hooks;
|
|
7364
7819
|
const allowedManaged = new Set(Object.values(expected)
|
|
7365
7820
|
.flatMap((raw) => Array.isArray(raw) ? raw : [])
|
|
@@ -7834,7 +8289,9 @@ function nativeIntegrationStatus(agent) {
|
|
|
7834
8289
|
const coreResolution = runtimeConfig.resolution.values["think.core"];
|
|
7835
8290
|
const coreConfigured = coreResolution.value === true;
|
|
7836
8291
|
const mcp = probeMcpBinary();
|
|
7837
|
-
const expectedRoute =
|
|
8292
|
+
const expectedRoute = agent === "codex"
|
|
8293
|
+
? codexGatewayBase(gatewayURL(), detectCodexWrapAuthMode() === "subscription")
|
|
8294
|
+
: appendUrlPath(gatewayURL(), agent === "claude" ? "/w/claude" : agent === "hermes" ? "/w/hermes/v1" : agent === "gemini" ? "/w/gemini" : agent === "opencode" ? "/w/opencode" : agent === "pi" ? "/w/pi" : "/w/aider/openai/v1");
|
|
7838
8295
|
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";
|
|
7839
8296
|
const routeOperation = journal?.operations.find((operation) => operation.kind === routeKind);
|
|
7840
8297
|
// Pi's artifact encodes no route: the extension resolves the gateway at
|
|
@@ -7871,7 +8328,13 @@ function nativeIntegrationStatus(agent) {
|
|
|
7871
8328
|
lifecycle_hooks: agent !== "aider" && ownedHealthy,
|
|
7872
8329
|
core: coreActive,
|
|
7873
8330
|
mcp_recovery: agent !== "aider" && ownedHealthy && Boolean(mcp?.probe.current),
|
|
7874
|
-
|
|
8331
|
+
// Codex is false for the same reason hermes is: no command rewrite happens. The
|
|
8332
|
+
// shrink-hook entry is still written into ~/.codex/hooks.json (removing it from
|
|
8333
|
+
// nativeHooksDocument would make every existing install read as degraded, since
|
|
8334
|
+
// nativeHookEntriesHealthy rejects a managed entry the expected document lacks),
|
|
8335
|
+
// but since #1037 shrinkHook declines every Codex tool event, so the presence of
|
|
8336
|
+
// that entry no longer evidences a rewrite. Report the behavior, not the file.
|
|
8337
|
+
tool_rewrite: agent !== "aider" && ownedHealthy && (agent === "hermes" || agent === "codex" ? false : agent === "pi" ? fileText.includes("caveman:native-pi") : fileText.includes("shrink-hook")),
|
|
7875
8338
|
shared_runtime: proxyHealthy,
|
|
7876
8339
|
};
|
|
7877
8340
|
const versionStatus = nativeVersionStatus(host.version, profile.tested_agent_version);
|
|
@@ -8172,9 +8635,6 @@ function buildOpenClawOverlay(_agent, baseConfig, ctx) {
|
|
|
8172
8635
|
const configuredRef = resolveOpenClawPrimaryRef(baseConfig);
|
|
8173
8636
|
const ref = configuredRef ?? freshOpenClawModelRef(ctx);
|
|
8174
8637
|
const synthesized = configuredRef === undefined;
|
|
8175
|
-
if (synthesized) {
|
|
8176
|
-
process.stderr.write(`caveman: openclaw primary model not found; routing fresh config through caveman/${ref.model}\n`);
|
|
8177
|
-
}
|
|
8178
8638
|
const provider = resolveOpenClawProvider(baseConfig, ref.provider);
|
|
8179
8639
|
if (!provider) {
|
|
8180
8640
|
process.stderr.write(`caveman: openclaw provider "${ref.provider}" not found; leaving primary model unchanged\n`);
|
|
@@ -8191,11 +8651,74 @@ function buildOpenClawOverlay(_agent, baseConfig, ctx) {
|
|
|
8191
8651
|
process.stderr.write(`caveman: openclaw provider "${ref.provider}" has no API adapter; leaving primary model unchanged\n`);
|
|
8192
8652
|
return overlay;
|
|
8193
8653
|
}
|
|
8194
|
-
const
|
|
8654
|
+
const originalBaseUrl = getString(provider, ["baseUrl"]) ?? getString(OPENCLAW_WELL_KNOWN_PROVIDERS[ref.provider], ["baseUrl"]);
|
|
8655
|
+
// A fresh managed setup has no original provider endpoint to preserve. An
|
|
8656
|
+
// existing setup needs the actual listener's routing map, unavailable from a
|
|
8657
|
+
// managed gateway. Preserve it until that endpoint proof exists.
|
|
8658
|
+
const baseUrl = synthesized && ctx.mode === "managed"
|
|
8659
|
+
? openClawProxyBaseUrl(api, ctx.gatewayUrl)
|
|
8660
|
+
: ctx.mode === "local" ? verifiedProviderRoute(ctx.gatewayUrl, api, ref.provider, openClawEffectiveBaseUrl(api, originalBaseUrl), ctx.upstreams) : undefined;
|
|
8195
8661
|
if (!baseUrl) {
|
|
8196
|
-
process.stderr.write(`caveman: openclaw provider
|
|
8662
|
+
process.stderr.write(`caveman: openclaw provider "${ref.provider}" endpoint is not verified by the running proxy; leaving primary model unchanged\n`);
|
|
8197
8663
|
return overlay;
|
|
8198
8664
|
}
|
|
8665
|
+
if (ctx.mode === "local") {
|
|
8666
|
+
// baseUrl is provider-wide in OpenClaw. A fallback or later model switch
|
|
8667
|
+
// must retain its own API, and every model sharing this override must map
|
|
8668
|
+
// to the same verified SDK base URL.
|
|
8669
|
+
const catalog = Array.isArray(provider.models) ? provider.models : [];
|
|
8670
|
+
const providerApi = openClawProviderApi(ref.provider, provider);
|
|
8671
|
+
const modelApis = [providerApi, ...catalog.map(model => openClawProviderApi(ref.provider, provider, asJsonObject(model)))].filter((value) => value !== undefined);
|
|
8672
|
+
if (modelApis.some(modelApi => verifiedProviderRoute(ctx.gatewayUrl, modelApi, ref.provider, openClawEffectiveBaseUrl(modelApi, originalBaseUrl), ctx.upstreams) !== baseUrl)) {
|
|
8673
|
+
process.stderr.write(`caveman: openclaw provider "${ref.provider}" uses model APIs with different routes; leaving provider unchanged\n`);
|
|
8674
|
+
return overlay;
|
|
8675
|
+
}
|
|
8676
|
+
const request = asJsonObject(provider.request);
|
|
8677
|
+
const requestIssue = openClawRequestCompatibilityIssue(provider.request);
|
|
8678
|
+
if (requestIssue) {
|
|
8679
|
+
process.stderr.write(`caveman: openclaw provider "${ref.provider}" stays direct because ${requestIssue}; proxy compression is off for this provider\n`);
|
|
8680
|
+
return overlay;
|
|
8681
|
+
}
|
|
8682
|
+
const headerRequirements = [{ api: providerApi ?? api, headers: { ...asJsonObject(provider.headers), ...asJsonObject(request?.headers) } }, ...catalog.map(model => ({
|
|
8683
|
+
api: openClawProviderApi(ref.provider, provider, asJsonObject(model)),
|
|
8684
|
+
headers: { ...asJsonObject(provider.headers), ...asJsonObject(asJsonObject(model)?.headers), ...asJsonObject(request?.headers) },
|
|
8685
|
+
}))];
|
|
8686
|
+
const missingHeaders = uniqueStrings(headerRequirements.flatMap(requirement => unforwardedProviderHeaders(requirement.api, ref.provider, requirement.headers, ctx.upstreams)));
|
|
8687
|
+
if (missingHeaders.length) {
|
|
8688
|
+
const remedy = missingHeaders.some(name => ["authorization", "x-api-key", "x-goog-api-key"].includes(name.toLowerCase()))
|
|
8689
|
+
? "the proxy cannot preserve this authentication override; keep the provider direct"
|
|
8690
|
+
: `configure compat.${ref.provider}.forward_headers or keep the provider direct`;
|
|
8691
|
+
process.stderr.write(`caveman: openclaw provider "${ref.provider}" requires headers not preserved by the running proxy (${missingHeaders.join(", ")}); ${remedy}\n`);
|
|
8692
|
+
return overlay;
|
|
8693
|
+
}
|
|
8694
|
+
const routedModels = [];
|
|
8695
|
+
for (const rawModel of catalog.length ? catalog : [openClawMirroredModel(ref, provider, providerModel)]) {
|
|
8696
|
+
const model = asJsonObject(rawModel);
|
|
8697
|
+
const modelApi = openClawProviderApi(ref.provider, provider, model);
|
|
8698
|
+
if (!model || typeof model.id !== "string" || !modelApi || !originalBaseUrl) {
|
|
8699
|
+
process.stderr.write(`caveman: openclaw provider "${ref.provider}" has an unresolved model catalog; leaving provider unchanged\n`);
|
|
8700
|
+
return overlay;
|
|
8701
|
+
}
|
|
8702
|
+
const preserved = preserveOpenClawProviderCompat({ provider: ref.provider, id: model.id, api: modelApi, baseUrl: originalBaseUrl, compat: model.compat });
|
|
8703
|
+
if (!preserved.ok) {
|
|
8704
|
+
process.stderr.write(`caveman: openclaw provider "${ref.provider}" stays direct because ${preserved.reason}; proxy compression is off for this provider\n`);
|
|
8705
|
+
return overlay;
|
|
8706
|
+
}
|
|
8707
|
+
routedModels.push({ ...model, ...(preserved.compat ? { compat: preserved.compat } : {}) });
|
|
8708
|
+
}
|
|
8709
|
+
const headers = { ...asJsonObject(provider.headers), [OPENCLAW_AGENT_HEADER]: "openclaw" };
|
|
8710
|
+
const workflowSlug = normalizeWorkflowSlug(process.env["CAVE_WORKFLOW"]);
|
|
8711
|
+
if (workflowSlug)
|
|
8712
|
+
headers["x-cave-workflow"] = workflowSlug;
|
|
8713
|
+
const routedProvider = { ...provider, baseUrl, ...(providerApi ? { api: providerApi } : {}), headers,
|
|
8714
|
+
models: routedModels };
|
|
8715
|
+
return deepMerge(overlay, {
|
|
8716
|
+
models: { mode: "merge", providers: { [ref.provider]: routedProvider } },
|
|
8717
|
+
...(synthesized ? { agents: { defaults: { model: { primary: ref.raw } } } } : {}),
|
|
8718
|
+
});
|
|
8719
|
+
}
|
|
8720
|
+
if (synthesized)
|
|
8721
|
+
process.stderr.write(`caveman: openclaw primary model not found; routing fresh config through caveman/${ref.model}\n`);
|
|
8199
8722
|
const sourceApiKey = openClawResolvedProviderApiKey(ref.provider, provider);
|
|
8200
8723
|
const headers = { [OPENCLAW_AGENT_HEADER]: "openclaw" };
|
|
8201
8724
|
const workflowSlug = normalizeWorkflowSlug(process.env["CAVE_WORKFLOW"]);
|
|
@@ -8252,14 +8775,53 @@ function withoutCavemanMcpServer(overlay) {
|
|
|
8252
8775
|
delete next["mcp"];
|
|
8253
8776
|
return next;
|
|
8254
8777
|
}
|
|
8255
|
-
function applyConfigFileInjection(env, agent, inj, gw, modeGw = gw, mcpMode = "auto") {
|
|
8778
|
+
function applyConfigFileInjection(env, agent, inj, gw, modeGw = gw, mcpMode = "auto", agentArgs = [], upstreams) {
|
|
8256
8779
|
const baseConfig = readBaseConfig(inj);
|
|
8257
8780
|
const mode = wrapMode(modeGw);
|
|
8258
8781
|
const staticOverlay = mode === "managed" && inj.config_overlay.managed !== undefined ? inj.config_overlay.managed : inj.config_overlay.local;
|
|
8259
8782
|
const builder = overlayBuilders[agent.id];
|
|
8260
|
-
const
|
|
8261
|
-
|
|
8783
|
+
const renderOptions = {};
|
|
8784
|
+
if (agent.id === "qwen" && mode === "managed") {
|
|
8785
|
+
const available = qwenEffectiveOpenAIKeyAvailable();
|
|
8786
|
+
if (available === null)
|
|
8787
|
+
throw new Error("cannot safely resolve Qwen's effective OPENAI_API_KEY");
|
|
8788
|
+
renderOptions.optionalOpenAIKeyEnvAvailable = available;
|
|
8789
|
+
}
|
|
8790
|
+
let rawOverlay = renderDeep(builder ? builder(agent, baseConfig, { mode, gatewayUrl: gw, env, upstreams }) : staticOverlay, gw, env, renderOptions);
|
|
8791
|
+
if (agent.id === "qwen" && mcpMode === "auto") {
|
|
8792
|
+
const ownedMcp = ownedMcpRegistration(agent.id, agentArgs);
|
|
8793
|
+
if (ownedMcp) {
|
|
8794
|
+
// Qwen merges system settings last. Mirror only a still-journaled native
|
|
8795
|
+
// entry into this temporary system overlay so project settings cannot
|
|
8796
|
+
// replace the recovery server after Caveman has claimed it is available.
|
|
8797
|
+
rawOverlay = deepMerge(rawOverlay, { mcpServers: { caveman: qwenMcpEntry(ownedMcp) } });
|
|
8798
|
+
}
|
|
8799
|
+
else {
|
|
8800
|
+
// Qwen can advertise MCP schemas even when enterprise policy blocks calls.
|
|
8801
|
+
// Suppress the exact server in this highest-precedence temporary overlay
|
|
8802
|
+
// whenever native registration + journal + effective policy do not agree.
|
|
8803
|
+
const configured = jsonValueAt(baseConfig, ["mcp", "excluded"]);
|
|
8804
|
+
const preserved = Array.isArray(configured)
|
|
8805
|
+
? configured.filter((item) => typeof item === "string")
|
|
8806
|
+
: [];
|
|
8807
|
+
rawOverlay = deepMerge(rawOverlay, {
|
|
8808
|
+
mcp: { excluded: [...new Set([...preserved, "caveman"])] },
|
|
8809
|
+
});
|
|
8810
|
+
}
|
|
8811
|
+
}
|
|
8812
|
+
const overlay = (mcpMode === "auto" ? rawOverlay : withoutCavemanMcpServer(rawOverlay));
|
|
8262
8813
|
const merged = deepMerge(baseConfig, overlay);
|
|
8814
|
+
if (agent.id === "qwen") {
|
|
8815
|
+
// Qwen treats these as whole-object REPLACE settings. Our generic merge is
|
|
8816
|
+
// intentionally conservative for other agents, but retaining a sibling
|
|
8817
|
+
// provider here would make it selectable at runtime outside /w/qwen.
|
|
8818
|
+
for (const key of ["modelProviders", "providerProtocol"]) {
|
|
8819
|
+
const value = overlay[key];
|
|
8820
|
+
if (value === undefined)
|
|
8821
|
+
throw new Error(`Qwen routed profile is missing ${key}`);
|
|
8822
|
+
merged[key] = cloneJsonValue(value);
|
|
8823
|
+
}
|
|
8824
|
+
}
|
|
8263
8825
|
const rendered = JSON.stringify(merged, null, 2);
|
|
8264
8826
|
if (rendered === undefined)
|
|
8265
8827
|
throw new Error("merged config is not JSON");
|
|
@@ -8283,10 +8845,46 @@ function cleanupWrapTempDirs() {
|
|
|
8283
8845
|
}
|
|
8284
8846
|
}
|
|
8285
8847
|
const WRAP_BASE_URL_ENV_VARS = ["ANTHROPIC_BASE_URL", "OPENAI_BASE_URL", "OPENAI_API_BASE", "GOOGLE_GEMINI_BASE_URL"];
|
|
8848
|
+
// A corporate HTTP(S)_PROXY in the operator's shell applies to the wrapped agent
|
|
8849
|
+
// too, so the agent's own hop to caveman's loopback listener gets handed to that
|
|
8850
|
+
// proxy and times out — #1001's symptom, one layer above the proxy's own
|
|
8851
|
+
// upstream_proxy support. Exempt exactly the gateway host, appending to whatever
|
|
8852
|
+
// NO_PROXY the operator already set and using the spelling they already use.
|
|
8853
|
+
// resolveProxyUrl returns null both when no proxy applies and when NO_PROXY
|
|
8854
|
+
// already covers the gateway, which are precisely the cases needing no change.
|
|
8855
|
+
function gatewayNoProxyEnv(gw, env = process.env) {
|
|
8856
|
+
let target;
|
|
8857
|
+
try {
|
|
8858
|
+
target = new URL(gw);
|
|
8859
|
+
}
|
|
8860
|
+
catch {
|
|
8861
|
+
return {};
|
|
8862
|
+
}
|
|
8863
|
+
// Only a loopback listener needs the exemption. A managed gateway is a public
|
|
8864
|
+
// host that the operator's proxy is supposed to carry; exempting it there
|
|
8865
|
+
// sends the agent straight at a firewall that drops direct egress.
|
|
8866
|
+
if (wrapMode(gw) !== "local")
|
|
8867
|
+
return {};
|
|
8868
|
+
if (!resolveProxyUrl(target, env))
|
|
8869
|
+
return {};
|
|
8870
|
+
// Append to each spelling the operator actually set, reading the value from
|
|
8871
|
+
// the same variable it is written back to. Choosing the name by definedness
|
|
8872
|
+
// and the value with ?? dropped the other spelling's entries.
|
|
8873
|
+
const names = env.NO_PROXY === undefined && env.no_proxy !== undefined ? ["no_proxy"] : ["NO_PROXY"];
|
|
8874
|
+
if (env.NO_PROXY !== undefined && env.no_proxy !== undefined)
|
|
8875
|
+
names.push("no_proxy");
|
|
8876
|
+
const out = {};
|
|
8877
|
+
for (const name of names) {
|
|
8878
|
+
const current = (env[name] ?? "").trim();
|
|
8879
|
+
out[name] = current ? `${current},${target.hostname}` : target.hostname;
|
|
8880
|
+
}
|
|
8881
|
+
return out;
|
|
8882
|
+
}
|
|
8286
8883
|
function wrapBaseUrlEnv(gw) {
|
|
8287
8884
|
const env = {};
|
|
8288
8885
|
for (const key of WRAP_BASE_URL_ENV_VARS)
|
|
8289
8886
|
env[key] = gw;
|
|
8887
|
+
Object.assign(env, gatewayNoProxyEnv(gw));
|
|
8290
8888
|
// Same reason as the native-enable path: redirecting ANTHROPIC_BASE_URL makes
|
|
8291
8889
|
// Claude Code drop tool search and inline every MCP tool schema. Inert for the
|
|
8292
8890
|
// other wrappable agents, which never read this variable. A value already in
|
|
@@ -8397,14 +8995,14 @@ function applyClaudeBedrockWrap(env, agent, renderedGw, modeGw) {
|
|
|
8397
8995
|
// - config-env-content: render the mode-selected inline config and set it as one var
|
|
8398
8996
|
// - config-file: merge a mode-selected overlay into a temp config file
|
|
8399
8997
|
// An unrecognized method falls through to the generic union (fail-open), not a guess.
|
|
8400
|
-
// mcpMode governs
|
|
8401
|
-
//
|
|
8998
|
+
// mcpMode governs every temporary config arm that can inject the caveman MCP
|
|
8999
|
+
// server. It defaults to "auto" — today's behavior — rather than
|
|
8402
9000
|
// resolving config here, so this exported function stays a function of its
|
|
8403
9001
|
// arguments and cannot pick up the developer's own global config in tests. The
|
|
8404
9002
|
// one production caller passes the SAME opts.mcpMode that wrapMcpRecoveryAvailable
|
|
8405
9003
|
// reads, which is what keeps "what we inject" and "what we tell the proxy" from
|
|
8406
9004
|
// ever disagreeing.
|
|
8407
|
-
export function buildWrapEnv(agent, gw = gatewayURL(), mcpMode = "auto") {
|
|
9005
|
+
export function buildWrapEnv(agent, gw = gatewayURL(), mcpMode = "auto", agentArgs = [], upstreams) {
|
|
8408
9006
|
if (agent?.id === "gemini" && wrapMode(gw) === "managed") {
|
|
8409
9007
|
throw new Error("managed Gemini CLI routing is unsupported because Gemini CLI cannot send separate Caveman and upstream credentials");
|
|
8410
9008
|
}
|
|
@@ -8422,6 +9020,23 @@ export function buildWrapEnv(agent, gw = gatewayURL(), mcpMode = "auto") {
|
|
|
8422
9020
|
return env;
|
|
8423
9021
|
if (applyClaudeBedrockWrap(env, agent, renderedGw, gw))
|
|
8424
9022
|
return env;
|
|
9023
|
+
const routeOverride = agentRouteOverride(agent, agentArgs);
|
|
9024
|
+
if (agent.id === "qwen") {
|
|
9025
|
+
const override = routeOverride;
|
|
9026
|
+
if (override?.surface === "effective settings") {
|
|
9027
|
+
throw new Error("cannot safely resolve Qwen's effective settings");
|
|
9028
|
+
}
|
|
9029
|
+
if (override?.surface === "--safe-mode" && override.reason === "ignores Caveman system settings") {
|
|
9030
|
+
throw new Error("Qwen safe mode ignores Caveman system settings");
|
|
9031
|
+
}
|
|
9032
|
+
// These environment switches outrank settings in pinned Qwen 0.22.3.
|
|
9033
|
+
// Keep side-request tools and workflow-spawned agents off in routed mode;
|
|
9034
|
+
// corresponding system settings provide the durable second lock.
|
|
9035
|
+
env.ENABLE_WEB_SEARCH = "0";
|
|
9036
|
+
env.QWEN_CODE_DISABLE_WORKFLOWS = "1";
|
|
9037
|
+
}
|
|
9038
|
+
if (routeOverride)
|
|
9039
|
+
throw new Error(`${routeOverrideLabel(agent)} ${routeOverride.surface} ${routeOverride.reason}`);
|
|
8425
9040
|
const inj = agent.injection;
|
|
8426
9041
|
if (inj.method === "env") {
|
|
8427
9042
|
for (const [k, raw] of Object.entries(inj.env)) {
|
|
@@ -8433,21 +9048,58 @@ export function buildWrapEnv(agent, gw = gatewayURL(), mcpMode = "auto") {
|
|
|
8433
9048
|
else if (inj.method === "config-env-content") {
|
|
8434
9049
|
const cc = inj.config_content;
|
|
8435
9050
|
const content = wrapMode(gw) === "managed" && cc.managed !== undefined ? cc.managed : cc.local;
|
|
8436
|
-
|
|
9051
|
+
const renderOptions = agent.id === "kilo"
|
|
9052
|
+
? { optionalOpenAIKeyReference: "{env:OPENAI_API_KEY}" }
|
|
9053
|
+
: {};
|
|
9054
|
+
let rendered = renderDeep(content, renderedGw, env, renderOptions);
|
|
9055
|
+
if (agent.id === "kilo" && mcpMode === "auto") {
|
|
9056
|
+
const ownedMcp = ownedMcpRegistration(agent.id, agentArgs);
|
|
9057
|
+
if (ownedMcp) {
|
|
9058
|
+
// Project exact owned registration into Kilo's highest user-controlled
|
|
9059
|
+
// layer. Route preflight rejects active org/managed sources that load
|
|
9060
|
+
// afterward, so no later known policy can silently disable recovery.
|
|
9061
|
+
rendered = deepMerge(rendered, { mcp: { caveman: kiloMcpEntry(ownedMcp) } });
|
|
9062
|
+
}
|
|
9063
|
+
}
|
|
9064
|
+
if (agent.id === "opencode" && process.env[inj.env_var]) {
|
|
9065
|
+
// OpenCode treats inline JSONC as its own configuration layer. Replacing
|
|
9066
|
+
// that layer loses the user's model, account, permissions and MCP servers.
|
|
9067
|
+
// Preserve native {env:...}/{file:...} references for OpenCode to resolve
|
|
9068
|
+
// in the same context; only our routing fields take precedence.
|
|
9069
|
+
let original;
|
|
9070
|
+
try {
|
|
9071
|
+
original = parseJsonc(process.env[inj.env_var]);
|
|
9072
|
+
}
|
|
9073
|
+
catch {
|
|
9074
|
+
throw new Error("cannot preserve opencode inline configuration; launching with the original configuration is required");
|
|
9075
|
+
}
|
|
9076
|
+
if (!isPlainObject(original))
|
|
9077
|
+
throw new Error("opencode inline configuration must be a JSON object");
|
|
9078
|
+
rendered = deepMerge(original, rendered);
|
|
9079
|
+
}
|
|
9080
|
+
env[inj.env_var] = JSON.stringify(rendered);
|
|
8437
9081
|
}
|
|
8438
9082
|
else if (inj.method === "config-file") {
|
|
8439
9083
|
try {
|
|
8440
|
-
applyConfigFileInjection(env, agent, inj, renderedGw, gw, mcpMode);
|
|
9084
|
+
applyConfigFileInjection(env, agent, inj, renderedGw, gw, mcpMode, agentArgs, upstreams);
|
|
8441
9085
|
}
|
|
8442
9086
|
catch (e) {
|
|
8443
9087
|
// OpenClaw ignores the generic base-URL union. Config injection is its only
|
|
8444
9088
|
// provider redirect, so a failed/missing route must abort the wrapped path;
|
|
8445
9089
|
// spawnWrapped then launches direct with an explicit warning.
|
|
8446
|
-
if (agent.id === "openclaw")
|
|
9090
|
+
if (agent.id === "openclaw" || agent.id === "qwen")
|
|
8447
9091
|
throw e;
|
|
8448
9092
|
process.stderr.write(`caveman: ${agent.id} config-file injection failed; using generic env wrap (${e.message})\n`);
|
|
8449
9093
|
}
|
|
8450
9094
|
}
|
|
9095
|
+
// Qwen 0.22 discovers MCP servers in the background by default. Its first
|
|
9096
|
+
// request can therefore omit caveman_retrieve even though our durable marker
|
|
9097
|
+
// says recovery is installed. Proxy compression must never outrun recovery,
|
|
9098
|
+
// so marker-backed Qwen wraps use Qwen's compatibility switch to finish MCP
|
|
9099
|
+
// discovery before the first model request.
|
|
9100
|
+
if (agent.id === "qwen" && mcpInstalled(agent.id, agentArgs)) {
|
|
9101
|
+
env.QWEN_CODE_LEGACY_MCP_BLOCKING = "1";
|
|
9102
|
+
}
|
|
8451
9103
|
if (agent.id === "hermes")
|
|
8452
9104
|
applyHermesAuthEnv(env, renderedGw, gw);
|
|
8453
9105
|
if (agent.id === "claude" && wrapMode(gw) === "local" && env[CLAUDE_ASSUME_FIRST_PARTY_ENV] === undefined && proxyAnthropicUpstreamIsFirstParty()) {
|
|
@@ -9535,6 +10187,41 @@ function cavemanBin(name, envVar) {
|
|
|
9535
10187
|
function mcpServerMarkerPath(agentId, serverName) {
|
|
9536
10188
|
return join(cavemanHome(), "mcp", serverName === "caveman" ? `${agentId}.json` : `${agentId}.${serverName}.json`);
|
|
9537
10189
|
}
|
|
10190
|
+
function canonicalOwnedMcpMarkerPath(agent, serverName) {
|
|
10191
|
+
const path = mcpServerMarkerPath(agent, serverName);
|
|
10192
|
+
try {
|
|
10193
|
+
if (lstatSync(path).isSymbolicLink()) {
|
|
10194
|
+
throw new Error(`${path} is a symlink; refusing transactional ownership mutation`);
|
|
10195
|
+
}
|
|
10196
|
+
}
|
|
10197
|
+
catch (error) {
|
|
10198
|
+
if (error.code !== "ENOENT")
|
|
10199
|
+
throw error;
|
|
10200
|
+
}
|
|
10201
|
+
return canonicalMcpConfigPath(path);
|
|
10202
|
+
}
|
|
10203
|
+
// A native MCP registration and its Caveman ownership journal form one logical
|
|
10204
|
+
// write. Prove the journal directory is writable before touching agent config;
|
|
10205
|
+
// otherwise Kilo/Qwen would refuse both a later upgrade and removal because the
|
|
10206
|
+
// surviving registration has no trustworthy owner.
|
|
10207
|
+
function preflightMcpServerMarker(agentId, serverName) {
|
|
10208
|
+
const path = mcpServerMarkerPath(agentId, serverName);
|
|
10209
|
+
const probe = join(dirname(path), `.${basename(path)}.preflight-${process.pid}-${randomUUID()}`);
|
|
10210
|
+
try {
|
|
10211
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
10212
|
+
chmodSync(dirname(path), 0o700);
|
|
10213
|
+
durableAtomicWriteFile(probe, Buffer.alloc(0));
|
|
10214
|
+
unlinkSync(probe);
|
|
10215
|
+
fsyncParentDirectory(probe);
|
|
10216
|
+
}
|
|
10217
|
+
catch (error) {
|
|
10218
|
+
try {
|
|
10219
|
+
unlinkSync(probe);
|
|
10220
|
+
}
|
|
10221
|
+
catch { /* no probe survived */ }
|
|
10222
|
+
throw new Error(`cannot persist ${agentId} ${serverName} MCP ownership journal at ${path}: ${error.message}`);
|
|
10223
|
+
}
|
|
10224
|
+
}
|
|
9538
10225
|
function mcpMarkerPath(agentId) {
|
|
9539
10226
|
return mcpServerMarkerPath(agentId, "caveman");
|
|
9540
10227
|
}
|
|
@@ -9546,7 +10233,9 @@ function mcpServerInstalled(agentId, serverName) {
|
|
|
9546
10233
|
return false;
|
|
9547
10234
|
}
|
|
9548
10235
|
}
|
|
9549
|
-
function mcpInstalled(agentId) {
|
|
10236
|
+
function mcpInstalled(agentId, agentArgs = []) {
|
|
10237
|
+
if (agentId === "kilo" || agentId === "qwen")
|
|
10238
|
+
return ownedMcpRegistration(agentId, agentArgs) !== null;
|
|
9550
10239
|
return mcpServerInstalled(agentId, "caveman");
|
|
9551
10240
|
}
|
|
9552
10241
|
// configFileOverlayHasMcp asks whether the PROFILE would inject this MCP server
|
|
@@ -9584,7 +10273,7 @@ function queueStaleMcpBinary(probe) {
|
|
|
9584
10273
|
// that is — the proxy would otherwise either elide bytes nothing can expand, or
|
|
9585
10274
|
// pass through while the agent still pays for tools it isn't allowed to use.
|
|
9586
10275
|
// (honesty rule: no-placeholder)
|
|
9587
|
-
function wrapMcpRecoveryAvailable(agent, opts) {
|
|
10276
|
+
function wrapMcpRecoveryAvailable(agent, opts, agentArgs = []) {
|
|
9588
10277
|
if (!wrapRecoveryEligible(opts) || !agent)
|
|
9589
10278
|
return false;
|
|
9590
10279
|
if (agent.id === "pi") {
|
|
@@ -9595,13 +10284,19 @@ function wrapMcpRecoveryAvailable(agent, opts) {
|
|
|
9595
10284
|
queueStaleMcpBinary(compatibility.probe);
|
|
9596
10285
|
return compatibility.probe.current;
|
|
9597
10286
|
}
|
|
10287
|
+
// Kilo and Qwen can apply policy after user-owned config. Never turn their
|
|
10288
|
+
// durable marker into a proxy-wide recovery assertion: each request must
|
|
10289
|
+
// carry the exact namespaced retrieve tool and prove recovery in band. The
|
|
10290
|
+
// validated registration below still drives launch-time projection/blocking.
|
|
10291
|
+
if (agent.id === "kilo" || agent.id === "qwen")
|
|
10292
|
+
return false;
|
|
9598
10293
|
// Two independent sources of a real caveman_retrieve: a marker from
|
|
9599
10294
|
// `caveman tools mcp install`, or the profile's own config-file overlay. The
|
|
9600
10295
|
// second only counts under `auto`, because that is exactly when buildWrapEnv
|
|
9601
10296
|
// still merges it — under marker-only/false the overlay is stripped, so
|
|
9602
10297
|
// counting it here would tell the proxy about a tool this launch removed.
|
|
9603
10298
|
const overlayInjects = opts.mcpMode === "auto" && configFileOverlayHasCavemanMcp(agent);
|
|
9604
|
-
if (!mcpInstalled(agent.id) && !overlayInjects)
|
|
10299
|
+
if (!mcpInstalled(agent.id, agentArgs) && !overlayInjects)
|
|
9605
10300
|
return false;
|
|
9606
10301
|
const compatibility = probeMcpBinary();
|
|
9607
10302
|
if (!compatibility)
|
|
@@ -9613,8 +10308,10 @@ function wrapMcpRecoveryAvailable(agent, opts) {
|
|
|
9613
10308
|
return true;
|
|
9614
10309
|
}
|
|
9615
10310
|
// Bare start cannot bind a machine-level MCP marker or inherited opt-in to the
|
|
9616
|
-
// client issuing a later request
|
|
9617
|
-
//
|
|
10311
|
+
// client issuing a later request, so it never CLAIMS recovery on their behalf:
|
|
10312
|
+
// CAVEMAN_RECOVERY stays off and the proxy decides per request, from the caveman
|
|
10313
|
+
// retrieve tool the caller's own tool list carries (gateway.mcpRecoveryAvailable).
|
|
10314
|
+
// Agent-scoped wrap performs the only supported out-of-band compatibility check.
|
|
9618
10315
|
function startMcpRecoveryAvailable() {
|
|
9619
10316
|
return false;
|
|
9620
10317
|
}
|
|
@@ -9676,8 +10373,16 @@ const HERMES_MCP_END = "# <<< caveman:mcp";
|
|
|
9676
10373
|
const HERMES_PLUGIN_ENABLE_BEGIN = "# >>> caveman:hermes-plugin-enable";
|
|
9677
10374
|
const HERMES_PLUGIN_ENABLE_END = "# <<< caveman:hermes-plugin-enable";
|
|
9678
10375
|
const HERMES_PLUGIN_NAME = "caveman_shrink";
|
|
9679
|
-
function hermesHome() {
|
|
9680
|
-
|
|
10376
|
+
export function hermesHome(env = process.env, platform = process.platform) {
|
|
10377
|
+
// Hermes 0.19.1 hermes_constants.py: native Windows uses LOCALAPPDATA,
|
|
10378
|
+
// overrides are stripped, and Path(value) does not expand a literal tilde.
|
|
10379
|
+
const override = env.HERMES_HOME?.trim();
|
|
10380
|
+
if (override)
|
|
10381
|
+
return resolve(override);
|
|
10382
|
+
if (platform === "win32") {
|
|
10383
|
+
return join(env.LOCALAPPDATA?.trim() || join(homedir(), "AppData", "Local"), "hermes");
|
|
10384
|
+
}
|
|
10385
|
+
return join(homedir(), ".hermes");
|
|
9681
10386
|
}
|
|
9682
10387
|
function hermesConfigPath() {
|
|
9683
10388
|
return join(hermesHome(), "config.yaml");
|
|
@@ -9852,20 +10557,28 @@ function mcpUninstall(target, serverName = "caveman") {
|
|
|
9852
10557
|
targets = [a];
|
|
9853
10558
|
}
|
|
9854
10559
|
else {
|
|
9855
|
-
targets = AGENTS.filter((a) => mcpServerInstalled(a.id, serverName)
|
|
10560
|
+
targets = AGENTS.filter((a) => mcpServerInstalled(a.id, serverName)
|
|
10561
|
+
|| ((a.id === "kilo" || a.id === "qwen") && (existsSync(mcpPendingJournalPath(a.id, serverName))
|
|
10562
|
+
|| existsSync(mcpConfigPendingJournalPath(a.id === "kilo" ? kiloConfigPath() : qwenConfigPath())))));
|
|
9856
10563
|
if (targets.length === 0) {
|
|
9857
10564
|
console.error(`no agents have the ${serverName} MCP tool installed`);
|
|
9858
10565
|
return;
|
|
9859
10566
|
}
|
|
9860
10567
|
}
|
|
9861
10568
|
for (const a of targets) {
|
|
9862
|
-
|
|
9863
|
-
|
|
9864
|
-
|
|
9865
|
-
}
|
|
9866
|
-
catch {
|
|
9867
|
-
// marker already gone — the visible state is what matters.
|
|
10569
|
+
const uninstallOne = (lockedConfigPath) => {
|
|
10570
|
+
if (a.id === "kilo" || a.id === "qwen") {
|
|
10571
|
+
return transactOwnedMcpConfig(a.id, serverName, "uninstall", undefined, lockedConfigPath);
|
|
9868
10572
|
}
|
|
10573
|
+
if (!uninstallMcpForAgent(a, serverName))
|
|
10574
|
+
return false;
|
|
10575
|
+
durableUnlink(mcpServerMarkerPath(a.id, serverName));
|
|
10576
|
+
return true;
|
|
10577
|
+
};
|
|
10578
|
+
const removed = a.id === "kilo" || a.id === "qwen"
|
|
10579
|
+
? withOwnedMcpTransactionLock(a.id, serverName, uninstallOne)
|
|
10580
|
+
: uninstallOne();
|
|
10581
|
+
if (removed) {
|
|
9869
10582
|
process.stderr.write(`${mark("ok")} ${a.display_name}: ${serverName} MCP tool removed\n`);
|
|
9870
10583
|
}
|
|
9871
10584
|
}
|
|
@@ -9888,8 +10601,11 @@ function uninstallMcpForAgent(a, serverName = "caveman") {
|
|
|
9888
10601
|
return removeMcpCodexToml(serverName);
|
|
9889
10602
|
case "opencode":
|
|
9890
10603
|
return removeMcpJson(join(homedir(), ".config", "opencode", "opencode.json"), ["mcp", serverName]);
|
|
10604
|
+
case "kilo":
|
|
10605
|
+
case "qwen":
|
|
10606
|
+
throw new Error(`${a.display_name} MCP changes require the ownership transaction`);
|
|
9891
10607
|
case "gemini":
|
|
9892
|
-
return removeMcpJson(
|
|
10608
|
+
return removeMcpJson(geminiSettingsPath(), ["mcpServers", serverName]);
|
|
9893
10609
|
case "hermes":
|
|
9894
10610
|
return removeMcpHermesYaml(serverName);
|
|
9895
10611
|
case "openclaw":
|
|
@@ -9901,7 +10617,7 @@ function uninstallMcpForAgent(a, serverName = "caveman") {
|
|
|
9901
10617
|
// removeMcpCodexToml drops the exact [mcp_servers.<name>] block mcpInstall wrote
|
|
9902
10618
|
// (header + its command/args lines, up to the next section or EOF).
|
|
9903
10619
|
function removeMcpCodexToml(serverName = "caveman") {
|
|
9904
|
-
const path = join(
|
|
10620
|
+
const path = join(codexHomeDir(), "config.toml");
|
|
9905
10621
|
let existing = "";
|
|
9906
10622
|
try {
|
|
9907
10623
|
existing = readFileSync(path, "utf8");
|
|
@@ -9966,12 +10682,1906 @@ function removeMcpJson(path, keyPath) {
|
|
|
9966
10682
|
return false;
|
|
9967
10683
|
}
|
|
9968
10684
|
}
|
|
9969
|
-
function
|
|
9970
|
-
if (
|
|
9971
|
-
|
|
9972
|
-
|
|
10685
|
+
function kiloPathFromEnv(value, name) {
|
|
10686
|
+
if (/[\0\r\n]/.test(value))
|
|
10687
|
+
throw new Error(`${name} contains an invalid path character`);
|
|
10688
|
+
// Kilo passes env paths directly to its loader. Shell-style "~/" expansion
|
|
10689
|
+
// does not occur inside an environment value; relative paths resolve from cwd.
|
|
10690
|
+
return normalize(isAbsolute(value) ? value : resolve(value));
|
|
10691
|
+
}
|
|
10692
|
+
function kiloConfigInDirectory(directory, source) {
|
|
10693
|
+
// Mirror pinned Kilo's native global writer: prefer an existing canonical
|
|
10694
|
+
// config in this order, otherwise create kilo.json. JSONC stays read-only here
|
|
10695
|
+
// because a JSON stringify would destroy comments.
|
|
10696
|
+
const candidates = ["kilo.jsonc", "kilo.json", "opencode.jsonc", "opencode.json"];
|
|
10697
|
+
const selected = candidates.map((name) => join(directory, name)).find((path) => existsSync(path))
|
|
10698
|
+
?? join(directory, "kilo.json");
|
|
10699
|
+
return { path: selected, jsonc: extname(selected).toLowerCase() === ".jsonc", source };
|
|
10700
|
+
}
|
|
10701
|
+
// Kilo 7.5.6's native config writer targets KILO_CONFIG_DIR when present. That
|
|
10702
|
+
// directory is also loaded after KILO_CONFIG, so it must win for effective MCP
|
|
10703
|
+
// ownership. Explicit KILO_CONFIG wins only without a custom config directory;
|
|
10704
|
+
// xdg-basedir is the final fallback.
|
|
10705
|
+
function kiloConfigLocation() {
|
|
10706
|
+
const configuredDirectory = process.env.KILO_CONFIG_DIR;
|
|
10707
|
+
if (configuredDirectory) {
|
|
10708
|
+
return kiloConfigInDirectory(kiloPathFromEnv(configuredDirectory, "KILO_CONFIG_DIR"), "KILO_CONFIG_DIR");
|
|
10709
|
+
}
|
|
10710
|
+
const explicit = process.env.KILO_CONFIG;
|
|
10711
|
+
if (explicit) {
|
|
10712
|
+
const path = kiloPathFromEnv(explicit, "KILO_CONFIG");
|
|
10713
|
+
return { path, jsonc: extname(path).toLowerCase() === ".jsonc", source: "KILO_CONFIG" };
|
|
10714
|
+
}
|
|
10715
|
+
// Pinned Kilo strips accidental newlines from xdg-basedir output before use.
|
|
10716
|
+
const configuredRoot = process.env.XDG_CONFIG_HOME || join(homedir(), ".config");
|
|
10717
|
+
const cleanedRoot = configuredRoot.replace(/[\r\n]+/g, "");
|
|
10718
|
+
if (!cleanedRoot)
|
|
10719
|
+
throw new Error("Kilo config root resolves to an empty path");
|
|
10720
|
+
const root = normalize(isAbsolute(cleanedRoot) ? cleanedRoot : resolve(cleanedRoot));
|
|
10721
|
+
return kiloConfigInDirectory(join(root, "kilo"), "XDG_CONFIG_HOME");
|
|
10722
|
+
}
|
|
10723
|
+
function kiloConfigPath() {
|
|
10724
|
+
return kiloConfigLocation().path;
|
|
10725
|
+
}
|
|
10726
|
+
function kiloMcpEntry(mcp) {
|
|
10727
|
+
return {
|
|
10728
|
+
type: "local",
|
|
10729
|
+
command: [mcp.command, ...mcp.args],
|
|
10730
|
+
enabled: true,
|
|
10731
|
+
};
|
|
10732
|
+
}
|
|
10733
|
+
function kiloMcpEntryMatches(value, mcp) {
|
|
10734
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
10735
|
+
return false;
|
|
10736
|
+
const entry = value;
|
|
10737
|
+
const keys = Object.keys(entry).sort();
|
|
10738
|
+
const command = [mcp.command, ...mcp.args];
|
|
10739
|
+
if (keys.length !== 3 || keys[0] !== "command" || keys[1] !== "enabled" || keys[2] !== "type")
|
|
10740
|
+
return false;
|
|
10741
|
+
return entry.type === "local"
|
|
10742
|
+
&& entry.enabled === true
|
|
10743
|
+
&& Array.isArray(entry.command)
|
|
10744
|
+
&& entry.command.length === command.length
|
|
10745
|
+
&& entry.command.every((arg, index) => typeof arg === "string" && arg === command[index]);
|
|
10746
|
+
}
|
|
10747
|
+
function readStrictMcpJsonRoot(path) {
|
|
10748
|
+
let bytes;
|
|
10749
|
+
try {
|
|
10750
|
+
bytes = readFileSync(path);
|
|
9973
10751
|
}
|
|
9974
|
-
|
|
10752
|
+
catch (e) {
|
|
10753
|
+
if (e.code === "ENOENT")
|
|
10754
|
+
return { root: {}, exists: false, bytes: null };
|
|
10755
|
+
console.error(`${mark("warn")} cannot read ${path}: ${e.message}; not modifying it`);
|
|
10756
|
+
return null;
|
|
10757
|
+
}
|
|
10758
|
+
const raw = bytes.toString("utf8");
|
|
10759
|
+
try {
|
|
10760
|
+
if (!raw.trim()) {
|
|
10761
|
+
console.error(`${mark("warn")} ${path} is empty; not modifying it`);
|
|
10762
|
+
return null;
|
|
10763
|
+
}
|
|
10764
|
+
const parsed = JSON.parse(raw);
|
|
10765
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
10766
|
+
console.error(`${mark("warn")} ${path} is not a JSON object; not modifying it`);
|
|
10767
|
+
return null;
|
|
10768
|
+
}
|
|
10769
|
+
return { root: parsed, exists: true, bytes };
|
|
10770
|
+
}
|
|
10771
|
+
catch (e) {
|
|
10772
|
+
console.error(`${mark("warn")} cannot read ${path}: ${e.message}; not modifying it`);
|
|
10773
|
+
return null;
|
|
10774
|
+
}
|
|
10775
|
+
}
|
|
10776
|
+
function canonicalMcpConfigPath(path) {
|
|
10777
|
+
const absolute = normalize(resolve(path));
|
|
10778
|
+
const missing = [];
|
|
10779
|
+
let ancestor = absolute;
|
|
10780
|
+
while (true) {
|
|
10781
|
+
try {
|
|
10782
|
+
return normalize(join(realpathSync(ancestor), ...missing));
|
|
10783
|
+
}
|
|
10784
|
+
catch {
|
|
10785
|
+
try {
|
|
10786
|
+
if (lstatSync(ancestor).isSymbolicLink()) {
|
|
10787
|
+
throw new Error(`MCP config path contains dangling symlink ${ancestor}; refusing mutation`);
|
|
10788
|
+
}
|
|
10789
|
+
}
|
|
10790
|
+
catch (error) {
|
|
10791
|
+
if (error.code !== "ENOENT")
|
|
10792
|
+
throw error;
|
|
10793
|
+
}
|
|
10794
|
+
const parent = dirname(ancestor);
|
|
10795
|
+
if (parent === ancestor)
|
|
10796
|
+
return absolute;
|
|
10797
|
+
missing.unshift(basename(ancestor));
|
|
10798
|
+
ancestor = parent;
|
|
10799
|
+
}
|
|
10800
|
+
}
|
|
10801
|
+
}
|
|
10802
|
+
function ownedMcpConfigPlan(agent, path, loaded, after) {
|
|
10803
|
+
const canonicalPath = canonicalMcpConfigPath(path);
|
|
10804
|
+
let beforeMode = 0o600;
|
|
10805
|
+
if (loaded.exists) {
|
|
10806
|
+
beforeMode = statSync(canonicalPath).mode & 0o777;
|
|
10807
|
+
if (!optionalBytesEqual(fileBytes(canonicalPath), loaded.bytes)) {
|
|
10808
|
+
throw new Error(`${canonicalPath} changed while planning MCP update; refusing overwrite`);
|
|
10809
|
+
}
|
|
10810
|
+
}
|
|
10811
|
+
return {
|
|
10812
|
+
agent,
|
|
10813
|
+
path: canonicalPath,
|
|
10814
|
+
before: loaded.bytes,
|
|
10815
|
+
beforeMode,
|
|
10816
|
+
after,
|
|
10817
|
+
changed: !optionalBytesEqual(loaded.bytes, after),
|
|
10818
|
+
};
|
|
10819
|
+
}
|
|
10820
|
+
function movedOwnedMcpEntryState(agent, serverName, marker) {
|
|
10821
|
+
const activePath = canonicalMcpConfigPath(agent === "kilo" ? kiloConfigPath() : qwenConfigPath());
|
|
10822
|
+
if (marker.config_path === activePath || fileBytes(activePath) === null)
|
|
10823
|
+
return "absent";
|
|
10824
|
+
const root = agent === "kilo" ? readOptionalJsonObject(activePath) : readQwenJsonObject(activePath);
|
|
10825
|
+
if (!root)
|
|
10826
|
+
return "ambiguous";
|
|
10827
|
+
const entry = jsonValueAt(root, agent === "kilo" ? ["mcp", serverName] : ["mcpServers", serverName]);
|
|
10828
|
+
if (entry === undefined)
|
|
10829
|
+
return "absent";
|
|
10830
|
+
// Exact match proves a physical move; a different value can be same moved
|
|
10831
|
+
// registration edited afterward. Both retain ownership marker fail-closed.
|
|
10832
|
+
return "present";
|
|
10833
|
+
}
|
|
10834
|
+
function movedOwnedMcpRemovalBlocked(agent, serverName, marker) {
|
|
10835
|
+
const state = movedOwnedMcpEntryState(agent, serverName, marker);
|
|
10836
|
+
if (state === "absent")
|
|
10837
|
+
return false;
|
|
10838
|
+
const activePath = canonicalMcpConfigPath(agent === "kilo" ? kiloConfigPath() : qwenConfigPath());
|
|
10839
|
+
console.error(`${mark("warn")} recorded ${agent} MCP config is missing while ${activePath} ${state === "present" ? "contains" : "may contain"} moved ${serverName} state; retaining ownership marker`);
|
|
10840
|
+
return true;
|
|
10841
|
+
}
|
|
10842
|
+
function kiloJsoncBlocksMutation(path) {
|
|
10843
|
+
const location = kiloConfigLocation();
|
|
10844
|
+
if (location.jsonc && canonicalMcpConfigPath(location.path) === path) {
|
|
10845
|
+
console.error(`${mark("warn")} ${location.source} selects JSONC ${path}; refusing comment-destructive mutation`);
|
|
10846
|
+
return true;
|
|
10847
|
+
}
|
|
10848
|
+
return false;
|
|
10849
|
+
}
|
|
10850
|
+
function planMcpKiloJson(mcp, serverName = "caveman") {
|
|
10851
|
+
const path = canonicalMcpConfigPath(kiloConfigPath());
|
|
10852
|
+
const marker = readMcpServerMarker("kilo", serverName);
|
|
10853
|
+
if (marker?.config_path && marker.config_path !== path) {
|
|
10854
|
+
console.error(`${mark("warn")} ${serverName} is owned in ${marker.config_path}; uninstall it before installing into ${path}`);
|
|
10855
|
+
return null;
|
|
10856
|
+
}
|
|
10857
|
+
if (kiloJsoncBlocksMutation(path))
|
|
10858
|
+
return null;
|
|
10859
|
+
const loaded = readStrictMcpJsonRoot(path);
|
|
10860
|
+
if (!loaded)
|
|
10861
|
+
return null;
|
|
10862
|
+
const { root } = loaded;
|
|
10863
|
+
if (root.mcp !== undefined && (!root.mcp || typeof root.mcp !== "object" || Array.isArray(root.mcp))) {
|
|
10864
|
+
console.error(`${mark("warn")} ${path} mcp must be a JSON object; not modifying it`);
|
|
10865
|
+
return null;
|
|
10866
|
+
}
|
|
10867
|
+
const servers = root.mcp;
|
|
10868
|
+
const current = servers?.[serverName];
|
|
10869
|
+
if (marker && !marker.config_path && current === undefined) {
|
|
10870
|
+
console.error(`${mark("warn")} legacy ${serverName} ownership marker does not identify its Kilo config; refusing relocation`);
|
|
10871
|
+
return null;
|
|
10872
|
+
}
|
|
10873
|
+
if (current !== undefined) {
|
|
10874
|
+
if (!marker) {
|
|
10875
|
+
console.error(`${mark("warn")} ${path} mcp.${serverName} exists but is not Caveman-journaled; refusing overwrite`);
|
|
10876
|
+
return null;
|
|
10877
|
+
}
|
|
10878
|
+
if (!kiloMcpEntryMatches(current, marker)) {
|
|
10879
|
+
console.error(`${mark("warn")} ${path} mcp.${serverName} changed since Caveman installed it; refusing overwrite`);
|
|
10880
|
+
return null;
|
|
10881
|
+
}
|
|
10882
|
+
if (kiloMcpEntryMatches(current, mcp)) {
|
|
10883
|
+
return ownedMcpConfigPlan("kilo", path, loaded, loaded.bytes);
|
|
10884
|
+
}
|
|
10885
|
+
}
|
|
10886
|
+
const nextServers = servers ?? {};
|
|
10887
|
+
nextServers[serverName] = kiloMcpEntry(mcp);
|
|
10888
|
+
root.mcp = nextServers;
|
|
10889
|
+
return ownedMcpConfigPlan("kilo", path, loaded, Buffer.from(JSON.stringify(root, null, 2) + "\n"));
|
|
10890
|
+
}
|
|
10891
|
+
function planRemoveMcpKiloJson(serverName = "caveman") {
|
|
10892
|
+
const marker = readMcpServerMarker("kilo", serverName);
|
|
10893
|
+
const path = marker?.config_path ?? canonicalMcpConfigPath(kiloConfigPath());
|
|
10894
|
+
const loaded = readStrictMcpJsonRoot(path);
|
|
10895
|
+
if (!loaded)
|
|
10896
|
+
return null;
|
|
10897
|
+
if (!loaded.exists) {
|
|
10898
|
+
if (marker && !marker.config_path) {
|
|
10899
|
+
console.error(`${mark("warn")} legacy ${serverName} ownership marker does not identify its Kilo config; refusing removal`);
|
|
10900
|
+
return null;
|
|
10901
|
+
}
|
|
10902
|
+
if (marker?.config_path && movedOwnedMcpRemovalBlocked("kilo", serverName, marker))
|
|
10903
|
+
return null;
|
|
10904
|
+
return ownedMcpConfigPlan("kilo", path, loaded, null);
|
|
10905
|
+
}
|
|
10906
|
+
const { root } = loaded;
|
|
10907
|
+
if (root.mcp !== undefined && (!root.mcp || typeof root.mcp !== "object" || Array.isArray(root.mcp))) {
|
|
10908
|
+
console.error(`${mark("warn")} ${path} mcp must be a JSON object; not modifying it`);
|
|
10909
|
+
return null;
|
|
10910
|
+
}
|
|
10911
|
+
const servers = root.mcp;
|
|
10912
|
+
const current = servers?.[serverName];
|
|
10913
|
+
if (current === undefined) {
|
|
10914
|
+
if (marker && !marker.config_path) {
|
|
10915
|
+
console.error(`${mark("warn")} legacy ${serverName} ownership marker does not identify its Kilo config; refusing removal`);
|
|
10916
|
+
return null;
|
|
10917
|
+
}
|
|
10918
|
+
return ownedMcpConfigPlan("kilo", path, loaded, loaded.bytes);
|
|
10919
|
+
}
|
|
10920
|
+
if (!marker) {
|
|
10921
|
+
console.error(`${mark("warn")} ${path} mcp.${serverName} exists but is not Caveman-journaled; refusing removal`);
|
|
10922
|
+
return null;
|
|
10923
|
+
}
|
|
10924
|
+
if (!kiloMcpEntryMatches(current, marker)) {
|
|
10925
|
+
console.error(`${mark("warn")} ${path} mcp.${serverName} changed since Caveman installed it; refusing removal`);
|
|
10926
|
+
return null;
|
|
10927
|
+
}
|
|
10928
|
+
delete servers[serverName];
|
|
10929
|
+
if (Object.keys(servers).length === 0)
|
|
10930
|
+
delete root.mcp;
|
|
10931
|
+
return ownedMcpConfigPlan("kilo", path, loaded, Buffer.from(JSON.stringify(root, null, 2) + "\n"));
|
|
10932
|
+
}
|
|
10933
|
+
const qwenHomeBootstrapKeys = [
|
|
10934
|
+
"QWEN_HOME",
|
|
10935
|
+
"QWEN_RUNTIME_DIR",
|
|
10936
|
+
"QWEN_CODE_MCP_APPROVALS_PATH",
|
|
10937
|
+
"QWEN_CODE_TRUSTED_FOLDERS_PATH",
|
|
10938
|
+
];
|
|
10939
|
+
function qwenReadDotEnv(path) {
|
|
10940
|
+
try {
|
|
10941
|
+
const parsed = parseEnv(readFileSync(path, "utf8"));
|
|
10942
|
+
return Object.fromEntries(Object.entries(parsed).filter((entry) => typeof entry[1] === "string"));
|
|
10943
|
+
}
|
|
10944
|
+
catch (error) {
|
|
10945
|
+
if (error.code === "ENOENT")
|
|
10946
|
+
return {};
|
|
10947
|
+
return null;
|
|
10948
|
+
}
|
|
10949
|
+
}
|
|
10950
|
+
function qwenResolveHomeRoot(value) {
|
|
10951
|
+
const configured = value?.trim();
|
|
10952
|
+
const root = configured ? expandTilde(configured) : join(homedir(), ".qwen");
|
|
10953
|
+
return isAbsolute(root) ? root : resolve(root);
|
|
10954
|
+
}
|
|
10955
|
+
// Qwen resolves QWEN_HOME from user-level dotenv before reading settings.
|
|
10956
|
+
// Mirror that bootstrap so install, uninstall, and recovery checks all inspect
|
|
10957
|
+
// the same settings file as pinned Qwen 0.22.3.
|
|
10958
|
+
function qwenHomeState() {
|
|
10959
|
+
const env = { ...process.env };
|
|
10960
|
+
const initialHome = env.QWEN_HOME;
|
|
10961
|
+
const initialRoot = qwenResolveHomeRoot(initialHome);
|
|
10962
|
+
const candidates = [join(initialRoot, ".env")];
|
|
10963
|
+
if (!initialHome)
|
|
10964
|
+
candidates.push(join(homedir(), ".env"));
|
|
10965
|
+
let ambiguous = false;
|
|
10966
|
+
const load = (path) => {
|
|
10967
|
+
const parsed = qwenReadDotEnv(path);
|
|
10968
|
+
if (!parsed) {
|
|
10969
|
+
ambiguous = true;
|
|
10970
|
+
return;
|
|
10971
|
+
}
|
|
10972
|
+
for (const key of qwenHomeBootstrapKeys) {
|
|
10973
|
+
if (parsed[key] && !Object.hasOwn(env, key))
|
|
10974
|
+
env[key] = parsed[key];
|
|
10975
|
+
}
|
|
10976
|
+
};
|
|
10977
|
+
for (const path of candidates)
|
|
10978
|
+
load(path);
|
|
10979
|
+
const discoveredRoot = qwenResolveHomeRoot(env.QWEN_HOME);
|
|
10980
|
+
if (env.QWEN_HOME && env.QWEN_HOME !== initialHome && discoveredRoot !== initialRoot) {
|
|
10981
|
+
// Pinned Qwen performs a second pass through a newly discovered QWEN_HOME.
|
|
10982
|
+
// Trust and approval paths can live there, not only QWEN_RUNTIME_DIR.
|
|
10983
|
+
load(join(discoveredRoot, ".env"));
|
|
10984
|
+
}
|
|
10985
|
+
return { root: discoveredRoot, env, ambiguous };
|
|
10986
|
+
}
|
|
10987
|
+
function qwenHomeEnvFallback(state = qwenHomeState()) {
|
|
10988
|
+
if (state.ambiguous)
|
|
10989
|
+
return null;
|
|
10990
|
+
const candidates = [join(state.root, ".env")];
|
|
10991
|
+
if (!state.env.QWEN_HOME)
|
|
10992
|
+
candidates.push(join(homedir(), ".env"));
|
|
10993
|
+
const fallback = {};
|
|
10994
|
+
for (const path of candidates) {
|
|
10995
|
+
const parsed = qwenReadDotEnv(path);
|
|
10996
|
+
if (!parsed)
|
|
10997
|
+
return null;
|
|
10998
|
+
for (const [key, value] of Object.entries(parsed)) {
|
|
10999
|
+
if (!Object.hasOwn(state.env, key) && fallback[key] === undefined)
|
|
11000
|
+
fallback[key] = value;
|
|
11001
|
+
}
|
|
11002
|
+
}
|
|
11003
|
+
return fallback;
|
|
11004
|
+
}
|
|
11005
|
+
function qwenConfigPath() {
|
|
11006
|
+
return join(qwenHomeState().root, "settings.json");
|
|
11007
|
+
}
|
|
11008
|
+
function qwenMcpEntry(mcp) {
|
|
11009
|
+
return { command: mcp.command, args: mcp.args };
|
|
11010
|
+
}
|
|
11011
|
+
function qwenMcpEntryMatches(value, mcp) {
|
|
11012
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
11013
|
+
return false;
|
|
11014
|
+
const entry = value;
|
|
11015
|
+
const keys = Object.keys(entry).sort();
|
|
11016
|
+
if (keys.length !== 2 || keys[0] !== "args" || keys[1] !== "command")
|
|
11017
|
+
return false;
|
|
11018
|
+
return entry.command === mcp.command
|
|
11019
|
+
&& Array.isArray(entry.args)
|
|
11020
|
+
&& entry.args.length === mcp.args.length
|
|
11021
|
+
&& entry.args.every((arg, index) => typeof arg === "string" && arg === mcp.args[index]);
|
|
11022
|
+
}
|
|
11023
|
+
function jsonValueAt(root, path) {
|
|
11024
|
+
let current = root;
|
|
11025
|
+
for (const key of path) {
|
|
11026
|
+
if (!current || typeof current !== "object" || Array.isArray(current))
|
|
11027
|
+
return undefined;
|
|
11028
|
+
current = current[key];
|
|
11029
|
+
}
|
|
11030
|
+
return current;
|
|
11031
|
+
}
|
|
11032
|
+
function readOptionalJsonObject(path) {
|
|
11033
|
+
try {
|
|
11034
|
+
const value = readJson5Lenient(path);
|
|
11035
|
+
return asJsonObject(value) ?? null;
|
|
11036
|
+
}
|
|
11037
|
+
catch (error) {
|
|
11038
|
+
return error.code === "ENOENT" ? {} : null;
|
|
11039
|
+
}
|
|
11040
|
+
}
|
|
11041
|
+
// Qwen settings and trust files are JSON-with-comments, not JSON5: trailing
|
|
11042
|
+
// commas are corruption in 0.22.3. Read-only safety checks must not accept a
|
|
11043
|
+
// policy or credential source the pinned binary will discard during recovery.
|
|
11044
|
+
function readQwenJsonObject(path) {
|
|
11045
|
+
try {
|
|
11046
|
+
const value = JSON.parse(stripJson5Comments(readFileSync(path, "utf8")));
|
|
11047
|
+
return asJsonObject(value) ?? null;
|
|
11048
|
+
}
|
|
11049
|
+
catch (error) {
|
|
11050
|
+
return error.code === "ENOENT" ? {} : null;
|
|
11051
|
+
}
|
|
11052
|
+
}
|
|
11053
|
+
function qwenResolvedSettingString(value, fallback = {}) {
|
|
11054
|
+
return value.replace(/\$(?:(\w+)|{([^}]+)})/g, (match, bare, braced) => {
|
|
11055
|
+
const name = bare || braced || "";
|
|
11056
|
+
if (typeof fallback[name] === "string")
|
|
11057
|
+
return fallback[name];
|
|
11058
|
+
return typeof process.env[name] === "string" ? process.env[name] : match;
|
|
11059
|
+
});
|
|
11060
|
+
}
|
|
11061
|
+
const qwenEnvReference = /\$(?:(\w+)|{([^}]+)})/;
|
|
11062
|
+
// Qwen 0.22.3 uses this complete indicator set to decide whether any legacy
|
|
11063
|
+
// V1 shape triggers migration for the whole settings scope. Keep detection
|
|
11064
|
+
// exact even though Caveman only materializes fields used by its safety gates.
|
|
11065
|
+
const qwenV1IndicatorKeys = [
|
|
11066
|
+
"theme", "model", "autoAccept", "hideTips", "vimMode", "checkpointing",
|
|
11067
|
+
"accessibility", "allowedTools", "allowMCPServers", "autoConfigureMaxOldSpaceSize",
|
|
11068
|
+
"bugCommand", "chatCompression", "coreTools", "contextFileName", "customThemes",
|
|
11069
|
+
"customWittyPhrases", "debugKeystrokeLogging", "dnsResolutionOrder", "enforcedAuthType",
|
|
11070
|
+
"excludeTools", "excludeMCPServers", "excludedProjectEnvVars", "fileFiltering",
|
|
11071
|
+
"folderTrustFeature", "folderTrust", "hasSeenIdeIntegrationNudge", "hideWindowTitle",
|
|
11072
|
+
"showStatusInTitle", "showLineNumbers", "showCitations", "ideMode", "includeDirectories",
|
|
11073
|
+
"loadMemoryFromIncludeDirectories", "maxSessionTurns", "mcpServerCommand",
|
|
11074
|
+
"memoryImportFormat", "preferredEditor", "sandbox", "selectedAuthType",
|
|
11075
|
+
"shouldUseNodePtyShell", "shellPager", "shellShowColor", "skipNextSpeakerCheck",
|
|
11076
|
+
"toolDiscoveryCommand", "toolCallCommand", "usageStatisticsEnabled", "useExternalAuth",
|
|
11077
|
+
"useRipgrep", "enableWelcomeBack", "approvalMode", "sessionTokenLimit", "contentGenerator",
|
|
11078
|
+
"skipLoopDetection", "skipStartupContext", "enableOpenAILogging", "tavilyApiKey",
|
|
11079
|
+
"disableAutoUpdate", "disableUpdateNag", "disableLoadingPhrases", "disableFuzzySearch",
|
|
11080
|
+
"disableCacheControl",
|
|
11081
|
+
];
|
|
11082
|
+
// Subset of V1 -> V2 relocations consumed by credential/trust/MCP gates below.
|
|
11083
|
+
// Migration still triggers from the complete upstream indicator set above.
|
|
11084
|
+
const qwenV1PolicyMigrationMap = {
|
|
11085
|
+
allowMCPServers: "mcp.allowed",
|
|
11086
|
+
coreTools: "tools.core",
|
|
11087
|
+
excludeMCPServers: "mcp.excluded",
|
|
11088
|
+
excludeTools: "tools.exclude",
|
|
11089
|
+
excludedProjectEnvVars: "advanced.excludedEnvVars",
|
|
11090
|
+
folderTrust: "security.folderTrust.enabled",
|
|
11091
|
+
};
|
|
11092
|
+
function qwenSetNestedPropertySafe(root, path, value) {
|
|
11093
|
+
const keys = path.split(".");
|
|
11094
|
+
if (keys.some((key) => !isSafeObjectKey(key)))
|
|
11095
|
+
return;
|
|
11096
|
+
const last = keys.pop();
|
|
11097
|
+
if (!last)
|
|
11098
|
+
return;
|
|
11099
|
+
let current = root;
|
|
11100
|
+
for (const key of keys) {
|
|
11101
|
+
if (current[key] === undefined)
|
|
11102
|
+
current[key] = {};
|
|
11103
|
+
const next = current[key];
|
|
11104
|
+
if (!next || typeof next !== "object")
|
|
11105
|
+
return;
|
|
11106
|
+
current = next;
|
|
11107
|
+
}
|
|
11108
|
+
current[last] = value;
|
|
11109
|
+
}
|
|
11110
|
+
// Mirror policy-relevant output of Qwen's per-scope V1 migration without
|
|
11111
|
+
// rewriting user files. Existing nested V2 content wins exactly as upstream's
|
|
11112
|
+
// parent-path carry step does.
|
|
11113
|
+
function qwenMigratePolicySettings(source) {
|
|
11114
|
+
const version = source["$version"];
|
|
11115
|
+
if (typeof version === "number" && version >= 2)
|
|
11116
|
+
return cloneJsonValue(source);
|
|
11117
|
+
const shouldMigrate = qwenV1IndicatorKeys.some((key) => {
|
|
11118
|
+
if (!Object.hasOwn(source, key))
|
|
11119
|
+
return false;
|
|
11120
|
+
const value = source[key];
|
|
11121
|
+
return !value || typeof value !== "object" || Array.isArray(value);
|
|
11122
|
+
});
|
|
11123
|
+
if (!shouldMigrate)
|
|
11124
|
+
return cloneJsonValue(source);
|
|
11125
|
+
const result = {};
|
|
11126
|
+
const processed = new Set();
|
|
11127
|
+
for (const [legacyKey, targetPath] of Object.entries(qwenV1PolicyMigrationMap)) {
|
|
11128
|
+
if (!Object.hasOwn(source, legacyKey))
|
|
11129
|
+
continue;
|
|
11130
|
+
qwenSetNestedPropertySafe(result, targetPath, source[legacyKey]);
|
|
11131
|
+
processed.add(legacyKey);
|
|
11132
|
+
}
|
|
11133
|
+
for (const [key, value] of Object.entries(source)) {
|
|
11134
|
+
if (processed.has(key))
|
|
11135
|
+
continue;
|
|
11136
|
+
const parentOfMigratedPath = [...processed].some((legacyKey) => qwenV1PolicyMigrationMap[legacyKey].startsWith(`${key}.`));
|
|
11137
|
+
if (!parentOfMigratedPath) {
|
|
11138
|
+
result[key] = value;
|
|
11139
|
+
continue;
|
|
11140
|
+
}
|
|
11141
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
11142
|
+
result[key] = value;
|
|
11143
|
+
continue;
|
|
11144
|
+
}
|
|
11145
|
+
for (const [nestedKey, nestedValue] of Object.entries(value)) {
|
|
11146
|
+
const nestedPath = `${key}.${nestedKey}`;
|
|
11147
|
+
const alreadyMigrated = [...processed].some((legacyKey) => qwenV1PolicyMigrationMap[legacyKey] === nestedPath);
|
|
11148
|
+
if (!alreadyMigrated)
|
|
11149
|
+
qwenSetNestedPropertySafe(result, nestedPath, nestedValue);
|
|
11150
|
+
}
|
|
11151
|
+
}
|
|
11152
|
+
result["$version"] = 2;
|
|
11153
|
+
return result;
|
|
11154
|
+
}
|
|
11155
|
+
function qwenResolveSettingValue(value, fallback) {
|
|
11156
|
+
if (typeof value === "string")
|
|
11157
|
+
return qwenResolvedSettingString(value, fallback);
|
|
11158
|
+
if (Array.isArray(value))
|
|
11159
|
+
return value.map((item) => qwenResolveSettingValue(item, fallback));
|
|
11160
|
+
if (!value || typeof value !== "object")
|
|
11161
|
+
return value;
|
|
11162
|
+
const resolved = { ...value };
|
|
11163
|
+
for (const [key, child] of Object.entries(resolved))
|
|
11164
|
+
resolved[key] = qwenResolveSettingValue(child, fallback);
|
|
11165
|
+
return resolved;
|
|
11166
|
+
}
|
|
11167
|
+
function qwenStringList(root, path, fallback) {
|
|
11168
|
+
const value = jsonValueAt(root, path);
|
|
11169
|
+
if (value === undefined)
|
|
11170
|
+
return undefined;
|
|
11171
|
+
if (!fallback)
|
|
11172
|
+
return null;
|
|
11173
|
+
if (!Array.isArray(value) || !value.every((item) => typeof item === "string"))
|
|
11174
|
+
return null;
|
|
11175
|
+
const resolved = value.map((item) => qwenResolvedSettingString(item, fallback)).filter(Boolean);
|
|
11176
|
+
// Qwen loads .env files after this wrapper starts. An unresolved reference
|
|
11177
|
+
// can therefore become a restrictive rule later; unknown policy fails closed.
|
|
11178
|
+
if (resolved.some((item) => qwenEnvReference.test(item)))
|
|
11179
|
+
return null;
|
|
11180
|
+
return resolved;
|
|
11181
|
+
}
|
|
11182
|
+
// Exact wildcard matcher used by Qwen 0.22 for mcp.allowed/mcp.excluded:
|
|
11183
|
+
// `*` spans any run, `?` spans one character, everything else is literal.
|
|
11184
|
+
function qwenMcpServerPatternMatches(name, pattern) {
|
|
11185
|
+
let nameIndex = 0;
|
|
11186
|
+
let patternIndex = 0;
|
|
11187
|
+
let starNameIndex = -1;
|
|
11188
|
+
let starPatternIndex = -1;
|
|
11189
|
+
while (nameIndex < name.length) {
|
|
11190
|
+
if (patternIndex < pattern.length && (pattern[patternIndex] === "?" || pattern[patternIndex] === name[nameIndex])) {
|
|
11191
|
+
nameIndex++;
|
|
11192
|
+
patternIndex++;
|
|
11193
|
+
}
|
|
11194
|
+
else if (patternIndex < pattern.length && pattern[patternIndex] === "*") {
|
|
11195
|
+
starPatternIndex = patternIndex++;
|
|
11196
|
+
starNameIndex = nameIndex;
|
|
11197
|
+
}
|
|
11198
|
+
else if (starPatternIndex !== -1) {
|
|
11199
|
+
patternIndex = starPatternIndex + 1;
|
|
11200
|
+
nameIndex = ++starNameIndex;
|
|
11201
|
+
}
|
|
11202
|
+
else {
|
|
11203
|
+
return false;
|
|
11204
|
+
}
|
|
11205
|
+
}
|
|
11206
|
+
while (patternIndex < pattern.length && pattern[patternIndex] === "*")
|
|
11207
|
+
patternIndex++;
|
|
11208
|
+
return patternIndex === pattern.length;
|
|
11209
|
+
}
|
|
11210
|
+
const qwenCavemanToolName = "mcp__caveman__caveman_retrieve";
|
|
11211
|
+
function qwenSanitizeToolName(value) {
|
|
11212
|
+
const sanitized = value.replace(/[^A-Za-z0-9_-]/g, "_");
|
|
11213
|
+
return /^[A-Za-z]/.test(sanitized) ? sanitized : `tool_${sanitized}`;
|
|
11214
|
+
}
|
|
11215
|
+
function qwenNormalizeToolName(value) {
|
|
11216
|
+
if (value.length <= 63 && /^[A-Za-z][A-Za-z0-9_-]*$/.test(value))
|
|
11217
|
+
return value;
|
|
11218
|
+
const sanitized = qwenSanitizeToolName(value);
|
|
11219
|
+
let hash = 2166136261;
|
|
11220
|
+
for (let index = 0; index < value.length; index++)
|
|
11221
|
+
hash = Math.imul(hash ^ value.charCodeAt(index), 16777619);
|
|
11222
|
+
const suffix = `_${(hash >>> 0).toString(36).padStart(7, "0")}`;
|
|
11223
|
+
return `${sanitized.slice(0, 63 - suffix.length)}${suffix}`;
|
|
11224
|
+
}
|
|
11225
|
+
// Port of Qwen 0.22.3's MCP permission matcher for one exact target tool.
|
|
11226
|
+
function qwenCavemanToolDenied(rule) {
|
|
11227
|
+
let pattern = rule.trim();
|
|
11228
|
+
const open = pattern.indexOf("(");
|
|
11229
|
+
if (open !== -1) {
|
|
11230
|
+
if (!pattern.endsWith(")") || pattern.slice(open + 1, -1).trim() !== "")
|
|
11231
|
+
return false;
|
|
11232
|
+
pattern = pattern.slice(0, open).trim();
|
|
11233
|
+
}
|
|
11234
|
+
else if (pattern.includes(")")) {
|
|
11235
|
+
return false;
|
|
11236
|
+
}
|
|
11237
|
+
if (pattern === qwenCavemanToolName)
|
|
11238
|
+
return true;
|
|
11239
|
+
if (!pattern.endsWith("*") && pattern.split("__").length >= 3) {
|
|
11240
|
+
const normalized = pattern.startsWith("mcp__") ? qwenNormalizeToolName(pattern) : pattern;
|
|
11241
|
+
if (normalized === qwenCavemanToolName)
|
|
11242
|
+
return true;
|
|
11243
|
+
}
|
|
11244
|
+
if (pattern.endsWith("*")) {
|
|
11245
|
+
return qwenCavemanToolName.startsWith(qwenSanitizeToolName(pattern.slice(0, -1)));
|
|
11246
|
+
}
|
|
11247
|
+
const patternParts = pattern.split("__");
|
|
11248
|
+
const toolParts = qwenCavemanToolName.split("__");
|
|
11249
|
+
return patternParts.length === 2
|
|
11250
|
+
&& patternParts[0] === toolParts[0]
|
|
11251
|
+
&& qwenSanitizeToolName(patternParts[1]) === qwenSanitizeToolName(toolParts[1]);
|
|
11252
|
+
}
|
|
11253
|
+
function qwenCavemanToolDisabled(name) {
|
|
11254
|
+
return name.trim() === qwenCavemanToolName;
|
|
11255
|
+
}
|
|
11256
|
+
function qwenConfigFileInjection() {
|
|
11257
|
+
const profile = AGENTS.find((agent) => agent.id === "qwen");
|
|
11258
|
+
return profile?.injection.method === "config-file" ? profile.injection : undefined;
|
|
11259
|
+
}
|
|
11260
|
+
function qwenSettingsLayerPaths() {
|
|
11261
|
+
const injection = qwenConfigFileInjection();
|
|
11262
|
+
if (!injection?.base_config)
|
|
11263
|
+
return null;
|
|
11264
|
+
const state = qwenHomeState();
|
|
11265
|
+
if (state.ambiguous)
|
|
11266
|
+
return null;
|
|
11267
|
+
const system = baseConfigPath(injection.base_config);
|
|
11268
|
+
const configuredDefaults = process.env.QWEN_CODE_SYSTEM_DEFAULTS_PATH?.trim();
|
|
11269
|
+
const defaultsRoot = configuredDefaults ? expandTilde(configuredDefaults) : join(dirname(system), "system-defaults.json");
|
|
11270
|
+
const defaults = isAbsolute(defaultsRoot) ? defaultsRoot : resolve(defaultsRoot);
|
|
11271
|
+
// Keep system settings last even when operator paths alias another layer;
|
|
11272
|
+
// last-layer identity matters for enterprise MCP server shadow checks.
|
|
11273
|
+
return [
|
|
11274
|
+
defaults,
|
|
11275
|
+
join(state.root, "settings.json"),
|
|
11276
|
+
join(process.cwd(), ".qwen", "settings.json"),
|
|
11277
|
+
system,
|
|
11278
|
+
];
|
|
11279
|
+
}
|
|
11280
|
+
function qwenMergedSettings(layers) {
|
|
11281
|
+
let merged = {};
|
|
11282
|
+
for (const layer of layers)
|
|
11283
|
+
merged = deepMerge(merged, layer);
|
|
11284
|
+
return merged;
|
|
11285
|
+
}
|
|
11286
|
+
function qwenPathVariants(rawPath) {
|
|
11287
|
+
const variants = new Set([normalize(resolve(rawPath))]);
|
|
11288
|
+
try {
|
|
11289
|
+
variants.add(normalize(realpathSync(rawPath)));
|
|
11290
|
+
}
|
|
11291
|
+
catch {
|
|
11292
|
+
// Qwen compares a lexical absolute path when a target cannot be resolved.
|
|
11293
|
+
}
|
|
11294
|
+
return variants;
|
|
11295
|
+
}
|
|
11296
|
+
function qwenPathWithinRoot(childPath, parentPath) {
|
|
11297
|
+
const remainder = relative(parentPath, childPath);
|
|
11298
|
+
return remainder === "" || (!remainder.startsWith(`..${sep}`) && remainder !== ".." && !isAbsolute(remainder));
|
|
11299
|
+
}
|
|
11300
|
+
function qwenPathDepth(path) {
|
|
11301
|
+
const remainder = relative(parse(path).root, path);
|
|
11302
|
+
return remainder === "" ? 0 : remainder.split(sep).filter(Boolean).length;
|
|
11303
|
+
}
|
|
11304
|
+
// Mirror Qwen 0.22.3's persisted trust-rule precedence. Unknown workspaces are
|
|
11305
|
+
// trusted by Qwen's initial settings load; malformed trust state is ambiguous
|
|
11306
|
+
// here and must fail closed before an optional credential reference is emitted.
|
|
11307
|
+
function qwenWorkspaceTrusted(settings, workspacePath) {
|
|
11308
|
+
const enabled = jsonValueAt(settings, ["security", "folderTrust", "enabled"]);
|
|
11309
|
+
if (enabled === undefined || enabled === false)
|
|
11310
|
+
return true;
|
|
11311
|
+
if (enabled !== true)
|
|
11312
|
+
return null;
|
|
11313
|
+
const state = qwenHomeState();
|
|
11314
|
+
if (state.ambiguous)
|
|
11315
|
+
return null;
|
|
11316
|
+
const configuredPath = state.env.QWEN_CODE_TRUSTED_FOLDERS_PATH;
|
|
11317
|
+
const trustedPath = configuredPath || join(state.root, "trustedFolders.json");
|
|
11318
|
+
const config = readQwenJsonObject(trustedPath);
|
|
11319
|
+
if (!config)
|
|
11320
|
+
return null;
|
|
11321
|
+
const workspaceVariants = qwenPathVariants(workspacePath);
|
|
11322
|
+
let winnerDepth = -1;
|
|
11323
|
+
let winnerTrusted;
|
|
11324
|
+
for (const [rulePath, rawLevel] of Object.entries(config)) {
|
|
11325
|
+
if (rawLevel !== "TRUST_FOLDER" && rawLevel !== "TRUST_PARENT" && rawLevel !== "DO_NOT_TRUST")
|
|
11326
|
+
return null;
|
|
11327
|
+
const rootPath = rawLevel === "TRUST_PARENT" ? dirname(rulePath) : rulePath;
|
|
11328
|
+
let matchDepth = -1;
|
|
11329
|
+
for (const workspaceVariant of workspaceVariants) {
|
|
11330
|
+
for (const ruleVariant of qwenPathVariants(rootPath)) {
|
|
11331
|
+
if (qwenPathWithinRoot(workspaceVariant, ruleVariant)) {
|
|
11332
|
+
matchDepth = Math.max(matchDepth, qwenPathDepth(ruleVariant));
|
|
11333
|
+
}
|
|
11334
|
+
}
|
|
11335
|
+
}
|
|
11336
|
+
if (matchDepth < 0)
|
|
11337
|
+
continue;
|
|
11338
|
+
const trusted = rawLevel !== "DO_NOT_TRUST";
|
|
11339
|
+
if (matchDepth > winnerDepth || (matchDepth === winnerDepth && !trusted && winnerTrusted !== false)) {
|
|
11340
|
+
winnerDepth = matchDepth;
|
|
11341
|
+
winnerTrusted = trusted;
|
|
11342
|
+
}
|
|
11343
|
+
}
|
|
11344
|
+
return winnerTrusted ?? true;
|
|
11345
|
+
}
|
|
11346
|
+
function qwenSettingsLayers() {
|
|
11347
|
+
const paths = qwenSettingsLayerPaths();
|
|
11348
|
+
if (!paths)
|
|
11349
|
+
return null;
|
|
11350
|
+
const fallback = qwenHomeEnvFallback();
|
|
11351
|
+
if (!fallback)
|
|
11352
|
+
return null;
|
|
11353
|
+
const layers = [];
|
|
11354
|
+
for (const path of paths) {
|
|
11355
|
+
const layer = readQwenJsonObject(path);
|
|
11356
|
+
if (!layer)
|
|
11357
|
+
return null;
|
|
11358
|
+
const migrated = qwenMigratePolicySettings(layer);
|
|
11359
|
+
layers.push(qwenResolveSettingValue(migrated, fallback));
|
|
11360
|
+
}
|
|
11361
|
+
// Qwen decides workspace trust from System + User settings (User wins in
|
|
11362
|
+
// this initial check), then drops the entire workspace layer when untrusted.
|
|
11363
|
+
const initialTrustSettings = deepMerge(layers[3], layers[1]);
|
|
11364
|
+
const workspaceTrusted = qwenWorkspaceTrusted(initialTrustSettings, process.cwd());
|
|
11365
|
+
if (workspaceTrusted === null)
|
|
11366
|
+
return null;
|
|
11367
|
+
if (!workspaceTrusted)
|
|
11368
|
+
layers[2] = {};
|
|
11369
|
+
return layers;
|
|
11370
|
+
}
|
|
11371
|
+
function qwenSettingsPermitRecovery(marker, layers) {
|
|
11372
|
+
const fallback = qwenHomeEnvFallback();
|
|
11373
|
+
if (!fallback)
|
|
11374
|
+
return false;
|
|
11375
|
+
// System settings are enterprise-owned and outrank Caveman's user entry.
|
|
11376
|
+
// Never replace a different server carrying the same name.
|
|
11377
|
+
const systemEntry = jsonValueAt(layers[layers.length - 1], ["mcpServers", "caveman"]);
|
|
11378
|
+
if (systemEntry !== undefined && !qwenMcpEntryMatches(systemEntry, marker))
|
|
11379
|
+
return false;
|
|
11380
|
+
let allowedConfigured = false;
|
|
11381
|
+
let allowed = false;
|
|
11382
|
+
for (const layer of layers) {
|
|
11383
|
+
const allowList = qwenStringList(layer, ["mcp", "allowed"], fallback);
|
|
11384
|
+
const excludeList = qwenStringList(layer, ["mcp", "excluded"], fallback);
|
|
11385
|
+
const denyRules = qwenStringList(layer, ["permissions", "deny"], fallback);
|
|
11386
|
+
const legacyDenyRules = qwenStringList(layer, ["tools", "exclude"], fallback);
|
|
11387
|
+
const disabledTools = qwenStringList(layer, ["tools", "disabled"], fallback);
|
|
11388
|
+
if (allowList === null || excludeList === null || denyRules === null || legacyDenyRules === null || disabledTools === null)
|
|
11389
|
+
return false;
|
|
11390
|
+
if (allowList !== undefined) {
|
|
11391
|
+
allowedConfigured = true;
|
|
11392
|
+
if (allowList.some((pattern) => qwenMcpServerPatternMatches("caveman", pattern)))
|
|
11393
|
+
allowed = true;
|
|
11394
|
+
}
|
|
11395
|
+
if (excludeList?.some((pattern) => qwenMcpServerPatternMatches("caveman", pattern)))
|
|
11396
|
+
return false;
|
|
11397
|
+
if (denyRules?.some(qwenCavemanToolDenied) || legacyDenyRules?.some(qwenCavemanToolDenied))
|
|
11398
|
+
return false;
|
|
11399
|
+
if (disabledTools?.some(qwenCavemanToolDisabled))
|
|
11400
|
+
return false;
|
|
11401
|
+
}
|
|
11402
|
+
return !allowedConfigured || allowed;
|
|
11403
|
+
}
|
|
11404
|
+
function qwenUserLevelEnvPaths(state = qwenHomeState()) {
|
|
11405
|
+
return new Set([
|
|
11406
|
+
normalize(join(homedir(), ".env")),
|
|
11407
|
+
normalize(join(state.root, ".env")),
|
|
11408
|
+
normalize(join(homedir(), ".qwen", ".env")),
|
|
11409
|
+
]);
|
|
11410
|
+
}
|
|
11411
|
+
function qwenEnvFileIsQwenScoped(path, state) {
|
|
11412
|
+
const normalized = normalize(path);
|
|
11413
|
+
return qwenUserLevelEnvPaths(state).has(normalized) || basename(dirname(normalized)) === ".qwen";
|
|
11414
|
+
}
|
|
11415
|
+
// advanced.excludedEnvVars uses Qwen's UNION merge strategy. Malformed final
|
|
11416
|
+
// state is ambiguous; fail closed instead of guessing which project env keys
|
|
11417
|
+
// the pinned binary will accept.
|
|
11418
|
+
function qwenExcludedEnvVars(layers) {
|
|
11419
|
+
let merged;
|
|
11420
|
+
for (const layer of layers) {
|
|
11421
|
+
const next = jsonValueAt(layer, ["advanced", "excludedEnvVars"]);
|
|
11422
|
+
if (next === undefined)
|
|
11423
|
+
continue;
|
|
11424
|
+
if (Array.isArray(merged)) {
|
|
11425
|
+
const additions = Array.isArray(next) ? next : [next];
|
|
11426
|
+
merged = [...new Set([...merged, ...additions])];
|
|
11427
|
+
}
|
|
11428
|
+
else {
|
|
11429
|
+
merged = next;
|
|
11430
|
+
}
|
|
11431
|
+
}
|
|
11432
|
+
if (merged === undefined)
|
|
11433
|
+
return ["DEBUG", "DEBUG_MODE"];
|
|
11434
|
+
return Array.isArray(merged) && merged.every((item) => typeof item === "string")
|
|
11435
|
+
? merged
|
|
11436
|
+
: null;
|
|
11437
|
+
}
|
|
11438
|
+
function qwenEnvironmentFilePaths(layers) {
|
|
11439
|
+
const state = qwenHomeState();
|
|
11440
|
+
const home = homedir();
|
|
11441
|
+
const legacy = join(home, ".qwen");
|
|
11442
|
+
const effectiveSettings = qwenMergedSettings(layers);
|
|
11443
|
+
const found = [];
|
|
11444
|
+
const push = (path) => {
|
|
11445
|
+
if (existsSync(path) && !found.includes(path))
|
|
11446
|
+
found.push(path);
|
|
11447
|
+
};
|
|
11448
|
+
const pushWorkspace = (path, workspacePath) => {
|
|
11449
|
+
if (!existsSync(path))
|
|
11450
|
+
return false;
|
|
11451
|
+
const trusted = qwenWorkspaceTrusted(effectiveSettings, workspacePath);
|
|
11452
|
+
if (trusted === null)
|
|
11453
|
+
return null;
|
|
11454
|
+
if (!trusted)
|
|
11455
|
+
return false;
|
|
11456
|
+
push(path);
|
|
11457
|
+
return true;
|
|
11458
|
+
};
|
|
11459
|
+
const pushHome = () => {
|
|
11460
|
+
push(join(state.root, ".env"));
|
|
11461
|
+
if (state.root !== legacy)
|
|
11462
|
+
push(join(legacy, ".env"));
|
|
11463
|
+
push(join(home, ".env"));
|
|
11464
|
+
};
|
|
11465
|
+
let current;
|
|
11466
|
+
try {
|
|
11467
|
+
current = realpathSync(process.cwd());
|
|
11468
|
+
}
|
|
11469
|
+
catch {
|
|
11470
|
+
current = resolve(process.cwd());
|
|
11471
|
+
}
|
|
11472
|
+
while (true) {
|
|
11473
|
+
if (current === home) {
|
|
11474
|
+
pushHome();
|
|
11475
|
+
break;
|
|
11476
|
+
}
|
|
11477
|
+
const scoped = join(current, ".qwen", ".env");
|
|
11478
|
+
const scopedAdded = pushWorkspace(scoped, current);
|
|
11479
|
+
if (scopedAdded === null)
|
|
11480
|
+
return null;
|
|
11481
|
+
if (scopedAdded) {
|
|
11482
|
+
pushHome();
|
|
11483
|
+
break;
|
|
11484
|
+
}
|
|
11485
|
+
const plain = join(current, ".env");
|
|
11486
|
+
const plainAdded = pushWorkspace(plain, current);
|
|
11487
|
+
if (plainAdded === null)
|
|
11488
|
+
return null;
|
|
11489
|
+
if (plainAdded) {
|
|
11490
|
+
pushHome();
|
|
11491
|
+
break;
|
|
11492
|
+
}
|
|
11493
|
+
const parent = dirname(current);
|
|
11494
|
+
if (!parent || parent === current) {
|
|
11495
|
+
pushHome();
|
|
11496
|
+
break;
|
|
11497
|
+
}
|
|
11498
|
+
current = parent;
|
|
11499
|
+
}
|
|
11500
|
+
return found;
|
|
11501
|
+
}
|
|
11502
|
+
function qwenEffectiveEnvValue(layers, key) {
|
|
11503
|
+
const inherited = process.env[key];
|
|
11504
|
+
if (inherited)
|
|
11505
|
+
return inherited;
|
|
11506
|
+
const state = qwenHomeState();
|
|
11507
|
+
const excluded = qwenExcludedEnvVars(layers);
|
|
11508
|
+
if (!excluded)
|
|
11509
|
+
return null;
|
|
11510
|
+
const envPaths = qwenEnvironmentFilePaths(layers);
|
|
11511
|
+
if (!envPaths)
|
|
11512
|
+
return null;
|
|
11513
|
+
for (const path of envPaths) {
|
|
11514
|
+
const parsed = qwenReadDotEnv(path);
|
|
11515
|
+
if (!parsed)
|
|
11516
|
+
return null;
|
|
11517
|
+
if (!qwenEnvFileIsQwenScoped(path, state) && excluded.includes(key))
|
|
11518
|
+
continue;
|
|
11519
|
+
const candidate = parsed[key];
|
|
11520
|
+
if (candidate)
|
|
11521
|
+
return candidate;
|
|
11522
|
+
}
|
|
11523
|
+
// settings.env is the lowest environment tier; system settings win over
|
|
11524
|
+
// workspace, user, and system defaults for each key. Qwen's normal loader
|
|
11525
|
+
// intentionally does not apply excludedEnvVars to settings.env.
|
|
11526
|
+
const env = jsonValueAt(qwenMergedSettings(layers), ["env"]);
|
|
11527
|
+
if (env === undefined)
|
|
11528
|
+
return undefined;
|
|
11529
|
+
if (!env || typeof env !== "object" || Array.isArray(env))
|
|
11530
|
+
return null;
|
|
11531
|
+
const candidate = env[key];
|
|
11532
|
+
if (candidate === undefined)
|
|
11533
|
+
return undefined;
|
|
11534
|
+
return typeof candidate === "string" ? candidate : null;
|
|
11535
|
+
}
|
|
11536
|
+
function qwenOpenAIKeyAvailability(value) {
|
|
11537
|
+
if (value === null)
|
|
11538
|
+
return null;
|
|
11539
|
+
if (value === undefined || !value.trim())
|
|
11540
|
+
return false;
|
|
11541
|
+
if (qwenEnvReference.test(value) || /[\r\n]/.test(value))
|
|
11542
|
+
return null;
|
|
11543
|
+
return true;
|
|
11544
|
+
}
|
|
11545
|
+
// Qwen resolves settings before loading project dotenv/settings.env. Its normal
|
|
11546
|
+
// process then relaunches once, inheriting those late-loaded values, and resolves
|
|
11547
|
+
// the temporary system settings again. Pre-existing no-relaunch/sandbox processes
|
|
11548
|
+
// skip that second pass, so only process env or Qwen's home fallback can safely
|
|
11549
|
+
// satisfy a header reference there.
|
|
11550
|
+
function qwenEffectiveOpenAIKeyAvailable() {
|
|
11551
|
+
const layers = qwenSettingsLayers();
|
|
11552
|
+
if (!layers)
|
|
11553
|
+
return null;
|
|
11554
|
+
const noRelaunch = qwenEffectiveEnvValue(layers, "QWEN_CODE_NO_RELAUNCH");
|
|
11555
|
+
const sandbox = qwenEffectiveEnvValue(layers, "SANDBOX");
|
|
11556
|
+
if (noRelaunch === null || sandbox === null)
|
|
11557
|
+
return null;
|
|
11558
|
+
if (!noRelaunch && !sandbox) {
|
|
11559
|
+
return qwenOpenAIKeyAvailability(qwenEffectiveEnvValue(layers, "OPENAI_API_KEY"));
|
|
11560
|
+
}
|
|
11561
|
+
const fallback = qwenHomeEnvFallback();
|
|
11562
|
+
if (!fallback)
|
|
11563
|
+
return null;
|
|
11564
|
+
const inherited = process.env.OPENAI_API_KEY;
|
|
11565
|
+
return qwenOpenAIKeyAvailability(typeof inherited === "string" ? inherited : fallback.OPENAI_API_KEY);
|
|
11566
|
+
}
|
|
11567
|
+
function qwenMatchedOption(arg, names) {
|
|
11568
|
+
for (const name of names) {
|
|
11569
|
+
if (arg === name)
|
|
11570
|
+
return { inline: false };
|
|
11571
|
+
if (arg.startsWith(`${name}=`))
|
|
11572
|
+
return { inline: true, value: arg.slice(name.length + 1) };
|
|
11573
|
+
}
|
|
11574
|
+
return null;
|
|
11575
|
+
}
|
|
11576
|
+
function kiloProfileModelIds(agent) {
|
|
11577
|
+
if (agent.id !== "kilo" || agent.injection.method !== "config-env-content")
|
|
11578
|
+
return new Set();
|
|
11579
|
+
const contents = [agent.injection.config_content.local, agent.injection.config_content.managed ?? agent.injection.config_content.local];
|
|
11580
|
+
let shared;
|
|
11581
|
+
for (const content of contents) {
|
|
11582
|
+
const enabled = jsonValueAt(content, ["enabled_providers"]);
|
|
11583
|
+
const models = jsonValueAt(content, ["provider", "caveman", "models"]);
|
|
11584
|
+
if (!Array.isArray(enabled) || enabled.length !== 1 || enabled[0] !== "caveman"
|
|
11585
|
+
|| !models || typeof models !== "object" || Array.isArray(models))
|
|
11586
|
+
return new Set();
|
|
11587
|
+
const ids = new Set(Object.keys(models).filter((id) => id && id.trim() === id).map((id) => `caveman/${id}`));
|
|
11588
|
+
shared = shared === undefined ? ids : new Set([...shared].filter((id) => ids.has(id)));
|
|
11589
|
+
}
|
|
11590
|
+
return shared ?? new Set();
|
|
11591
|
+
}
|
|
11592
|
+
function kiloManagedPolicyPresent() {
|
|
11593
|
+
const directory = process.env.KILO_TEST_MANAGED_CONFIG_DIR || (process.platform === "darwin"
|
|
11594
|
+
? "/Library/Application Support/kilo"
|
|
11595
|
+
: process.platform === "win32"
|
|
11596
|
+
? join(process.env.ProgramData || "C:\\ProgramData", "kilo")
|
|
11597
|
+
: "/etc/kilo");
|
|
11598
|
+
// Exact Kilo 7.5.6 managed file set. config.json is a legacy global filename,
|
|
11599
|
+
// but managed loading deliberately excludes it.
|
|
11600
|
+
const configFiles = ["kilo.jsonc", "kilo.json", "opencode.jsonc", "opencode.json"];
|
|
11601
|
+
if (configFiles.some((name) => existsSync(join(directory, name))))
|
|
11602
|
+
return true;
|
|
11603
|
+
if (process.platform !== "darwin")
|
|
11604
|
+
return false;
|
|
11605
|
+
const preferenceFiles = ["/Library/Managed Preferences/ai.opencode.managed.plist"];
|
|
11606
|
+
try {
|
|
11607
|
+
preferenceFiles.unshift(join("/Library/Managed Preferences", userInfo().username, "ai.opencode.managed.plist"));
|
|
11608
|
+
}
|
|
11609
|
+
catch {
|
|
11610
|
+
// System-level preference remains covered; an unreadable username is itself
|
|
11611
|
+
// unusual, but no user path can be resolved safely enough to claim absence.
|
|
11612
|
+
return true;
|
|
11613
|
+
}
|
|
11614
|
+
return preferenceFiles.some((path) => existsSync(path));
|
|
11615
|
+
}
|
|
11616
|
+
function kiloDatabasePath() {
|
|
11617
|
+
const rawDataRoot = process.env.XDG_DATA_HOME || join(homedir(), ".local", "share");
|
|
11618
|
+
const cleanedDataRoot = rawDataRoot.replace(/[\r\n]+/g, "");
|
|
11619
|
+
if (!cleanedDataRoot)
|
|
11620
|
+
throw new Error("Kilo data root resolves to an empty path");
|
|
11621
|
+
const dataRoot = normalize(isAbsolute(cleanedDataRoot) ? cleanedDataRoot : resolve(cleanedDataRoot));
|
|
11622
|
+
const configured = process.env.KILO_DB;
|
|
11623
|
+
if (configured === ":memory:")
|
|
11624
|
+
return null;
|
|
11625
|
+
if (configured) {
|
|
11626
|
+
if (/[\0\r\n]/.test(configured))
|
|
11627
|
+
throw new Error("KILO_DB contains an invalid path character");
|
|
11628
|
+
return normalize(isAbsolute(configured) ? configured : join(dataRoot, "kilo", configured));
|
|
11629
|
+
}
|
|
11630
|
+
return join(dataRoot, "kilo", "kilo.db");
|
|
11631
|
+
}
|
|
11632
|
+
function kiloActiveOrganizationState() {
|
|
11633
|
+
let path;
|
|
11634
|
+
try {
|
|
11635
|
+
path = kiloDatabasePath();
|
|
11636
|
+
if (path === null)
|
|
11637
|
+
return "none";
|
|
11638
|
+
const stat = statSync(path);
|
|
11639
|
+
if (!stat.isFile())
|
|
11640
|
+
return "unknown";
|
|
11641
|
+
}
|
|
11642
|
+
catch (error) {
|
|
11643
|
+
if (error.code === "ENOENT")
|
|
11644
|
+
return "none";
|
|
11645
|
+
return "unknown";
|
|
11646
|
+
}
|
|
11647
|
+
const script = [
|
|
11648
|
+
'const { DatabaseSync } = require("node:sqlite");',
|
|
11649
|
+
'const db = new DatabaseSync(process.argv[1], { readOnly: true });',
|
|
11650
|
+
'try {',
|
|
11651
|
+
' const row = db.prepare("SELECT 1 AS active FROM account_state WHERE id = 1 AND active_account_id IS NOT NULL AND active_org_id IS NOT NULL LIMIT 1").get();',
|
|
11652
|
+
' process.stdout.write(row?.active === 1 ? "active" : "none");',
|
|
11653
|
+
'} finally { db.close(); }',
|
|
11654
|
+
].join("\n");
|
|
11655
|
+
const probe = spawnSync(process.execPath, ["--no-warnings", "-e", script, path], {
|
|
11656
|
+
encoding: "utf8",
|
|
11657
|
+
timeout: 2_000,
|
|
11658
|
+
env: { ...process.env, NODE_NO_WARNINGS: "1", NODE_OPTIONS: "" },
|
|
11659
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
11660
|
+
});
|
|
11661
|
+
if (probe.status !== 0 || probe.signal || probe.error)
|
|
11662
|
+
return "unknown";
|
|
11663
|
+
return probe.stdout === "active" ? "active" : probe.stdout === "none" ? "none" : "unknown";
|
|
11664
|
+
}
|
|
11665
|
+
function kiloHigherPriorityRouteOverride() {
|
|
11666
|
+
if (kiloManagedPolicyPresent()) {
|
|
11667
|
+
return { surface: "managed policy", reason: "loads after Caveman's inline routing config" };
|
|
11668
|
+
}
|
|
11669
|
+
const organization = kiloActiveOrganizationState();
|
|
11670
|
+
if (organization === "active") {
|
|
11671
|
+
return { surface: "active organization", reason: "can load routing policy after Caveman's inline config" };
|
|
11672
|
+
}
|
|
11673
|
+
if (organization === "unknown") {
|
|
11674
|
+
return { surface: "organization state", reason: "cannot be verified safely" };
|
|
11675
|
+
}
|
|
11676
|
+
return null;
|
|
11677
|
+
}
|
|
11678
|
+
// Kilo's inline config selects a routed default, but its CLI model option has
|
|
11679
|
+
// higher precedence and attach mode delegates inference to another server whose
|
|
11680
|
+
// environment this process cannot control. Detect both before proxy/bootstrap
|
|
11681
|
+
// work. Unknown short-option clusters fail direct instead of guessing yargs.
|
|
11682
|
+
function kiloRouteOverride(agent, args) {
|
|
11683
|
+
const higherPriority = kiloHigherPriorityRouteOverride();
|
|
11684
|
+
if (higherPriority)
|
|
11685
|
+
return higherPriority;
|
|
11686
|
+
const separator = args.indexOf("--");
|
|
11687
|
+
const parsedArgs = separator === -1 ? args : args.slice(0, separator);
|
|
11688
|
+
const valueOptions = new Set([
|
|
11689
|
+
"--log-level", "--port", "--hostname", "--mdns-domain", "--cors",
|
|
11690
|
+
"--session", "-s", "--worktree", "--prompt", "--agent", "--replay-limit",
|
|
11691
|
+
"--command", "--format", "--file", "-f", "--title", "--password", "-p",
|
|
11692
|
+
"--username", "-u", "--dir", "--variant", "--timeout", "--parallel", "--output",
|
|
11693
|
+
"--repo", "--repo-type", "--branch", "--mode", "--org-id", "--session-id", "--message-id",
|
|
11694
|
+
]);
|
|
11695
|
+
const booleanOptions = new Set([
|
|
11696
|
+
"-h", "--help", "-v", "--version", "--print-logs", "--pure", "--mdns",
|
|
11697
|
+
"-c", "--continue", "--fork", "--cloud-fork", "--auto", "--mini", "--no-replay",
|
|
11698
|
+
"--share", "--thinking", "-i", "--interactive", "--stream", "--verbose", "--quiet",
|
|
11699
|
+
]);
|
|
11700
|
+
let command;
|
|
11701
|
+
let modelValue;
|
|
11702
|
+
let modelOccurrences = 0;
|
|
11703
|
+
for (let index = 0; index < parsedArgs.length; index++) {
|
|
11704
|
+
const arg = parsedArgs[index];
|
|
11705
|
+
if (arg === "--attach" || arg.startsWith("--attach=")) {
|
|
11706
|
+
return { surface: "--attach", reason: "uses another server's provider route" };
|
|
11707
|
+
}
|
|
11708
|
+
const model = qwenMatchedOption(arg, ["--model", "--m", "-m"]);
|
|
11709
|
+
if (model) {
|
|
11710
|
+
modelOccurrences++;
|
|
11711
|
+
const value = model?.inline ? model.value : parsedArgs[index + 1];
|
|
11712
|
+
if (typeof value !== "string" || !value || value.startsWith("-")) {
|
|
11713
|
+
return { surface: "--model", reason: "is repeated or malformed" };
|
|
11714
|
+
}
|
|
11715
|
+
modelValue = value;
|
|
11716
|
+
if (!model?.inline)
|
|
11717
|
+
index++;
|
|
11718
|
+
continue;
|
|
11719
|
+
}
|
|
11720
|
+
if (arg.startsWith("-") && !arg.startsWith("--") && arg.slice(1).includes("m")) {
|
|
11721
|
+
return { surface: "-m", reason: "is ambiguous inside a short-option cluster" };
|
|
11722
|
+
}
|
|
11723
|
+
const equals = arg.indexOf("=");
|
|
11724
|
+
const optionName = equals === -1 ? arg : arg.slice(0, equals);
|
|
11725
|
+
if (valueOptions.has(optionName)) {
|
|
11726
|
+
if (equals === -1) {
|
|
11727
|
+
const value = parsedArgs[index + 1];
|
|
11728
|
+
if (typeof value !== "string" || !value || value.startsWith("-")) {
|
|
11729
|
+
return { surface: optionName, reason: "is malformed and makes command routing ambiguous" };
|
|
11730
|
+
}
|
|
11731
|
+
index++;
|
|
11732
|
+
}
|
|
11733
|
+
else if (!arg.slice(equals + 1)) {
|
|
11734
|
+
return { surface: optionName, reason: "is malformed and makes command routing ambiguous" };
|
|
11735
|
+
}
|
|
11736
|
+
continue;
|
|
11737
|
+
}
|
|
11738
|
+
if (booleanOptions.has(optionName)) {
|
|
11739
|
+
if (equals !== -1) {
|
|
11740
|
+
const value = arg.slice(equals + 1);
|
|
11741
|
+
if (value !== "true" && value !== "false") {
|
|
11742
|
+
return { surface: optionName, reason: "has a non-boolean value and makes command routing ambiguous" };
|
|
11743
|
+
}
|
|
11744
|
+
}
|
|
11745
|
+
else if (parsedArgs[index + 1] === "true" || parsedArgs[index + 1] === "false") {
|
|
11746
|
+
index++;
|
|
11747
|
+
}
|
|
11748
|
+
continue;
|
|
11749
|
+
}
|
|
11750
|
+
if (arg.startsWith("-")) {
|
|
11751
|
+
return { surface: "arguments", reason: "cannot be parsed safely with Kilo 7.5.6 option arities" };
|
|
11752
|
+
}
|
|
11753
|
+
if (command === undefined) {
|
|
11754
|
+
command = arg;
|
|
11755
|
+
if (command === "attach")
|
|
11756
|
+
return { surface: "attach", reason: "uses another server's provider route" };
|
|
11757
|
+
if (command === "cloud" || command === "roll-call") {
|
|
11758
|
+
return { surface: command, reason: "runs outside Kilo's local single-model route" };
|
|
11759
|
+
}
|
|
11760
|
+
if (command === "daemon" || command === "console") {
|
|
11761
|
+
return { surface: command, reason: "can outlive Caveman's wrap session" };
|
|
11762
|
+
}
|
|
11763
|
+
}
|
|
11764
|
+
}
|
|
11765
|
+
if (modelOccurrences > 1)
|
|
11766
|
+
return { surface: "--model", reason: "is repeated or malformed" };
|
|
11767
|
+
const routedModels = kiloProfileModelIds(agent);
|
|
11768
|
+
if (routedModels.size === 0)
|
|
11769
|
+
return { surface: "routing profile", reason: "does not confine Kilo to Caveman providers" };
|
|
11770
|
+
if (modelValue !== undefined && !routedModels.has(modelValue)) {
|
|
11771
|
+
return { surface: "--model", reason: "selects a model outside Caveman's routed profile" };
|
|
11772
|
+
}
|
|
11773
|
+
return null;
|
|
11774
|
+
}
|
|
11775
|
+
function qwenProfileModelIds(agent) {
|
|
11776
|
+
if (agent.id !== "qwen" || agent.injection.method !== "config-file")
|
|
11777
|
+
return new Set();
|
|
11778
|
+
const overlays = [agent.injection.config_overlay.local, agent.injection.config_overlay.managed ?? agent.injection.config_overlay.local];
|
|
11779
|
+
let shared;
|
|
11780
|
+
for (const overlay of overlays) {
|
|
11781
|
+
const models = jsonValueAt(overlay, ["modelProviders", "openai"]);
|
|
11782
|
+
if (!Array.isArray(models))
|
|
11783
|
+
return new Set();
|
|
11784
|
+
const ids = new Set(models.flatMap((model) => {
|
|
11785
|
+
const id = jsonValueAt(model, ["id"]);
|
|
11786
|
+
return typeof id === "string" && id.trim() === id && id ? [id] : [];
|
|
11787
|
+
}));
|
|
11788
|
+
shared = shared === undefined ? ids : new Set([...shared].filter((id) => ids.has(id)));
|
|
11789
|
+
}
|
|
11790
|
+
return shared ?? new Set();
|
|
11791
|
+
}
|
|
11792
|
+
function qwenBooleanArg(args, index, positive, negative) {
|
|
11793
|
+
const arg = args[index];
|
|
11794
|
+
const negated = qwenMatchedOption(arg, negative);
|
|
11795
|
+
if (negated?.inline)
|
|
11796
|
+
return { matched: true, malformed: true, consumed: 0 };
|
|
11797
|
+
if (negated)
|
|
11798
|
+
return { matched: true, value: false, malformed: false, consumed: 0 };
|
|
11799
|
+
const enabled = qwenMatchedOption(arg, positive);
|
|
11800
|
+
if (!enabled)
|
|
11801
|
+
return { matched: false, malformed: false, consumed: 0 };
|
|
11802
|
+
if (enabled.inline) {
|
|
11803
|
+
if (enabled.value === "true" || enabled.value === "false") {
|
|
11804
|
+
return { matched: true, value: enabled.value === "true", malformed: false, consumed: 0 };
|
|
11805
|
+
}
|
|
11806
|
+
return { matched: true, malformed: true, consumed: 0 };
|
|
11807
|
+
}
|
|
11808
|
+
const next = args[index + 1];
|
|
11809
|
+
if (next === "true" || next === "false") {
|
|
11810
|
+
return { matched: true, value: next === "true", malformed: false, consumed: 1 };
|
|
11811
|
+
}
|
|
11812
|
+
return { matched: true, value: true, malformed: false, consumed: 0 };
|
|
11813
|
+
}
|
|
11814
|
+
// Qwen's temporary system settings route can be superseded by CLI routing and
|
|
11815
|
+
// auth flags, while safe/bare modes can discard it entirely. Parse the pinned
|
|
11816
|
+
// 0.22.3 spellings before proxy startup. Ambiguous or repeated selectors launch
|
|
11817
|
+
// direct: preserving the user's argv is safer than claiming traffic was routed.
|
|
11818
|
+
function qwenShortOptionLetters(arg) {
|
|
11819
|
+
if (!arg.startsWith("-") || arg.startsWith("--") || arg.length < 2)
|
|
11820
|
+
return new Set();
|
|
11821
|
+
const letters = new Set();
|
|
11822
|
+
// yargs expands boolean clusters left-to-right, but these aliases consume the
|
|
11823
|
+
// remaining suffix as their value. Do not mistake model/prompt text for flags.
|
|
11824
|
+
const takesValue = new Set(["e", "i", "m", "o", "p", "r"]);
|
|
11825
|
+
for (const letter of arg.slice(1).split("=", 1)[0]) {
|
|
11826
|
+
letters.add(letter);
|
|
11827
|
+
if (takesValue.has(letter))
|
|
11828
|
+
break;
|
|
11829
|
+
}
|
|
11830
|
+
return letters;
|
|
11831
|
+
}
|
|
11832
|
+
function qwenExtensionRouteOverride(args) {
|
|
11833
|
+
let confined = 0;
|
|
11834
|
+
for (const arg of args) {
|
|
11835
|
+
if (arg === "--extensions=none") {
|
|
11836
|
+
confined++;
|
|
11837
|
+
continue;
|
|
11838
|
+
}
|
|
11839
|
+
if (arg === "--extensions" || arg === "-e" || arg.startsWith("--extensions=") || arg.startsWith("-e")
|
|
11840
|
+
|| qwenShortOptionLetters(arg).has("e")) {
|
|
11841
|
+
return { surface: "--extensions", reason: "can load model-routing code outside Caveman's locked session" };
|
|
11842
|
+
}
|
|
11843
|
+
}
|
|
11844
|
+
return confined > 1
|
|
11845
|
+
? { surface: "--extensions", reason: "is repeated or ambiguous" }
|
|
11846
|
+
: null;
|
|
11847
|
+
}
|
|
11848
|
+
function qwenControlSurfaceOverride(args) {
|
|
11849
|
+
for (const arg of args) {
|
|
11850
|
+
if (arg === "--")
|
|
11851
|
+
break;
|
|
11852
|
+
const shortOptions = qwenShortOptionLetters(arg);
|
|
11853
|
+
if (arg === "--continue" || arg.startsWith("--continue=") || shortOptions.has("c")
|
|
11854
|
+
|| arg === "--resume" || arg.startsWith("--resume=") || shortOptions.has("r")
|
|
11855
|
+
|| arg === "--fork-session" || arg.startsWith("--fork-session=")
|
|
11856
|
+
|| arg === "--forkSession" || arg.startsWith("--forkSession=")) {
|
|
11857
|
+
return { surface: "session restore", reason: "can reactivate a recorded provider route outside Caveman's locked session" };
|
|
11858
|
+
}
|
|
11859
|
+
}
|
|
11860
|
+
const directFlags = ["--acp", "--experimental-acp", "--experimentalAcp", "--experimental-skills", "--experimentalSkills"];
|
|
11861
|
+
for (let index = 0; index < args.length; index++) {
|
|
11862
|
+
const match = qwenBooleanArg(args, index, directFlags, []);
|
|
11863
|
+
if (!match.matched)
|
|
11864
|
+
continue;
|
|
11865
|
+
if (match.malformed || match.value === true) {
|
|
11866
|
+
return { surface: args[index].split("=", 1)[0], reason: "exposes runtime model selection outside Caveman's locked session" };
|
|
11867
|
+
}
|
|
11868
|
+
index += match.consumed;
|
|
11869
|
+
}
|
|
11870
|
+
if (args.some((arg) => {
|
|
11871
|
+
return arg === "--list-extensions" || arg === "--listExtensions" || qwenShortOptionLetters(arg).has("l") || arg.startsWith("--channel=") || arg === "--channel";
|
|
11872
|
+
})) {
|
|
11873
|
+
return { surface: "control mode", reason: "does not run one confined Qwen model session" };
|
|
11874
|
+
}
|
|
11875
|
+
const controlCommands = new Set(["auth", "channel", "extensions", "hooks", "mcp", "review", "serve", "sessions", "update"]);
|
|
11876
|
+
const booleanOptions = new Set([
|
|
11877
|
+
"--telemetry", "--debug", "--bare", "--safe-mode", "--insecure", "--chat-recording",
|
|
11878
|
+
"--sandbox", "--yolo", "--experimental-lsp", "--restore-ask-user-question",
|
|
11879
|
+
"--screen-reader", "--include-partial-messages", "--continue", "--fork-session", "--worktree",
|
|
11880
|
+
"-s", "-c", "-v", "--version", "-h", "--help",
|
|
11881
|
+
]);
|
|
11882
|
+
const valueOptions = new Set([
|
|
11883
|
+
"--telemetry-target", "--telemetry-otlp-endpoint", "--telemetry-otlp-protocol", "--telemetry-log-prompts",
|
|
11884
|
+
"--telemetry-outfile", "--proxy", "--model", "-m", "--prompt", "-p", "--prompt-interactive", "-i",
|
|
11885
|
+
"--system-prompt", "--append-system-prompt", "--sandbox-image", "--approval-mode", "--allowed-mcp-server-names",
|
|
11886
|
+
"--mcp-config", "--allowed-tools", "--include-directories", "--openai-logging", "--openai-logging-dir",
|
|
11887
|
+
"--openai-api-key", "--openai-base-url", "--input-format", "--output-format", "-o", "--json-fd",
|
|
11888
|
+
"--json-file", "--json-schema", "--input-file", "--resume", "-r", "--session-id", "--sandbox-session-id",
|
|
11889
|
+
"--max-session-turns", "--max-wall-time", "--max-tool-calls", "--max-subagent-depth", "--core-tools",
|
|
11890
|
+
"--exclude-tools", "--disabled-slash-commands", "--auth-type",
|
|
11891
|
+
]);
|
|
11892
|
+
const routedArgs = args.filter((arg) => arg !== "--extensions=none");
|
|
11893
|
+
for (let index = 0; index < routedArgs.length; index++) {
|
|
11894
|
+
const arg = routedArgs[index];
|
|
11895
|
+
if (arg === "--")
|
|
11896
|
+
break;
|
|
11897
|
+
if (arg.startsWith("--") && arg.includes("="))
|
|
11898
|
+
continue;
|
|
11899
|
+
if (booleanOptions.has(arg)) {
|
|
11900
|
+
if (routedArgs[index + 1] === "true" || routedArgs[index + 1] === "false")
|
|
11901
|
+
index++;
|
|
11902
|
+
continue;
|
|
11903
|
+
}
|
|
11904
|
+
if (valueOptions.has(arg)) {
|
|
11905
|
+
if (routedArgs[index + 1] !== undefined)
|
|
11906
|
+
index++;
|
|
11907
|
+
continue;
|
|
11908
|
+
}
|
|
11909
|
+
if (arg.startsWith("-"))
|
|
11910
|
+
continue;
|
|
11911
|
+
return controlCommands.has(arg)
|
|
11912
|
+
? { surface: arg, reason: "is a Qwen control command, not one confined model session" }
|
|
11913
|
+
: null;
|
|
11914
|
+
}
|
|
11915
|
+
return null;
|
|
11916
|
+
}
|
|
11917
|
+
function qwenRouteOverride(agent, args) {
|
|
11918
|
+
const extensionOverride = qwenExtensionRouteOverride(args);
|
|
11919
|
+
if (extensionOverride)
|
|
11920
|
+
return extensionOverride;
|
|
11921
|
+
const controlOverride = qwenControlSurfaceOverride(args);
|
|
11922
|
+
if (controlOverride)
|
|
11923
|
+
return controlOverride;
|
|
11924
|
+
// Qwen 0.22.3 checks raw process.argv before yargs and forces SIMPLE mode
|
|
11925
|
+
// whenever this exact token occurs, even after `--` or beside `false`.
|
|
11926
|
+
if (args.includes("--bare"))
|
|
11927
|
+
return { surface: "--bare", reason: "ignores Caveman system settings" };
|
|
11928
|
+
const modelValues = [];
|
|
11929
|
+
const fallbackValues = [];
|
|
11930
|
+
const authValues = [];
|
|
11931
|
+
const safeValues = [];
|
|
11932
|
+
const bareValues = [];
|
|
11933
|
+
let modelOccurrences = 0;
|
|
11934
|
+
let authOccurrences = 0;
|
|
11935
|
+
let safeMalformed = false;
|
|
11936
|
+
let bareMalformed = false;
|
|
11937
|
+
let modelMalformed = false;
|
|
11938
|
+
let fallbackMalformed = false;
|
|
11939
|
+
let authMalformed = false;
|
|
11940
|
+
for (let index = 0; index < args.length; index++) {
|
|
11941
|
+
const arg = args[index];
|
|
11942
|
+
if (arg === "--")
|
|
11943
|
+
break;
|
|
11944
|
+
if (qwenMatchedOption(arg, ["--openai-api-key", "--openaiApiKey"])) {
|
|
11945
|
+
return { surface: "--openai-api-key", reason: "overrides Caveman's credential route" };
|
|
11946
|
+
}
|
|
11947
|
+
if (qwenMatchedOption(arg, ["--openai-base-url", "--openaiBaseUrl"])) {
|
|
11948
|
+
return { surface: "--openai-base-url", reason: "overrides Caveman's gateway route" };
|
|
11949
|
+
}
|
|
11950
|
+
const model = qwenMatchedOption(arg, ["--model", "--m"]);
|
|
11951
|
+
if (model || arg === "-m") {
|
|
11952
|
+
modelOccurrences++;
|
|
11953
|
+
const value = model?.inline ? model.value : args[index + 1];
|
|
11954
|
+
if (typeof value !== "string" || !value || value === "--" || (!model?.inline && value.startsWith("-"))) {
|
|
11955
|
+
modelMalformed = true;
|
|
11956
|
+
}
|
|
11957
|
+
else {
|
|
11958
|
+
modelValues.push(value);
|
|
11959
|
+
if (!model?.inline)
|
|
11960
|
+
index++;
|
|
11961
|
+
}
|
|
11962
|
+
continue;
|
|
11963
|
+
}
|
|
11964
|
+
if (arg.startsWith("-") && !arg.startsWith("--") && arg.slice(1).includes("m")) {
|
|
11965
|
+
if (!arg.startsWith("-m=")) {
|
|
11966
|
+
return { surface: "-m", reason: "is ambiguous inside a short-option cluster" };
|
|
11967
|
+
}
|
|
11968
|
+
modelOccurrences++;
|
|
11969
|
+
const value = arg.slice(3);
|
|
11970
|
+
if (!value)
|
|
11971
|
+
modelMalformed = true;
|
|
11972
|
+
else
|
|
11973
|
+
modelValues.push(value);
|
|
11974
|
+
continue;
|
|
11975
|
+
}
|
|
11976
|
+
const fallback = qwenMatchedOption(arg, ["--fallback-model", "--fallbackModel"]);
|
|
11977
|
+
if (fallback) {
|
|
11978
|
+
const raw = [];
|
|
11979
|
+
if (fallback.inline) {
|
|
11980
|
+
if (fallback.value !== undefined)
|
|
11981
|
+
raw.push(fallback.value);
|
|
11982
|
+
}
|
|
11983
|
+
// yargs arrays consume every following non-option token even when first
|
|
11984
|
+
// value used `=`; all of them participate in the effective fallback list.
|
|
11985
|
+
while (index + 1 < args.length && !args[index + 1].startsWith("-"))
|
|
11986
|
+
raw.push(args[++index]);
|
|
11987
|
+
const values = raw.flatMap((value) => value.split(",").map((item) => item.trim()).filter(Boolean));
|
|
11988
|
+
if (values.length === 0)
|
|
11989
|
+
fallbackMalformed = true;
|
|
11990
|
+
else
|
|
11991
|
+
fallbackValues.push(...values);
|
|
11992
|
+
continue;
|
|
11993
|
+
}
|
|
11994
|
+
const auth = qwenMatchedOption(arg, ["--auth-type", "--authType"]);
|
|
11995
|
+
if (auth) {
|
|
11996
|
+
authOccurrences++;
|
|
11997
|
+
const value = auth.inline ? auth.value : args[index + 1];
|
|
11998
|
+
if (typeof value !== "string" || !value || value === "--" || (!auth.inline && value.startsWith("-"))) {
|
|
11999
|
+
authMalformed = true;
|
|
12000
|
+
}
|
|
12001
|
+
else {
|
|
12002
|
+
authValues.push(value);
|
|
12003
|
+
if (!auth.inline)
|
|
12004
|
+
index++;
|
|
12005
|
+
}
|
|
12006
|
+
continue;
|
|
12007
|
+
}
|
|
12008
|
+
const safe = qwenBooleanArg(args, index, ["--safe-mode", "--safeMode"], ["--no-safe-mode", "--no-safeMode"]);
|
|
12009
|
+
if (safe.matched) {
|
|
12010
|
+
safeMalformed ||= safe.malformed;
|
|
12011
|
+
if (safe.value !== undefined)
|
|
12012
|
+
safeValues.push(safe.value);
|
|
12013
|
+
index += safe.consumed;
|
|
12014
|
+
continue;
|
|
12015
|
+
}
|
|
12016
|
+
const bare = qwenBooleanArg(args, index, ["--bare"], ["--no-bare"]);
|
|
12017
|
+
if (bare.matched) {
|
|
12018
|
+
bareMalformed ||= bare.malformed;
|
|
12019
|
+
if (bare.value !== undefined)
|
|
12020
|
+
bareValues.push(bare.value);
|
|
12021
|
+
index += bare.consumed;
|
|
12022
|
+
}
|
|
12023
|
+
}
|
|
12024
|
+
if (modelMalformed || modelOccurrences > 1 || modelValues.length !== modelOccurrences) {
|
|
12025
|
+
return { surface: "--model", reason: "is repeated or malformed" };
|
|
12026
|
+
}
|
|
12027
|
+
if (fallbackMalformed || fallbackValues.length > 3) {
|
|
12028
|
+
return { surface: "--fallback-model", reason: "is repeated or malformed" };
|
|
12029
|
+
}
|
|
12030
|
+
if (authMalformed || authOccurrences > 1 || authValues.length !== authOccurrences) {
|
|
12031
|
+
return { surface: "--auth-type", reason: "is repeated or malformed" };
|
|
12032
|
+
}
|
|
12033
|
+
if (safeMalformed || safeValues.length > 1)
|
|
12034
|
+
return { surface: "--safe-mode", reason: "is repeated or malformed" };
|
|
12035
|
+
if (bareMalformed || bareValues.length > 1)
|
|
12036
|
+
return { surface: "--bare", reason: "is repeated or malformed" };
|
|
12037
|
+
const routedModels = qwenProfileModelIds(agent);
|
|
12038
|
+
if (routedModels.size === 0)
|
|
12039
|
+
return { surface: "routing profile", reason: "has no common local and managed model" };
|
|
12040
|
+
if (modelValues.some((model) => !routedModels.has(model))) {
|
|
12041
|
+
return { surface: "--model", reason: "selects a model outside Caveman's routed profile" };
|
|
12042
|
+
}
|
|
12043
|
+
if (fallbackValues.some((model) => !routedModels.has(model))) {
|
|
12044
|
+
return { surface: "--fallback-model", reason: "selects a model outside Caveman's routed profile" };
|
|
12045
|
+
}
|
|
12046
|
+
if (authValues.some((auth) => auth !== "openai")) {
|
|
12047
|
+
return { surface: "--auth-type", reason: "selects an auth provider outside Caveman's routed profile" };
|
|
12048
|
+
}
|
|
12049
|
+
const layers = qwenSettingsLayers();
|
|
12050
|
+
if (!layers)
|
|
12051
|
+
return { surface: "effective settings", reason: "cannot be resolved safely" };
|
|
12052
|
+
for (const layer of layers) {
|
|
12053
|
+
const enforcedType = jsonValueAt(layer, ["security", "auth", "enforcedType"]);
|
|
12054
|
+
if (enforcedType !== undefined && enforcedType !== "openai") {
|
|
12055
|
+
return { surface: "enforced auth policy", reason: "requires a provider outside Caveman's routed profile" };
|
|
12056
|
+
}
|
|
12057
|
+
}
|
|
12058
|
+
const safeEnv = qwenEffectiveEnvValue(layers, "QWEN_CODE_SAFE_MODE");
|
|
12059
|
+
const bareEnv = qwenEffectiveEnvValue(layers, "QWEN_CODE_SIMPLE");
|
|
12060
|
+
if (safeEnv === null || bareEnv === null)
|
|
12061
|
+
return { surface: "effective settings", reason: "cannot be resolved safely" };
|
|
12062
|
+
const truthy = (value) => !!value && ["1", "true", "yes", "on"].includes(value.toLowerCase().trim());
|
|
12063
|
+
const safeMode = safeValues[0] ?? truthy(safeEnv);
|
|
12064
|
+
// Pinned Qwen implements bare mode as CLI-true OR QWEN_CODE_SIMPLE. An
|
|
12065
|
+
// explicit CLI false cannot neutralize an ambient true value.
|
|
12066
|
+
const bareMode = bareValues[0] === true || truthy(bareEnv);
|
|
12067
|
+
if (safeMode)
|
|
12068
|
+
return { surface: "--safe-mode", reason: "ignores Caveman system settings" };
|
|
12069
|
+
if (bareMode)
|
|
12070
|
+
return { surface: "--bare", reason: "ignores Caveman system settings" };
|
|
12071
|
+
return null;
|
|
12072
|
+
}
|
|
12073
|
+
function agentRouteOverride(agent, args) {
|
|
12074
|
+
if (agent.id === "kilo")
|
|
12075
|
+
return kiloRouteOverride(agent, args);
|
|
12076
|
+
if (agent.id === "qwen")
|
|
12077
|
+
return qwenRouteOverride(agent, args);
|
|
12078
|
+
// Claude Code 2.1.196+ refuses Remote Control unless ANTHROPIC_BASE_URL is
|
|
12079
|
+
// api.anthropic.com, and the first-party escape hatch does not apply (#947).
|
|
12080
|
+
if (agent.id === "claude" && args.includes("remote-control")) {
|
|
12081
|
+
return { surface: "remote-control", reason: "only runs against api.anthropic.com, so it cannot route through the proxy" };
|
|
12082
|
+
}
|
|
12083
|
+
return null;
|
|
12084
|
+
}
|
|
12085
|
+
function routeOverrideLabel(agent) {
|
|
12086
|
+
if (agent.id === "qwen")
|
|
12087
|
+
return "Qwen";
|
|
12088
|
+
if (agent.id === "kilo")
|
|
12089
|
+
return "Kilo";
|
|
12090
|
+
return agent.display_name;
|
|
12091
|
+
}
|
|
12092
|
+
function qwenCliBoolean(args, name) {
|
|
12093
|
+
let value;
|
|
12094
|
+
const camel = name.replace(/-([a-z])/g, (_match, char) => char.toUpperCase());
|
|
12095
|
+
const names = new Set([name, camel]);
|
|
12096
|
+
for (let index = 0; index < args.length; index++) {
|
|
12097
|
+
const arg = args[index];
|
|
12098
|
+
if (arg === "--")
|
|
12099
|
+
break;
|
|
12100
|
+
if ([...names].some((candidate) => arg === `--no-${candidate}`)) {
|
|
12101
|
+
value = false;
|
|
12102
|
+
continue;
|
|
12103
|
+
}
|
|
12104
|
+
const withValue = [...names].find((candidate) => arg.startsWith(`--${candidate}=`));
|
|
12105
|
+
if (withValue) {
|
|
12106
|
+
value = arg.slice(arg.indexOf("=") + 1) === "true";
|
|
12107
|
+
continue;
|
|
12108
|
+
}
|
|
12109
|
+
if (![...names].some((candidate) => arg === `--${candidate}`))
|
|
12110
|
+
continue;
|
|
12111
|
+
const next = args[index + 1];
|
|
12112
|
+
if (next === "true" || next === "false") {
|
|
12113
|
+
value = next === "true";
|
|
12114
|
+
index++;
|
|
12115
|
+
}
|
|
12116
|
+
else {
|
|
12117
|
+
value = true;
|
|
12118
|
+
}
|
|
12119
|
+
}
|
|
12120
|
+
return value;
|
|
12121
|
+
}
|
|
12122
|
+
function qwenModeEnabled(args, name, envKey, layers) {
|
|
12123
|
+
const explicit = qwenCliBoolean(args, name);
|
|
12124
|
+
if (explicit !== undefined)
|
|
12125
|
+
return explicit;
|
|
12126
|
+
const raw = qwenEffectiveEnvValue(layers, envKey);
|
|
12127
|
+
if (raw === null)
|
|
12128
|
+
return null;
|
|
12129
|
+
return !!raw && ["1", "true", "yes", "on"].includes(raw.toLowerCase().trim());
|
|
12130
|
+
}
|
|
12131
|
+
function qwenArgsPermitRecovery(args, layers) {
|
|
12132
|
+
if (qwenModeEnabled(args, "safe-mode", "QWEN_CODE_SAFE_MODE", layers) !== false)
|
|
12133
|
+
return false;
|
|
12134
|
+
if (qwenModeEnabled(args, "bare", "QWEN_CODE_SIMPLE", layers) !== false)
|
|
12135
|
+
return false;
|
|
12136
|
+
let allowedConfigured = false;
|
|
12137
|
+
const allowed = [];
|
|
12138
|
+
for (let index = 0; index < args.length; index++) {
|
|
12139
|
+
const arg = args[index];
|
|
12140
|
+
if (arg === "--")
|
|
12141
|
+
break;
|
|
12142
|
+
if (arg === "--mcp-config" || arg.startsWith("--mcp-config="))
|
|
12143
|
+
return false;
|
|
12144
|
+
if (arg.startsWith("--exclude-tools=")) {
|
|
12145
|
+
const denied = arg.slice(arg.indexOf("=") + 1).split(",").map((item) => item.trim()).filter(Boolean);
|
|
12146
|
+
if (denied.some(qwenCavemanToolDenied))
|
|
12147
|
+
return false;
|
|
12148
|
+
continue;
|
|
12149
|
+
}
|
|
12150
|
+
if (arg === "--exclude-tools") {
|
|
12151
|
+
while (index + 1 < args.length && !args[index + 1].startsWith("-")) {
|
|
12152
|
+
const denied = args[++index].split(",").map((item) => item.trim()).filter(Boolean);
|
|
12153
|
+
if (denied.some(qwenCavemanToolDenied))
|
|
12154
|
+
return false;
|
|
12155
|
+
}
|
|
12156
|
+
continue;
|
|
12157
|
+
}
|
|
12158
|
+
if (arg.startsWith("--allowed-mcp-server-names=")) {
|
|
12159
|
+
allowedConfigured = true;
|
|
12160
|
+
allowed.push(...arg.slice(arg.indexOf("=") + 1).split(",").map((item) => item.trim()).filter(Boolean));
|
|
12161
|
+
continue;
|
|
12162
|
+
}
|
|
12163
|
+
if (arg !== "--allowed-mcp-server-names")
|
|
12164
|
+
continue;
|
|
12165
|
+
allowedConfigured = true;
|
|
12166
|
+
while (index + 1 < args.length && !args[index + 1].startsWith("-")) {
|
|
12167
|
+
allowed.push(...args[++index].split(",").map((item) => item.trim()).filter(Boolean));
|
|
12168
|
+
}
|
|
12169
|
+
}
|
|
12170
|
+
return !allowedConfigured || allowed.some((pattern) => qwenMcpServerPatternMatches("caveman", pattern));
|
|
12171
|
+
}
|
|
12172
|
+
function ownedMcpRegistration(agentId, agentArgs = []) {
|
|
12173
|
+
const marker = readMcpServerMarker(agentId, "caveman");
|
|
12174
|
+
if (!marker)
|
|
12175
|
+
return null;
|
|
12176
|
+
if (agentId === "kilo") {
|
|
12177
|
+
const activePath = canonicalMcpConfigPath(kiloConfigPath());
|
|
12178
|
+
if (marker.config_path && marker.config_path !== activePath)
|
|
12179
|
+
return null;
|
|
12180
|
+
const config = readOptionalJsonObject(marker.config_path ?? activePath);
|
|
12181
|
+
return config && kiloMcpEntryMatches(jsonValueAt(config, ["mcp", "caveman"]), marker) ? marker : null;
|
|
12182
|
+
}
|
|
12183
|
+
if (agentId === "qwen") {
|
|
12184
|
+
const activePath = canonicalMcpConfigPath(qwenConfigPath());
|
|
12185
|
+
if (marker.config_path && marker.config_path !== activePath)
|
|
12186
|
+
return null;
|
|
12187
|
+
const layers = qwenSettingsLayers();
|
|
12188
|
+
if (!layers || !qwenArgsPermitRecovery(agentArgs, layers))
|
|
12189
|
+
return null;
|
|
12190
|
+
const config = readQwenJsonObject(marker.config_path ?? activePath);
|
|
12191
|
+
if (!config || !qwenMcpEntryMatches(jsonValueAt(config, ["mcpServers", "caveman"]), marker))
|
|
12192
|
+
return null;
|
|
12193
|
+
return qwenSettingsPermitRecovery(marker, layers) ? marker : null;
|
|
12194
|
+
}
|
|
12195
|
+
return marker;
|
|
12196
|
+
}
|
|
12197
|
+
function planMcpQwenJson(mcp, serverName = "caveman") {
|
|
12198
|
+
const path = canonicalMcpConfigPath(qwenConfigPath());
|
|
12199
|
+
const marker = readMcpServerMarker("qwen", serverName);
|
|
12200
|
+
if (marker?.config_path && marker.config_path !== path) {
|
|
12201
|
+
console.error(`${mark("warn")} ${serverName} is owned in ${marker.config_path}; uninstall it before installing into ${path}`);
|
|
12202
|
+
return null;
|
|
12203
|
+
}
|
|
12204
|
+
const loaded = readStrictMcpJsonRoot(path);
|
|
12205
|
+
if (!loaded)
|
|
12206
|
+
return null;
|
|
12207
|
+
const { root } = loaded;
|
|
12208
|
+
if (root.mcpServers !== undefined && (!root.mcpServers || typeof root.mcpServers !== "object" || Array.isArray(root.mcpServers))) {
|
|
12209
|
+
console.error(`${mark("warn")} ${path} mcpServers must be a JSON object; not modifying it`);
|
|
12210
|
+
return null;
|
|
12211
|
+
}
|
|
12212
|
+
const servers = root.mcpServers;
|
|
12213
|
+
const current = servers?.[serverName];
|
|
12214
|
+
if (marker && !marker.config_path && current === undefined) {
|
|
12215
|
+
console.error(`${mark("warn")} legacy ${serverName} ownership marker does not identify its Qwen config; refusing relocation`);
|
|
12216
|
+
return null;
|
|
12217
|
+
}
|
|
12218
|
+
if (current !== undefined) {
|
|
12219
|
+
if (!marker) {
|
|
12220
|
+
console.error(`${mark("warn")} ${path} mcpServers.${serverName} exists but is not Caveman-journaled; refusing overwrite`);
|
|
12221
|
+
return null;
|
|
12222
|
+
}
|
|
12223
|
+
if (!qwenMcpEntryMatches(current, marker)) {
|
|
12224
|
+
console.error(`${mark("warn")} ${path} mcpServers.${serverName} changed since Caveman installed it; refusing overwrite`);
|
|
12225
|
+
return null;
|
|
12226
|
+
}
|
|
12227
|
+
if (qwenMcpEntryMatches(current, mcp)) {
|
|
12228
|
+
return ownedMcpConfigPlan("qwen", path, loaded, loaded.bytes);
|
|
12229
|
+
}
|
|
12230
|
+
}
|
|
12231
|
+
const nextServers = servers ?? {};
|
|
12232
|
+
nextServers[serverName] = qwenMcpEntry(mcp);
|
|
12233
|
+
root.mcpServers = nextServers;
|
|
12234
|
+
return ownedMcpConfigPlan("qwen", path, loaded, Buffer.from(JSON.stringify(root, null, 2) + "\n"));
|
|
12235
|
+
}
|
|
12236
|
+
function planRemoveMcpQwenJson(serverName = "caveman") {
|
|
12237
|
+
const marker = readMcpServerMarker("qwen", serverName);
|
|
12238
|
+
const path = marker?.config_path ?? canonicalMcpConfigPath(qwenConfigPath());
|
|
12239
|
+
const loaded = readStrictMcpJsonRoot(path);
|
|
12240
|
+
if (!loaded)
|
|
12241
|
+
return null;
|
|
12242
|
+
if (!loaded.exists) {
|
|
12243
|
+
if (marker && !marker.config_path) {
|
|
12244
|
+
console.error(`${mark("warn")} legacy ${serverName} ownership marker does not identify its Qwen config; refusing removal`);
|
|
12245
|
+
return null;
|
|
12246
|
+
}
|
|
12247
|
+
if (marker?.config_path && movedOwnedMcpRemovalBlocked("qwen", serverName, marker))
|
|
12248
|
+
return null;
|
|
12249
|
+
return ownedMcpConfigPlan("qwen", path, loaded, null);
|
|
12250
|
+
}
|
|
12251
|
+
const { root } = loaded;
|
|
12252
|
+
if (root.mcpServers !== undefined && (!root.mcpServers || typeof root.mcpServers !== "object" || Array.isArray(root.mcpServers))) {
|
|
12253
|
+
console.error(`${mark("warn")} ${path} mcpServers must be a JSON object; not modifying it`);
|
|
12254
|
+
return null;
|
|
12255
|
+
}
|
|
12256
|
+
const servers = root.mcpServers;
|
|
12257
|
+
const current = servers?.[serverName];
|
|
12258
|
+
if (current === undefined) {
|
|
12259
|
+
if (marker && !marker.config_path) {
|
|
12260
|
+
console.error(`${mark("warn")} legacy ${serverName} ownership marker does not identify its Qwen config; refusing removal`);
|
|
12261
|
+
return null;
|
|
12262
|
+
}
|
|
12263
|
+
return ownedMcpConfigPlan("qwen", path, loaded, loaded.bytes);
|
|
12264
|
+
}
|
|
12265
|
+
if (!marker) {
|
|
12266
|
+
console.error(`${mark("warn")} ${path} mcpServers.${serverName} exists but is not Caveman-journaled; refusing removal`);
|
|
12267
|
+
return null;
|
|
12268
|
+
}
|
|
12269
|
+
if (!qwenMcpEntryMatches(current, marker)) {
|
|
12270
|
+
console.error(`${mark("warn")} ${path} mcpServers.${serverName} changed since Caveman installed it; refusing removal`);
|
|
12271
|
+
return null;
|
|
12272
|
+
}
|
|
12273
|
+
delete servers[serverName];
|
|
12274
|
+
if (Object.keys(servers).length === 0)
|
|
12275
|
+
delete root.mcpServers;
|
|
12276
|
+
return ownedMcpConfigPlan("qwen", path, loaded, Buffer.from(JSON.stringify(root, null, 2) + "\n"));
|
|
12277
|
+
}
|
|
12278
|
+
function optionalBytesHash(bytes) {
|
|
12279
|
+
return bytes ? bytesHash(bytes) : null;
|
|
12280
|
+
}
|
|
12281
|
+
function mcpPendingJournalPath(agent, serverName) {
|
|
12282
|
+
return `${canonicalOwnedMcpMarkerPath(agent, serverName)}.pending`;
|
|
12283
|
+
}
|
|
12284
|
+
function mcpConfigPendingJournalPath(configPath) {
|
|
12285
|
+
const canonicalPath = canonicalMcpConfigPath(configPath);
|
|
12286
|
+
return join(dirname(canonicalPath), `.${basename(canonicalPath)}.caveman-mcp.pending.json`);
|
|
12287
|
+
}
|
|
12288
|
+
function mcpMarkerBytes(mcp, tool, configPath) {
|
|
12289
|
+
return Buffer.from(JSON.stringify({
|
|
12290
|
+
...(configPath ? { schema_version: 1 } : {}),
|
|
12291
|
+
tool,
|
|
12292
|
+
command: mcp.command,
|
|
12293
|
+
args: mcp.args,
|
|
12294
|
+
...(configPath ? { config_path: canonicalMcpConfigPath(configPath) } : {}),
|
|
12295
|
+
}, null, 2) + "\n");
|
|
12296
|
+
}
|
|
12297
|
+
function validMcpMarkerBytes(bytes, agent, serverName) {
|
|
12298
|
+
return parseMcpServerMarkerBytes(agent, serverName, bytes) !== null;
|
|
12299
|
+
}
|
|
12300
|
+
function decodePendingBytes(value, field) {
|
|
12301
|
+
if (value === null)
|
|
12302
|
+
return null;
|
|
12303
|
+
if (typeof value !== "string")
|
|
12304
|
+
throw new Error(`${field} must be base64 or null`);
|
|
12305
|
+
const bytes = Buffer.from(value, "base64");
|
|
12306
|
+
if (bytes.toString("base64") !== value)
|
|
12307
|
+
throw new Error(`${field} is not canonical base64`);
|
|
12308
|
+
return bytes;
|
|
12309
|
+
}
|
|
12310
|
+
function validOptionalHash(value) {
|
|
12311
|
+
return value === null || (typeof value === "string" && /^sha256:[0-9a-f]{64}$/.test(value));
|
|
12312
|
+
}
|
|
12313
|
+
function ownedMcpPendingLabel(agent, serverName) {
|
|
12314
|
+
return agent && serverName ? `${agent} ${serverName} MCP` : "owned MCP";
|
|
12315
|
+
}
|
|
12316
|
+
function readOwnedMcpPendingJournalAt(path, expected = {}) {
|
|
12317
|
+
const label = ownedMcpPendingLabel(expected.agent, expected.serverName);
|
|
12318
|
+
let bytes;
|
|
12319
|
+
let value;
|
|
12320
|
+
try {
|
|
12321
|
+
bytes = readFileSync(path);
|
|
12322
|
+
value = JSON.parse(bytes.toString("utf8"));
|
|
12323
|
+
}
|
|
12324
|
+
catch (error) {
|
|
12325
|
+
if (error.code === "ENOENT")
|
|
12326
|
+
return null;
|
|
12327
|
+
throw new Error(`cannot read pending ${label} transaction: ${error.message}`);
|
|
12328
|
+
}
|
|
12329
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
12330
|
+
throw new Error(`pending ${label} transaction is malformed; refusing recovery`);
|
|
12331
|
+
}
|
|
12332
|
+
if (process.platform !== "win32" && (statSync(path).mode & 0o077) !== 0) {
|
|
12333
|
+
throw new Error(`pending ${label} transaction has unsafe permissions; refusing recovery`);
|
|
12334
|
+
}
|
|
12335
|
+
const keys = [
|
|
12336
|
+
"action", "agent", "config_after_sha256", "config_before_base64", "config_before_mode", "config_path",
|
|
12337
|
+
"config_before_sha256", "marker_after_base64", "marker_after_sha256", "marker_before_base64", "marker_before_mode",
|
|
12338
|
+
"marker_before_sha256", "marker_path", "schema_version", "server_name", "transaction_id",
|
|
12339
|
+
].sort();
|
|
12340
|
+
const journalAgent = value.agent;
|
|
12341
|
+
const journalServer = value.server_name;
|
|
12342
|
+
if (Object.keys(value).sort().join("\0") !== keys.join("\0")
|
|
12343
|
+
|| value.schema_version !== 1
|
|
12344
|
+
|| typeof value.transaction_id !== "string"
|
|
12345
|
+
|| !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(value.transaction_id)
|
|
12346
|
+
|| (journalAgent !== "kilo" && journalAgent !== "qwen")
|
|
12347
|
+
|| typeof journalServer !== "string"
|
|
12348
|
+
|| !mcpServerToolName(journalServer)
|
|
12349
|
+
|| (expected.agent !== undefined && journalAgent !== expected.agent)
|
|
12350
|
+
|| (expected.serverName !== undefined && journalServer !== expected.serverName)
|
|
12351
|
+
|| (value.action !== "install" && value.action !== "uninstall")
|
|
12352
|
+
|| typeof value.config_path !== "string"
|
|
12353
|
+
|| value.config_path !== canonicalMcpConfigPath(value.config_path)
|
|
12354
|
+
|| (expected.configPath !== undefined && value.config_path !== canonicalMcpConfigPath(expected.configPath))
|
|
12355
|
+
|| typeof value.marker_path !== "string"
|
|
12356
|
+
|| value.marker_path !== canonicalMcpConfigPath(value.marker_path)
|
|
12357
|
+
|| (expected.locatorPath !== undefined && `${value.marker_path}.pending` !== canonicalMcpConfigPath(expected.locatorPath))
|
|
12358
|
+
|| !Number.isInteger(value.config_before_mode) || value.config_before_mode < 0 || value.config_before_mode > 0o777
|
|
12359
|
+
|| !Number.isInteger(value.marker_before_mode) || value.marker_before_mode < 0 || value.marker_before_mode > 0o777
|
|
12360
|
+
|| !validOptionalHash(value.config_before_sha256)
|
|
12361
|
+
|| !validOptionalHash(value.config_after_sha256)
|
|
12362
|
+
|| !validOptionalHash(value.marker_before_sha256)
|
|
12363
|
+
|| !validOptionalHash(value.marker_after_sha256)) {
|
|
12364
|
+
throw new Error(`pending ${label} transaction is malformed; refusing recovery`);
|
|
12365
|
+
}
|
|
12366
|
+
try {
|
|
12367
|
+
const configBefore = decodePendingBytes(value.config_before_base64, "config_before_base64");
|
|
12368
|
+
const markerBefore = decodePendingBytes(value.marker_before_base64, "marker_before_base64");
|
|
12369
|
+
const markerAfter = decodePendingBytes(value.marker_after_base64, "marker_after_base64");
|
|
12370
|
+
if (optionalBytesHash(configBefore) !== value.config_before_sha256
|
|
12371
|
+
|| optionalBytesHash(markerBefore) !== value.marker_before_sha256
|
|
12372
|
+
|| optionalBytesHash(markerAfter) !== value.marker_after_sha256
|
|
12373
|
+
|| (markerBefore !== null && !validMcpMarkerBytes(markerBefore, journalAgent, journalServer))
|
|
12374
|
+
|| (markerAfter !== null && !validMcpMarkerBytes(markerAfter, journalAgent, journalServer))
|
|
12375
|
+
|| (markerBefore !== null && parseMcpServerMarkerBytes(journalAgent, journalServer, markerBefore)?.config_path !== undefined
|
|
12376
|
+
&& parseMcpServerMarkerBytes(journalAgent, journalServer, markerBefore)?.config_path !== value.config_path)
|
|
12377
|
+
|| (markerAfter !== null && parseMcpServerMarkerBytes(journalAgent, journalServer, markerAfter)?.config_path !== value.config_path)
|
|
12378
|
+
|| (value.action === "install") !== (markerAfter !== null)) {
|
|
12379
|
+
throw new Error("journal bytes do not match declared transaction state");
|
|
12380
|
+
}
|
|
12381
|
+
return {
|
|
12382
|
+
journal: value,
|
|
12383
|
+
configBefore,
|
|
12384
|
+
markerBefore,
|
|
12385
|
+
markerAfter,
|
|
12386
|
+
path,
|
|
12387
|
+
bytes,
|
|
12388
|
+
};
|
|
12389
|
+
}
|
|
12390
|
+
catch (error) {
|
|
12391
|
+
throw new Error(`pending ${label} transaction is malformed: ${error.message}`);
|
|
12392
|
+
}
|
|
12393
|
+
}
|
|
12394
|
+
function readOwnedMcpPendingLocator(agent, serverName) {
|
|
12395
|
+
const path = canonicalMcpConfigPath(mcpPendingJournalPath(agent, serverName));
|
|
12396
|
+
return readOwnedMcpPendingJournalAt(path, { agent, serverName, locatorPath: path });
|
|
12397
|
+
}
|
|
12398
|
+
function readOwnedMcpConfigPending(configPath) {
|
|
12399
|
+
const canonicalPath = canonicalMcpConfigPath(configPath);
|
|
12400
|
+
return readOwnedMcpPendingJournalAt(mcpConfigPendingJournalPath(canonicalPath), { configPath: canonicalPath });
|
|
12401
|
+
}
|
|
12402
|
+
function recoverOwnedMcpTransaction(pending) {
|
|
12403
|
+
if (!pending)
|
|
12404
|
+
return "none";
|
|
12405
|
+
const { journal, configBefore, markerBefore } = pending;
|
|
12406
|
+
const agent = journal.agent;
|
|
12407
|
+
const serverName = journal.server_name;
|
|
12408
|
+
const configPath = journal.config_path;
|
|
12409
|
+
const markerPath = journal.marker_path;
|
|
12410
|
+
const configPendingPath = mcpConfigPendingJournalPath(configPath);
|
|
12411
|
+
const locatorPath = `${markerPath}.pending`;
|
|
12412
|
+
const configPending = readOwnedMcpPendingJournalAt(configPendingPath, { agent, serverName, configPath });
|
|
12413
|
+
const locatorPending = readOwnedMcpPendingJournalAt(locatorPath, { agent, serverName, configPath, locatorPath });
|
|
12414
|
+
if (configPending && locatorPending && !configPending.bytes.equals(locatorPending.bytes)) {
|
|
12415
|
+
throw new Error(`${agent} ${serverName} MCP transaction journals disagree; refusing recovery`);
|
|
12416
|
+
}
|
|
12417
|
+
const configCurrent = fileBytes(configPath);
|
|
12418
|
+
const markerCurrent = fileBytes(markerPath);
|
|
12419
|
+
const configHash = optionalBytesHash(configCurrent);
|
|
12420
|
+
const markerHash = optionalBytesHash(markerCurrent);
|
|
12421
|
+
const configIsBefore = configHash === journal.config_before_sha256;
|
|
12422
|
+
const configIsAfter = configHash === journal.config_after_sha256;
|
|
12423
|
+
const markerIsBefore = markerHash === journal.marker_before_sha256;
|
|
12424
|
+
const markerIsAfter = markerHash === journal.marker_after_sha256;
|
|
12425
|
+
const removePendingCopies = () => {
|
|
12426
|
+
if (configPending)
|
|
12427
|
+
durableUnlink(configPendingPath);
|
|
12428
|
+
if (locatorPending)
|
|
12429
|
+
durableUnlink(locatorPath);
|
|
12430
|
+
};
|
|
12431
|
+
if (configIsAfter && markerIsAfter) {
|
|
12432
|
+
removePendingCopies();
|
|
12433
|
+
process.stderr.write(`${mark("warn")} finalized interrupted ${agent} ${serverName} MCP transaction\n`);
|
|
12434
|
+
return "finalized";
|
|
12435
|
+
}
|
|
12436
|
+
if (configIsBefore && markerIsBefore) {
|
|
12437
|
+
removePendingCopies();
|
|
12438
|
+
process.stderr.write(`${mark("warn")} discarded uncommitted ${agent} ${serverName} MCP transaction\n`);
|
|
12439
|
+
return "discarded";
|
|
12440
|
+
}
|
|
12441
|
+
if ((!configIsBefore && !configIsAfter) || (!markerIsBefore && !markerIsAfter)) {
|
|
12442
|
+
throw new Error(`${agent} ${serverName} MCP config or ownership journal changed during interrupted transaction; refusing destructive recovery`);
|
|
12443
|
+
}
|
|
12444
|
+
if (!configPending || !locatorPending) {
|
|
12445
|
+
throw new Error(`${agent} ${serverName} MCP transaction lost one durable journal copy; refusing destructive recovery`);
|
|
12446
|
+
}
|
|
12447
|
+
if (!configIsBefore) {
|
|
12448
|
+
durableReplaceFileIfUnchanged(configPath, configCurrent, configBefore, journal.config_before_mode);
|
|
12449
|
+
}
|
|
12450
|
+
if (!markerIsBefore) {
|
|
12451
|
+
durableReplaceFileIfUnchanged(markerPath, markerCurrent, markerBefore, journal.marker_before_mode);
|
|
12452
|
+
}
|
|
12453
|
+
if (optionalBytesHash(fileBytes(configPath)) !== journal.config_before_sha256
|
|
12454
|
+
|| optionalBytesHash(fileBytes(markerPath)) !== journal.marker_before_sha256) {
|
|
12455
|
+
throw new Error(`${agent} ${serverName} MCP rollback postflight mismatch`);
|
|
12456
|
+
}
|
|
12457
|
+
removePendingCopies();
|
|
12458
|
+
process.stderr.write(`${mark("warn")} rolled back interrupted ${agent} ${serverName} MCP transaction\n`);
|
|
12459
|
+
return "rolled-back";
|
|
12460
|
+
}
|
|
12461
|
+
function transactOwnedMcpConfig(agent, serverName, action, mcp, lockedConfigPath) {
|
|
12462
|
+
const plan = action === "install"
|
|
12463
|
+
? agent === "kilo" ? planMcpKiloJson(mcp, serverName) : planMcpQwenJson(mcp, serverName)
|
|
12464
|
+
: agent === "kilo" ? planRemoveMcpKiloJson(serverName) : planRemoveMcpQwenJson(serverName);
|
|
12465
|
+
if (!plan)
|
|
12466
|
+
return false;
|
|
12467
|
+
if (lockedConfigPath && plan.path !== canonicalMcpConfigPath(lockedConfigPath)) {
|
|
12468
|
+
throw new Error(`${agent} ${serverName} MCP config target changed while acquiring lock; refusing mutation`);
|
|
12469
|
+
}
|
|
12470
|
+
const markerPath = canonicalOwnedMcpMarkerPath(agent, serverName);
|
|
12471
|
+
const markerBefore = fileBytes(markerPath);
|
|
12472
|
+
if (markerBefore !== null && !validMcpMarkerBytes(markerBefore, agent, serverName)) {
|
|
12473
|
+
throw new Error(`${markerPath} is not a valid Caveman ownership journal; refusing overwrite`);
|
|
12474
|
+
}
|
|
12475
|
+
const markerBeforeMode = markerBefore === null ? 0o600 : statSync(markerPath).mode & 0o777;
|
|
12476
|
+
if (!optionalBytesEqual(fileBytes(markerPath), markerBefore)) {
|
|
12477
|
+
throw new Error(`${markerPath} changed while planning MCP update; refusing overwrite`);
|
|
12478
|
+
}
|
|
12479
|
+
const markerAfter = action === "install" ? mcpMarkerBytes(mcp, mcpServerToolName(serverName), plan.path) : null;
|
|
12480
|
+
if (!plan.changed && optionalBytesEqual(markerBefore, markerAfter))
|
|
12481
|
+
return true;
|
|
12482
|
+
const journal = {
|
|
12483
|
+
schema_version: 1,
|
|
12484
|
+
transaction_id: randomUUID(),
|
|
12485
|
+
agent,
|
|
12486
|
+
server_name: serverName,
|
|
12487
|
+
action,
|
|
12488
|
+
config_path: plan.path,
|
|
12489
|
+
marker_path: markerPath,
|
|
12490
|
+
config_before_base64: plan.before?.toString("base64") ?? null,
|
|
12491
|
+
config_before_mode: plan.beforeMode,
|
|
12492
|
+
config_before_sha256: optionalBytesHash(plan.before),
|
|
12493
|
+
config_after_sha256: optionalBytesHash(plan.after),
|
|
12494
|
+
marker_before_base64: markerBefore?.toString("base64") ?? null,
|
|
12495
|
+
marker_before_mode: markerBeforeMode,
|
|
12496
|
+
marker_before_sha256: optionalBytesHash(markerBefore),
|
|
12497
|
+
marker_after_base64: markerAfter?.toString("base64") ?? null,
|
|
12498
|
+
marker_after_sha256: optionalBytesHash(markerAfter),
|
|
12499
|
+
};
|
|
12500
|
+
const locatorPath = `${markerPath}.pending`;
|
|
12501
|
+
const configPendingPath = mcpConfigPendingJournalPath(plan.path);
|
|
12502
|
+
const pendingBytes = Buffer.from(JSON.stringify(journal, null, 2) + "\n");
|
|
12503
|
+
if (fileBytes(locatorPath) !== null || fileBytes(configPendingPath) !== null) {
|
|
12504
|
+
throw new Error(`${agent} ${serverName} MCP transaction journal already exists; refusing overwrite`);
|
|
12505
|
+
}
|
|
12506
|
+
durableCreateFile(locatorPath, pendingBytes);
|
|
12507
|
+
try {
|
|
12508
|
+
durableCreateFile(configPendingPath, pendingBytes);
|
|
12509
|
+
}
|
|
12510
|
+
catch (error) {
|
|
12511
|
+
durableUnlink(locatorPath);
|
|
12512
|
+
throw error;
|
|
12513
|
+
}
|
|
12514
|
+
try {
|
|
12515
|
+
if (action === "install") {
|
|
12516
|
+
if (plan.changed)
|
|
12517
|
+
durableReplaceFileIfUnchanged(plan.path, plan.before, plan.after, plan.beforeMode);
|
|
12518
|
+
if (!optionalBytesEqual(markerBefore, markerAfter))
|
|
12519
|
+
durableReplaceFileIfUnchanged(markerPath, markerBefore, markerAfter);
|
|
12520
|
+
}
|
|
12521
|
+
else {
|
|
12522
|
+
if (!optionalBytesEqual(markerBefore, markerAfter))
|
|
12523
|
+
durableReplaceFileIfUnchanged(markerPath, markerBefore, markerAfter);
|
|
12524
|
+
if (plan.changed)
|
|
12525
|
+
durableReplaceFileIfUnchanged(plan.path, plan.before, plan.after, plan.beforeMode);
|
|
12526
|
+
}
|
|
12527
|
+
if (optionalBytesHash(fileBytes(plan.path)) !== journal.config_after_sha256
|
|
12528
|
+
|| optionalBytesHash(fileBytes(markerPath)) !== journal.marker_after_sha256) {
|
|
12529
|
+
throw new Error(`${agent} ${serverName} MCP transaction postflight mismatch`);
|
|
12530
|
+
}
|
|
12531
|
+
durableUnlink(configPendingPath);
|
|
12532
|
+
durableUnlink(locatorPath);
|
|
12533
|
+
return true;
|
|
12534
|
+
}
|
|
12535
|
+
catch (error) {
|
|
12536
|
+
try {
|
|
12537
|
+
const recovery = recoverOwnedMcpTransaction(readOwnedMcpConfigPending(plan.path) ?? readOwnedMcpPendingLocator(agent, serverName));
|
|
12538
|
+
if (recovery === "finalized")
|
|
12539
|
+
return true;
|
|
12540
|
+
}
|
|
12541
|
+
catch (recoveryError) {
|
|
12542
|
+
throw new Error(`${agent} ${serverName} MCP transaction failed and safe recovery was blocked: ${recoveryError.message}; original error: ${error.message}`);
|
|
12543
|
+
}
|
|
12544
|
+
throw new Error(`${agent} ${serverName} MCP transaction failed and rolled back: ${error.message}`);
|
|
12545
|
+
}
|
|
12546
|
+
}
|
|
12547
|
+
function withOwnedMcpTransactionLock(agent, serverName, run) {
|
|
12548
|
+
const markerPath = canonicalOwnedMcpMarkerPath(agent, serverName);
|
|
12549
|
+
return withMcpConfigLock(markerPath, () => {
|
|
12550
|
+
const activeConfigPath = () => canonicalMcpConfigPath(agent === "kilo" ? kiloConfigPath() : qwenConfigPath());
|
|
12551
|
+
const resourcePath = () => readOwnedMcpPendingLocator(agent, serverName)?.journal.config_path
|
|
12552
|
+
?? readMcpServerMarker(agent, serverName)?.config_path
|
|
12553
|
+
?? activeConfigPath();
|
|
12554
|
+
for (let attempt = 0; attempt < 8; attempt++) {
|
|
12555
|
+
const lockPath = canonicalMcpConfigPath(resourcePath());
|
|
12556
|
+
const outcome = withMcpConfigLock(lockPath, () => {
|
|
12557
|
+
const locatorPending = readOwnedMcpPendingLocator(agent, serverName);
|
|
12558
|
+
if (locatorPending) {
|
|
12559
|
+
if (locatorPending.journal.config_path !== lockPath)
|
|
12560
|
+
return { retry: true };
|
|
12561
|
+
recoverOwnedMcpTransaction(locatorPending);
|
|
12562
|
+
return { retry: true };
|
|
12563
|
+
}
|
|
12564
|
+
const configPending = readOwnedMcpConfigPending(lockPath);
|
|
12565
|
+
if (configPending) {
|
|
12566
|
+
recoverOwnedMcpTransaction(configPending);
|
|
12567
|
+
return { retry: true };
|
|
12568
|
+
}
|
|
12569
|
+
if (canonicalMcpConfigPath(resourcePath()) !== lockPath)
|
|
12570
|
+
return { retry: true };
|
|
12571
|
+
return { retry: false, value: run(lockPath) };
|
|
12572
|
+
});
|
|
12573
|
+
if (!outcome.retry)
|
|
12574
|
+
return outcome.value;
|
|
12575
|
+
}
|
|
12576
|
+
throw new Error(`${agent} ${serverName} MCP transaction state kept changing; refusing mutation`);
|
|
12577
|
+
});
|
|
12578
|
+
}
|
|
12579
|
+
function mcpInstall(target, serverName = "caveman") {
|
|
12580
|
+
if (serverName !== "caveman" && serverName !== "caveman-browse" && serverName !== "caveman-cloud" && serverName !== "caveman-delegate") {
|
|
12581
|
+
console.error(`unknown MCP server '${serverName}'. valid: caveman, caveman-browse, caveman-cloud, caveman-delegate`);
|
|
12582
|
+
process.exit(2);
|
|
12583
|
+
}
|
|
12584
|
+
let mcp;
|
|
9975
12585
|
if (serverName === "caveman") {
|
|
9976
12586
|
mcp = resolveMcpCommand();
|
|
9977
12587
|
}
|
|
@@ -10012,13 +12622,30 @@ function mcpInstall(target, serverName = "caveman") {
|
|
|
10012
12622
|
}
|
|
10013
12623
|
let installed = 0;
|
|
10014
12624
|
for (const a of targets) {
|
|
10015
|
-
|
|
10016
|
-
|
|
10017
|
-
|
|
12625
|
+
preflightMcpServerMarker(a.id, serverName);
|
|
12626
|
+
const installOne = (lockedConfigPath) => {
|
|
12627
|
+
if (a.id === "kilo" || a.id === "qwen") {
|
|
12628
|
+
return transactOwnedMcpConfig(a.id, serverName, "install", mcp, lockedConfigPath);
|
|
10018
12629
|
}
|
|
10019
|
-
|
|
10020
|
-
|
|
12630
|
+
if (!installMcpForAgent(a, mcp, serverName))
|
|
12631
|
+
return false;
|
|
12632
|
+
try {
|
|
12633
|
+
if (serverName === "caveman") {
|
|
12634
|
+
writeMcpMarker(a.id, mcp);
|
|
12635
|
+
}
|
|
12636
|
+
else {
|
|
12637
|
+
writeMcpServerMarker(a.id, serverName, mcp, serverName === "caveman-browse" ? "caveman_browse" : serverName === "caveman-delegate" ? "caveman_delegate" : "caveman_context");
|
|
12638
|
+
}
|
|
12639
|
+
}
|
|
12640
|
+
catch (error) {
|
|
12641
|
+
throw new Error(`${a.display_name}: MCP ownership journal failed; native config may already contain the registration: ${error.message}`);
|
|
10021
12642
|
}
|
|
12643
|
+
return true;
|
|
12644
|
+
};
|
|
12645
|
+
const installedForAgent = a.id === "kilo" || a.id === "qwen"
|
|
12646
|
+
? withOwnedMcpTransactionLock(a.id, serverName, installOne)
|
|
12647
|
+
: installOne();
|
|
12648
|
+
if (installedForAgent) {
|
|
10022
12649
|
installed++;
|
|
10023
12650
|
const tool = serverName === "caveman"
|
|
10024
12651
|
? "caveman_retrieve"
|
|
@@ -10050,8 +12677,11 @@ function installMcpForAgent(a, mcp, serverName = "caveman") {
|
|
|
10050
12677
|
command: [mcp.command, ...mcp.args],
|
|
10051
12678
|
enabled: true,
|
|
10052
12679
|
});
|
|
12680
|
+
case "kilo":
|
|
12681
|
+
case "qwen":
|
|
12682
|
+
throw new Error(`${a.display_name} MCP changes require the ownership transaction`);
|
|
10053
12683
|
case "gemini":
|
|
10054
|
-
return installMcpJson(
|
|
12684
|
+
return installMcpJson(geminiSettingsPath(), ["mcpServers", serverName], {
|
|
10055
12685
|
command: mcp.command,
|
|
10056
12686
|
args: mcp.args,
|
|
10057
12687
|
});
|
|
@@ -10132,7 +12762,7 @@ function installMcpClaude(mcp, serverName = "caveman") {
|
|
|
10132
12762
|
}
|
|
10133
12763
|
}
|
|
10134
12764
|
function installMcpCodexToml(mcp, serverName = "caveman") {
|
|
10135
|
-
const path = join(
|
|
12765
|
+
const path = join(codexHomeDir(), "config.toml");
|
|
10136
12766
|
let existing = "";
|
|
10137
12767
|
try {
|
|
10138
12768
|
existing = readFileSync(path, "utf8");
|
|
@@ -10145,7 +12775,8 @@ function installMcpCodexToml(mcp, serverName = "caveman") {
|
|
|
10145
12775
|
}
|
|
10146
12776
|
const header = `[mcp_servers.${serverName}]`;
|
|
10147
12777
|
const argsLine = mcp.args.length ? `\nargs = [${mcp.args.map((s) => JSON.stringify(s)).join(", ")}]` : "";
|
|
10148
|
-
const
|
|
12778
|
+
const recoveryEnv = serverName === "caveman" ? `\n${CODEX_RECOVERY_ENV}` : "";
|
|
12779
|
+
const expectedBlock = `${header}\ncommand = ${JSON.stringify(mcp.command)}${argsLine}${recoveryEnv}\n`;
|
|
10149
12780
|
if (existing.includes(header)) {
|
|
10150
12781
|
const headerMatch = new RegExp(`(^|\\n)[ \\t]*\\[mcp_servers\\.${escapeRegExp(serverName)}\\][ \\t]*(?:\\r?\\n|$)`, "m").exec(existing);
|
|
10151
12782
|
if (!headerMatch) {
|
|
@@ -10182,7 +12813,7 @@ function installMcpCodexToml(mcp, serverName = "caveman") {
|
|
|
10182
12813
|
}
|
|
10183
12814
|
}
|
|
10184
12815
|
function codexMcpRegistrationMatches(serverName, mcp) {
|
|
10185
|
-
const path = join(
|
|
12816
|
+
const path = join(codexHomeDir(), "config.toml");
|
|
10186
12817
|
let existing = "";
|
|
10187
12818
|
try {
|
|
10188
12819
|
existing = readFileSync(path, "utf8");
|
|
@@ -10198,7 +12829,8 @@ function codexMcpRegistrationMatches(serverName, mcp) {
|
|
|
10198
12829
|
const nextHeaderOffset = existing.slice(contentStart).search(/^[ \\t]*\[/m);
|
|
10199
12830
|
const blockEnd = nextHeaderOffset === -1 ? existing.length : contentStart + nextHeaderOffset;
|
|
10200
12831
|
const argsLine = mcp.args.length ? `\nargs = [${mcp.args.map((arg) => JSON.stringify(arg)).join(", ")}]` : "";
|
|
10201
|
-
const
|
|
12832
|
+
const recoveryEnv = serverName === "caveman" ? `\n${CODEX_RECOVERY_ENV}` : "";
|
|
12833
|
+
const expected = `[mcp_servers.${serverName}]\ncommand = ${JSON.stringify(mcp.command)}${argsLine}${recoveryEnv}`;
|
|
10202
12834
|
return existing.slice(blockStart, blockEnd).trim() === expected.trim();
|
|
10203
12835
|
}
|
|
10204
12836
|
// installMcpJson merges a value at a nested key into an agent's JSON config without
|
|
@@ -10248,13 +12880,7 @@ function writeMcpMarker(agentId, mcp) {
|
|
|
10248
12880
|
}
|
|
10249
12881
|
function writeMcpServerMarker(agentId, serverName, mcp, tool) {
|
|
10250
12882
|
const path = mcpServerMarkerPath(agentId, serverName);
|
|
10251
|
-
|
|
10252
|
-
mkdirSync(dirname(path), { recursive: true });
|
|
10253
|
-
writeFileSync(path, JSON.stringify({ tool, command: mcp.command, args: mcp.args }, null, 2) + "\n");
|
|
10254
|
-
}
|
|
10255
|
-
catch {
|
|
10256
|
-
// best-effort: without the marker, wrap simply tries the loadout again later.
|
|
10257
|
-
}
|
|
12883
|
+
durableAtomicWriteFile(path, mcpMarkerBytes(mcp, tool));
|
|
10258
12884
|
}
|
|
10259
12885
|
// compress streams stdin through the caveman-engine binary (resolved via
|
|
10260
12886
|
// CAVEMAN_ENGINE_BIN, default `caveman-engine` on PATH) and writes the compressed
|
|
@@ -10550,12 +13176,21 @@ function cavemanBinForHook(powershell = process.platform === "win32") {
|
|
|
10550
13176
|
// CLI (BeforeTool, tool "run_shell_command"). It reads the tool event on stdin and,
|
|
10551
13177
|
// for a noisy command, rewrites it to run through `caveman shrink`. Anything it won't
|
|
10552
13178
|
// safely shrink it passes through: exit 0 with NO stdout = "no rewrite, run as-is".
|
|
13179
|
+
//
|
|
13180
|
+
// Codex is deliberately NOT in that list, and re-adding it is the #1037 regression:
|
|
13181
|
+
// Codex matches a saved approval against the command text itself (`prefix_rule`), so
|
|
13182
|
+
// any rewrite makes an already-approved command look new and re-prompts the user —
|
|
13183
|
+
// and the rewrite leads with the resolved caveman/node path, which differs per
|
|
13184
|
+
// machine, so no rule the user writes can cover it either. The old Codex branch also
|
|
13185
|
+
// answered the host's approval question with permissionDecision:"allow" against an
|
|
13186
|
+
// unverified contract; if Codex ever honors that, caveman silently auto-approves a
|
|
13187
|
+
// command the user's `approval_policy` meant to gate. Both ends fail closed instead.
|
|
10553
13188
|
async function shrinkHook() {
|
|
10554
13189
|
if (nativePolicyMode() === "record" || !new Set(["full-safe", "full-max"]).has(nativeProfile()))
|
|
10555
13190
|
process.exit(0);
|
|
10556
13191
|
let raw;
|
|
10557
13192
|
try {
|
|
10558
|
-
raw = await
|
|
13193
|
+
raw = await readHookStdin();
|
|
10559
13194
|
}
|
|
10560
13195
|
catch {
|
|
10561
13196
|
process.exit(0);
|
|
@@ -10570,8 +13205,9 @@ async function shrinkHook() {
|
|
|
10570
13205
|
const tool = evt?.tool_name;
|
|
10571
13206
|
const isGemini = tool === "run_shell_command"; // Gemini CLI's shell tool
|
|
10572
13207
|
const isBash = tool === "Bash"; // Claude Code + the opencode plugin
|
|
10573
|
-
|
|
10574
|
-
|
|
13208
|
+
// Every other tool name — Codex's shell/shell_command/exec_command included — runs
|
|
13209
|
+
// as the host received it. See the #1037 note above before widening this.
|
|
13210
|
+
if (!isGemini && !isBash)
|
|
10575
13211
|
process.exit(0);
|
|
10576
13212
|
const command = evt.tool_input?.command;
|
|
10577
13213
|
if (typeof command !== "string" || !shouldShrink(command))
|
|
@@ -10579,9 +13215,8 @@ async function shrinkHook() {
|
|
|
10579
13215
|
// updatedInput.command executes in host shell (Git Bash on Claude Windows),
|
|
10580
13216
|
// not hook's explicit PowerShell shell. Never leak PowerShell `&` into it.
|
|
10581
13217
|
const rewritten = `${cavemanBinForHook(false)} shrink -- ${command.trim()}`;
|
|
10582
|
-
//
|
|
10583
|
-
// hookSpecificOutput.
|
|
10584
|
-
// via hookSpecificOutput.updatedInput (camelCase + hookEventName). Emit the right one.
|
|
13218
|
+
// Gemini merges hookSpecificOutput.tool_input (snake_case, no event discriminator);
|
|
13219
|
+
// Claude replaces via hookSpecificOutput.updatedInput (camelCase + hookEventName).
|
|
10585
13220
|
const out = isGemini
|
|
10586
13221
|
? { hookSpecificOutput: { tool_input: { command: rewritten } } }
|
|
10587
13222
|
: { hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "allow", updatedInput: { command: rewritten } } };
|
|
@@ -11154,7 +13789,7 @@ async function nativeHook(argv) {
|
|
|
11154
13789
|
process.exit(0);
|
|
11155
13790
|
let raw;
|
|
11156
13791
|
try {
|
|
11157
|
-
raw = await
|
|
13792
|
+
raw = await readHookStdin();
|
|
11158
13793
|
}
|
|
11159
13794
|
catch {
|
|
11160
13795
|
process.exit(0);
|
|
@@ -11200,10 +13835,10 @@ async function nativeHook(argv) {
|
|
|
11200
13835
|
if (cwd)
|
|
11201
13836
|
entry.cwd_sha256 = `sha256:${createHash("sha256").update(cwd).digest("hex")}`;
|
|
11202
13837
|
// SessionStart revives a missing local proxy, but native routing points every
|
|
11203
|
-
// LATER turn of the session at that proxy too
|
|
11204
|
-
//
|
|
11205
|
-
//
|
|
11206
|
-
//
|
|
13838
|
+
// LATER turn of the session at that proxy too. Current proxies never expire,
|
|
13839
|
+
// but crashes and older binaries can still leave a dead base URL. A plain
|
|
13840
|
+
// session needs prompt-time recovery as well. The port check makes revival
|
|
13841
|
+
// idempotent, so run
|
|
11207
13842
|
// it for the mid-session events that reach the full CLI as well.
|
|
11208
13843
|
if (normalizedEvent === "SessionStart" || normalizedEvent === "UserPromptSubmit" || normalizedEvent === "PostCompact") {
|
|
11209
13844
|
try {
|
|
@@ -11285,13 +13920,13 @@ async function nativeHook(argv) {
|
|
|
11285
13920
|
}
|
|
11286
13921
|
}
|
|
11287
13922
|
function claudeSettingsPath() {
|
|
11288
|
-
return join(
|
|
13923
|
+
return join(claudeConfigDir(), "settings.json");
|
|
11289
13924
|
}
|
|
11290
13925
|
function geminiSettingsPath() {
|
|
11291
|
-
return join(
|
|
13926
|
+
return join(geminiConfigDir(), "settings.json");
|
|
11292
13927
|
}
|
|
11293
13928
|
function codexHooksPath() {
|
|
11294
|
-
return join(
|
|
13929
|
+
return join(codexHomeDir(), "hooks.json");
|
|
11295
13930
|
}
|
|
11296
13931
|
// installSettingsHook registers a command-output shrink hook in a settings.json that
|
|
11297
13932
|
// follows the Claude/Gemini shape — root.hooks[<event>] is an array of
|
|
@@ -11414,7 +14049,7 @@ function commandHookKind(a) {
|
|
|
11414
14049
|
}
|
|
11415
14050
|
function instructionFileForAgent(a) {
|
|
11416
14051
|
const hook = a.command_hook;
|
|
11417
|
-
return hook && "file" in hook ? hook.file : undefined;
|
|
14052
|
+
return hook && "file" in hook ? agentUserPath(a.id, hook.file) : undefined;
|
|
11418
14053
|
}
|
|
11419
14054
|
// (hard methods: claude-pretooluse, codex-pretooluse, opencode-plugin, gemini-beforetool, hermes-plugin, openclaw-plugin.)
|
|
11420
14055
|
// installShrinkHookForAgent installs the command-output compression hook using the
|
|
@@ -11536,7 +14171,7 @@ function writeRecallHookMarker(agentId) {
|
|
|
11536
14171
|
async function memRecallHook() {
|
|
11537
14172
|
let raw;
|
|
11538
14173
|
try {
|
|
11539
|
-
raw = await
|
|
14174
|
+
raw = await readHookStdin();
|
|
11540
14175
|
}
|
|
11541
14176
|
catch {
|
|
11542
14177
|
process.exit(0);
|
|
@@ -11630,6 +14265,17 @@ function hookInstalledPhrase(a) {
|
|
|
11630
14265
|
return `shrink preference added to ${ch.file} ${dim("(a model nudge, not a hard rewrite)")}`;
|
|
11631
14266
|
return "command-output rewrite hook installed";
|
|
11632
14267
|
}
|
|
14268
|
+
// codexRewriteRetired: codex's profile still declares the `codex-pretooluse` hard
|
|
14269
|
+
// tier, but shrinkHook has declined every Codex tool event since #1037 — rewriting
|
|
14270
|
+
// the command breaks the user's saved approval rules. Installing that hook would
|
|
14271
|
+
// register a callback with no behavior behind it and report a rewrite that does not
|
|
14272
|
+
// happen. Retiring the tier in the profile is the real fix and is NOT done here: the
|
|
14273
|
+
// same `command_hook` entry carries codex's directives instructions-file, and
|
|
14274
|
+
// nativeHooksDocument would have to migrate the entry `caveman enable codex` already
|
|
14275
|
+
// wrote. Both are maintainer decisions; this just stops making the false claim.
|
|
14276
|
+
function codexRewriteRetired(a) {
|
|
14277
|
+
return a.id === "codex";
|
|
14278
|
+
}
|
|
11633
14279
|
// ── soft tier: instruction-note ──────────────────────────────────────────────
|
|
11634
14280
|
// For agents with no deterministic command-rewrite surface, we append a
|
|
11635
14281
|
// clearly-delimited note to a file the agent auto-reads as model instructions,
|
|
@@ -12402,6 +15048,10 @@ function hooksCmd(rest) {
|
|
|
12402
15048
|
let n = 0;
|
|
12403
15049
|
let hard = 0;
|
|
12404
15050
|
for (const a of targets) {
|
|
15051
|
+
if (codexRewriteRetired(a)) {
|
|
15052
|
+
process.stderr.write(`${mark("warn")} ${a.display_name}: no command-output rewrite — it breaks saved Codex approval rules (#1037); run noisy commands through ${cyan("caveman shrink -- <cmd>")}\n`);
|
|
15053
|
+
continue;
|
|
15054
|
+
}
|
|
12405
15055
|
if (installShrinkHookForAgent(a)) {
|
|
12406
15056
|
writeShrinkHookMarker(a.id);
|
|
12407
15057
|
n++;
|
|
@@ -12489,12 +15139,45 @@ function evalsRun(argv = []) {
|
|
|
12489
15139
|
// owns the ~/.caveman/ SQLite store. The CLI carries no database dependency, so
|
|
12490
15140
|
// it reads through the same Go binary `caveman start` launches.
|
|
12491
15141
|
function stats(argv = []) {
|
|
12492
|
-
if (argv.length
|
|
12493
|
-
|
|
15142
|
+
if (argv.length === 1 && ["--help", "-h", "help"].includes(argv[0])) {
|
|
15143
|
+
process.stdout.write(STATS_HELP);
|
|
15144
|
+
return;
|
|
15145
|
+
}
|
|
15146
|
+
let options;
|
|
15147
|
+
try {
|
|
15148
|
+
options = parseStatsOptions(argv);
|
|
15149
|
+
}
|
|
15150
|
+
catch (error) {
|
|
15151
|
+
console.error(error.message);
|
|
15152
|
+
commandUsage(STATS_USAGE);
|
|
15153
|
+
}
|
|
12494
15154
|
const bin = cavemanBin("caveman-proxy", "CAVEMAN_PROXY_BIN");
|
|
12495
15155
|
try {
|
|
12496
|
-
const
|
|
12497
|
-
|
|
15156
|
+
const args = ["stats", "--report", ...options.filters];
|
|
15157
|
+
if (!options.json || options.out)
|
|
15158
|
+
args.push("--write-report");
|
|
15159
|
+
if (options.out)
|
|
15160
|
+
args.push("--out", resolve(options.out));
|
|
15161
|
+
const out = execFileSync(bin, args, { encoding: "utf8", timeout: 60_000, maxBuffer: 32 * 1024 * 1024 });
|
|
15162
|
+
const report = JSON.parse(out);
|
|
15163
|
+
// Older companion binaries ignore --report. Keep their measurements
|
|
15164
|
+
// readable, but never pretend they generated the new accounting report.
|
|
15165
|
+
if (report.schema !== "caveman.stats.v1") {
|
|
15166
|
+
if (options.filters.length || options.out || options.open) {
|
|
15167
|
+
throw new Error("installed proxy does not support filtered stats or HTML reports; run caveman setup --install");
|
|
15168
|
+
}
|
|
15169
|
+
process.stdout.write(out);
|
|
15170
|
+
if (!options.json)
|
|
15171
|
+
process.stderr.write("Detailed stats require an updated proxy: caveman setup --install\n");
|
|
15172
|
+
return;
|
|
15173
|
+
}
|
|
15174
|
+
if (options.json)
|
|
15175
|
+
process.stdout.write(out);
|
|
15176
|
+
else {
|
|
15177
|
+
process.stdout.write(renderStatsSummary(report));
|
|
15178
|
+
if (report.report_path && (options.open || (!options.plain && learnTuiTerminal())))
|
|
15179
|
+
openLearnReport(report.report_path);
|
|
15180
|
+
}
|
|
12498
15181
|
}
|
|
12499
15182
|
catch (error) {
|
|
12500
15183
|
console.error(`failed to read stats via ${bin}: ${error.message}`);
|
|
@@ -13321,7 +16004,7 @@ function learnImplementPrompt(focus) {
|
|
|
13321
16004
|
function ensureLearnAgentGuide(agent) {
|
|
13322
16005
|
const path = agent.id === "claude"
|
|
13323
16006
|
? join(process.cwd(), ".claude", "skills", "caveman-learn", "SKILL.md")
|
|
13324
|
-
: join(
|
|
16007
|
+
: join(codexHomeDir(), "skills", "caveman-learn", "SKILL.md");
|
|
13325
16008
|
try {
|
|
13326
16009
|
readFileSync(path);
|
|
13327
16010
|
return "";
|
|
@@ -13900,6 +16583,57 @@ function readStdin() {
|
|
|
13900
16583
|
process.stdin.on("error", reject);
|
|
13901
16584
|
});
|
|
13902
16585
|
}
|
|
16586
|
+
// readHookStdin is for host hook callbacks (shrink-hook, mem recall, native-hook):
|
|
16587
|
+
// the host writes ONE JSON object and closes, but under the Windows pipe
|
|
16588
|
+
// implementation that close can lag arbitrarily (#729/#833, #949), and a hook that
|
|
16589
|
+
// waits for EOF burns the host's whole budget with its work already done. Resolve
|
|
16590
|
+
// on the first complete JSON object; EOF still resolves for hosts that close
|
|
16591
|
+
// promptly. Same 2 MiB cap as native-hook-fast.
|
|
16592
|
+
function readHookStdin() {
|
|
16593
|
+
return new Promise((resolve, reject) => {
|
|
16594
|
+
if (process.stdin.isTTY) {
|
|
16595
|
+
reject(new Error("no hook payload on stdin"));
|
|
16596
|
+
return;
|
|
16597
|
+
}
|
|
16598
|
+
const chunks = [];
|
|
16599
|
+
let bytes = 0;
|
|
16600
|
+
let done = false;
|
|
16601
|
+
const finish = () => {
|
|
16602
|
+
if (done)
|
|
16603
|
+
return;
|
|
16604
|
+
done = true;
|
|
16605
|
+
// pause() stops the flow but the 'data' listener keeps the handle referenced;
|
|
16606
|
+
// unref() lets the process exit as soon as stdout flushes.
|
|
16607
|
+
process.stdin.pause();
|
|
16608
|
+
try {
|
|
16609
|
+
process.stdin.unref();
|
|
16610
|
+
}
|
|
16611
|
+
catch { /* not every stream type supports it */ }
|
|
16612
|
+
resolve(Buffer.concat(chunks));
|
|
16613
|
+
};
|
|
16614
|
+
process.stdin.on("data", (chunk) => {
|
|
16615
|
+
if (done)
|
|
16616
|
+
return;
|
|
16617
|
+
bytes += chunk.length;
|
|
16618
|
+
if (bytes > 2 * 1024 * 1024) {
|
|
16619
|
+
done = true;
|
|
16620
|
+
reject(new Error("hook payload too large"));
|
|
16621
|
+
return;
|
|
16622
|
+
}
|
|
16623
|
+
chunks.push(chunk);
|
|
16624
|
+
// A partial payload throws here and we simply wait for more bytes.
|
|
16625
|
+
try {
|
|
16626
|
+
JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
16627
|
+
}
|
|
16628
|
+
catch {
|
|
16629
|
+
return;
|
|
16630
|
+
}
|
|
16631
|
+
finish();
|
|
16632
|
+
});
|
|
16633
|
+
process.stdin.on("end", finish);
|
|
16634
|
+
process.stdin.on("error", reject);
|
|
16635
|
+
});
|
|
16636
|
+
}
|
|
13903
16637
|
async function init(argv) {
|
|
13904
16638
|
// Reuse login's own resolution (C8 review finding 6): init used to compute
|
|
13905
16639
|
// its own baseURL with a bare localhost:8080 literal and no CAVE_API_URL
|
|
@@ -13951,6 +16685,9 @@ function readRawProxyRunState(port) {
|
|
|
13951
16685
|
...(typeof parsed.started_at === "string" ? { started_at: parsed.started_at } : {}),
|
|
13952
16686
|
...(typeof parsed.version === "string" ? { version: parsed.version } : {}),
|
|
13953
16687
|
...(typeof parsed.recovery_via_mcp === "boolean" ? { recovery_via_mcp: parsed.recovery_via_mcp } : {}),
|
|
16688
|
+
provider_upstreams: publishedUpstreamsOf(parsed.provider_upstreams),
|
|
16689
|
+
compat_upstreams: publishedUpstreamsOf(parsed.compat_upstreams),
|
|
16690
|
+
compat_forward_headers: publishedForwardHeadersOf(parsed.compat_forward_headers),
|
|
13954
16691
|
};
|
|
13955
16692
|
}
|
|
13956
16693
|
catch {
|
|
@@ -13967,6 +16704,7 @@ function processAlive(pid) {
|
|
|
13967
16704
|
}
|
|
13968
16705
|
}
|
|
13969
16706
|
function createProxySessionMarker(port) {
|
|
16707
|
+
pruneDeadProxySessionMarkers(port);
|
|
13970
16708
|
const dir = proxySessionDir(port);
|
|
13971
16709
|
try {
|
|
13972
16710
|
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
@@ -13988,51 +16726,40 @@ function createProxySessionMarker(port) {
|
|
|
13988
16726
|
}
|
|
13989
16727
|
return null;
|
|
13990
16728
|
}
|
|
13991
|
-
|
|
13992
|
-
|
|
13993
|
-
|
|
13994
|
-
try {
|
|
13995
|
-
unlinkSync(marker);
|
|
13996
|
-
}
|
|
13997
|
-
catch (error) {
|
|
13998
|
-
if (error.code !== "ENOENT") {
|
|
13999
|
-
// Marker cleanup is best-effort; the next reader prunes a dead owner.
|
|
14000
|
-
}
|
|
14001
|
-
}
|
|
14002
|
-
}
|
|
14003
|
-
function countOtherLiveProxySessions(port, ownMarker) {
|
|
16729
|
+
// pruneDeadProxySessionMarkers removes markers whose owner died. Their absence
|
|
16730
|
+
// never authorizes a restart, so nothing reads the surviving count.
|
|
16731
|
+
function pruneDeadProxySessionMarkers(port) {
|
|
14004
16732
|
let names;
|
|
14005
16733
|
try {
|
|
14006
16734
|
names = readdirSync(proxySessionDir(port));
|
|
14007
16735
|
}
|
|
14008
16736
|
catch {
|
|
14009
|
-
return
|
|
16737
|
+
return;
|
|
14010
16738
|
}
|
|
14011
|
-
let live = 0;
|
|
14012
16739
|
for (const name of names) {
|
|
14013
|
-
const marker = join(proxySessionDir(port), name);
|
|
14014
|
-
if (ownMarker && marker === ownMarker)
|
|
14015
|
-
continue;
|
|
14016
16740
|
const match = /^(\d+)-/.exec(name);
|
|
14017
16741
|
const pid = match ? Number(match[1]) : NaN;
|
|
14018
|
-
if (
|
|
14019
|
-
try {
|
|
14020
|
-
unlinkSync(marker);
|
|
14021
|
-
}
|
|
14022
|
-
catch {
|
|
14023
|
-
// Concurrent cleanup or a read-only directory: neither upgrades ownership.
|
|
14024
|
-
}
|
|
16742
|
+
if (Number.isSafeInteger(pid) && pid > 0 && processAlive(pid))
|
|
14025
16743
|
continue;
|
|
16744
|
+
try {
|
|
16745
|
+
unlinkSync(join(proxySessionDir(port), name));
|
|
16746
|
+
}
|
|
16747
|
+
catch {
|
|
16748
|
+
// Concurrent cleanup or a read-only directory: neither upgrades ownership.
|
|
14026
16749
|
}
|
|
14027
|
-
live++;
|
|
14028
16750
|
}
|
|
14029
|
-
return live;
|
|
14030
16751
|
}
|
|
14031
|
-
function
|
|
14032
|
-
|
|
14033
|
-
|
|
14034
|
-
|
|
14035
|
-
|
|
16752
|
+
function removeProxySessionMarker(marker) {
|
|
16753
|
+
if (!marker)
|
|
16754
|
+
return;
|
|
16755
|
+
try {
|
|
16756
|
+
unlinkSync(marker);
|
|
16757
|
+
}
|
|
16758
|
+
catch (error) {
|
|
16759
|
+
if (error.code !== "ENOENT") {
|
|
16760
|
+
// Marker cleanup is best-effort; the next reader prunes a dead owner.
|
|
16761
|
+
}
|
|
16762
|
+
}
|
|
14036
16763
|
}
|
|
14037
16764
|
function probeProxyVersion() {
|
|
14038
16765
|
const binary = resolveGoBin("caveman-proxy", "CAVEMAN_PROXY_BIN");
|
|
@@ -14082,12 +16809,26 @@ function readProxyRuntimeState(port, versionInfo) {
|
|
|
14082
16809
|
...(typeof parsed.started_at === "string" ? { started_at: parsed.started_at } : {}),
|
|
14083
16810
|
...(typeof parsed.version === "string" ? { version: parsed.version } : {}),
|
|
14084
16811
|
...(typeof parsed.recovery_via_mcp === "boolean" ? { recovery_via_mcp: parsed.recovery_via_mcp } : {}),
|
|
16812
|
+
provider_upstreams: publishedUpstreamsOf(parsed.provider_upstreams),
|
|
16813
|
+
compat_upstreams: publishedUpstreamsOf(parsed.compat_upstreams),
|
|
16814
|
+
compat_forward_headers: publishedForwardHeadersOf(parsed.compat_forward_headers),
|
|
14085
16815
|
};
|
|
14086
16816
|
}
|
|
14087
16817
|
catch {
|
|
14088
16818
|
return { owner: "unknown" };
|
|
14089
16819
|
}
|
|
14090
16820
|
}
|
|
16821
|
+
// A proxy caveman just started binds its port before its run state is
|
|
16822
|
+
// readable; polling briefly keeps that window from reading as a foreign owner.
|
|
16823
|
+
async function awaitProxyRuntimeState(port, versionInfo, timeoutMs = 3000) {
|
|
16824
|
+
const deadline = Date.now() + timeoutMs;
|
|
16825
|
+
for (;;) {
|
|
16826
|
+
const state = readProxyRuntimeState(port, versionInfo);
|
|
16827
|
+
if (state.owner !== "unknown" || Date.now() >= deadline)
|
|
16828
|
+
return state;
|
|
16829
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
16830
|
+
}
|
|
16831
|
+
}
|
|
14091
16832
|
function capabilitySourcesForStatus() {
|
|
14092
16833
|
const resolution = resolveCapabilities();
|
|
14093
16834
|
const sourceOrder = ["proxy-yaml", "legacy-wrap", "global", "project", "env"];
|